首页 > 解决方案 > Reading webpack's .env files with grunt

问题描述

I'm using grunt-replace to perform some substitutions of variables according to the environment (dev/testing/production). Those variables are set like this:

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

Then I'm replacing the variables with grunt-replace, like this:

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

Since I'm using an .env file configured for the mentioned environments, is it possible to tell grunt-env to load that file and perform the replacements in replacement of grunt-config? I would like to do this in order to avoid having duplicated code for setting those variables in each environment along both webpack and grunt.

Thanks!

标签: javascriptwebpackgruntjs

解决方案


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

const dotenv = require('dotenv');

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

推荐阅读