我的应用程序应该从AngularJS迁移到Angular。
我正在创建新的角度组件。是否有一种优雅的方式可以自动导入和降级组件?
当前代码:
import { ColorPickerComponent } from './angular-comp/color-picker/color-picker.component';
import {FileSelectComponent } from './angular-comp/file-select/file-select.component';
export default angular
.module('kn-components', myModuleNames)
.directive('colorPicker', downgradeComponent({component: ColorPickerComponent}))
.directive('fileSelect', downgradeComponent({component: FileSelectComponent}))
.name;
每次我创建一个组件时,我都需要做,这很冗长....
例如,对于我的angularjs组件,我做了以下操作:const myModuleNames = [];
const loadModules = require.context(".", true, /.module.js$/);
loadModules.keys().forEach(function (key) {
if(loadModules(key).default)
myModuleNames.push(loadModules(key).default);
});
然后:
export default angular
.module('kn-components', myModuleNames)
我所有的模块/组件均导入
如果目标是摆脱样板代码,则可以获取要升级的组件列表,获取每个组件的选择名称,并注册相应的指令
-
获取组件的列表。这取决于您的代码结构。最简单的选项是明确返回您需要降级的组件。或者,您可以像示例中一样使用
require.context
。function getComponents() { // depends on how your components are organized // for example, iterate over require.context(".", true, /.component.ts$/); // or return fixed array return [ColorPickerComponent, FileSelectComponent]; }
-
对于每个组件,获取选择器名称。如果您不使用AOT汇编,则可以从
制作选择器@Component
装饰器中获得selector
值。但是,如果您确实使用它,那将不起作用,您可以从组件名称function getComponentSelector(component) { // if you don't need AOT return toCamelCase(component.__annotations__[0].selector); // if you do need it let name: string = component.name; const suffix = 'Component'; if (name.endsWith(suffix)) { name = name.substr(0, name.length - suffix.length); } return uncapitalize(name); } function toCamelCase(selector: string) { const splitted = selector.split('-'); for (let i = 1; i < splitted.length; i++) { splitted[i] = capitalize(splitted[i]); } return splitted.join(''); } function capitalize(name: string) { return name.charAt(0).toUpperCase() + name.slice(1); } function uncapitalize(name: string) { return name.charAt(0).toLowerCase() + name.slice(1); }
-
迭代您的组件并注册降级的组件
downgradeComponents(angular.module('kn-components')); function downgradeComponents(module: ng.IModule) { const components = getComponents(); for (const component of components) { const selector = getComponentSelector(component); module.directive(selector, downgradeComponent({ component })); } }