Categories: Webpack 教程

ProvidePlugin

Automatically load modules instead of having to ​import​ or ​require​ them everywhere.

new webpack.ProvidePlugin({
  identifier: module1,
  // ...
});

or

new webpack.ProvidePlugin({
  identifier: [module1, property1],
  // ...
});

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

还可以指定完整路径:

const path = require(path);

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

每当在模块中遇到标识符作为自由变量时,模块都会自动加载,并将标识符填充为加载的模块的导出(或属性,以支持命名导出)。

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

Usage: jQuery

为了自动加载 ​jquery​ ,我们可以将其公开的两个变量指向相应的​ node​ 模块:

new webpack.ProvidePlugin({
  $: jquery,
  jQuery: jquery,
});

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

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

Usage: jQuery with Angular 1

Angular寻找 ​window.jQuery​ 以确定jQuery是否存在,请参见源代码

new webpack.ProvidePlugin({
  window.jQuery: jquery,
});

Usage: Lodash Map

new webpack.ProvidePlugin({
  _map: [lodash, map],
});

Usage: Vue.js

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

terry

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

6 天 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

2 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

3 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

4 周 ago