rollup-plugin-swc
rollup-plugin-swc copied to clipboard
Cannot import from package which has "type": "module"
I'm using native ES modules in Node v16.15.0. This is done by specifying "type"
prop in package.json
:
"type": "module"
Here are repro steps:
mkdir test-proj
cd ./test-proj
npm init -y
npm pkg set type module
echo 'import swc from "rollup-plugin-swc";console.log("", swc());' > index.js
npm add rollup-plugin-swc
node ./index.js
Would get me something like this:
file:///home/rz/projects/test-proj/index.js:1
import swc from "rollup-plugin-swc";console.log("", swc());
^
TypeError: swc is not a function
at file:///home/rz/projects/test-proj/index.js:1:53
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:61:12)
The swc
that we import above is evaluated as { default: [Function: swc] }
So, this happens because the package.json
doesn't have the type
field, so all .js
files are treated as CommonJs even if they use import/export
syntax.
This happens because Node.js ignores "module"
prop in package.json
of the rollup-plugin-swc
. As per https://nodejs.org/api/packages.html#dual-commonjses-module-packages.
So, if we rename ./dist/esm/index.js
to ./dist/esm/index.mjs
and change the package.json
of the rollup-plugin-swc
to look like below:
"main": "dist/cjs/index.js",
"module": "dist/esm/index.mjs",
"types": "dist/index.d.ts",
"type": "commonjs",
"exports": {
"require": "./dist/cjs/index.js",
"import": "./dist/esm/index.mjs"
},
Then it works. I didn't go far to test for backward compatibility with prior versions of Node - but it should work.
@rollup/plugin-node-resolve
adopts similar approach but they use extra package.json
in es
directory:
{"type":"module"}
instead of renaming to .mjs
https://github.com/rollup/plugins/blob/master/packages/node-resolve/rollup.config.js#L16
Hack solution
import * as _swc from "rollup-plugin-swc";
const swc = _swc.default.default;