ReferenceError: __dirname is not defined in ES module scope

简介: ReferenceError: __dirname is not defined in ES module scope

运行代码

// $ node -v
// v16.14.0
console.log(__dirname);

报错:

ReferenceError: __dirname is not defined in ES module scope

原因

package.json 加了以下配置

{
  "type": "module",
  "engines": {
    "node": ">=14.16"
  }
}

解决

1、方法一

删除文件 package.json 中的配置项:"type": "module"

2、方法二

注意:该方法得到的是运行目录,并不是该文件的所在目录

import path from "path"
const __dirname = path.resolve();
console.log(__dirname);

3、方法三

import { fileURLToPath } from "url";
import path from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
console.log(import.meta.url);
console.log(__filename);
console.log(__dirname);
// 输出如下:
// file:///Users/user/Desktop/demo/src/demo.js
// /Users/user/Desktop/demo/src/demo.js
// /Users/user/Desktop/demo/src

ESM下,不能直接引入json文件了,需要通过文件接口读取解析


import fs from 'fs';


const packageJson = JSON.parse(fs.readFileSync('package.json'));

console.log(packageJson);


参考


https://stackoverflow.com/questions/8817423/why-is-dirname-not-defined-in-node-repl

Node报错 ReferenceError xxxx is not defined

Pure ESM package


相关文章
|
JavaScript
Syntax Error: Error: Cannot find module ‘node-sass‘
Syntax Error: Error: Cannot find module ‘node-sass‘
340 0
|
7月前
|
API iOS开发 MacOS
WAServiceMainContext.js:2 ReferenceError: result is not defined
WAServiceMainContext.js:2 ReferenceError: result is not defined
57 0
|
7月前
vue2项目安装出现Syntax Error: Error: Cannot find module ‘less‘
vue2项目安装出现Syntax Error: Error: Cannot find module ‘less‘
122 0
|
7月前
Angular启动/node_modules/@types/node/index.d.ts (20,1): Invalid ‘reference‘ directive syntax.
Angular启动/node_modules/@types/node/index.d.ts (20,1): Invalid ‘reference‘ directive syntax.
85 2
|
机器学习/深度学习 缓存 JavaScript
vue报错-Error: Cannot find module 'fs/promises'
vue报错-Error: Cannot find module 'fs/promises'
192 1
node Express.js node:internal/modules/cjs/loader:988 throw err; ^ Error: Cannot find module ‘
node Express.js node:internal/modules/cjs/loader:988 throw err; ^ Error: Cannot find module ‘
1129 0
node Express.js node:internal/modules/cjs/loader:988 throw err; ^ Error: Cannot find module ‘
(node)Warning: Accessing non-existent property ‘xxx‘ of module exports inside circular depen
(node)Warning: Accessing non-existent property ‘xxx‘ of module exports inside circular depen
|
资源调度 JavaScript Windows
yarn create vite的时候,报错:SyntaxError: Unexpected token ‘.‘ at Loader.moduleStrategy (internal/modules/
yarn create vite的时候,报错:SyntaxError: Unexpected token ‘.‘ at Loader.moduleStrategy (internal/modules/
684 0
打包报错Error: ‘default‘ is not exported by node_modules/qs/lib/index.js
打包报错Error: ‘default‘ is not exported by node_modules/qs/lib/index.js
281 0

热门文章

最新文章