Is it possible to import modules dynamically?

I have a lot of import for angular components, and it looks like I can write a function to simplify the import. I just don't know how to do this, but it should be simple.

Import Samples:

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

The function below demonstrates what I want to achieve, however, I lack two concepts to make it work:

  • How to put a variable ( name ) in {} ?
  • Is it possible to use angular filter in functions like | ucfirst | ucfirst in a | ucfirst file?
 componentImporter('header'); function componentImporter(name) { import {name | ucfirst + 'Component'} from './app/components/'+ name + '/' + name +'.component'; angular.module('app.components').component(name, name | ucfirst + 'Component'); } 

Finally, I encountered an error:

'import' and 'export' can only be displayed at the top level

So can this ever work?

+3
angularjs ecmascript-6
source share
1 answer

So can this ever work?

Short answer: No

Long answer

The error you saw to a large extent says that all this ... import cannot be nested inside conditional expressions, loops, or other expressions. Here's a great article on ES6 modules that go deep on this. Another interesting note also mentioned in this article is that imports go up like functions.

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

From the article:

... ES6 module structure is static

Using a variable in import will make it dynamic. The parenthesis syntax you use can only be written for partial import (i.e., Import named export from this module). This is very convenient if you use rubbish shaking , another article by Dr. Rauschmeier.

Personally, I like to store all my import data at the top of each file, which is very easy to understand what this particular module depends on.

Update

Now there is a dynamic import() method. Some bundles such as webpack already support this method natively. This method is intended for dynamic import of modules. Please note that Dynamic Import is a thematic section containing several subtopics, including Code Separation, Module Dynamic Expressions, and the use of logic to determine if a module and its dependencies should be loaded.

+4
source share

All Articles