🏠 首页 › 日志 › 正文 nodejs: type module 相关/ESM 问题汇总 关于 type module 遇到的问题汇总 🕐 2024-02-24 12:10:09 cheatsheet问题解决方案__dirname is not defined in ES module scope// 方案1 import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // 方案2(个人推荐) import { URL } from 'url'; const __filename = new URL('', import.meta.url).pathname; const __dirname = new URL('.', import.meta.url).pathname;package.json 获取import { createRequire } from 'module'; // 当前文件在 bin/index.js 里 const __dirname = new URL('../', import.meta.url).pathname; const require = createRequire(__dirname); const pkg = require('./package.json'); $ tree -I node_modules . ├── README.md ├── bin │ └── index.js(😎it's me) ├── package.json ├── pnpm-lock.yaml └── rif.config.yaml参考https://flaviocopes.com/fix-dirname-not-defined-es-module-scope/https://www.stefanjudis.com/snippets/how-to-import-json-files-in-es-modules-node-js/https://byby.dev/node-dirname-not-definedhttps://the-guild.dev/blog/support-nodejs-esm