将函数注入到Webpack中,如DefinePlugin
问题描述:
我想在加载器和运行时代码之间进行通信。具体而言,我想编写一个加载器,该加载器存储已加载到可在运行时读取的变量中的所有CSS。下面是一些伪代码来说明:将函数注入到Webpack中,如DefinePlugin
myLoader.js
module.exports = function(content) {
// This should store the content accessible to the runtime code
storeCss(content);
return content;
};
app.js
// This should load the CSS as stored by the loader
const css = getStoredCss();
例如与webpack.DefinePlugin
我可以这样做:
new webpack.DefinePlugin({
SOME_GLOBALLY_AVAILABLE_CONST: JSON.stringify('my value'),
}),
现在在我的装载程序和我的运行时代码中,我可以访问SOME_GLOBALLY_AVAILABLE_CONST
并获得'my value'
。是否可以编写一个插件来执行相同的操作,但是实现storeCss
和getStoredCss
,这样我就可以在我的加载程序和运行时代码中访问它们了?
答
new webpack.DefinePlugin({
SOME_GLOBALLY_AVAILABLE_FUNCTION_THAT_PROBABLY_SHOULDNT_BE_ALL_CAPS: require('./myLoader.js').toString(),
}),