Writing in the front

Why learn to build NPM private libraries

A:

  • npmPrivate library is only for the company’s internal LAN open, not external public, with a certain confidentiality
  • The velocity ratio is directly innpmDownload faster, even faster than taobao source. Because it’s on the company Intranet
  • For publishing and downloadingnpmConfigure permission management for packages
  • Private libraries can cache package resources and respond faster to downloads
  • Building the NPM private library was a technical highlight for the team

verdaccio

Verdaccio is a lightweight private NPM Proxy registry created by Nodejs, froked at [email protected], which is an open source NPM private library building tool. You can build a set of NPM repositories of your own company.

  • withYarn, NPM and PNMP100% compatible with
  • To provide theDockerandKubernetesSupport, easy to install and use
  • Published packages are private and configured for access
  • verdaccioYes, all related items need to be cached, and installation can be accelerated on local or private networks

Set up process

X YARN >v1.x PNPM >v2.x. The Web application supports Chrome, Firefox, Edge, and Internet Explorer 11Copy the code

Install verdaccio

// Enter in CMD
npm install -g verdaccio  / / NPM download

yarn global add verdaccio  // YARN Download If Verdaccio does not work, change to NPM download

If permission error is reported, select CMD < Run as administrator > and enter it again
// Or enter the following command in CMD:
npm install -g verdaccio --unsafe-perm  
//--unsafe-perm is added to prevent gyp ERR! Permission denied Permission problem

// After the download is complete, there will be a red font indicating that the environment does not have Python.

// Enter verdaccio in CMD: verdaccio
Copy the code

Configuration information

Yaml file configuration information

This is the default configuration file. It will allow us to do just about anything, # so don't use it in production.//github.com/verdaccio/verdaccio/tree/master/conf# # Contains the directory path of all packages, the directory where the NPM private server packages are stored and the cache addressstorage/storage # Contains the directory path to plugins, the default plugin file location, which is generally only relevant for Docker deploymentplugins: ./plugins

webVerdaccio interfacetitle: Verdaccio # comment out to disable gravatar supportfalse
  # by defaultPackages are ordercer ascendant (asc | desc) two packages is prepared by default option # sort_packages: Asc # convert your UI to the Dark Side # darkMode:trueTake a look at your registry, the I18N API does not yet use # i18n: # listofThe available Translations See the address for a list of registrations available: HTTPS://github.com/verdaccio/ui/tree/master/i18n/translations
#   web: en-US

auth# Maximum amount: : htpasswd: file:./htpasswdof users allowed to register, defaults to "+inf"The maximum number of users allowed to register can be infinite # You can setthis to -1To disable registration. You can set -1To disallow users from registering # max_users via NPM adduser:1000The default maximum number of registered users is1000

# a list ofOther Known Repositories we can talk touplinksIf the requested library does not exist, you can go to the upstream server to obtain it. You can configure the upstream link linknpmjs:
    url: https://registry.npmjs.org/Agent_options: # Configuration item for the agentkeepAlive: true 
      maxSockets: 40
      maxFreeSockets: 10

packages: # configure the module,access to download permission, pushlish package publishing permission'@ * / *'Scoped packages is used to configure privilege managementaccess: $all # indicates which type of user can install and view package information for matching projectspublish$authenticated # specifies which type of user can publish matching projects.unpublish$authenticated # specifies which type of user can publish matching projects.proxyUplinks: NPMJS # This value corresponds to the name of the uplinks, allowing the corresponding uplinks to pull if they do not exist'* *': # allow all users (including non-authenticated users) to read and # publish all # You can specify usernames/groupnames (depending on your auth plugin) You can specify the username/organization name (depending on the plug-in that authenticates you) # and three keywords:"$all"."$anonymous"."$authenticated"Three keywords: all, anonymous, and authenticated can also be used with a specific user name or organization name (a private company name) associated with the configured user table htPASSwdaccess: $all # Allow all known users to publish/publish packages # (anyone can register bydefault, remember?) Anyone can register by defaultpublish: $authenticated
    unpublish: $authenticated

    # if package is not available locally, proxy requests to 'npmjs'If the package is not allowed to be used locally, you can request a proxy for the NPMJS registry using proxyproxy: npmjs

# You can specify HTTP/1.1 server keep alive timeout in seconds forIncoming connections. Incoming HTTP/ for a specified connection1.1The server remains active until time out, in seconds # A valueof 0 makes the http server behave similarly to Node.js versions prior to 8.0. 0, which did not have a keep-alive timeout. A value of0When service performance behavior and8.0. 0The previous version of NodeJS did not remain active when linking, causing a timeout. Through given configuration you can workaround following issues with the known configuration: HTTPS://github.com/verdaccio/verdaccio/issues/301. Set to 0 in case 60 is not enough. If 60 is not enough, you can set it to 0
server:
  keepAliveTimeout: 60 

middlewares:
  audit:
    enabled: true# log Settings Setting loglogs:
  - { type: stdout, format: pretty, level: http }
  #- {type: file, path: verdaccio.log, levelInfo} #experiments are based on # # supportforNPM Token Command supports NPM token token # token:false
#  # support for the new v1 search endpoint, functional by incomplete read more on ticket 1732
#  search: false
#  # disable writing body size to logs, read more on ticket 1912
#  bytesin_off: false#i18n: #web: en-us # This is not available by default, it can only be accessed locally, and can be accessed via the Internet after being addedlisten:0.0. 0. 0:4873
Copy the code

Start Verdaccio from pM2

  • What is the pm2?

Pm2 is a well-known nodeJS daemon and management tool. We use PM2 to start Verdaccio:

npm install -g pm2 / / install pm2

pm2 start verdaccio If verdaccio status is online, it is successful, as shown in the following figure:
Copy the code

Pm2 common commands

 npm install pm2 -g     // Install pM2
 pm2 start app.js       // Start the app.js application
 pm2 start app.js -i 4  // Run pm2 in the background to start 4 app.js
                        // You can also pass the 'Max' argument to star
                        // The correct number of processes depends on the number of Cpu cores

pm2 start app.js  --watch      // Automatically restart the application when the file changes
pm2 list                       // List all applications started by PM2
pm2 monit                      // Displays the CPU and memory usage for each application
pm2 logs                       // Displays all process logs
pm2 start app.js --name="api"  // Start the application and name it "API"
pm2 start script.sh            // Start the bash script
pm2 show [app-name]            // Displays all information about the application
pm2 logs [app-name]            // Displays logs for the specified application
pm2 stop all                   // Stop all applications
pm2 stop 0                     // Stop the specified application with id 0
pm2 restart all                // Restart all applications
pm2 restart 0                  // Restart the specified process
pm2 delete all                 // Close and delete all applications
pm2 delete 0                   // Delete the specified application whose id is 0. You can look it up on BaiduCopy the code

The process for publishing NPM packages

  1. Create a new folder named npm-test and enter it in the CMD console
cd npm-test  
npm init        // Initialize the default file to index.js, so create a new index.js file

/ / index. Js file
module.exports.Say = function(name){
    return  ("Hello " + name);
}
Copy the code

Ok, execute the verdaccio command to publish

 npm adduser --registry http://localhost:4873 // add function, no account added directly package
 npm login --registry=http://localhost:4873 //
 npm publish --registry http://localhost:4873 //
Copy the code

NRM can be used to manage NPM sources to avoid manually entering Registry

nrm add company http://localhost:4873 //company can be added with any name
nrm use company       // use the source address of company

// Enter registry manually
npm addUser  
npm login
npm publish

// Note: Registry needs to switch to the company private server address. If NRM is not used to manage the switch, you need to bring the private Registry (repeat!)
Copy the code

Update at this point on the http://localhost:4873/ page and you’ll find the package you published (the package name is the file name).

Next, let’s download the package we just released


// Note: Registry to switch to the company private server address, if not NRM to manage the switch, you need to bring the private Registry (again)
// Create a new folder named app
cd app
npm install npm-test  If not, manually add --registry=http://localhost:4873
// Success as shown in the figure
Copy the code
  • Delete a published package

npm unpublish npm-test --force  // Clear published packages
Copy the code

NPM private library permission management

Since Verdaccio is available to anyone by default, you need to close the registration window first

auth:
  htpasswd:
    file: ./htpasswd
    // This configuration item can turn off registration
    max_users: -1
Copy the code

Verdaccio certification is based on verdaccio – htpasswd, can through the official to provide tools to generate www.htaccesstools.com/htpasswd-ge… Htpasswd to log in to the NPM private library

Then you need to modify the config. Yaml configuration in the Verdaccio file: Set access, publish, and unpublish permissions for each package. Htpasswd is the default authentication plug-in, so only the corresponding user names (all, authenticated, and $anonymous) can be written

// For a small example:
auth:
  htpasswd:
    file: ./htpasswd
    // This configuration item can turn off registration
    max_users: -1 
    duGroup:
    // You can customize user groups here
    demoPublish: [xiaoming, xiaohong, xiaoli]
    demoUnpublish: [xiaojun, xiaoming]
    testPublish: [xiaoming,xiaojun]

 packages:
        '@demo/*':
            access: $all
        // For different packages, different user groups can be specified to satisfy the permission control
            publish: demoPublish
            unpublish: demoUnpublish
            proxy: npmjs
     'test': 
            access: $all
            publish: testPublish
            unpublish: demoUnpublish
            proxy: npmjs
Copy the code

Or add an account by installing the htpasswd-for-Sinopia tool

 npm install htpasswd-for-sinopia -g

 sinopia-adduser   // Execute in the htpasswd directory
Copy the code

Generate usernames and passwords for other logins, then write the usernames and passwords to the htpasswd file in the Verdaccio folder, and follow the same steps.

Ok, that’s all. Thank you