【问题标题】:Command in package.json for setup environmentpackage.json 中用于设置环境的命令
【发布时间】:2020-10-07 21:21:02
【问题描述】:

使用 Angular 7,我需要可以在命令行/终端中点击的命令,例如 yarn serve --SERVER_API_URL = 'https://localhost:8000', 但我不需要在我的代码中将硬编码值写入 SERVER_API_URL。

我尝试在 package.json 中编写命令 "serve:dev": "export NODE_ENV=development && yarn run webpack:dev-run" 但我仍然得到的是 localhost 服务器,而不是像 "dev.hello.net" 这样的开发服务器。测试环境和生产环境类似。

export const SERVER_API_URL = process.env.SERVER_API_URL;
"serve:dev": "export NODE_ENV=development && yarn run webpack:dev-run",
 plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: `'${options.env}'`,
                DEBUG_INFO_ENABLED: options.env === 'development',
                SERVER_API_URL: `''`
            }
        }),
        new CleanWebpackPlugin(utils.root('../public/app'), {root: utils.root(), verbose: true}),
        new CopyWebpackPlugin([
            {
                from: './src/assets',
                to: 'assets',
                ignore: ['images/**/*', 'fonts/**/*']
            },
        ]),

【问题讨论】:

    标签: node.js webpack angular7


    【解决方案1】:

    您需要在 webpack.config.js 文件中进行更改以接受 env 值。对于该查找插件部分并进行如下修改。

    webpack.config.js

    plugins: [
                // Define useful constants like TNS_WEBPACK
                new webpack.DefinePlugin({
                    "global.TNS_WEBPACK": "true",
                    // "process": undefined,
                    'process.env': {
                        'buildmode': JSON.stringify(env && env.buildmode ? env.buildmode : "")                   
                        // etc, these are just examples
                    }
                })
    ]
    

    所以在运行您的应用程序时使用以下参数和 ng 命令

    --env.buildmode='Production'
    

    在您的 Angular 应用程序中获取环境变量。

    declare var process: any;
    export class test{
    constructor(){
     console.log('env variables', this.getEnvironmentVars('buildmode'));
    }
    
    private getEnvironmentVars(key: string): string {
        console.log('process', process);
        if (typeof process !== 'undefined' && process && process.env) {
          return process.env[key];
        } else {
          return BuildMode.DEVELOPMENT
        }
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2012-03-24
      相关资源
      最近更新 更多