webpack报错处理:The extension in the request is mandatory for it to be fully specified.

发布时间 2023-05-26 17:56:35作者: Malign
完整的报错提示如下:

BREAKING CHANGE: The request './module2' 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.

复盘:

错误发生在我使用webpack提供的node接口webpack()方法调用打包时。报错的直接原因是导入模块时没有填写完整的模块后缀,不过webpack本身就支持这种写法,只要你在配置文件中配置resolve.extensions属性指定匹配的后缀即可,我这里实际上配置了但是报错还是发生了。根本原因是我当前的package.json(或离当前文件最近的package.json配置文件)内配置了type='module'属性来支持ecma的导入,如下图所示:

但是这跟webpack打包有什么关系呢,webpack文档是这样说的:

 意思是如果如果启用了该属性,js文件中使用ecma规范导入文件时应该写后缀,看样子webpack默认开启了该属性。

解决方法;

如文档所示,对所有js文件应用,将该属性改为false。点击前往文档

{
        test: /\.m?js$/,
        resolve: {
          fullySpecified: false, // disable the behaviour
        },
}