How to disable Dynamic Import transform on CJS?
azu opened this issue · 7 comments
It looks like that packemon transform import()
to require()
.
index.ts
const main = async () => {
const pkgDir = await import("pkg-dir");
console.log(await pkgDir.packageDirectory());
}
main();
to be index.cjs
'use strict';
function _interopNamespace(e) {
if (e && e.__esModule) return e;
const n = Object.create(null);
if (e) {
for (const k in e) {
if (k !== 'default') {
const d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: () => e[k]
});
}
}
}
n.default = e;
return Object.freeze(n);
}
const main = async () => {
const pkgDir = await Promise.resolve().then(() => /*#__PURE__*/_interopNamespace(require('pkg-dir')));
console.log(await pkgDir.packageDirectory());
};
main();
//# sourceMappingURL=index.cjs.map
I want to use native import()
in CJS because it is only way to load ESM from CJS package.
Expected
The output use native import()
Actual
The output use require()
Config
"scripts": {
"build": "packemon pack --addEngines --addExports --declaration --declarationConfig tsconfig.json",
"tsc:build": "tsc"
},
"packemon": [
{
"inputs": {
"index": "./src/index.ts"
},
"platform": "node",
"format": "cjs"
},
{
"inputs": {
"node": "./src/index.ts"
},
"platform": "node",
"format": "mjs"
}
],
Reproduce Repository
https://github.com/azu/packemon-native-dynamic-import
This repo use TypeScript and set "module": "NodeNext"
.
tsc output includes import()
expectly.
Workaround
Use new Function
const _importDynamic = new Function("modulePath", "return import(modulePath)");
This is an interesting one, since I force it to always use import()
unless on the legacy support. https://github.com/milesj/packemon/blob/master/packages/packemon/src/babel/config.ts#L9
Is this using babel or swc?
Will dig into.
Probably, it uses babel? (It will use default transpiler)
However, I've tried to run PACKEMON_SWC=true npm run build
and I get similar output.
https://github.com/azu/packemon-native-dynamic-import/blob/swc/cjs/index.cjs
This is confusing. This is the line in Babel where the call gets transformed: https://github.com/babel/babel/blob/main/packages/babel-plugin-transform-modules-commonjs/src/index.ts#L184
Yet when I debug and log, this line is never called, YET the imports are still being transformed. Either this is a bug in Babel, or something else is going on that I'm not aware of.
Turns out, it's rollup causing this. Digging into further.
Thanks!