报错:ReferenceError: __dirname is not defined in ES module scope

报错: __dirname is not defined in ES module scope

前言

新版 NodeJS 支持通过 ESM 方式导入模块,代码如:

// CommonJS 规范(旧)
const { readFileSync, writeFileSync } = require('fs')
const path = require('path')
// ESModule 规范(新)
import { readFileSync, writeFileSync } from 'fs'
import path from 'path'
// ESModule 规范(最新)
import { readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'

在最新 ESModule 规范中,CommonJS 规范的全局方法和全局变量均无法使用:

require()  // ❌ ESM 规范报错,未定义不能使用
module.exports    // ❌报错,不能使用
exports   // ❌报错,不能使用
__dirname  // ❌报错,不能使用
__filename  // ❌报错,不能使用

报错:ReferenceError: __dirname is not defined in ES module scope

报错原因:现在是 ESM 规范,没有全局变量 __dirname ,在 ESM 规范中需要自己定义变量才能使用。

// 最新 node 核心包的导入写法
import { fileURLToPath } from 'node:url'
import { dirname } from 'node:path'
// 获取 __filename 的 ESM 写法
const __filename = fileURLToPath(import.meta.url)
// 获取 __dirname 的 ESM 写法
const __dirname = dirname(fileURLToPath(import.meta.url))

报错:ReferenceError: require is not defined in ES module scope, you can use import instead

requireESM 规范中未定义,使用 ESM 规范的 import 代替。

// ESModule 规范(新)
import fs from 'fs'
// CommonJS 规范(旧)
const fs = require('fs')

报错:ReferenceError: exports is not defined in ES module scope

exportsESM 规范中未定义,可使用 ESM 规范的 export 导出代替。

// ESModule 规范(新)
export const name = 'Megasu'
export const age = 18
// CommonJS 规范(旧)
exports.name = 'Megasu'
exports.age = 18

报错:ReferenceError: module is not defined in ES module scope

moduleESM 规范中未定义,可使用 ESM 规范的 export default 默认导出代替。

// ESModule 规范(新)
export default {
  name: 'Megasu',
  age: 18
}
// CommonJS 规范(旧)
module.exports = {
  name: 'Megasu',
  age: 18
}
posted @ 2022-08-29 12:34  MegaSu  阅读(6250)  评论(0编辑  收藏  举报