Search code examples
javascriptwebpackwebpack-2

using definePlugin to pass constants to dependent packages


I have three projects configured this way:

  1. Main app
    1. Module A
    2. Module B

On my main app, I'm using DefinePlugin to pass my dependent modules an API URL, like this:

//webpack-1
loaders:[{
    test:/\.jsx?$/,
    exclude: /(node_modules)/,
    loader: "babel",
    query: {
        presets:["es2015","stage-2","react"]
    }
}],
plugins:[new webpack.DefinePlugin({"API_URL":"http://www.google.com"})]

Then, within my modules A & B, I could use this constant like this

axios.get(`${API_URL}/getProducts`).then(response=>console.log(response));

I've migrated to webpack v2 so my code config file changes to:

//webpack-2
rules:[{
    test:/\.jsx?$/,
    exclude: /(node_modules)/,
    loader: "babel",
    options: {
        presets:["es2015","stage-2","react"]
    }
}],
plugins:[new webpack.DefinePlugin({"API_URL":"http://www.google.com"})]

but when I try to use API_URL on my dependent modules I get the following error:

ReferenceError:API_URL is not defined

What am I doing wrong? What else do I need to configure?


Solution

  • The main webpack config needs to be configured like this:

        plugins: [
        new webpack.DefinePlugin({
            API_URL:"http://www.google.com"
            PRODUCTION: JSON.stringify(true),
            VERSION: JSON.stringify("5fa3b9"),
            BROWSER_SUPPORTS_HTML5: true,
            TWO: "1+1"
        })]
    

    Then, on your dependent package, you can do so:

    console.log('%c DEPENDENT APP! ', 'background: #222; color: #bada55');
    console.info("Production:", PRODUCTION);
    console.info("Version:", VERSION);
    console.info("HTML5 support:", BROWSER_SUPPORTS_HTML5);
    console.info("Two:", TWO);
    

    I've made a github repo with a proof of concept demonstrating how to implement it.