我正在以编程方式使用 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.
相关模块确实在其
"type": "module"
中设置了 package.json
。我尝试在导入中添加 .js
,但没有帮助。
我正在开玩笑:
node --experimental-vm-modules --experimental-specifier-resolution=node node_modules/jest/bin/jest.js
按照文档中的建议(除了 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',
],
},
],
},
}
这里。
基本上,必须在module.rules
下的 webpack 配置中添加 2 件事:
{
test: /\.m?js/,
type: "javascript/auto",
},
{
test: /\.m?js/,
resolve: {
fullySpecified: false,
},
},
module.exports = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
],
}
...
}
我把它改成了这个
module.exports = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
},
resolve: {
fullySpecified: false,
}
}
],
}
...
}
.mjs' 文件或 '.js' 文件,其中 package.json 包含 'ge.json 包含 '"type": "模块”')。 请求中的扩展是必需的,以便完全指定。 将扩展添加到请求中。 ./src/index.js 中的错误 8:0-24 找不到模块:错误:无法解析“C:\Users\NEHA\Desktop”中的“./App” eact_project\stackoverflow_clon