简体   繁体   中英

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!

You can read your .env file using dotenv , and then pass it to grunt config.

const dotenv = require('dotenv');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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