【发布时间】:2021-11-24 08:23:55
【问题描述】:
我以编程方式使用 webpack,包括 typescript、ESM 和 jest。在一个开玩笑的测试中,我在导入 ES 模块时遇到了不包括 .js 文件扩展名的错误。例如:
Module not found: Error: Can't resolve 'modulename' in '/path/components'
Did you mean 'modulename.js'?
BREAKING CHANGE: The request 'modulename' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
有问题的模块确实在其package.json 中设置了"type": "module"。我尝试将.js 添加到导入中,但没有帮助。
我在开玩笑:
node --experimental-vm-modules --experimental-specifier-resolution=node node_modules/jest/bin/jest.js
推荐 in the docs (除了 webpack 之外的一切都有效)。请注意,我尝试过使用和不使用--experimental-specifier-resolution=node(这在其他类似情况下有所帮助)。
关于如何让 webpack 工作有什么想法吗?提前致谢!
注意:在全部转换为 ESM 之前,一切正常!现在只有程序化 webpack 不起作用。
Webpack 配置:
{
entry,
target: 'web',
output: {
path: outputDir,
filename: '[name].js',
},
mode: process.env.NODE_ENV as 'development' | 'production' | 'none' | undefined,
resolve: {
extensions: [
'.ts',
'.tsx',
'.js',
'.jsx',
'.ttf',
'.eot',
'.otf',
'.svg',
'.png',
'.woff',
'.woff2',
'.css',
'.scss',
'.sass',
],
},
module: {
rules: [
{
test: /\.(ttf|eot|otf|svg|png)$/,
loader: 'file-loader',
},
{
test: /\.(woff|woff2)$/,
loader: 'url-loader',
},
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
sourceType: 'unambiguous',
presets: [
[
'@babel/preset-env',
{
corejs: '3.0.0,',
useBuiltIns: 'usage',
},
],
'@babel/preset-react',
'@babel/preset-typescript',
],
plugins: [
'css-modules-transform',
[
'babel-plugin-react-scoped-css',
{
include: '.scoped.(sa|sc|c)ss$',
},
],
'@babel/plugin-proposal-class-properties',
],
},
},
{
test: /\.(sc|c|sa)ss$/,
use: [
'style-loader',
'css-loader',
'scoped-css-loader',
'sass-loader',
],
},
],
},
}
【问题讨论】:
标签: node.js typescript webpack jestjs es6-modules