在准系统 Webpack 项目中导入
request
时,我收到三个警告消息。 GitHub 上提供了重现该错误的最小示例(运行 npm install
和 npm start
)。
Critical dependency: the request of a dependency is an expression
我怎样才能摆脱这个警告?
更多信息:
Webpack 尝试静态解析
require
调用以生成最小包。当库在 require 调用中使用变量或表达式时(例如 require('' + 'nodent')
的 这些行中的 ajv
),Webpack 无法静态解析它们并导入整个包。
我的理由是这种动态导入在生产中是不可取的,并且代码最好保持无警告。这意味着我想要任何能够解决问题的解决方案。例如:
hack.js
文件,以某种方式覆盖 require 调用。ajv-5.0.1-beta.3
有一个修复程序可以消除警告。不过,如果我想使用它,我必须等到它发布,然后等到har-validator
和request
发布后续更新。如果有办法强制 har-validator
使用 ajv
的 beta 版本,那就可以解决我的问题了。延迟加载资源时遇到的问题
const asset = 'config.json';
lazy(async () => await import(asset));
通过显式将导入参数更改为字符串来解决它
const asset = 'config.json';
lazy(async () => await import(`${asset}`));
更换这个
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)@angular/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
有了这个-
new webpack.ContextReplacementPlugin( /(.+)?angular(\\|\/)core(.+)?/, root('./src'), {} )
此警告可以链接到(依赖项或 devDependency)中的包注入。
如果问题突然出现,请检查 package.json 中的最后修改。
如果您打算重新启动
npm install
,请考虑删除 package-lock.json。
我在尝试“过程式”延迟加载时得到了这个,webpack 需要在编译时理解导入语句。
//BAD - webpack can't tell this is constant
const pages = ['privacy-policy', 'terms-of-service']
.map(name =>
lazy(() => import(`./${name}`)))
//OK - webpack can tell this is constant
const names = ['privacy-policy', 'terms-of-service']
const pages = names.map((name, index) =>
lazy(() => import(`./${names[index]}`)))
当我偶然从“量角器”导入 EventEmitter 时,我在 Angular 中得到了这个。我怪我的 IDE 甚至建议它!
它应该从核心导入:
import { EventEmitter } from '@angular/core';
我在使用 typeorm 和 nextjs 时也遇到了同样的警告。 我通过使用here
中的代码来使其静音const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
module.exports = {
...
plugins: [
//ignore the drivers you don't want. This is the complete list of all drivers -- remove the suppressions for drivers you want to use.
new FilterWarningsPlugin({
exclude: [/mongodb/, /mssql/, /mysql/, /mysql2/, /oracledb/, /pg/, /pg-native/, /pg-query-stream/, /react-native-sqlite-storage/, /redis/, /sqlite3/, /sql.js/, /typeorm-aurora-data-api-driver/]
})
]
};
我在上面的排除数组中添加了一个像这样的正则表达式。
/Critical dependency/
我也遇到过同样的问题。首先我放弃了,但现在有以下解决方案。
webpack.config.js
var entries = {
app: [
pathToDefaultAssets+'js/app.js',
pathToDefaultAssets+'scss/index.scss'
],
dev: [
pathToDefaultAssets+'js/dev.js'
],
...
app.js 和 index.scss 是您项目的引导程序。
主要部分:
dev.js
import { a } from './module-one.js';
模块-one.js
var a = function () {
return 'a';
};
export { a }
我是你的app.js,你现在可以使用:
var src = 'one';
document.body.addEventListener('click', function () {
import('./module-'+src+'.js').then(function (module) {
console.log(module.a());
});
});
确实如此!