Skip to content

Instantly share code, notes, and snippets.

@ehbc221
Created October 27, 2022 17:21
Show Gist options
  • Save ehbc221/3604dfbc87e160058569ea5d0c0896d8 to your computer and use it in GitHub Desktop.
Save ehbc221/3604dfbc87e160058569ea5d0c0896d8 to your computer and use it in GitHub Desktop.
Create and publish a npm package

Create and publish a npm package

How to create and configure your own npm repository

Let's take example as our new project name:

  1. Create and open the directory

    mkdir example
    cd example
    
  2. Initialize the npm project

    npm init -y
    
  3. Install typescript:

    npm install typescript
    
  4. We are using typescript, so copy these settings:

    {
       "main": "dist/index.js",
       "types": "dist/index.d.ts",
       "files": [
         "/dist"
       ],
    }
    
  5. Initialize typescript

    npx tsx --init
    
  6. Setup tsconfig.json base options (you can customize it to your needs)

    {
       "compilerOptions": {
       "module": "CommonJS",
       "target": "ES2015",
       "sourceMap": true,
       "outDir": "./dist",
       "moduleResolution": "node",
       "noImplicitAny": true,
       "declaration": true
    },
       "include": ["src/**/*"],
       "exclude": ["node_modules"]
    }
    
  7. Create the source directory and add an index file

    mkdir src
    cd src
    touch index.ts
    
  8. Add whatever files you want and export them

Once you're finished editing your project and are ready to publish:

  1. let's convert our typescript to javascript

    npx tsc
    

It creates the dist folder with all the typescript files converted.

We are now ready to publish our library to npm.

  1. Login to npm

Note: You should first register to npm.com

    npm login
  1. Now we can finally push the library to npm

    npm publish
    

How to test new features of your library before releasing it

Note: You should not commit publish new versions before committing them to npm. Instead, you should create a new folder and use it to test everything before publishing the main package.

  1. Say you edit something into your library, before using it, you should:
    • Re-build your typescript project (example)

      npx tsc
      
    • Create a test project where you could import your library, with the new changes, and add it as dependency

      mkdir example-test
      cd example-test
      npm init -y
      npm install example
      

Now you can import your new features and test them. before publishing a new version of the example.

Note: Don't forget to specify the new version of your project in the package.json file of example.

@ehbc221
Copy link
Author

ehbc221 commented Oct 27, 2022

Hello everyone. Feel free to add new comments or ask anything for more clarifications.

Don't forget to star it ✌️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment