How to create a JavaScript Library
Asked Answered
T

3

6

I've created some functions in JavaScript.

I've found out that I reuse them in many projects.

So I decided to create a small JavaScript Library for my coding. A Library like react, react-dom, jquery which I can install with npm: npm install <my-personal-library>

I searched the net. I learned that I can use npm publish <my-personal-library, but I do not know how to format my library and functions to use and install them like an npm package.

Also, I have no idea about creating type definitions for my functions and library. like @types/react Any guidence?

Toplevel answered 2/5, 2021 at 8:30 Comment(1)
docs.npmjs.com/packages-and-modules/…Garratt
F
1
  • To install your package in a pc you have to set up a cli package inside npm module.

      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);
          }
        });
    
  • To make cli run the code, in your main file

    //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);
    
  • as you see you might have different sub packages and each sub packages will have their own package.json. To communicate between those sub packages, you add them in their dependencies inside package.json. for example, you have to use cli package inside your main package. so in package.json

     "dependencies": {
        "@my-npm-package/cli": "^1.0.15",
         // other dependencies
        "express": "^4.17.1",
      }
    
  • Since you have different sub packages and you have to group them together. Assgin those pacakges into an "organization". another term is to "create scoped package". "@types/cors" and "@types/express" are scoped packages.

Declaring Scoped Packages

  • in npm page, on the right, cick on "Add organization"

  • organization name should be unique

  • update name of the dependencies in package.json of each package.

  • Manage packages

Use Lerna to manage all of those npm packages. it is for managing multi project packages. - Lerna is one tool out there in the wild that we can use for managing a multi package project. Yarn and Npm are similar to lerna. there are also Bolt and Luigi.

Foreclosure answered 16/3, 2022 at 1:0 Comment(0)
P
0

About how to publish your library

You can read the official npm documentation on how to create nodejs package modules: https://docs.npmjs.com/creating-node-js-modules

Basically, what you need is a JS module file (IE test.js) to be exported with exports keyword like:

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

Then publish the module with npm publish (add --access public if you want it to be public) Finally import the package in the project you need it with npm install <your-module-name>

About the type definitions

I understand that you are using typescript? Then the following link is a good read: https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html

Palliative answered 2/5, 2021 at 9:3 Comment(0)
K
0

I'd highly recommend checking out 'jslib-base' for developing JS libraries (https://github.com/yanhaijing/jslib-base). It’s a useful scaffold to simplify your JS library development process!

Kauffmann answered 27/11, 2023 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.