简体   繁体   English

如何使用 dotenv (.env) 自动将 NODE_ENV 从开发更改为生产

[英]How to change the NODE_ENV from development to production automatically by using dotenv (.env)

Hello Guys I have a simple question I'm using webpack 4 to build a simple application大家好,我有一个简单的问题,我正在使用 webpack 4 构建一个简单的应用程序

I'm trying to change the NODE_ENV variable automatically by using the dotenv package我正在尝试使用dotenv包自动更改NODE_ENV变量

I use many tricks to do this but nothing works.我使用了很多技巧来做到这一点,但没有任何效果。

please some help thank you...请帮忙谢谢...

this is my all config file please help guys thank you这是我的所有配置文件,请大家帮忙谢谢

webpack.config.js webpack.config.js

"use strict";

// Libraries
const path = require('path')
const webpack = require('webpack')
require('dotenv').config()

// Plugin(s)
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const TerserJSPlugin = require('terser-webpack-plugin')

// Configuration

const isDevMode = process.env.NODE_ENV !== 'production'

module.exports = {
    mode: process.env.NODE_ENV,
    context: path.resolve(__dirname, '../src'),
    entry: {
        app: [
            '../src/resources/assets/js/app.js', 
            '../src/resources/assets/sass/app.scss'
        ]
    },
    output: {
        path: path.resolve(process.cwd(), 'public/dist/.vuxt'),
        filename: 'assets/js/[name].bundle.js',
        chunkFilename: 'assets/js/[id].bundle.js'
    },
    devtool: 'source-map',
    devServer: {
        contentBase: path.resolve(__dirname, '../public'),
        watchContentBase: true,
        compress: true,
        host: process.env.APP_HOST,
        port: process.env.APP_PORT
    },
    resolve: {
        modules: [
          'node_modules',
          path.resolve(__dirname, '../src')
        ],
        extensions: ['.*', 'json', '.js', '.jsx', '.ts', '.tsx', '.css', '.scss'],
        alias: {}
    },
    module: {
        rules: [
          {
            test: [/.js$|.jsx$|.ts$|.tsx$/],
            exclude: /(node_modules|bower_components)/,
            use: {
              loader: 'babel-loader',
              options: {
                cwd: __dirname,
                presets: ['@babel/preset-env', '@babel/typescript']
              }
            }
          },
            {
                test: /\.html$/,
                use: ['ejs-loader', 'extract-loader', 'html-loader']
            },
            {
              test: [/.css$|.scss$/],
              use: [
                {
                  loader: MiniCssExtractPlugin.loader,
                  options: { 
                    hmr: process.env.NODE_ENV === 'development',
                    reloadAll: true
                  }
                },
                {
                    loader: 'css-loader',
                    options: { sourceMap: true }
                },
                {
                  loader: 'postcss-loader',
                  options: { sourceMap: true }
                },
                {
                    loader: 'sass-loader',
                    options: { sourceMap: true }
                }
              ]
            },
            {
                test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
                use: [
                  {
                    loader: 'file-loader',
                    options: {
                      name: '[name].[hash].[ext]',
                      outputPath: 'assets/images/'
                    }
                  }
                ]
            },
            {
              test: /\.((woff2?|svg)(\?v=[0-9]\.[0-9]\.[0-9]))|(woff2?|svg|jpe?g|png|gif|ico)$/,
              use: ['url-loader?limit=10000']
            }
        ]
    },
    optimization: {
      minimizer: [
        new UglifyJsPlugin({
          cache: true,
          parallel: true,
          uglifyOptions: {
            compress: false,
            ecma: 6,
            mangle: true
          },
          sourceMap: true
        }),
        new TerserJSPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {},
            mangle: true,
            module: false,
            output: null,
            toplevel: false,
            nameCache: null,
            ie8: false,
            keep_classnames: undefined,
            keep_fnames: false,
            safari10: false,
          }
        }), 
        new OptimizeCSSAssetsPlugin({
          cssProcessorPluginOptions: {
            preset: ['default', { discardComments: { removeAll: true } }],
          }
        })
      ]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            hash: true,
            inject: true,
            minify: {
              collapseWhitespace: true,
              removeComments: true,
              removeRedundantAttributes: true,
              removeScriptTypeAttributes: true,
              removeStyleLinkTypeAttributes: true,
              useShortDoctype: true
            },
            title: process.env.APP_NAME,
            meta: {
              viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no',
              'theme-color': '#0000'
            },
            favicon: '../src/resources/assets/images/favicon.png',
            template: path.resolve(__dirname, '../src/resources/views/index.html')
        }),
        new MiniCssExtractPlugin({
            filename: isDevMode ? 'assets/css/[name].css' : 'assets/css/[name].[hash].css',
            chunkFilename: isDevMode ? 'assets/css/[id].css' : 'assets/css/[id].[hash].css',
        })
    ]
};

.env .env

NODE_ENV=production

app.js应用程序.js

console.log('You are in ', process.env.NODE_ENV, 'Mode')

package.json包.json

  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node node_modules/webpack/bin/webpack.js --progress --hide-modules --config webpack/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production webpack -p --no-progress --hide-modules --config webpack/webpack.config.js",
    "serve": "npm run start",
    "start": "cross-env NODE_ENV=development node node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --open --config webpack/webpack.config.js"
  }

you can try passing env value via command line while starting the app.您可以尝试在启动应用程序时通过命令行传递 env 值。 example: npm start env=production示例: npm start env=production

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM