vuejs-templates / webpack

A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction.
MIT License
9.7k stars 4.38k forks source link

Can I add .env file to my project ? #1410

Open lefuturiste opened 6 years ago

lefuturiste commented 6 years ago

Hi!

I want to add a .env file because I have to store variables depend on the environment, but I can't use config/dev.env.js because my var depend on the developer environment. How I can do that? I want to use https://github.com/mrsteele/dotenv-webpack in my project based on webpack template, I know I have to add the plugin somewhere but where ? And the webpack.DefinePlugin overwrite process.env

Thanks.

DarwinniwraD commented 6 years ago

you can add the dotenv-webpack plugins in the webpack.base.conf.js, like this: first, you may need to import the package:

const Dotenv = require('dotenv-webpack');

then, config the path for it:

 module: {
   ...
 },
 node: {
   ...
 },
 plugins:[
    new Dotenv({
      // set the path for the dot-env, more config information you can visit the official documents 
      path: path.resolve(__dirname, `../.env.${process.env.NODE_ENV}`),
    })
  ],

next, you need to disable the

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

in webpack.prod.conf.js, it would overwrite the dot-env.

One more step, you need to add the basic environmental flag for the build file, because the process.env.NODE_ENV have been set in the build.js file, so you don't need to set it for the production stage, but you need to add the NODE_ENV flag for the development stage in the package.json file, like this:

...
"scripts": {
"dev": "NODE_ENV=development webpack-dev-server  --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
...
}
...
lefuturiste commented 6 years ago

ok, but I have to disable also the DefinePlugin in webpack.dev.conf.js ?

DarwinniwraD commented 6 years ago

@lefuturiste yes, sorry for missed it, and you'll got the same situation at the webpack.test.conf.js file.

fritx commented 6 years ago

@lefuturiste I was using dotenv-cli, hope that helps with you:

npm i -D dotenv-cli
   "scripts": {
-    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
+    "dev": "dotenv webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
-    "build": "node build/build.js"
+    "build": "dotenv node build/build.js"
   },
ctf0 commented 5 years ago

@DarwinniwraD why not simply use https://www.npmjs.com/package/dotenv-webpack ?