代码之家  ›  专栏  ›  技术社区  ›  IsraGab

降低Angular JS所有角度组件的优雅方法

  •  0
  • IsraGab  · 技术社区  · 7 年前

    我的应用程序应该从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 回复  |  直到 7 年前
        1
  •  2
  •   Random    7 年前

    如果目标是去掉样板代码,则可以获取要升级的组件列表,获取每个组件的选择器名称并注册相应的指令

    1. 获取组件列表。这取决于你的代码结构。最简单的方法是显式返回需要降级的组件。或者你可以用 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];
      }
      
    2. 为每个组件获取选择器名称。如果不使用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);
      }
      
    3. 遍历组件并注册降级的组件

      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 }));
        }
      }