gpt4 book ai didi

angularjs - 是否可以动态导入模块?

转载 作者:行者123 更新时间:2023-12-02 10:50:37 25 4
gpt4 key购买 nike

我有很多 Angular 组件的导入,看起来我可以编写一个函数来简化导入。我只是不知道怎么做,但这应该很简单。

示例导入:

import {DashboardComponent} from './app/components/dashboard/dashboard.component';
angular.module('app.components').component('dashboard', DashboardComponent);

import {HeaderComponent} from './app/components/header/header.component';
angular.module('app.components').component('header', HeaderComponent);

下面的函数演示了我想要实现的目标,但是我缺少两个概念来使其工作:

  1. 如何将变量(名称)放入{}中?
  2. 我可以在像 | 这样的函数中使用 Angular 过滤器吗? ucfirst 在 JS 文件中?
componentImporter('header');

function componentImporter(name)
{
import {name | ucfirst + 'Component'} from './app/components/'+ name + '/' + name +'.component';

angular.module('app.components').component(name, name | ucfirst + 'Component');
}

最后我遇到的错误是:

'import' and 'export' may only appear at the top level

那么这真的可行吗?

最佳答案

So can this actually ever work?

简短回答:

长答案

您看到的错误几乎说明了一切...import不能嵌套在条件、循环或其他表达式中。这是 great article深入探讨该主题的 ES6 模块。该文章中也提到了另一个有趣的说明,即导入是提升的,与函数类似。

How to put a name in the {} and 2) can I use an angular filter in the fuction like | ucfirst in a js file?

摘自文章:

...the structure of ES6 modules is static

导入中使用变量将使其动态化。您使用的括号语法只能编写为执行部分导入(即从给定模块导入命名导出)。如果您使用tree shaking,这真的很简洁,Rauschmayer 博士的另一篇文章。

我个人喜欢将所有导入保留在每个文件的顶部,这样可以很容易地看到该特定模块所依赖的内容。

更新

现在有 dynamic import()方法。一些打包程序,例如 webpack already support原生这个方法。该方法应该用于动态导入模块。请注意,“动态导入”是一个总主题,其中包含一些子主题,包括“代码分割”、“动态模块表达式”以及使用逻辑来确定是否应加载模块及其依赖项。

关于angularjs - 是否可以动态导入模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com