简体   繁体   English

如何在 nodejs 中使用 NODE_PATH 避免 require(..\\..\\src\\test)

[英]How to avoid require(..\..\src\test) using NODE_PATH in nodejs

How can I replace long relative file paths like require(..\\..\\src\\test) with the more convenient notation require(src\\test) ?如何用更方便的表示法require(src\\test)替换像require(..\\..\\src\\test)这样的长相对文件路径?

I try the solution of NODE_PATH in package.json following this article: https://www.coreycleary.me/escaping-relative-path-hell/我在本文之后尝试了 package.json 中NODE_PATH的解决方案: https : NODE_PATH

but when run npm start , I get a 'MODULE_NOT_FOUND' error.但是当运行npm start ,出现“MODULE_NOT_FOUND”错误。

My package.json look like this:我的 package.json 看起来像这样:

"scripts": {
    "start": "NODE_PATH=/src/zip && node index.js"
  },

I work in a windows environment and get the error 'NODE_PATH' is not recognized as an internal or external command, operable program or batch file .我在 Windows 环境中工作并收到错误'NODE_PATH' is not recognized as an internal or external command, operable program or batch file

You can manually replace the path before \\src\\test with /*$__dirname$*/ and then read the JSON file from your node application, and replace /*$__dirname$*/ with the value of the __dirname JavaScript variable.您可以手动将 \\src\\test 之前的路径替换为/*$__dirname$*/ ,然后从您的节点应用程序中读取 JSON 文件,并将/*$__dirname$*/替换为__dirname JavaScript 变量的值。

So do this before creating the server or listening to it.因此,请在创建服务器或收听服务器之前执行此操作。

const fs = require('fs');
const jsonFilePath = '<path>';

// Read the json file
let json = fs.readFileSync(jsonFilePath, 'utf-8');

if(json.includes('/*$__dirname$*/')) {
    // Replace /*$__dirname$*/ with the variable __dirname's value
    json = json.replace('/*$__dirname$*/', __dirname);
    
    // Change the JSON file text
    fs.writeFile('jsonFilePath', json, (err) => {
        if(err) { console.log(err); }
    });
};

There is a solution to this without changing any process.env variables.有一个解决方案,无需更改任何process.env变量。

You can use the package.json exports field.您可以使用package.json exports字段。 More information about this is on the node.js docs .有关这方面的更多信息,请参见 node.js 文档 The exports field can be used to define exported files and directories. exports字段可用于定义导出的文件和目录。 For example, if your package name is my-package and you want to make the /deep/deeper/src/ folder available as just my-package/src , you can use the exports field.例如,如果您的包名称是my-package并且您想让/deep/deeper/src/文件夹仅作为my-package/src可用,则可以使用exports字段。

Example:例子:

Files:文件:

deep/
    deeper/
        src/
            test.js
            more.js
package.json
index.js

package.json content: package.json内容:

{
    "name": "my-module"
    "exports": {
        ".": "./index.js"
        "./src/": "./deep/deeper/src"
    }
}

Note: The / after ./src tells node that it's for everything in /src/ , not just a file named /src .注意: ./src之后的/告诉节点它用于/src/所有内容,而不仅仅是名为/src的文件。

index.js content: index.js内容:

//Self referencing the module is allowed if you use --experimental-modules flag.
require("my-package/src/test");

//This is the 'hell' that you would be avoiding.
require("./deep/deeper/src/test");

I like this solution because you can specify many different paths and files just by changing package.json .我喜欢这个解决方案,因为您可以通过更改package.json来指定许多不同的路径和文件。 The files in the module can refer their own package which this section of the docs explains.模块中的文件可以引用他们自己的包, 这部分文档解释了这一点

Note: Depending on the version of node you are using, you might need to use the --exerimental-modules flag.注意:根据您使用的节点版本,您可能需要使用--exerimental-modules标志。 For example:例如:

node --experimental-modules index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM