Home

How To Use import Syntax in NodeJS and the Browser

Import vs require in NodeJS and the Browser. We’ve all been there…

The Problem

You want to write a multi file JavaScript project that works both in NodeJS and the browser without needing a build step.

You tried using require and your browser slapped you in the face:

Uncaught ReferenceError: require is not defined
What a slap!

Then you tried import. You wrote two simple files:

businessLogic.js
export function businessLogic() {
  console.log('Woa! This is some complex business logic');
}
main.js
import { businessLogic } from './business-logic.js';

businessLogic();

You ran it in NodeJS and BAM! You get another slap with the errors:

$ npm start

SyntaxError: Unexpected token import

or

$ npm start

SyntaxError: Cannot use import statement outside a module

The Solution

Edit your package.json to use the --experimental-modules flag and "type": "module':

package.json
{
  "type": "module",  "name": "import-nodejs",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "start": "node \"--experimental-modules\" main.js"  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Now, Node will not slap you anymore :

$ npm start

Woa! This is some complex business logic

For the browser, just add type="module" in your script tag:

index.html
<script type="module" src="./main.js"></script>

And no more slapping by the browser either:

No more SyntaxError: Unexpected token import
No more slaps!

Notes

  1. As of NodeJS 13 you don’t need the --experimental-modules flag anymore.
  2. Consider using Babel and Webpack if you are worried about browser support.

The demo code is available on github.