npm 如何创建JavaScript库

vmpqdwk3  于 5个月前  发布在  Java
关注(0)|答案(3)|浏览(65)

我用JavaScript创建了一些函数。
我发现我在许多项目中重复使用它们。
所以我决定为我的编码创建一个小的JavaScript库。
我在网上搜索了一下。我知道我可以使用npm publish <my-personal-library,但我不知道如何格式化我的库和函数,让它们像npm包一样使用和安装。
另外,我不知道如何为我的函数和库创建类型定义。比如@types/react。

fnx2tebb

fnx2tebb1#

  • 要在PC上安装你的包,你必须在npm模块中设置一个npm包。
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);
      }
    });

字符串

  • 若要使JavaScript运行代码,请在主文件中
//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中的依赖项中。例如,你必须在你的主包中使用package.json包。所以在package.json中
"dependencies": {
    "@my-npm-package/cli": "^1.0.15",
     // other dependencies
    "express": "^4.17.1",
  }

  • 因为你有不同的子包,你必须把它们组合在一起。将这些包分配到一个“组织”中。另一个术语是“创建作用域包”。“@types/cors”和“@types/express”是作用域包。

声明作用域包

  • 在npm页面,在右边,点击“添加组织”
  • 组织名称应唯一
  • 更新每个包的package.json中依赖项的名称。
  • 管理程序包

使用Lerna来管理所有这些npm包。它用于管理多项目包。- Lerna是一个我们可以用来管理多包项目的工具。Yarn和Npm类似于Lerna。还有Bolt和Luigi。

sr4lhrrt

sr4lhrrt2#

关于如何发布您的库

你可以阅读官方npm文档了解如何创建nodejs包模块:https://docs.npmjs.com/creating-node-js-modules
基本上,你需要的是一个JS模块文件(IE test.js),用exports关键字导出:

exports.printMsg = function() {
  console.log("This is a message from the demo package");
}

字符串
然后使用npm publish发布模块(如果您希望它是公共的,请添加--access public)最后使用npm install <your-module-name>导入项目中需要的包

关于类型定义

我知道你正在使用 typescript ?那么下面的链接是一个很好的阅读:https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html

laawzig2

laawzig23#

我强烈推荐你使用jslib-base来开发JS库(https://github.com/yanhaijing/jslib-base),这是一个非常有用的脚手架,可以简化你的JS库开发过程!

相关问题