Webpack:表达模块依赖 [英] Webpack: expressing module dependency
问题描述
我正在尝试在我的 webpacked 应用程序中require
bootstrap-webpack 模块.
I'm trying to require
the bootstrap-webpack module in my webpacked application.
它似乎需要 jQuery,因为捆绑的 javascript 会抛出以下内容:
It appears to need jQuery, since the bundled javascript then throws the following:
未捕获的引用错误:未定义 jQuery
如何向 webpack 指定 jQuery 是 bootstrap-webpack 模块的依赖项,以解决此问题?感觉这应该是微不足道的,但我一直在努力弄清楚.
How do I go about specifying to webpack that jQuery is a dependency for the bootstrap-webpack module, to fix this issue? It feels like it should be trivial, but I've been struggling to figure it out.
我尝试添加:
"jquery": "latest"
到 bootstrap-webpack 的 package.json
中的依赖项,但这不起作用.文档 不完整,我似乎找不到太多关于此问题的信息.它应该是微不足道的,对吧?帮助!
to the dependecies in the bootstrap-webpack's package.json
, but this didn't work. The documentation is incomplete, and I can't seem to find much about this issue. It should be trivial, right? Help!
推荐答案
有两种可能的解决方案:
There are two possible solutions:
使用ProvidePlugin:它扫描给定标识符的源代码,并将其替换为对给定模块的引用,就像需要的那样.
Use the ProvidePlugin: It scans the source code for the given identifier and replaces it with a reference to the given module, just like it has been required.
// webpack.config.js
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
};
使用 imports-loader:它提供了预先准备诸如 require()
语句之类的准备工作.
Use the imports-loader: It provides the possibility to prepend preparations like require()
statements.
// webpack.config.js
{
...
module: {
loaders: [
{ test: require.resolve("jquery"), loader: "imports?jQuery=jquery" }
]
}
}
在这种情况下,您需要先运行 npm installimports-loader --save
.
In that case you need to run npm install imports-loader --save
before.
这篇关于Webpack:表达模块依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!