使用自定义 CMS 设置构建 Ember CLI



业务问题:对于一系列 Ember 应用程序,允许颜色、徽标、特定内容由 CMS 控制,以支持软件的白/灰标签。

建议的解决方案:将创建一个 Ember CLI 插件,在构建时,该插件拉入适当的样式表规则、徽标 URL 等,并将内容注入适当的树中。

插件的初始实现:

// index.js
/* jshint node: true */
'use strict';
const BroccoliMergeTrees = require('broccoli-merge-trees');
const broccoliSource = require('broccoli-source');
const UnwatchedDir = broccoliSource.UnwatchedDir;
const apiFactory = require('./lib/cms-integration-addon/api.js');
const writeFile = require('write');
module.exports = {
name: 'cms-integration-addon',
cmsIntegrationConfig: {},
isDevelopingAddon() {
return true;
},
included(app) {
const config = app.project.config(app.env)['cms-integration'] || {};
this.cmsIntegrationConfig = config;
},
treeForAddon() {
let tree = this._super.treeForAddon.apply(this, arguments);
const cmsDetailsSource = new UnwatchedDir(this.app.project.root + '/tmp/cms-integration-addon');
tree = new BroccoliMergeTrees([tree, cmsDetailsSource]);
return tree;
},
preBuild() {
const cms = apiFactory(this.cmsIntegrationConfig);
return cms.fetchSettings().then((settings) => {
const configPath = `${this.app.project.root}/tmp/cms-integration-addon/config/my-config.js`;
return writeFile(configPath, `export default ${JSON.stringify(settings)}`);
});
}
};

问题是使用此代码,CMS 中的相应 JSON 对象不会像我预期的那样插入cms-integration-addon模块下的vendor.js中。但是,如果我将treeForAddon更改为treeForApp则设置对象确实会插入到应用程序模块下的app-name.js中。这并不理想,最好将此代码注入到插件的模块下。

为了能够将我的 JSON 对象注入插件的模块,我缺少什么?

虽然我无法确定为什么treeForApp允许注入,但其他treeFor*方法不允许,但我无法确定如何在构建时将代码适当地注入插件。使用上面的示例,需要进行一些更改,并在ember-cli-build.js中添加新的app.import()调用。

  1. 将 JSON 对象的输出路径更改为位于vendor/下,而不是tmp/下。根据 Ember CLI 文档,只有存在于bower_componentsvendor下的文件才能导入到您的应用程序中。

  2. 使用define()将实际文件输出更改为vendor/目录以遵循 AMD 格式。

  3. 将以下行添加到ember-cli-build.js文件中:

    app.import('vendor/cms-integration/config/my-config.js');

此时,您应该看到注入到供应商.js文件中的相应对象,您可以通过调用以下命令来使用它:

import CmsSettings from 'cms-integration/config/my-config';

最新更新