javascript - 在 next.config.js 中支持 ESM

标签 javascript node.js next.js

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

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


似乎 next.config.js 还不支持 ESM。
这里已经讨论过的问题:https://github.com/vercel/next.js/issues/9607但我还可以找到解决方案。
有什么帮助吗?
我在用着:node v12.17.0next 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)
我的 package.json 文件
{
  "type": "module"
  ...
}
更新:
我优化的是改变从 'ant' 调用组件的方式包裹。
形式
import { Row, Col } from 'antd'
import Row from 'antd/es/row'
import Col from 'antd/es/col'
然后导致此错误

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

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

SyntaxError: Cannot use import statement outside a module


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

最佳答案

从 Next.js 12 开始,config file 现在支持 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
})

关于javascript - 在 next.config.js 中支持 ESM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68909624/

相关文章:

javascript - 如何将查询url中的值插入 Node js中的mysql表?

node.js - 错误:property 'token' does not exist on type' () => any'

javascript - 使用nodejs中的集群在两个不同的worker中运行两个任务

Javascript 异步调用链接

github - next js 应用程序目录 github 操作 CI/CD 路径

javascript - dropDatabase 后不强制执行唯一字段约束

java - Jenkins 在 npm install 上的构建失败

javascript - 在javascript中转换日期

reactjs - Next.js 页面转换上的加载屏幕

import - 我如何在 Next.js 中使用我的 jquery 插件?