【问题标题】:Reading webpack's .env files with grunt使用 grunt 读取 webpack 的 .env 文件
【发布时间】:2020-03-30 20:59:38
【问题描述】:

我正在使用 grunt-replace 根据环境(开发/测试/生产)执行一些变量替换。这些变量是这样设置的:

config: {
            dev: {
                options: {
                    variables: {
                        base_url: 'localhost'
                    }
                }
            },
            testing: {
                options: {
                    variables: {
                        base_url: 'testing.example.com'
                    }
                }
            },
            prod: {
                options: {
                    variables: {
                        base_url: 'production.example.com'
                    }
                }
            }
        },

然后我用 grunt-replace 替换变量,如下所示:

replace: {
            main: {
                options: {
                    patterns: [
                        {
                            match: 'BASE_URL',
                            replacement: '<%= grunt.config.get("base_url") %>'
                        }
                    ]
                },
                src: 'src/main.js' ,
                dest: 'dist/main.js'
            },
}

由于我正在使用为上述环境配置的.env 文件,是否可以告诉 grunt-env 加载该文件并执行替换以替换 grunt-config?我想这样做是为了避免在 webpack 和 grunt 的每个环境中设置这些变量的重复代码。

谢谢!

【问题讨论】:

    标签: javascript webpack gruntjs


    【解决方案1】:

    您可以使用dotenv 读取您的 .env 文件,然后将其传递给 grunt config。

    const dotenv = require('dotenv');
    
    const envConfig = dotenv.config({ path: '/custom/path/to/.env' }).parsed;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2013-12-10
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 2017-12-08
      相关资源
      最近更新 更多