How to use `import/export` in Node without Babel

Have you ever found yourself wanting to ditch using require for your Node imports, ditch writing code like this?

const knex = require('knex')
const itemService = require('../services')

If you've been writing any modern client-side JavaScript with React, Vue, etc., you've been importing code like so:

import React from 'react'
import TodoComponent from './components'

It would be so great to be able to write in the same style in Node for your server-side code.

And if you have code that you need to share between client and server, you can easily just use import!

Sure, you can use Babel on the server... but if you're just using it for import/export, it's a big waste and headache to maintain the Babel config.

Plus... you have to still wait for Babel to transpile and that can be kinda slow...

The solution

There is experimental support for ECMAScript modules in newer version of Node using the --experimental-modules flag.

But I've found a more robust and interoperable solution to use is the esm module.

Instructions

First, install the module with npm i esm or yarn add esm (if you're using Yarn).

Then, in "scripts" in package.json, for your start script: node -r esm [.js entrypoint]. If you're using nodemon this can be nodemon -r esm [.js entrypoint]!

And in the test script in package.json, mocha -r esm [rest of your mocha config here]

In case it's not already clear, you just have to add -r esm to your scripts!

And now instead of:

const knex = require('knex')
const itemService = require(../services)

...you can write:

import knex from 'knex'
import itemService from '../services'

Found this post helpful? Understanding how to configure your application for development is one hurdle. Understanding how to structure your application is another. Sign up below to receive a repo with how I structure all my Express REST API's and a post explaining how that structure works / why it's setup that way. You'll also receive all my new posts directly to your inbox!

Subscribe for more Node and JavaScript content!

No spam ever. Unsubscribe any time.