0

I tried adding this to the plugins section of my webpack config, but that makes the build unusable. I am not using cra.

new webpack.DefinePlugin({
    'process.env': dotenv.parsed,
})

Changing this to

new webpack.DefinePlugin({
    'APP_URL': dotenv.APP_URL,
})

Didn't help -> APP_URL stayed undefined in the app :(

I did not find another syntax for injecting variables.

1 Answer 1

1

Looks like DefinePlugin just replaces text and does not introduce global variables.

So it needs quotes around the value so the replacement makes a correct JS syntax:

'APP_URL': `"${dotenv.APP_URL}"`,

Here's my webpack.config.js:

const webpack = require('webpack');

const dotenv = { APP_URL: 'http://localhost/app' };

module.exports = [
    {
        entry: './src/test.js',
        mode: 'production',
        plugins: [
            new webpack.DefinePlugin({
                'APP_URL': `"${dotenv.APP_URL}"`,
            })
        ]
    }
]

Don't forget to put quotes around the values or use JSON.stringify

And here's ./src/test.js file:

const url = APP_URL;
console.log(url);

Development build outputs eval statement with the whole code and replacement:

/***/ "./src/test.js":
/*!*********************!*\
  !*** ./src/test.js ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

eval("const url = \"http://localhost/app\";\nconsole.log(url);\n\n//# sourceURL=webpack:///./src/test.js?");

/***/ })

/******/ });

While production build keeps just resulting console.log call:

[function(e,t){console.log("http://localhost/app")}]
Sign up to request clarification or add additional context in comments.

2 Comments

I forgot to use 'JSON.stringify`. It is weird because you need to stringify a string ... :D (Added that in an edit, you can update your answer and I'll accept it :) )
thanks. yep JSON.stringify() would be the safest option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.