swc-project / swc-loader

Moved to https://github.com/swc-project/pkgs
MIT License
394 stars 29 forks source link

Dynamically importing JSON module containing simple string in CJS loads wrong shape #43

Closed Josh-Cena closed 2 years ago

Josh-Cena commented 2 years ago
webpack.config.js ```js module.exports = { name: "SWC", mode: "production", entry: "./test.js", output: { filename: "swc-out.js", }, module: { rules: [ { test: /\.[jt]sx?$/i, use: [ { loader: require.resolve("swc-loader"), options: { jsc: { parser: { syntax: "ecmascript", }, target: "es2017", }, module: { type: "commonjs", }, }, }, ], }, ], }, }; ```

test.js

import("./data.json").then(console.log);

data.json

"foo"

Run:

yarn webpack
node ./dist/swc-out.js

Output:

{ '0': 'f', '1': 'o', '2': 'o', default: 'foo' }

As reference, here's Babel's equivalent config:

webpack.config.js ```js module.exports = { name: "Babel", mode: "production", entry: "./test.js", output: { filename: "babel-out.js", }, module: { rules: [ { test: /\.[jt]sx?$/i, use: [ { loader: require.resolve("babel-loader"), options: { presets: [ [ require.resolve("@babel/preset-env"), { targets: { node: "current", }, }, ], ], plugins: [require.resolve("babel-plugin-dynamic-import-node")], }, }, ], }, ], }, }; ```

Output:

{ default: 'foo' }

Env:

Josh-Cena commented 2 years ago

Babel's output contains a

if (
  obj === null ||
  (typeof obj !== "object" && typeof obj !== "function")
) {
  return { default: obj };
}

check, which is lacking in SWC's output. This may be a problem in the core?

Josh-Cena commented 2 years ago

Re-filed in upstream. https://github.com/swc-project/swc/issues/4284