Skip to content

Using ESM in Next.js

Next.js/

Although ES modules in Next.js work out of box, there are cases when you might run into an issue.

If you don’t know what ES modules (ESM) are, then here’s a short explanation. It’s a way to include code from other JavaScript files, like npm packages, using the import keyword.

// ES modules
import { moduleFunction } from 'module';

moduleFunction();

export function myFunction() {
  console.log('hello');
}

You should already be familiar with it by writing React components.

Originally though, CommonJS modules were the way to go.

// CommonJS modules
const moduleFunction = require('module');

moduleFunction();

module.exports = function () {
  console.log('hello');
};

But, many modern packages are now using ESM instead of CommonJS modules.

And if you try to import them using require, you end up with the following error:

SyntaxError: Cannot use import statement outside a module

If Next.js already uses ES modules, what’s the problem? Well, the next.config.js file does not support ESM. Also, if you want to run custom npm scripts in your project using node, you will face the same issue.

There’s a fix though. If you want to use ES Modules in your project you have 2 options:

  • Use the .mjs filename extension for your scripts, for example next.config.mjs

  • Or, update your package.json to include "type": "module"

    {
      "name": "nextjs-esm",
      "version": "0.1.0",
      "type": "module",
      // ✂️
    }
    

The former option automatically assumes all .js files in your project use ESM.