[英]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:根据我的经验,在这种情况下通常要做的是:
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.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
并且您只需要更改根文件并且您的用户代码仍然可以工作。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.
如果确实存在,该选项可能会很方便。
Install the module-alias package:安装模块别名包:
npm i --save module-alias
Add paths to your package.json
like this:像这样向
package.json
添加路径:
{ "_moduleAliases": { "@lib": "app/lib", "@models": "app/models" } }
In your entry-point file, before any require()
calls:在您的入口点文件中,在任何
require()
调用之前:
require('module-alias/register')
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.