ProvidePlugin

自動載入模組,無需在各處使用 importrequire

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

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

預設情況下,模組解析路徑為目前資料夾 (./**)node_modules

也可以指定完整路徑

const path = require('path');

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

每當在模組中遇到 identifier 作為自由變數時,module 會自動載入,而 identifier 會填入載入的 module 的 exports (或 property 以支援命名 exports)。

要匯入 ES2015 模組的預設 export,您必須指定模組的預設屬性。

用法:jQuery

要自動載入 jquery,我們可以將它公開的兩個變數指向對應的節點模組

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

然後在我們的任何原始碼中

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

用法:jQuery 搭配 Angular 1

Angular 會尋找 window.jQuery 以判斷 jQuery 是否存在,請參閱 原始碼

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

用法:Lodash Map

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

用法:Vue.js

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

5 貢獻者

sokrasimon04re-fortbyzykseckin92