Skip to main content

如何从代码中访问配置值

🌐 How to access to configuration values from the code

所有的配置文件都会在启动时加载,并可以通过 strapi.config 配置提供程序访问。

🌐 All the configuration files are loaded on startup and can be accessed through the strapi.config configuration provider.

如果 /config/server.ts|js 文件具有以下配置:

🌐 If the /config/server.ts|js file has the following configuration:

module.exports = {
host: '0.0.0.0',
};

那么可以这样访问 server.host 键:

🌐 then the server.host key can be accessed as:

strapi.config.get('server.host', 'defaultValueIfUndefined');

嵌套键可以通过 dot notation访问。

Note

文件名用作访问配置的前缀。

🌐 The filename is used as a prefix to access the configurations.

配置文件可以是 .js.ts.json 文件。

🌐 Configuration files can either be .js, .ts, or .json files.

使用 .js.ts 文件时,可以导出配置:

🌐 When using a .js or .ts file, the configuration can be exported:

  • 作为一个对象:

    module.exports = {
    mySecret: 'someValue',
    };
  • 或者作为返回配置对象的函数(推荐用法)。该函数将可以访问env 工具

    module.exports = ({ env }) => {
    return {
    mySecret: env('MY_SECRET_KEY', 'defaultSecretValue'),
    };
    };