前端项目中增加全局常量设置
·
2 min read
项目中需要增加一些设置值,有些会影响feat,有些只是单纯的展示,比如站点名称。一种是在TS/JS这种程序代码中,设置一种是非程序文件-配置文件中设定,比如自定义一个file文件,或者常用的package.json。
针对后者,如何优雅去做呢,这里贴出我的一种方案。
具体做法
package.json中增加自定义字段配置项
"chainConfig": { "sdkVersion": "v2.1.0", "subscribeMinSdkVersion": "v2.0.0" }
注意,自定义字段不要以下划线来命名,且避开保留字。
webpack中读取package.json中字段,利用DefinePlugin将字段打包进前端构建项目中
const PACKAGE = require('../package.json'); ... new webpack.DefinePlugin({ 'CHAIN_CONFIG': JSON.stringify(PACKAGE.chainConfig) }), ...
前端项目源码中使用变量形式来操作,同时TS项目下为了类型安全,增加类型定义
... console.log(CHAIN_CONFIG.sdkVersion) ...
// typing.d.ts /** * @description 具体配置值见Package.json */ declare const CHAIN_CONFIG: { sdkVersion: string; subscribeMinSdkVersion: string; };
如上即实现常量配置,但还是有坑,继续看。
webpack.DefinePlugin
Uncaught SyntaxError: Missing } in template expression
针对DefinePlugin中进行变量定义,一开始我的写法如下,但启动执行后即报错。
...
new webpack.DefinePlugin({
'CHAIN_CONFIG': PACKAGE.chainConfig
}),
...
查看文档,发现变量值的解析,规则如下
Each key passed into
DefinePlugin
is an identifier or multiple identifiers joined with.
.
- If the value is a string it will be used as a code fragment.
- If the value isn’t a string, it will be stringified (including functions).
- If the value is an object all keys are defined the same way.
- If you prefix
typeof
to the key, it’s only defined for typeof calls.
因此,对于如上我的配置,值是对象,对象的属性值是字符串,遍历执行后,字符串值都会作为代码块存在,所以语法即报错。
所以这里需要增加JSON.stringify进行序列化,最终使用时就可以当对象来用。
写在最后
done