导出未在 ES 模块范围内定义

exports is not defined in ES module scope

我创建的 nest js 项目如下。

nest new project-name

并从 nuxt3 导入以下内容,它是节点 js 的 module 类型,具有 mjs 文件扩展名(导入的类型定义不需要编写 mjs)。

import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge';

它给我以下错误。

Uncaught Error Error [ERR_REQUIRE_ESM]: require() of ES Module c:\project\node_modules\@nuxt\vite-builder-edge\dist\index.mjs not supported. Instead change the require of c:\project\node_modules\@nuxt\vite-builder-edge\dist\index.mjs to a dynamic import() which is available in all CommonJS modules.

所以我尝试在 package.json 中添加 "type": "module" 所以现在我遇到了以下错误。

Uncaught ReferenceError ReferenceError: exports is not defined in ES module scope This file is being treated as an ES module because it has a '.js' file extension and 'c:\project\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension. at <anonymous> (c:\project\dist\main.js:2:23)

我该如何解决这个问题?错误与打字稿有关(或者说已编译 javascript)无法导入 mjs 导出。有什么解决办法?

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

从您的问题的评论来看,您似乎也在使用 Babel。 “模块”类型和 Babel 不能一起工作。

此外,@Teemu 提到您需要使用 export default {} 语法而不是 module.exports 来导出 ES6 样式。

将 tsconfig“模块”和“目标”更新为“ES6”解决了这个问题。

但在那之后导入停止工作,没有扩展名。

所以我不得不在导入中添加“.js”,即使它们是“.ts”文件。

例如我必须按以下方式导入 app.module.ts 文件(注意扩展名)。

import { AppModule } from './app.module.js';