【问题标题】:How can I pass an npm param to angular.json如何将 npm 参数传递给 angular.json
【发布时间】:2020-11-07 07:32:42
【问题描述】:

我是 Angular 的新手,试图将参数传递给我的 Angular 构建过程。

我想为特定客户端构建我的应用程序,因此我使用 npm 变量来复制客户端设置:

npm run build --client=cocacola

但是,我不知道如何将我的客户名称(例如:cocacola)传递给我的 angular.js

这是我在 package.json

中的脚本
"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "prebuild": "cp src/app/clients/$npm_config_client.settings.ts src/app/app.settings.ts",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

这是我的 angular.json

的一部分
"build": {
  "builder": "@angular-devkit/build-angular:browser",
  "options": {
    "outputPath": "dist",
    "index": "src/index.html",
    "main": "src/main.ts",
    "polyfills": "src/polyfills.ts",
    "tsConfig": "src/tsconfig.app.json",
    "assets": [
      "src/favicon.ico",
      "src/assets",
      {"glob": "**/*", "input" : "src/$npm_config_client/assets", "output": "/assets/"}
    ],
    "styles": [
      "src/styles.scss"
    ],
    "scripts": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/popper.js/dist/umd/popper.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.min.js"
    ]
  },

我试图在options/assets 中使用我的--client 来加载特定的客户端资产。

{"glob": "**/*", "input" : "src/$npm_config_client/assets", "output": "/assets/"}

在 Angular 中可以做到这一点吗?

我还为每个客户端创建了一个 angular.json,但必须有更好的方法。

【问题讨论】:

    标签: angular angular-cli package.json angular-workspace-configuration


    【解决方案1】:

    我建议你实际构建multiple projects,所以:

    angular.json:

    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "version": 1,
      "newProjectRoot": "projects",
      "projects": {
          "main":{
             "architect": {
                "build": {
                   ... standard build configuration
                }
             }
          }
          "cocacola":{
             "architect": {
                "build": {
                   ... add cocacola wherever you need here
                }
             }
    
          }
       }
       "defaultProject": "main"
    }
    

    然后您可以使用 angular 命令的 project 选项打开或关闭此选项,因此:

    package.json:

    "scripts": {
        "build": "ng build",
        "build:cocacola": "ng build cocacola"
    }
    

    npm run build:cocacola 现在将运行 cocacola 项目,npm run build 运行无 cocacola 选项。

    【讨论】:

    • 这太棒了@Liam,非常感谢你:) 但是用你的方法我一次又一次地重复相同的代码,因为项目配置(主要、可口可乐、百事可乐等)几乎相同。唯一改变的是他们的资产(徽标)。
    • 我认为没有更好的方法可以做到这一点@JohnnyJohnny。你可以看看一个 webpack 插件,但这是我知道你可以实现你想要的唯一方法。 Angular 构建有很多很多移动部件,所以可能还有另一种方法,但你必须做一些实验才能弄清楚
    猜你喜欢
    • 2019-03-15
    • 2020-12-02
    • 2016-05-09
    • 2016-07-03
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2021-02-14
    • 2019-01-06
    相关资源
    最近更新 更多