DEV Community

Corey Cleary
Corey Cleary

Posted on • Originally published at coreycleary.me

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

Originally published at coreycleary.me. This is a cross-post from my content blog. I publish new content every week or two, and you can sign up to my newsletter if you'd like to receive my articles directly to your inbox! I also regularly send cheatsheets and other freebies.

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'

Love JavaScript but still getting tripped up by asynchronous code? I publish articles on JavaScript and Node every 1-2 weeks, so if you want to receive all new articles directly to your inbox, here's that link again to subscribe to my newsletter!

Top comments (1)

Collapse
 
nickytonline profile image
Nick Taylor • Edited

John Dalton did some great work on esm. 🔥