Webpack ProvidePlugin 与外部插件? [英] Webpack ProvidePlugin vs externals?
问题描述
我正在探索将 Webpack 与 Backbone.js.
I'm exploring the idea of using Webpack with Backbone.js.
我已经按照快速入门指南对 Webpack 的工作原理有了大致的了解,但我不清楚如何加载像 jquery/backbone/underscore 这样的依赖库.
I've followed the quick start guide and has a general idea of how Webpack works, but I'm unclear on how to load dependency library like jquery / backbone / underscore.
它们应该使用 外部加载还是 Webpack 可以像 RequireJS 的 shim 那样处理?
Should they be loaded externally with <script>
or is this something Webpack can handle like RequireJS's shim?
根据webpack doc: shimming modules,ProvidePlugin
和 externals
似乎与此有关(bundle!
加载器在某处也是如此),但我不知道何时使用哪个.
According to the webpack doc: shimming modules, ProvidePlugin
and externals
seem to be related to this (so is bundle!
loader somewhere) but I cannot figure out when to use which.
谢谢
推荐答案
这两种可能:您可以使用 <script>
包含库(即使用来自 CDN 的库)或包含将它们放入生成的包中.
It's both possible: You can include libraries with a <script>
(i. e. to use a library from a CDN) or include them into the generated bundle.
如果你通过 标签加载它,你可以使用
externals
选项来允许编写 require(...)
在您的模块中.
If you load it via <script>
tag, you can use the externals
option to allow to write require(...)
in your modules.
CDN 库示例:
<script src="https://code.jquery.com/jquery-git2.min.js"></script>
// the artifial module "jquery" exports the global var "jQuery"
externals: { jquery: "jQuery" }
// inside any module
var $ = require("jquery");
包含在包中的库示例:
copy `jquery-git2.min.js` to your local filesystem
// make "jquery" resolve to your local copy of the library
// i. e. through the resolve.alias option
resolve: { alias: { jquery: "/path/to/jquery-git2.min.js" } }
// inside any module
var $ = require("jquery");
<小时>
ProvidePlugin
可以将模块映射到(自由)变量.所以你可以定义:每次我在模块中使用(免费)变量 xyz
时,你(webpack)应该将 xyz
设置为 require("abc")
."
The ProvidePlugin
can map modules to (free) variables. So you could define: "Every time I use the (free) variable xyz
inside a module you (webpack) should set xyz
to require("abc")
."
没有ProvidePlugin
的例子:
// You need to require underscore before you can use it
var _ = require("underscore");
_.size(...);
ProvidePlugin
示例:
plugins: [
new webpack.ProvidePlugin({
"_": "underscore"
})
]
// If you use "_", underscore is automatically required
_.size(...)
<小时>
总结:
- 来自 CDN 的库:使用
标签和
externals
选项 - 来自文件系统的库:在包中包含库.(也许可以修改
resolve
选项来查找库) externals
:使全局变量可用作模块ProvidePlugin
:使模块可作为模块内的自由变量使用
- Library from CDN: Use
<script>
tag andexternals
option - Library from filesystem: Include the library in the bundle.
(Maybe modify
resolve
options to find the library) externals
: Make global vars available as moduleProvidePlugin
: Make modules available as free variables inside modules
这篇关于Webpack ProvidePlugin 与外部插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!