(由于我使用的配置文件是 webpack.config.ts
,并且在 package.json
中 type
为 module
。如果你使用的是 js
,则应该不会有这个问题)
因为想要使用顶级 await
语法,我将 tsconfig.json
中的 module
设置为了 ESNext
,不过这样 Webpack 就遇到了问题
[webpack-cli] Failed to load './webpack.config.ts' config
[webpack-cli] TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for ./webpack.config.ts
at new NodeError (node:internal/errors:329:5)
at Loader.defaultGetFormat [as _getFormat] (node:internal/modules/esm/get_format:71:15)
at Loader.getFormat (node:internal/modules/esm/loader:104:42)
at Loader.getModuleJob (node:internal/modules/esm/loader:242:31)
at async Loader.import (node:internal/modules/esm/loader:176:17)
at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
at async loadConfig (./node_modules/webpack-cli/lib/webpack-cli.js:1182:35)
at async WebpackCLI.resolveConfig (./node_modules/webpack-cli/lib/webpack-cli.js:1290:38)
at async WebpackCLI.createCompiler (./node_modules/webpack-cli/lib/webpack-cli.js:1670:22)
at async WebpackCLI.buildCommand (./node_modules/webpack-cli/lib/webpack-cli.js:1785:20) {
code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
经过研究,Webpack 不支持使用 esm
的加载器,需要修改加载器。最后根据 https://github.com/webpack/webpack-cli/issues/2916#issuecomment-904536387 得出需要使用
node --loader ts-node/esm node_modules/.bin/webpack-cli --entry ./index.js --mode production
接下来马上迎来的新的错误
(node:29864) ExperimentalWarning: Custom ESM Loaders is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
***\node_modules\.bin\webpack-cli:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
^^^^^^^
SyntaxError: missing ) after argument list
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1178:20)
at Module._compile (node:internal/modules/cjs/loader:1220:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Object.require.extensions.<computed> [as .js] (***\node_modules\ts-node\src\index.ts:1608:43)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Function.Module._load (node:internal/modules/cjs/loader:960:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
后面经过一番查找,发现是 node 20.x 并不能很好的支持,但是我也有看到相关的问题已经被修复 (https://github.com/privatenumber/tsx/pull/337) ,不过在我的测试下仍然是不行的
最终还是选择了折中的方法,将 Webpack 的配置文件修改成了 JavaScript 形式的 ,但是由于在 package.json
中,将 type
配置成了 module
,导致并不能解析。因此将后缀名改为 .cjs
,然后在配置文件中使用 CommonJS 的语法,如 request 、module.exports
这应该不是最终解,带后续研究之后再来更新吧
推荐下 vite