[Bug]: `import "binaryen"` throws error "'import.meta' cannot be used outside of module code" when minimize is on
xc2 opened this issue Β· comments
System Info
System:
OS: macOS 14.5
CPU: (12) arm64 Apple M2 Max
Memory: 97.03 MB / 32.00 GB
Shell: 3.7.1 - /opt/homebrew/bin/fish
Binaries:
Node: 20.12.2 - ~/.managed/n/bin/node
Yarn: 1.22.21 - ~/.managed/n/bin/yarn
npm: 10.5.0 - ~/.managed/n/bin/npm
pnpm: 8.15.4 - ~/.managed/n/bin/pnpm
bun: 1.0.34 - /opt/homebrew/bin/bun
Watchman: 2024.03.18.00 - /opt/homebrew/bin/watchman
Browsers:
Chrome: 124.0.6367.158
Safari: 17.5
npmPackages:
@rspack/cli: ^0.6.3 => 0.6.5
@rspack/core: ^0.6.3 => 0.6.5
Details
Code
import a from 'binaryen';
console.log(a);
Configuration
module.exports = {
mode: "none",
optimization: {
// when minimize is on, importing binaryen will produce error "'import.meta' cannot be used outside of module code"
minimize: true,
},
}
Got
> rspack-repro@1.0.0 build:rspack /Users/kfll/Developer/rspack-repro-binaryen
> rspack -c rspack.config.js
ERROR in Γ JavaScript parsing error: 'import.meta' cannot be used outside of module code.
ββ[4:1]
4 β * SPDX-License-Identifier: Apache-2.0
5 β */
6 β var JC=(()=>{var vA=import.meta.url;return async fun...
Expected
There's type:"module"
in binaryen/package.json
so it should be considered as module code
More
This only happens when minimize is on
Reproduce link
https://github.com/xc2/rspack-repro-binaryen
Reproduce Steps
pnpm i
pnpm build:rspack | less
Try to enable module
in SWC js minifier plugin.
I've simplified the reproduction.
This problem occurs when importing a "module"
package whose main file contains new URL("./", import.meta.url)
.
Both rspack and webpack will create an asset file xxx.js
for the main file itself because of the statement new URL("./", import.meta.url)
as documented: https://webpack.js.org/guides/asset-modules/#url-assets
Consider the foo
example, the package foo
has these two traits:
- there's
new URL("./", import.meta.url)
infoo/index.js
- is a
"module"
package
When importing foo
, both rspack and webpack will
- bundle content of
foo/index.js
into the main asset file - and also create an asset file
xxxx.js
whose content is same asfoo/index.js
When minimizing the xxxx.js
file, depending on the value of package "type"
package type of foo |
minimize | rspack | webpack |
---|---|---|---|
"module" |
ON | β[1] | β |
"commonjs" |
ON | β[2] | β[2] |
"module" |
OFF | β | β |
"commonjs" |
OFF | β[2] | β[2] |
After dig into it, I just found
- failure [2] is dropped before minimizing which is as expected and has nothing to do with this issue.
- while [1] is dropped on minimizing which causes this issue.
- webpack minifies the file with
module: undefined
while rspack minifies it withmodule: false