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

参考