简体   繁体   English

您如何组织js文件,以便可以在一个npm包中要求它们?

[英]How do you organize js files so that you can require from them within one npm package?

I have a couple of nodejs files I want to group together in one folder, because they fit together logically. 我有几个nodejs文件,我想将它们分组到一个文件夹中,因为它们在逻辑上可以放在一起。

Say they're called a.js, b.js, c.js 假设它们被称为a.js,b.js,c.js

In my app, I have code that imports from these files like: 在我的应用中,我有从这些文件中导入的代码,例如:

require('a') require('b') require('c').

How do I package those files together so that I don't have to change my individual require s? 如何将这些文件打包在一起,这样就不必更改我的个人require Is there an option in package.json file so that I can make those files exportable on a global scale without relying on the directory that contains those files? package.json文件中是否有一个选项,以便我可以使这些文件在全球范围内可导出,而不必依赖包含这些文件的目录?

You could always create a project (package.json) and include the js files and then manually move it to your corresponding's OS NPM global modules path. 您总是可以创建一个项目(package.json)并包含js文件,然后将其手动移动到相应的OS NPM全局模块路径。 For windows this is %AppData%\\Roaming\\npm\\node_modules. 对于Windows,这是%AppData%\\ Roaming \\ npm \\ node_modules。 After than you can confirm using npm list -g that your package is globally installed 之后,您可以使用npm list -g确认您的软件包已全局安装

You could create packages a, b, c separately. 您可以分别创建包a,b,c。 Like this: 像这样:

|Custom checks' packages
|- package a
|-- package.json
|-- index.js // with the code of your a.js
|- package b
|-- package.json
|-- index.js // with the code of your b.js
|-package c
|-- package.json
|-- index.js // with the code of your c.js

On each package.json, you define its entry file by setting the main property, so it could be: 在每个package.json上,您可以通过设置main属性来定义其入口文件,因此它可以是:

{
  "name": "a",
  ... some properties
  "main" : "index.js",
  ... some other properties
}

Then within each package folder, you run in your console: 然后在每个包文件夹中,在控制台中运行:

npm install .

Finally in any local project, you can do 最后,在任何本地项目中,您都可以做

require('a')
require('b')
require('c')

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

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