【问题标题】:How to create a JavaScript Library如何创建 JavaScript 库
【发布时间】:2022-03-16 09:05:58
【问题描述】:
我在 JavaScript 中创建了一些函数。
我发现我在许多项目中重复使用它们。
所以我决定为我的编码创建一个小型 JavaScript 库。
我可以使用 npm 安装的库,如 react、react-dom、jquery:
npm install <my-personal-library>
我搜索了网络。我知道我可以使用npm publish <my-personal-library,但我不知道如何格式化我的库和函数,以便像 npm 包一样使用和安装它们。
另外,我不知道为我的函数和库创建类型定义。
像@types/react
有什么指导吗?
【问题讨论】:
标签:
javascript
npm
package
node-modules
npm-publish
【解决方案2】:
-
要在电脑上安装你的包,你必须在 npm 模块中设置一个 cli 包。
import { Command } from "commander";
import open from "open";
// [] indicates that this is optional
// <> indicates that this is a required value
export const serveCommand = new Command()
.command("serve [filename]")
// when user enters node index.js --help, it sees description
.description("ADd a description")
.option("-p, --port <number>", "port to run server on", "4005")
.option("-v, --version", "show version", version, "")
// first arg will be the arg that passed in command() SO filename
// second arg is all other options
// THIS IS WE TELL WHAT TO DO
.action(async (filename = "main.js", options: { port: string }) => {
try {
// this is where you add logic about what to do when enterd the command
open("http://localhost:4005");
} catch (error: any) {
if (error.code === "EADDRINUSE") {
console.error("Port is in use. Try runnng on a different port ");
} else {
console.log("Issue is :", error.message);
}
process.exit(1);
}
});
-
要让 cli 在你的主文件中运行代码
//whenever anyone runs cli from command line, this file will be executed.
!/usr/bin/env node
import { program } from "commander";
// this is the above command
import { serveCommand } from "./commands/serve";
// you could chain other commands .addCommand(otherCommand)
program.addCommand(serveCommand);
// parse this and run the aprropriate command that you put together
program.parse(process.argv);
-
如您所见,您可能有不同的子包,每个子包都有自己的package.json。要在这些子包之间进行通信,请将它们添加到 package.json 中的依赖项中。例如,您必须在主包中使用 cli 包。所以在 package.json 中
"dependencies": {
"@my-npm-package/cli": "^1.0.15",
// other dependencies
"express": "^4.17.1",
}
-
由于您有不同的子包,因此您必须将它们组合在一起。将这些包分配到一个“组织”中。另一个术语是“创建范围包”。 “@types/cors”和“@types/express”是作用域包。
声明作用域包
使用Lerna 管理所有这些 npm 包。它用于管理多项目包。 - Lerna 是一种我们可以用来管理多包项目的工具。 Yarn 和 Npm 类似于 lerna。还有博尔特和路易吉。