ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-08-29 13:04:15  阅读:206  来源: 互联网

标签:__ defined 规范 module 报错 ESM dirname


报错: __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 规范中,CommonJS 规范的全局方法和全局变量均无法使用:

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

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

报错原因就是现在是 ESM 规范,而 __dirnameCommonJS 规范的全局变量,ESM 规范中需要自己定义变量才能使用。

// 获取 __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

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

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

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

exports 在 ESM 规范中未定义,可使用 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

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

// ESModule 规范(新)
export default {
  name: 'Megasu',
  age: 18
}
// CommonJS 规范(旧)
module.exports = {
  name: 'Megasu',
  age: 18
}

标签:__,defined,规范,module,报错,ESM,dirname
来源: https://www.cnblogs.com/Megasu/p/16635566.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有