Update docs and sort content

This commit is contained in:
github-actions[bot]
2025-02-08 11:06:40 +00:00
parent 8e8dc71801
commit 8b97554932
145 changed files with 712 additions and 651 deletions

View File

@ -1,6 +1,6 @@
---
title: __dirname is not defined in ES module scope
date: 2024-05-29
date: 2024-05-29T00:00:00.000Z
author: KazooTTT
type: Post
status: Published
@ -18,25 +18,17 @@ link-notionnext: >-
https://kazoottt.notion.site/__dirname-is-not-defined-in-ES-module-scope-543bfc66a416470492be9a93fed191a8
rinId: 14
description: >-
# ES Module 问题__dirname 不定义
在使用
# ES Module 问题__dirname 不定义 在使用
TypeScript创建的ESM文件中遇到__dirname不定义的问题通常是因为使用了module的语法应该改为ESM的写法。两种解决方法分别是改为module的写法和改为ESM的写法。
## 改为module的写法
这种方法中需要把import改为require将后缀从ts改为cts。
但这种方式并不推荐,因为它可能会导致文件相对路径的问题。
## 改为ESM的写法
## 改为module的写法 在这种方法中需要把import改为require将后缀从ts改为cts。
这种方式并不推荐,因为它可能会导致文件相对路径的问题。 ## 改为ESM的写法
可以通过利用import.meta.url和fileURLToPath函数获取当前模块的目录路径来解决__dirname不定义的问题。
```typescript
import { fileURLToPath } from "url"
import path from "path"
// 获取当前模块的目录路径
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
```
这种方法推荐使用,避免了相对路径的问题。
```typescript import { fileURLToPath } from "url" import path from "path" //
获取当前模块的目录路径 const __filename = fileURLToPath(import.meta.url) const __dirname
= path.dirname(__filename) ``` 这种方法推荐使用,避免了相对路径的问题。
toAstro: true
date_created: 2025-01-04T11:44:53+08:00
date_modified: 2025-02-07T11:25:34+08:00
date_created: 2025-01-04T03:44:53.000Z
date_modified: 2025-02-07T03:25:34.000Z
---
# __dirname Is not Defined in ES Module Scope