简体   繁体   English

是否可以设置节点模块的根目录?

[英]Is it possible to set the root directory of a node module?

If I publish a node module with source files in a src directory, and people would like to import a file in their project, they would need to specify the full path from the module.如果我在src目录中发布一个带有源文件的节点模块,并且人们想在他们的项目中导入一个文件,他们需要指定模块的完整路径。

Example:示例:

Structure:结构:

my-module
--src
----index.js
----something-else.js

package.json : package.json :

{
  "name": "my-module",
  "root": "src/index.js"
}

Implementation:实施:

import myModule from 'my-module';
import somethingElse from 'my-module/src/something-else';

(or using require ) (或使用require

var myModule = require('my-module');
var somethingElse = require('my-module/src/something-else');

Is there any way to set up the package so that it knows src is my sources root, allowing users to require somethingElse with my-module/something-else ?有什么方法可以设置包,使其知道src是我的源根目录,从而允许用户使用my-module/something-else来要求somethingElse吗?

If this isn't possible, would it be a good/bad idea to pull the files out of src on prepublish?如果这是不可能的,在预发布时将文件从src拉出是一个好/坏主意吗?

From my experience, what is typically done in this instance is either:根据我的经验,在这种情况下通常要做的是:

  1. Have a something-else.js file in the root which contains only require('src/something-else');在根目录中有一个something-else.js文件,其中只包含require('src/something-else'); Users can then just require('my-module/something-else');然后用户可以只require('my-module/something-else'); In this case you have a nicer API which means any changes to your directory structure in future wouldn't break your users code.在这种情况下,您有一个更好的 API,这意味着将来对目录结构的任何更改都不会破坏您的用户代码。 ie you might move something-else to my-module/other-sources/something-else and you need only change the root file and your users code will still work.即您可能将something-else移动到my-module/other-sources/something-else并且您只需要更改根文件并且您的用户代码仍然可以工作。
  2. You create a core my-module which requires everything that your module has available and users can then choose which part of the module via myModule.somethingElse您创建一个核心my-module ,它需要您的模块可用的所有内容,然后用户可以通过myModule.somethingElse选择模块的哪个部分

Otherwise, I haven't come across a method to set the sources root explicitly.否则,我还没有遇到明确设置源根的方法。 That option could be handy though if it does exist.如果确实存在,该选项可能会很方便。

Possible solutions可能的解决方案

The Alias别名

  1. Install the module-alias package:安装模块别名包:

     npm i --save module-alias
  2. Add paths to your package.json like this:像这样向package.json添加路径:

     { "_moduleAliases": { "@lib": "app/lib", "@models": "app/models" } }
  3. In your entry-point file, before any require() calls:在您的入口点文件中,在任何require()调用之前:

     require('module-alias/register')
  4. You can now require files like this:你现在可以要求这样的文件:

     const Article = require('@models/article');

Reference :: https://gist.github.com/branneman/8048520参考 :: https://gist.github.com/branneman/8048520

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

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