简体   繁体   中英

Support ESM in next.config.js

I'm making some optimation on nextjs project and need to has type: 'module' on the package.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

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
})

您是否尝试过“ssr:false”然后动态导入它?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM