Reputation: 159
I'm having issues using .env
variables to configure my Webpack config.
Let me explain: I want to be able to use a .env
file to configure/setup my Webpack config. In my case, this is setting up a proxy URL for BrowserSync. The idea is to make it simple/easy to change certain (predefined) parts of the wp-config, rather than diving into the wp-config itself.
Example of the .env
file:
APP_NAME=Test Application
PROXY_URL=test-application.test
Webpack config example:
module.exports = {
plugins: [
new BrowserSyncPlugin({
host: 'localhost',
port: 7777,
proxy: PROXY_URL // inserted from .env
})
],
});
I have been fiddling around with webpack.DefinePlugin
and the Dotenv
npm module, but these seem to be unreachable (undefined) inside the actual Webpack config (but works fine inside the application itself, index.js etc.).
So my questions is; is this doable? and what would be the easiest/cleanest way to achieve this?
Upvotes: 0
Views: 1847
Reputation: 46
This is how I solved it using dotenv package.
First parse the .env file:
var dotenv = require('dotenv').config({path: __dirname + '/.env'});
const devURL = dotenv.parsed.BASE_URL;
const devPORT = dotenv.parsed.PORT;
Then you can use it in your config.
devServer: {
host: devURL || '0.0.0.0',
port: devPORT || 9000,
}
Upvotes: 3