is it possible to import something into module providing variable name while using ES6 import?
I.e. I want to import some module at a runtime depending on values provided in a config:
import something from './utils/' + variableName;
is it possible to import something into module providing variable name while using ES6 import?
I.e. I want to import some module at a runtime depending on values provided in a config:
import something from './utils/' + variableName;
I would do it like this
Whilst this is not actually a dynamic import (eg in my circumstance, all the files I'm importing below will be imported and bundled by webpack, not selected at runtime), a pattern I've been using which may assist in some circumstances is:
or alternatively:
I don't think I can fall back to a default as easily with
require()
, which throws an error if I try to import a constructed template path that doesn't exist.Good examples and comparisons between require and import can be found here: http://www.2ality.com/2014/09/es6-modules-final.html
Excellent documentation on re-exporting from @iainastacio: http://exploringjs.com/es6/ch_modules.html#sec_all-exporting-styles
I'm interested to hear feedback on this approach :)
There is a new specification which is called a dynamic import for ES modules. Basically, you just call
import('./path/file.js')
and your good to go. The function returns a promise, which resolves with the module if the import was successful.Major use cases include route based module importing for Polymer 3.0, React and Vue, which reduces download bandwidth because the bundles for the routes are only loaded when they're required.
Here's the proposed spec on Github.
Right now (January 2017) this feature is working in Chrome 62. The other major browsers are probably picking up this feature and implementing it down the line when ESmodules are fully supported.
Edit:
I should add that the spec requires imports to be statically analyzable, both the regular import as well as the dynamic import, which means that you can't use a variable name to declare your import path. So there is no solution to your question because the ES spec prevents this by design.
you can use the non-ES6 notation to do that. this is what worked for me:
Not with the
import
statement.import
andexport
are defined in such a way that they are statically analyzable, so they cannot depend on runtime information.You are looking for the loader API (polyfill), but I'm a bit unclear about the status of the specification:
I less like this syntax, but it work:
instead of writing
use this syntax: