Migrating from requirejs to es6 imports

Viewed 1604

I have a javascript app that uses requireJS to load its components. This is simple example of how it works:

require(['eventHandler'], function(eventHandler)) {
    ... // app code that uses the eventHandler in some way
}

It uses several components, but let's simplify it and pretend its only this one.

I have two different "versions" of my miniapp in 2 parts of the bigger web application we develop in my company. In order to improve reusability I came up with the following idea:

I have 2 files of require configuration that define the location of the modules the app needs to run and I can define the set of components it should use for each case.

Standard config:

require.config({
paths : {
    // components
    eventHandler : 'lib/eventHandlers/standardEventHandler',
    ...
});

Especial config:

require.config({
paths : {
    // components
    eventHandler : 'lib/eventHandlers/specialEventHandler',
    ...
});

When I load the app I do the following:

 <script data-main="@standardConfigFile" src="/lib/require/require.js"
        type="text/javascript" charset="UTF-8"></script>

And this is how I can load different components for each configuration. Currently I have 2 different ones but I expect to increase that number soon.

Now we are switching to es6 modules with native import and export and I wonder how can I migrate my current architecture to native js imports and exports and the documentation does not cover this particular problem.

Any ideas?

1 Answers

I found the answer, it's actually really simple. I only need to make an "importer" module.

In my main component I'll do:

import * as components from '@standardComponentsLoader.js';

And then do all the imports in standardComponentsLoader:

import * as eventHandler from '@standardEventHandler.js';

export { eventHandler };
Related