我的应用程序应该从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)
所有我的模块/组件都已导入
答案 0 :(得分:2)
如果目标是删除样板代码,则可以获取要升级的组件列表,获取每个组件的选择器名称并注册相应的指令
获取组件列表。这取决于您的代码结构。最简单的选择是仅显式返回需要降级的组件。或者,您可以像在示例中一样使用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编译,则可以从selector
装饰器获取@Component
的值。但是,如果您确实使用它,那将无法正常工作,您可以从组件名称中选择一个选择器
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 }));
}
}