dotenv-webpack icon indicating copy to clipboard operation
dotenv-webpack copied to clipboard

Can't make dotenv-webpack work when using webpack-merge

Open caedev opened this issue 2 years ago • 5 comments

I'm basically new to webpack and node, and I can't seem to make dotenv-webpack work when using webpack-merge. My webpack config files are in 3 separate files (webpack.common.js, webpack.prod.js, and webpack.dev.js). My dotenv-webpack is defined in webpack.common.js. When I run npm run dev (also attached is a portion of my package.json), and I check the console for my process.env values, it only returns undefined.

webpack.common.js

`const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const Dotenv = require("dotenv-webpack");

module.exports = { entry: { app: "./src/client/index.tsx", }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title: "Production", template: "./public/index.html", favicon: "./public/favicon.ico", }), new Dotenv(), ],`

webpack.dev.js

`const { merge } = require("webpack-merge"); const common = require("./webpack.common.js");

module.exports = merge(common, { mode: "development", devtool: "inline-source-map", devServer: { static: "./dist", port: 3000, open: true, historyApiFallback: true, hot: true, proxy: { "/api": "http://localhost:8080", }, }, }); `

package.json

"scripts": { "build": "webpack --config webpack.prod.js", "start": "npm run build && node src/server/index.js", "client": "webpack serve --config webpack.dev.js", "server": "nodemon src/server/index.ts", "dev": "concurrently \"npm run server\" \"npm run client\"" },

I have tried dotenv-webpack with only a single webpack.config.js file, and it works as expected. Maybe I missed something? Thank you.

caedev avatar Aug 19 '22 20:08 caedev

I have the same issue. If you have the dotenv in the webpack.common.js file (the one shared across configs) it won't work. It does work when you copy it over to the different configs (dev, prod).

0xryowa avatar Dec 22 '22 15:12 0xryowa

@0xryowa can you setup a simplified example repo? I can check it out after that’s done (sorry I’m not familiar with the merge concept)

mrsteele avatar Dec 28 '22 12:12 mrsteele

const common = require("./webpack.common.js"); const { mergeWithCustomize } = require("webpack-merge"); const customMerge = mergeWithCustomize({ customizeArray(a, b, key) { if (key === "plugins") { return [...a.filter((item) => !(item instanceof Dotenv)), ...b]; } }, });

const config = customMerge(common, { ... plugins: [ new Dotenv({ path: path.resolve(__dirname, ".env.development"), }), ], ... });

wpfzuishuai avatar Dec 03 '23 14:12 wpfzuishuai

Same problem here.

artuska avatar May 07 '24 12:05 artuska

Thanks has anyone checked with webpack-merge ? When my constructor resolves you have a built-in webpack plugin.

mrsteele avatar May 07 '24 13:05 mrsteele