Iannazzi
Iannazzi

Reputation: 1388

Is it possible to dynamically import modules?

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

Sample imports:

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'm missing two concepts to make it work:

  1. How do I put a variable (name) in the {}?
  2. Can I use an Angular filter in a function like | ucfirst in a JS 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 an error I run into is:

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

So can this actually ever work?

Upvotes: 5

Views: 8063

Answers (1)

Greg Venech
Greg Venech

Reputation: 9040

So can this actually ever work?

Short Answer: No

Long Answer

The error you saw pretty much says it all... imports can't be nested inside conditionals, loops, or other expressions. Here's a great article on ES6 Modules that goes in depth on the subject. Another interesting note, also mentioned in that article, is that imports are hoisted, similar to functions.

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

From the article:

...the structure of ES6 modules is static

Using a variable in the import would make it dynamic. The bracket syntax you're using can only be written to do a partial import (i.e. Importing named exports from the given module). This is really neat if you're using tree shaking, another article by Dr. Rauschmayer.

Personally I like keeping all my imports at the top of each file making it very easy to see what that particular module is dependent on.

Update

There is now the dynamic import() method. Some bundlers like webpack already support this method natively. This method is what should be used for dynamic importing of modules. Note that "Dynamic Imports" is an umbrella topic that contains a few subtopics including "Code Splitting", "Dynamic Module Expressions", as well as using logic to determine whether a module and its dependencies should be loaded.

Upvotes: 4

Related Questions