2

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

myLoader.js

module.exports = function(content) {
    // This should store the content accessible to the runtime code
    storeCss(content);
    return content;
};

应用程序.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所以我可以在我的加载器和我的运行时代码中访问它们?

4

2 回答 2

2

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

webpack.config.js

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

应用程序.js

const css = STORED_CSS

于 2019-10-04T18:10:49.613 回答
-1
new webpack.DefinePlugin({
  SOME_GLOBALLY_AVAILABLE_FUNCTION_THAT_PROBABLY_SHOULDNT_BE_ALL_CAPS: require('./myLoader.js').toString(),
}),
于 2017-08-13T17:57:00.430 回答