像 Def​​inePlugin 一样将函数注入 Webpack

Inject function into Webpack like the DefinePlugin

我想在加载程序和我的运行时代码之间进行通信。具体来说,我想编写一个加载程序,将所有已加载的 CSS 存储在一个变量中,我可以在运行时读取该变量。下面是一些虚拟代码来说明:

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'。是否可以编写一个插件来做同样的事情但实现 storeCssgetStoredCss 以便我可以在我的加载程序和我的运行时代码中访问它们?

new webpack.DefinePlugin({
  SOME_GLOBALLY_AVAILABLE_FUNCTION_THAT_PROBABLY_SHOULDNT_BE_ALL_CAPS: require('./myLoader.js').toString(),
}),

您现在可以使用新的 DefinePlugin 执行此操作。runtimeValue

webpack.config.js

new webpack.DefinePlugin({
    STORED_CSS: webpack.DefinePlugin.runtimeValue(
        function () { return JSON.stringify(getStoredCss()) }, []
    )
})

app.js

const css = STORED_CSS