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