在Ember插件中如何访问config/environment内的ENV配置?
Ember插件中访问config/environment配置的最优方案
首先说明两种常用错误方式失效的原因:
import ENV from '../config/environment'导入的是插件本地dummy测试应用的配置,和实际运行时的宿主应用配置完全无关,部署到生产环境会直接失效。getOwner(this).lookup('config:environment')失效通常是调用时机过早,在实例还未被Ember容器挂载时就执行了查找,此时getOwner(this)会返回undefined。
通用最优方案:依赖注入读取(适用所有容器管理类场景)
这是官方推荐的标准用法,无需额外配置,直接在组件、服务、路由、控制器等被Ember容器管理的类中使用即可:
import { getOwner } from '@ember/application'; // 确保在实例初始化完成后的方法/生命周期钩子中调用 const ENV = getOwner(this).resolveRegistration('config:environment'); // 读取插件专属配置:const pluginConfig = ENV['你的插件包名'];
注意:禁止在类的构造函数、字段初始化语句中直接调用该方法,此时实例还未关联到容器。如果需要初始化阶段读取配置,可以放到
init生命周期钩子中执行。
特殊场景方案:全局注入配置(适用非容器管理的模块)
如果需要在工具函数、普通JS模块等不受Ember容器管理的代码中访问配置,可以在插件构建钩子中把配置注入到全局命名空间:
- 编辑插件根目录的
index.js文件,添加如下配置:
module.exports = { name: require('./package').name, included(app) { this._super.included.apply(this, arguments); const hostEnv = app.project.config(app.env); const pluginConfig = hostEnv[this.name] || {}; this.treeForVendor = () => { const content = `window['${this.name}'] = window['${this.name}'] || {}; window['${this.name}'].config = ${JSON.stringify(pluginConfig)};`; return require('broccoli-stew').writeFile(`${this.name}/runtime-config.js`, content); }; app.import(`vendor/${this.name}/runtime-config.js`, { prepend: true }); } }
- 之后在插件的任意模块中都可以直接读取全局配置:
const pluginConfig = window['你的插件包名'].config;
内容的提问来源于stack exchange,提问作者NullVoxPopuli
相关产品推荐
相关产品推荐

