typescript dynamic import clashes with webpack.config in tsconfig.json?

Viewed 883
// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom","esnext"],
    // "module": "commonjs",
    "module": "esNext",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "moduleResolution": "node"
  }
}
//webpack.config.ts
import merge from 'webpack-merge'
import base from './webpack.base'
import webpack from 'webpack';
// ...

With configuration above, when I run npm run build, it throws error:

(function (exports, require, module, __filename, __dirname) { import merge from 'webpack-merge';
SyntaxError: Cannot use import statement outside a module`

I found the solution that I should use "module": "commonjs", that's no doubt that webpack runs in node environment.

While dynamic import of webpack needs "module": "esNext" in tsconfig.json, and if I use "module": "commonjs" configuration, webpack with webpackChunkName doesn't work.

My dynamic-import code is like this, along with configuration in babel.

const starsDance = () => import(/* webpackChunkName: "starsDance" */'./game-stars-dance')

I can't find the finally solution through many googles, how could I do? And thanks very much for help.

2 Answers

I fixed this by installing ts-node before trying to run the webpack --mode production command causing issues. I believe ts-node is used to transform the webpack.config.ts file into something node can understand.

Related