javascriptwebpackwebpack-plugin

Inject function into Webpack like the DefinePlugin


I want to communicate between a loader and my runtime code. Specifically I want to write a loader that stores all CSS that has been loaded in a variable that I can read out in my runtime. Here is some dummy code to illustrate:

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();

For instance with the webpack.DefinePlugin I can do this:

new webpack.DefinePlugin({
  SOME_GLOBALLY_AVAILABLE_CONST: JSON.stringify('my value'),
}),

Now in both, my loader and my runtime code I can access SOME_GLOBALLY_AVAILABLE_CONST and get 'my value'. Is it possible to write a plugin that does the same thing but implements storeCss and getStoredCss so I can access them in my loader and my runtime code?


Solution

  • You can do this now with the new DefinePlugin.runtimeValue.

    webpack.config.js

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

    app.js

    const css = STORED_CSS