在 next.config.js 中支持 ESM

bir*_*ird 16 javascript node.js next.js

我正在对 nextjs 项目进行一些优化,并且需要对type: 'module'文件进行优化package.json。但后来得到了错误

错误 [ERR_REQUIRE_ESM]:必须使用 import 加载 ES 模块:不支持 ES 模块的 my_path/next.config.js require()。

看来 next.config.js 还不支持 ESM。这个问题已经在这里讨论过:https://github.com/vercel/next.js/issues/9607,但我还可以找到解决方案。大家有什么帮助吗?

我在用着: node v12.17.0 next 11.1.0

这是我的 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)
Run Code Online (Sandbox Code Playgroud)

我的 package.json 文件

{
  "type": "module"
  ...
}
Run Code Online (Sandbox Code Playgroud)

更新:我优化的是更改从包中调用组件的方式'ant'

形式

import { Row, Col } from 'antd'
Run Code Online (Sandbox Code Playgroud)

import Row from 'antd/es/row'
import Col from 'antd/es/col'
Run Code Online (Sandbox Code Playgroud)

然后导致这个错误

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

从'../grid'导入{行};^^^^^^

语法错误:无法在模块外部使用 import 语句

我通过添加解决了这个问题type: "module"并且文件package.json有问题next.config.js

jul*_*ves 23

从 Next.js 12 开始,配置文件中现在支持 ES 模块,方法是将其重命名为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
})
Run Code Online (Sandbox Code Playgroud)

  • 您只需要选择一个:您可以*将每个文件重命名为`.mjs`*或者*您可以在`package.json`中添加`"type": "module"`。 (4认同)
  • package.json 中包含 next.config.mjs 和 ```type: 'module'``` 会导致错误:来自 /usr 的 ES 模块 /usr/app/.next/server/pages/_document.js 的 require()不支持 /app/node_modules/next/dist/server/require.js。 (3认同)