构建问题:语法错误:无法在模块外部使用 import 语句

问题描述 投票:0回答:1

信息:

构建命令

yarn run build
发生错误,返回此SyntarError,它指向一个node_modules文件。 我没有更改任何默认设置。

包.json

{
  "name": "controle-financeiro",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "antd": "^5.12.8",
    "next": "14.0.4",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "typescript": "^5"
  }
}

错误(终端):

$ yarn run build
yarn run v1.22.5
$ next build
   ▲ Next.js 14.0.4

 ✓ Creating an optimized production build
 ✓ Compiled successfully
   Skipping validation of types
 ✓ Linting
   Collecting page data  .G:\Dev\controle-financeiro\controle-financeiro\node_modules\rc-util\es\Children\toArray.js:1
import React from 'react';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:77:18)
    at wrapSafe (node:internal/modules/cjs/loader:1288:20)
    at Module._compile (node:internal/modules/cjs/loader:1340:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at mod.require (G:\Dev\controle-financeiro\controle-financeiro\node_modules\next\dist\server\require-hook.js:65:28)
    at require (node:internal/modules/helpers:176:18)
    at 4393 (G:\Dev\controle-financeiro\controle-financeiro\.next\server\pages\controle-financeiro.js:1:848)

> Build error occurred
Error: Failed to collect page data for /controle-financeiro
    at G:\Dev\controle-financeiro\controle-financeiro\node_modules\next\dist\build\utils.js:1220:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

尝试过:

  1. 删除node_modules并运行
    yarn install
    ;
  2. 删除.next文件夹并运行
    yarn build
    ;
  3. 运行
    npm upgrade next
    (最新);
reactjs typescript next.js build syntax-error
1个回答
0
投票

我认为这个问题是下一个 14 及以上版本所独有的。当您尝试使用“导入”在 Node.js 中引入额外代码时,就会发生这种情况。这就像尝试向您的应用程序添加一个新方法,但有时应用程序并不知道您要使用这个新方法。

想象一下你有一个书架,里面有不同的书架。如果您不告诉书架您想要添加新类型的书籍(比方说,通过提及“type='novel'”),它可能无法让您正确放置和访问新书籍。因此,告诉书架您要添加的新书籍类型非常重要!

在您的情况下,类型是模块。因此,将“type”:“module”添加到 package.json 文件并重建。像这样:

{
  "name": "your-package",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    // Your dependencies go here
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.