CC 4.0 许可证
本节内容来自以下链接,并受 CC BY 4.0 许可证保护。
除非另有说明,以下内容可以被认为是基于原始内容进行修改和删除的结果。
ProvidePlugin
自动加载模块,而不是在每个地方都必须 import
或 require
它们。
new rspack.ProvidePlugin({
identifier: 'module1',
// ...
});
或
new rspack.ProvidePlugin({
identifier: ['module1', 'property1'],
// ...
});
默认情况下,模块解析路径是当前文件夹(./**
)和 node_modules
。
也可以指定完整路径
const path = require('path');
new rspack.ProvidePlugin({
identifier: path.resolve(path.join(__dirname, 'src/module1')),
// ...
});
每当在模块中遇到 identifier
作为自由变量时,就会自动加载 module
,并且 identifier
将填充加载的 module
的导出内容(或 property
以支持命名导出)。
要导入 ES2015 模块的默认导出,必须指定模块的默认属性。
选项
- 类型:
Record<string, string | string[]>
示例
在浏览器中使用 process
在浏览器上下文中启用 process
对象支持。
new rspack.ProvidePlugin({
process: [require.resolve('process/browser')],
});
代码片段
console.log(process.version);
将在后台转换为
import process from 'process/browser';
console.log(process.version);
jQuery
要自动加载 jquery
,我们可以将它公开的两个变量都指向相应的节点模块
new rspack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
});
然后在我们的任何源代码中
// in a module
$('#item'); // <= works
jQuery('#item'); // <= also works
// $ is automatically set to the exports of module "jquery"
Lodash Map
new rspack.ProvidePlugin({
_map: ['lodash', 'map'],
});
Vue.js
new rspack.ProvidePlugin({
Vue: ['vue/dist/vue.esm.js', 'default'],
});