ESM 的当前工作目录问题

问题描述 投票:0回答:1

假设您有一个 Node.js Express 服务器,并且您的结构如下所示:

app.mjs

services
-utils
--test.mjs


website
-js
--web.mjs
--req.mjs
-index.html

web.mjs:

import * as req from '/js/req.mjs';
export const sample = ()=>{/*..*/};
export const sampletwo = ()=>{/*..*/};

index.html:

<script type="module">
  import * as web from '/js/web.mjs';
</script>

这个路径工作正常,因为工作目录来自我们导入 web.mjs 的index.html!但是,当我想在服务器端读取 web.mjs 文件时,我收到错误 Cannot find module '/js/req.mjs' 因为工作目录现在不同了。

测试.mjs:

import * as web from '../../website/js/web.mjs';

有没有办法在ESM中设置当前工作目录?就像你在终端中使用 CD 一样。这样,当我尝试读取 web.mjs 时,它总是会使用文件本身所在的工作目录?

javascript node.js es6-modules
1个回答
0
投票

您的代码使用“/js/”作为路径,该路径是相对于根目录的,而不是您的项目。要获取项目的根路径,请使用:

import { existsSync } from 'fs'
import path from 'path'

export function findPRoot() {
  let currentDir = new URL(import.meta.url).pathname

  while (true) {
    const packageJsonPath = `${currentDir}/package.json`
    if (existsSync(packageJsonPath)) {
      return currentDir
    }

    currentDir = path.dirname(currentDir)

    if (currentDir === '/') {
      return null
    }
  }
}

使用示例:

~/.../src/utils
$ tsx
> const { findPRoot } = await import('./paths.ts')
> findPRoot()
'/home/runner/MyProject'
© www.soinside.com 2019 - 2024. All rights reserved.