11

In an "old way" of managing modules in Node.JS (CommonJS modules) you can do something like this:

Example of Express.js route: app.use('/user', require("./user"));

How to do this when I am using ES6 Modules (import, export) and transcribing by Node.JS server by babel?

I can't just do: app.use('/user', import {user} from './user');

7
  • 2
    Do the import as a separate statement and then app.use("/user", user); Commented Mar 18, 2019 at 13:49
  • Sure it is option but then its loosing point of my question becase same way I can require module into variable and then do app.use('/user', user); Commented Mar 18, 2019 at 13:57
  • 1
    Well import and export have to be done at the outer lexical level, so you really cannot do what you're asking. Commented Mar 18, 2019 at 14:00
  • What import("./user") do? Commented Mar 18, 2019 at 14:02
  • 1
    @Baterka That is a) a proposal only, not standard syntax b) returns a promise Commented Mar 18, 2019 at 14:13

3 Answers 3

4

There is a way to do dynamic inline imports in node, detailed here: https://javascript.info/modules-dynamic-imports

This code has worked for me:

let {default: foo} = await import('./foo.js'); 

Here is a working example of a function I wrote as part of a db migration tool in node.

const getMigrations = async (path) => { const migrateDir = await fs.readdirSync(path); const migrations = await Promise.all(migrateDir.map(async (filename) => { let {default: migration} = await import(`${path}/${filename}`); return migration; })); migrations.sort((a, b) => { return a.seq - b.seq; }); return migrations; }; 

Where an example migration is like:

export default { seq: 1.1, label: 'create user table', sql: ` DROP TABLE IF EXISTS user; CREATE TABLE user ( ... ); ` }; 

I am using node v12.18.4 with "type": "module" in my package.json. When I run the script, I get a warning that the ESM module loader is experimental, but it works. However, there is a note on the page linked to above that says:

Dynamic imports work in regular scripts, they don’t require script type="module".

I hope this helps. I believe you should be able to apply this to your problem.

Sign up to request clarification or add additional context in comments.

Comments

1

Try separating it out into multiple expressions - import (as well as export) are not available at the same lexical level as you are trying to use it the example:

import { user } from './user' ... app.use('/user', user) 

1 Comment

If its reallz not possible to do it like in old modules I consider this as right answer
1

You can achieve what you want using the following syntax:

app.use('/user', (await import('./user')).user) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.