Webpack ProvidePlugin与外部?

骨架 Webpack

神乐前端

2020-03-23

我正在探索将WebpackBackbone.js结合使用的想法

我遵循了快速入门指南,并对Webpack的工作原理有一个大致的了解,但是我不清楚如何加载依赖库,例如jquery / boneer / underscore。

它们应该从外部加载<script>还是Webpack可以像RequireJS的shim一样处理?

按照的WebPack DOC:垫补模块ProvidePlugin并且externals似乎与此有关(因此是bundle!装载机的地方),但我不能想出什么时候使用。

谢谢

第2768篇《Webpack ProvidePlugin与外部?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
西门 2020.03.23

两者都有:您可以在库中包含一个<script>(即使用CDN中的库)或将它们包含在生成的包中。

如果通过<script>标签加载,则可以使用该externals选项允许写入require(...)模块。

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");

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")."

Example without ProvidePlugin:

// You need to require underscore before you can use it
var _ = require("underscore");
_.size(...);

Example with ProvidePlugin:

plugins: [
  new webpack.ProvidePlugin({
    "_": "underscore"
  }) 
]

// If you use "_", underscore is automatically required
_.size(...)

Summary:

  • Library from CDN: Use <script> tag and externals option
  • Library from filesystem: Include the library in the bundle. (Maybe modify resolve options to find the library)
  • externals: Make global vars available as module
  • ProvidePlugin: Make modules available as free variables inside modules

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android