Baterka
Baterka

Reputation: 722

Inline import by ES6 modules in Node.js

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');

Upvotes: 11

Views: 17616

Answers (3)

thomazmz
thomazmz

Reputation: 192

You can achieve what you want using the following syntax:

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

Upvotes: 1

Chris Wade
Chris Wade

Reputation: 113

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.

Upvotes: 4

jakemingolla
jakemingolla

Reputation: 1649

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)

Upvotes: 1

Related Questions