自動載入模組,無需在各處使用 import
或 require
。
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
,我們可以將它公開的兩個變數指向對應的節點模組
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
});
然後在我們的任何原始碼中
// in a module
$('#item'); // <= works
jQuery('#item'); // <= also works
// $ is automatically set to the exports of module "jquery"
Angular 會尋找 window.jQuery
以判斷 jQuery 是否存在,請參閱 原始碼。
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
});
new webpack.ProvidePlugin({
_map: ['lodash', 'map'],
});
new webpack.ProvidePlugin({
Vue: ['vue/dist/vue.esm.js', 'default'],
});