Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing modules using ES6 syntax and dynamic path [duplicate]

This works:

import app from './../app.js'; 

But this doesn't:

import app from path.join(process.cwd(), 'app'); 

I'm Getting:

SyntaxError: /path/file.js: Unexpected token (5:16) > 5 | import app from path.join(process.cwd(), 'app');     |                 ^ 

It is possible (and/or how) to use "dynamic" paths? (not hardcoding the path or rely in relative paths).

like image 366
Félix Sanz Avatar asked May 20 '15 03:05

Félix Sanz


People also ask

How do I import a module dynamically?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module.

How can I conditionally import an ES6 module?

To conditionally import an ES6 module with JavaScript, we can use the import function. const myModule = await import(moduleName); in an async function to call import with the moduleName string to import the module named moduleName . And then we get the module returned by the promise returned by import with await .

Why do we need to use dynamic imports?

Dynamic module imports play a very important role if you want your code to be fast and more performant. Most of the time, you don't have to load all those heavy and bulky files in one go. It will be super helpful if we can somehow import those files whenever they are required.

What is dynamic import in JavaScript?

Dynamic imports or Code Splitting is the practice of breaking up your JavaScript modules into smaller bundles and loading them dynamically at runtime to improve and increase the performance of your website dramatically.


1 Answers

No, this is not possible. ES6 modules need to be able to statically resolve their dependencies, without executing module code, so that import statements do work reliably. The module specifier must be a string literal.

However, the module loader of your choice should support dynamic loading of modules with variable names. You wouldn't be able to get a bound app identifier in your module scope however (and cannot reexport it), it typically would only be available in a callback or so.

like image 167
Bergi Avatar answered Sep 18 '22 18:09

Bergi