知海

ProvidePlugin 插件

webpackjsorg-main插件参考

ProvidePlugin 插件

自动加载模块,而不必在每个地方 importrequire 它们。

js 复制代码
new webpack.ProvidePlugin({
  identifier: "module1",
  // ...
});

或者

js 复制代码
new webpack.ProvidePlugin({
  identifier: ["module1", "property1"],
  // ...
});

默认情况下,模块解析路径是当前文件夹(./**)和 node_modules

也可以指定完整路径:

js 复制代码
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

new webpack.ProvidePlugin({
  identifier: path.resolve(path.join(__dirname, "src/module1")),
  // ...
});

每当模块中遇到 identifier 作为自由变量时,module 会自动加载,并且 identifier 会被加载的 module 的导出(或 property,以支持命名导出)填充。

要导入 ES2015 模块的默认导出,你必须指定模块的 default 属性。

用法:jQuery

要自动加载 jquery,我们可以将它暴露的两个变量都指向对应的 node 模块:

js 复制代码
new webpack.ProvidePlugin({
  $: "jquery",
  jQuery: "jquery",
});

然后在我们的任何源代码中:

js 复制代码
// in a module
$("#item"); // <= works
jQuery("#item"); // <= also works
// $ is automatically set to the exports of module "jquery"

用法:jQuery with Angular 1

Angular 会查找 window.jQuery 以判断 jQuery 是否存在,请参阅源代码

js 复制代码
new webpack.ProvidePlugin({
  "window.jQuery": "jquery",
});

用法:Lodash Map

js 复制代码
new webpack.ProvidePlugin({
  _map: ["lodash", "map"],
});

用法:Vue.js

js 复制代码
new webpack.ProvidePlugin({
  Vue: ["vue/dist/vue.esm.js", "default"],
});

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。