@anxin/web-config
v0.0.26
Published
ax-web-config
Downloads
40
Readme
前端多项目多环境统一配置开发方案
思路
- 统一使用一个NPM包进行管理配置
- 使用yaml作为配置文件
- 写脚本将配置项以环境变量的形式插入到项目中去
- 每个项目只需要修改package.json及打包脚本
- 在CI中添加install @anxin/web-config@latest
文件
包文件路径:
-- an-web-config
---- config
------ config.yml
---- index.js
---- package.json
代码:
// index.js
'use strict'
const yaml = require('js-yaml')
const fs = require('fs')
const path = require('path')
const config = yaml.safeLoad(
fs.readFileSync(path.join(__dirname, './config/config.yml'), 'utf8')
)
const setEnv = (obj) => {
for (let attr in obj) {
process.env[attr] = obj[attr]
}
}
module.exports = () => {
const pack = require(`${path.join(path.resolve(), 'package.json')}`)
let axmEnv
for (let i = 0; i < process.argv.length; i++) {
if (process.argv[i] === '-axm' && i + 1 < process.argv.length) {
axmEnv = process.argv[i + 1]
break
}
}
if (!axmEnv) {
return
}
const { common } = config
const project = config[pack.name]
const env = { ...common[axmEnv], ...project[axmEnv] }
setEnv(env)
}
# config/config.yml
common: # 通用配置项
development: # development环境配置项
VUE_APP_LOGIN_URL: "https://xxx.axhome.com.cn/login.html#/"
NODE_ENV: "development"
OA-Projects: # 示例项目配置项
development: # 示例项目development环境配置项
VUE_APP_TEST: "hello anxin"
// package.json
{
"name": "@anxin/web-config",
"version": "0.0.6",
"description": "ax-web-config",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"ax",
"config"
],
"files": [
"config",
"index.js"
],
"author": "",
"license": "ISC",
"dependencies": {
"fs": "^0.0.1-security",
"js-yaml": "^3.13.1",
"path": "^0.12.7"
}
}
使用示例
在项目中安装@anxin/web-config:
npm install @anxin/web-config@latest
# 或者
yarn add @anxin/web-config@latest
在项目中的vue.config.js或者其他打包脚本中引用配置脚本:
require('an-web-config')()
在package.json中的build script中插入参数axm:
-axm dev表示使用dev环境的配置项,其他同理
"scripts": {
"build-dev": "vue-cli-service build -axm dev",
"build-release": "vue-cli-service build -axm release",
"build-prod": "vue-cli-service build -axm production"
}
在CI配置文件中的npm install 后插入:
- cnpm install @anxin/web-config@latest
完成