Add Global Constants to a Frontend Project

· 1 min read · 412 Words · -Views -Comments

Projects often need settings: some feature‑gating, some just for display (e.g., site name). You can hardcode in TS/JS or keep them in config files (e.g., a custom file or package.json). For the latter, here’s a clean approach.

Approach

  1. package.json中增加自定义字段配置项

    "chainConfig": {
       "sdkVersion": "v2.1.0",
       "subscribeMinSdkVersion": "v2.0.0"
     }
    

    Note: avoid leading underscores and reserved keys for custom fields.

  2. webpack中读取package.json中字段,利用DefinePlugin将字段打包进前端构建项目中

    const PACKAGE = require('../package.json');
    
    ...
    new webpack.DefinePlugin({
      'CHAIN_CONFIG': JSON.stringify(PACKAGE.chainConfig)
    }),
    ...
    
  3. Consume in source as a variable; for TS, add a type definition for safety

    ...
    console.log(CHAIN_CONFIG.sdkVersion)
    ...
    
    // typing.d.ts
    /**
     * @description 具体配置值见Package.json
     */
    declare const CHAIN_CONFIG: {
      sdkVersion: string;
      subscribeMinSdkVersion: string;
    };
    

This wires up constants cleanly, but there’s a subtle pitfall — read on.

webpack.DefinePlugin

Uncaught SyntaxError: Missing } in template expression

When first defining a variable with DefinePlugin, I wrote the following — it threw at runtime:

...
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.

Because the value is an object, its string properties are treated as code fragments, causing syntax errors. Wrap the object with JSON.stringify so it’s injected as a stringified literal; you can then use it as an object in code.

Final Thoughts

Keep config in one place (e.g., package.json), inject via DefinePlugin, and type it for TS. Remember to stringify objects when defining constants.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover