Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support ESM in next.config.js

I'm making some optimation on nextjs project and need to has type: 'module' on thepackage.json file. But then got the error

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: my_path/next.config.js require() of ES modules is not supported.

Seem next.config.js is not support ESM yet. The issue already discussed here: https://github.com/vercel/next.js/issues/9607 but I can find a solution yet. Any help guys?

I'm using: node v12.17.0 next 11.1.0

And here is my next.config.js

import withLess from '@zeit/next-less'

const nextConfig = {
  target: 'serverless',
  productionBrowserSourceMaps: true,
  webpack5: true,
  onDemandEntries: {
    maxInactiveAge: 1000 * 60 * 60,
    pagesBufferLength: 5
  },
  lessLoaderOptions: {
    javascriptEnabled: true
  },
  trailingSlash: false,
}

export default withLess(nextConfig)

My package.json file

{
  "type": "module"
  ...
}

UPDATE: What I optimated is changing the way to call Component from 'ant' package.

Form

import { Row, Col } from 'antd'

To

import Row from 'antd/es/row'
import Col from 'antd/es/col'

then cause this error

my_path/node_modules/antd/es/row/index.js:1

import { Row } from '../grid'; ^^^^^^

SyntaxError: Cannot use import statement outside a module

I fixed this by add type: "module" in package.json and have problem with next.config.js file

like image 334
bird Avatar asked Aug 24 '21 15:08

bird


People also ask

Does Nodejs support ESM?

In May, 2020, Node. js v12. 17.0 made ESM support available to all Node. js applications (without experimental flags).

Does Next JS support ES6?

In addition to ES6 features, Next. js also supports: Async/await (ES2017) Object Rest/Spread Properties (ES2018)

What is ESM file JavaScript?

ECMAScript modules, also known as ESM, is the official standard format to package JavaScript, and fortunately Node. js supports it 🎉.


1 Answers

From Next.js 12, ES modules is now supported in the config file by renaming it to next.config.mjs.

// next.config.mjs
import withLess from '@zeit/next-less'

export default withLess({
    productionBrowserSourceMaps: true,
    onDemandEntries: {
        maxInactiveAge: 1000 * 60 * 60,
        pagesBufferLength: 5
    },
    lessLoaderOptions: {
        javascriptEnabled: true
    },
    trailingSlash: false
})
like image 172
juliomalves Avatar answered Oct 21 '22 14:10

juliomalves