如何在没有路径问题的情况下从外部源/目录中需要JS文件?

发布于 2025-02-02 03:46:00 字数 494 浏览 2 评论 0 原文

我如何在没有路径问题的情况下从其他目录中需要另一个模块?

例如, src/index.js ,具有 require('../其他/main')语句

哦,有错误,因为在 main.js.js < /code> js文件,有些东西要从路径中获取文件,这只是一个路径问题。 (例如 ./ somefile 显然在该其他目录路径时将无法工作),

但是,如果我单独使用CLI,则将其单独使用,请 cd其他 npm start (或 node main.js ),没有路径问题。

我如何需要而无需 cd 进入目录才能使路径起作用?

但是我不明白,我如何很容易地需要一个JS文件,而是从带有包装的另一个目录。

How do I require another module from a different directory without having path issues?

For example,
src/index.js, has a require('../other/main') statement

Oh, there's an error, because in the main.js JS file, there are things like getting files from paths, and it's just a path issue. (e.g. ./SOMEFILE won't work when it's clearly in that other directory path)

But, if I individually on my CLI, to cd other, and npm start (or node main.js), no path issue.

How do I require without having to cd into the directory to make the path work?

But I don't get it, how do I just easily require a JS file but from another directory with a package.json or whatever?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长亭外,古道边 2025-02-09 03:46:00

只需使用 process.chdir(Directory)就没有路径问题。 httpps://nodejs.org/api/process.htmlpprocess.html#processchdml#processchdirdirrectory

您可以使用 child_process.fork 为您的外部JS脚本的新过程(因此运行)。

我们必须使用 process.chdir ,我找不到其他方法。

Just use process.chdir(directory) so you don't have path issues. https://nodejs.org/api/process.html#processchdirdirectory

You can use child_process.fork to make a new process of your external JS script (so it runs).
https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options

We would have to use process.chdir, I cannot find another way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文