Angular | 项目配置(angular.json、envrionment、proxy、tailwind)(三)

发布时间 2024-01-04 17:32:43作者: 两块五的菜鸟

1.angular.json 和 package.json 配置部分详解

​ angular.json 是angular 项目的一些默认的配置,包括不限于运行命令、打包配置、unit test 配置

​ package.json 是node 项目的npm 包管理文件,但其中会涉及到一些angualr的默认script命令,包括但不限于start,test,watch,build...

package.json 的 angular 命令

"scripts": {
    "ng": "ng",
    "start": "ng serve",    //运行angular项目
    "build": "ng build",    //打包angular项目
    "watch": "ng build --watch --configuration development", //
    "test": "ng test"       //单元测试ng项目
  }

angular.json 中 常用的配置项

"architect":{
    "build": {...},   // 打包的一些配置,输入、输出目录、打包策略
    "serve": {...},   // angular服务启动命令
    "extract-i18n": {...}, //从源码中提取i18n的消息 (不常用)
    "test": {...}     // 单元测试命令 karma,jasmine自带的单元测试
}

2.environment

"production": {
  "fileReplacements": [
    {
      "replace": "src/environments/environment.ts",
      "with": "src/environments/environment.prod.ts"
    }
  ],
}

​ angular 不同环境的配置是根据环境文件的不同来控制的,上述配置的意思是build:production的时候enviroment.ts 会被environment.prod.ts 替换,从而实现不同环境的配置文件替换。

3.proxy.json

​ 这个文件的作用是代理端口,可以实现后台不容许跨域时,代理接口,规避跨域问题。

// proxy.config.json
{
    "/api": {
        "target": "https://localhost:7237", //可以把http://localhost:4200/api代理成http://localhost:8080/api
        "secure": true, //是否时安全协议下的访问
        "logLevel": "debug", //代理日志级别
        "changeOrigin": true,  //非本地域名,即可以http://localhost:4200/api/users代理到http://test.domain.com/users
        "header": {
            "Origin": ""
        },
        "pathRewirte": {
            "^/api": ""  //如果后端没有/api,rewrite功能就是重写路径
        }
    }
}

​ 这个文件的作用就是把url中的域名进行替换,从而避免跨域。

//可以利用命令行
ng serve --proxy-config=proxy.config.json
// 可以在angular.json 中配置
"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "proxy.conf.json"
    },
  }
}

多个代理入口:

const PROXY_CONFIG = [
    {
        context: [
            "/my",
            "/many",
            "/endpoints",
            "/i",
            "/need",
            "/to",
            "/proxy"
        ],
        target: "http://localhost:3000",
        secure: false
    }
]

module.exports = PROXY_CONFIG;
"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "proxy.conf.js"
    },
  }
}

4.引入 tailwind css (一个国外比较热门的css angular 框架)

4.1 引入依赖

npm install -D tailwindcss postcss autoprefixer

4.2 生成tailwind 配置文件并修改

npx tailwindcss init

module.exports = {
  content: ['./src/**/*.{html,ts}'],
  theme: {
    extend: {},
  },
  plugins: [],
};

4.3 在 styles.css 全局 css 入口处加入

@tailwind base;
@tailwind components;
@tailwind utilities;