自动加载模块,无需在任何地方使用 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
的导出(或 property
以支持命名导出)。
为了导入 ES2015 模块的默认导出,必须指定模块的默认属性。
为了自动加载 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"
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'],
});