Reproduced by: yard workers

Original link: juejin.cn/post/684490…

JavaScript used to only run on the browser side,

With the Nodejs environment, JavaScript can also run on the back end.

NPM is the JavaScript package manager for Nodejs,

Provides plenty of wheels for veteran driver programmers to speed up takeoff in an instant.

In this example, we made a package that implements data structures using JavaScript

npm install data-struct-js

Github.com/codermonkie…

Premise 0.

If Nodejs is installed, NPM is installed with Nodejs.

Without the Node environment, there would probably be no need for NPM package development.

1. Register the NPM user

Since it is an NPM package, the first natural is to have an NPM account.

Registering is easy. Go to the website.

/ NPM’s official website (www.npmjs.com/)

Ps: If you want to learn, here is a good Chinese document website:

[NPM Chinese document](www.npmjs.cn/)

Remember the username and password to use when Posting.

2. Create a repository and initialize an NPM project

2.1 Create a repository on Github or Gitee

This project is called data-struct-js.

Clone to a local computer.

git clone https://github.com/CoderMonkie/data-struct-js.git
Copy the code

2.2 Initializing the NPM Project

VSCode opens data-struct-js folder and executes in terminal

npm init -y
Copy the code

If -y is not added, you need to confirm step by step or manually enter the value

Arguments with -y are all generated by default

The above command automatically generates a package.json file for us.

{
  "name": "data-struct-js"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git"."url": "git+https://github.com/CoderMonkie/data-struct-js.git"
  },
  "keywords": []."author": ""."license": "ISC"."bugs": {
    "url": "https://github.com/CoderMonkie/data-struct-js/issues"
  },
  "homepage": "https://github.com/CoderMonkie/data-struct-js#readme"
}
Copy the code

Each item shall be modified according to the actual situation.

The URL in there,

It is generated according to the Git information of our Github project.

Git information exists in the.git folder.

We will elaborate on each attribute when we modify it.

3. Prepare to start NPM package development

3.1 Editing the package.json file

To illustrate the related attribute items,

  • Name: indicates the project name
  • Version: indicates the package version
  • Description: Indicates the description
  • Main: specifies the entry file
  • Scripts: scripts command
  • Repository: source repository address
  • Keywords:
  • Author: Indicates the author information
  • License: copyright type
  • I have some bugs in my system
  • Homepage: the project homepage

Among them,

The items that must be included are name and version

Author information format official recommendations

Your Name <[email protected]> (http://example.com)
Copy the code

Copyright type, changed to the least restrictive MIT type in this project.

In this example, the package.json file is modified:

{" name ":" the data struct - js ", "version" : "0.0.1", "description" : "Provide commonly used data-structures for javascript.", "main": "index.js", "scripts": { "compile": "npx babel src --out-dir compiled" }, "repository": { "type": "git", "url": "git+https://github.com/CoderMonkie/data-struct-js.git" }, "keywords": [ "data-structure", "javascript" ], "author": "Mao NianYou <[email protected]> (http://github.com/codermonkie)", "license": "MIT", "bugs": { "url": "https://github.com/CoderMonkie/data-struct-js/issues" }, "homepage": "https://github.com/CoderMonkie/data-struct-js#readme" }Copy the code

In addition to those listed above,

You have dependencies and devDependencies,

Represents the dependency packages of the project and those used in project development respectively.

I’m not going to write it here because, when we add a dependency,

Install by NPM install –save or NPM install –save-dev,

The dependent package and version information is added to the corresponding properties above,

Basically no manual editing required.

3.2 Planning project directories and files

It could be more complicated than that,

The most basic structure in this example includes the following:

data-struct-js
|--examples
|  |--(for sample files)
|--lib
|  |--(for compiled files)
|--src
|  |--(for development files)
|--.babelrc
|--.gitignore
|--.npmignore
|--index.js
|--LICENSE
|--package.json
|--README.md
Copy the code

* Note: there are subhierarchy representing folders above, others are files

3.2.1 Directory Structure Overview

  • Data-struct-js: the root directory of this project
  • Examples: Examples file for storing this project
  • Lib: Store compilation results (ES6 standard JavaScript compiles to ES5 for browser compatibility)
  • SRC: development directory
  • .babelrc: configuration file for Babel (you can also write it in webpack.config if you use webpack)
  • .gitignore: git configuration file that configures objects that ignore version management
  • .npmignore: NPM configuration file that configures the ignored object when publishing to NPM
  • Index. js: a unified export file
  • LICENSE: a copyright information file that is automatically generated when you create a warehouse
  • Package. json: project management file, automatically generated when the project is initialized
  • Readme. md: project description file, which can be generated when a new repository is created and edited according to the project content
  • Also, if you are using Webpack, there is a webpack.config configuration file

* Note: This article project configures WebPack in the sample project under examples

3.2.2 Description of special files

.babelrc

Babel allows us to use the latest JavaScript syntax,

Without worrying about browser compatibility,

Because it can help us compile ES6 code into ES5.

Example:

{
    "presets": [
        "@babel/preset-env"]}Copy the code

.gitignore

Configure the files or folders to ignore for Git version management here.

The default configuration can be generated based on the selection when you create a new repository.

If you edit it yourself, you should have at least the following:

examples/dist/
lib/
node_modules/
.npmignore
Copy the code

.npmignore

Non-npm publish object configuration.

Example:

examples/
node_modules/
src/
.babelrc
.gitignore
.npmignore
Copy the code

LICENSE

This file is automatically generated when a new repository is created based on the copyright type selected.

Example:

MIT License

Copyright (c) 2019 Mao NianYou

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Copy the code

package.json

Project configuration management file, as described in 3.1 above.

README.md

Project description documents using markdown tags,

Introduce yourself to the project. Such as:

# Background
# Project Introduction
# see sample
# Instructions
# License
Contact #
# Contributors/acknowledgements
Copy the code

Fill in the details according to the above major items

4. Develop our own NPM package

After configuring the above, it’s time for the main part,

Develop our NPM package.

4.1 Installing Dependencies

In this development, we are currently using only babel-related packages.

From the VSCode terminal (or another command line tool), execute the following command:

npm install --save-dev @babel/cli
npm install --save-dev @babel/core
npm install --save-dev @babel/preset-env
Copy the code

It can also be abbreviated as the following command:

npm i -D @babel/cli @babel/core @babel/preset-env
Copy the code

–save-dev equals -d

The dependencies are added to devDependencies

–save equals -s

Adds dependencies to dependencies

Because the code uses the class attribute note, running Babel will cause an error if you install only the above,

According to the error message, @babel/plugin-proposal-class-properties should also be installed

Note: See the code arrayBasedstruct.js below

Error: Cannot find module '@babel/plugin-proposal-class-properties' from...
Copy the code
  1. The installation
npm i -D @babel/plugin-proposal-class-properties
Copy the code
  1. Modify the Babel configuration file (.babelrc) to add plugins
{
    "presets": [
        "@babel/preset-env"]."plugins": [["@babel/plugin-proposal-class-properties",
          {
              "loose": true}}]]Copy the code

After installation, the devDependencies field was added to the package.json file.

{
  "name": "data-struct-js"."version": "0.0.1"."description": "Provide commonly used data-structures for javascript."."main": "index.js"."scripts": {
    "compile": "npx babel src --out-dir compiled"
  },
  "repository": {
    "type": "git"."url": "git+https://github.com/CoderMonkie/data-struct-js.git"
  },
  "keywords": [
    "data-structure"."javascript"]."author": "CoderMonkey <[email protected]> (http://github.com/codermonkie)"."license": "MIT"."bugs": {
    "url": "https://github.com/CoderMonkie/data-struct-js/issues"
  },
  "homepage": "https://github.com/CoderMonkie/data-struct-js#readme"."devDependencies": {
    "@babel/cli": "^ 7.7.5"."@babel/core": "^ 7.7.5"."@babel/plugin-proposal-class-properties": "^ 7.7.4"."@babel/preset-env": "^ 7.7.6"}}Copy the code

4.2 ES6 code Implementation (Example: stack.js)

Since the topic of this article is how to publish your own NPM package from scratch,

As an example, the complete code can be viewed:

[making] (github.com/CoderMonkie…).

The following is the implementation code of the stack structure in this project.

Other files referenced in it,

Post it below for your reference.

data-struct-js/src/Stack.js

import {
    deepCopy,
    isFunction
} from './common_utils'
import ArrayBasedStruct from './ArrayBasedStruct'/** ** stack structure ** @export
 * @class Stack
 * @extends {ArrayBasedStruct}
 */
export class Stack extends ArrayBasedStruct {
    constructor() {super()} /** * new element to the Stack ** @param {*} element * @memberof Stack */ push(element) {returnThis.__items. Push (element)} /** * the top element returns to the Stack ** @memberof Stack */pop() {
        returnThis.__items.pop ()} /** * check the top element ** @returns the top element * @memberof Stack */peek() {
        if(! this.__items.length)return undefined
        returnDeepCopy (this.__items[this.__items. Length - 1])} /** * traversal stack structure ** @param {function} callback
     * @param {boolean} [reversal=false]
     * @memberof Stack
     */
    traverse(callback, reversal = false) {// Check the callback functionif(! isFunction(callback))returnvar items = this.getItems(this.__items) var from = reversal ? items.length - 1 : 0 var to = reversal ? Var loopCondition = 0: items.length -1 var loopCondition = 0: items.length -1function (current) {
            if (reversal) {
                return current >= to
            } else {
                returnCurrent <= to}} // cursor forward var stepIn =function (current) {
            if (reversal) {
                return current - 1
            } else {
                returnCurrent + 1}} // Iteratefor(var index = from; loopCondition(index); index = stepIn(index)) { var element = items[index]; Callback (element, index)}} /** * to string ** @returns * @memberof Stack */toString() {
        return this.__items.map(element => element.toString()).join(' ')}}Copy the code

Data-struct-js/SRC /common_utils.js

/** ** deep copy ** @export
 * @param {*} sourceThe object to be copied * @returns deep copy results */export function deepCopy(source) {
    var dest
    if(Array.isArray(source)) {
        dest = []
        for (let i = 0; i < source.length; i++) {
            dest[i] =deepCopy(source[i])
        }
    }
    else if(toString.call(source) = = ='[object Object]') {
        dest = {}
        for(var p in source) {if(source.hasOwnProperty(p)){
                dest[p]=deepCopy(source[p])
            }
        }
    }
    else {
        dest = source
    }
    returnDest} /** * Determines whether the passed argument is a function ** @export* @param {*} func argument (function) * @returnstrue: is the functionfalse: is not a function */export function isFunction (func) {
    if(! func || toString.call(func) ! = ='[object Function]') return false
    return true
}
Copy the code

data-struct-js/src/ArrayBasedStruct.js

The base class provided to the stack structure

Import {deepCopy} from "./common_utils" /** * Base class of array-based data structures ** @class ArrayBasedStruct */ export class ArrayBasedStruct () {constructor() {this.__items = []} /** * return {memberof Stack */ getItems () { Return deepCopy(this.__items)} /** * Whether the data structure instance contains elements ** @readonly * @memberof ArrayBasedStruct */ get isEmpty() {return This.__items. length === 0} /** * Number of elements of the data structure instance ** @readonly * @memberof ArrayBasedStruct */ get size() {return ** @memberof ArrayBasedStruct */ clear() {this.__items.length = 0}}Copy the code

Export it in the index.js file

data-struct-js/index.js

import { Stack } from './lib/Stack'
export { Stack }
Copy the code

Note: Currently, only Stack is used in this example, and all subsequent additions are exported here

4.3 Compiling with Babel

Remember the script commands we configured in package.json,

  "scripts": {
    "compile": "npx babel src/ --out-dir lib"
  },
Copy the code

Execution method:

npm run compile
Copy the code

Execution Result:

> [email protected] compile F:\path\to\data-struct-js > NPX Babel SRC / -- out-of-dir lib Successfully compiled 3 files with Babel.Copy the code

/ struct-js/lib/; / struct-js/lib/; / struct-js/lib/; / struct-js/lib/

These compiled files are what we download and import when the packages we make are used by others.

5. Test your NPM package

NPM package development requires testing just like normal project development.

Reduce or avoid bugs through testing.

5.1 Creating a Demo Project

Create our test project under data-struct-js/examples/.

cd examples
npm init
package name: data_struct_js_demo
Copy the code

The generated package.json project file:

{
  "name": "data_struct_js_demo"."version": "1.0.0"."description": "demo for data-struct-js"."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": ""."license": "MIT"
}
Copy the code

Let me tell you a little secret:

This project is located under our main project directory,

The dependency packages to be used here, if this project is not installed,

It automatically looks for the upper directory,

That is, if the outer layer is installed, it works.

In addition,

If you can’t find the root directory, you’ll look at the global installation,

An error is reported when none exists

5.2 Completing Related Configurations

5.2.0 installation data struct – js

Note:

The following installation methods are not applicable to this example.

Because demo project is located under package project directory,

This results in recursive references.

This parameter is available only when new projects are not created in the same path.

npm install --save-dev .. /.. /data-struct-jsCopy the code

So, here we need to manually reference the files in our package.

data-struct-js/examples/src/index.js

// Import Stack from directly'.. /.. /src/Stack'// Import Stack from'.. /.. /lib/Stack'
Copy the code

Note:

There is a pit, is the modular approach must be unified!

That is, if you use ES6 modularity in your code (import/export),

Node exports (require/module.exports=)

An error will be reported. (XXX is not a constructor)

=> data-struct-js/index.js does the same

5.2.1 Installing other required dependency packages

Here are the development dependencies we used this time:

(Write in two lines to avoid being too long)

npm i -D webpack webpack-cli webpack-dev-server
npm i -D html-webpack-plugin clean-webpack-plugin
Copy the code

data-struct-js/examples/package.json

{"name": "data_struct_js_demo", "version": "1.0.0", "description": "Demo for data-struct-js", "main": "index.js", "scripts": { }, "author": "CoderMonkey <[email protected]>", "license": "MIT", "devDependencies": {" Babel - loader ", "^ 8.0.6", "the clean - webpack - plugin" : "^ 3.0.0", "HTML - webpack - plugin" : "^ 3.2.0", "webpack" : "^ 4.41.3 webpack -", "cli" : "^ 3.3.10", "webpack - dev - server" : "^ 3.9.0"}}Copy the code

5.2.2 Configuring WebPack, Add the script command

data-struct-js/examples/webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebpackPlugin({
    template: path.join(__dirname, "./src/index.html"),
    filename: "./index.html"
});
const {CleanWebpackPlugin} = require("clean-webpack-plugin");

module.exports = {
    mode: 'development',
    entry: path.join(__dirname, "./src/index.js"),
    output: {
        path: path.join(__dirname, "dist/"),
        filename: "[name].[hash:6].js"
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: "babel-loader",
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        htmlWebpackPlugin, new CleanWebpackPlugin()
    ],
    resolve: {
        extensions: [".js".".jsx"]
    },
    devServer: {
        port: 8080
    }
};
Copy the code

data-struct-js/examples/package.json

/ /... A little... "scripts": { "start": "webpack-dev-server --open", "build": "webpack --config webpack.config.js" }, // ... A little...Copy the code

5.2.3 Write simple test content, start and view

data-struct-js/examples/src/index.js

// Import {Stack} from directly'.. /.. /src/Stack'

var stack = new Stack()
for (var i = 0; i < 5; i++) {
    stack.push(i)
}
console.log('isEmpty: ', stack.isEmpty)
console.log('size: ', stack.size)
console.log(stack.toString())
console.log(`pop: `, stack.pop())

stack.traverse((ele,index)=>{
    console.log(`Traversing-Stack:${index}: ${ele}`)
})

stack.traverse((ele,index)=>{
    console.log(`Traversing-Stack:${index}: ${ele}`)},true)

console.log(`claer: `, stack.clear())
console.log('isEmpty: ', stack.isEmpty)
console.log('size: ', stack.size)
Copy the code

data-struct-js/examples/src/index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Demo of data-struct-js</title>
</head>
<body>
</body>
</html>
Copy the code

5.3 Confirming the Running result

Execute the script commands we configured,

Start the local service and open the webpage:

Note the current directory: data-struct-js/examples

npm run start
Copy the code

Attach the output to the code for easy reading

// Import {Stack} from directly'.. /.. /src/Stack'

var stack = new Stack()
for (var i = 0; i < 5; i++) {
    stack.push(i)
}
console.log('isEmpty: ', stack.isEmpty)
// isEmpty:  false

console.log('size: ', stack.size)
// size:  5

console.log(stack.toString())
// 0 1 2 3 4

console.log(`pop: `, stack.pop())
// pop:  4

stack.traverse((ele,index)=>{
    console.log(`Traversing-Stack:${index}: ${ele}`)
})
// Traversing-Stack:0: 0
// Traversing-Stack:1: 1
// Traversing-Stack:2: 2
// Traversing-Stack:3: 3

stack.traverse((ele,index)=>{
    console.log(`Traversing-Stack:${index}: ${ele}`)},true)
// Traversing-Stack:3: 3
// Traversing-Stack:2: 2
// Traversing-Stack:1: 1
// Traversing-Stack:0: 0

console.log(`claer: `, stack.clear())
// claer:  undefined

console.log('isEmpty: ', stack.isEmpty)
// isEmpty:  true

console.log('size: ', stack.size)
// size:  0
Copy the code

TODO

So it’s easy to confirm the results,

Then we can consider using a testing framework.

The result shows that the operation is correct and meets the expectation.

So we’re ready to launch.

6. Publish to NPM

Note: The path is back to the root directory of this project, namely data-struct-js/

6.1 Release Notes

6.1.1 User Login

The following error will be reported if the user is not logged in:

npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! [no_perms] Private mode enable, only admin can publish
this module [no_perms] Private mode enable,
only admin can publish this module: data-struct-js
Copy the code

To log in, run:

npm login
Copy the code

NPM login Enter username and password as prompted,

Then I made an error and found that Taobao is used by NPM source.

Note here: When publishing an NPM package, switch the source to NPM.

npm ERR! code E409
npm ERR! Registry returned 409 for PUT on
https://registry.npm.taobao.org/-/user/org.couchdb.
user:maonianyou: [conflict] User maonianyou already exists
Copy the code

W I use NRM here to manage the installation source.

Switch:

> nrm use npm

    Registry has been set to: https://registry.npmjs.org/
Copy the code

Successful login:

> npm login
Username: yourname
Password: (yourpassword)
Email: (this IS public) [email protected]
Logged in as yourname on https://registry.npmjs.org/.
Copy the code

[bug Mc-108366] – Register user’s email address is not verified

npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! you must verify your email before publishing a new package:
https://www.npmjs.com/email-edit : your-package
Copy the code

6.1.2 Do not have the same name

First check the NPM website for packages with the same name.

Otherwise, the following error will be reported because there is no permission:

npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You do not have permission to publish "xxxxxxx". Are you logged in as
the correct user? : xxxxxxxxx
Copy the code

6.2 release

6.2.1 Compilation and Publishing

Note:

  • First compile NPM run compile
  • Then publish NPM publish
npm run compile
npm publish
Copy the code

For convenience, let’s configure a script command:

data-struct-js/package.json

/ /... A little..."scripts": {
    "dopublish": "npm run compile && npm publish"} / /... A little...Copy the code

In the future:

npm run dopublish
Copy the code

6.2.2 Release Succeeded

>npm publish npm notice npm notice package: [email protected] NPM notice === Tarball Contents === NPM notice 866B package.json NPM notice 55B index.js NPM notice 1.1kB LICENSE NPM notice 26B readme. md NPM notice 1.8kB lib/ arrayBasedstruct. js NPM notice 947B lib/common_utils.js NPM Notice 5.1KB lib/ stack. js NPM notice === Tarball Details === NPM notice name: data-struct-js NPM notice version: 0.0.1 NPM notice Package Size: 3.7KB NPM notice Unpacked size: 9.9KB NPM notice SHasum: 2001495314blsd9gaj9g0b7b15aewr6we5207aac npm notice integrity: sha512-UzOx7tFP8/qJp[...] DPJ1wherlFJyQ== NPM notice Total Files: 7 NPM notice + [email protected]Copy the code

Go to the NPM website to view the data-struct-js release

www.npmjs.com/package/dat…

6.3 Download and Installation

Install and test it on your own project.

npm install data-struct-js
Copy the code

Introduction to use

import { Stack } from 'data-struct-js'
Copy the code

With reference to:

5.3 Confirming the Running result

6.4 Publishing Revocation

6.4.1 Revoking the Entire Package

npm unpublish --force your-package-name
Copy the code

6.4.2 Revoking only a Version

npm unpublish <package-name>@<version>
Copy the code

See the Internet said:”

You can’t delete it after 24 hours

But if you check the website, it can be revoked within 72 hours,

Contact NPM Support for more than 72 hours.

There is no practice confirmation, please refer to the official website

7. Updates to packages

After adding features or fixing bugs,

We need to update our package.

This is mainly about version management.

Version 7.0 cannot be released without changes

After modifying the project code, the version number remains unchanged.

If you continue to publish, you will get an error:

npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You cannot publish over the previously published versions:
0.0.1. : data-struct-js
Copy the code

7.1 Semantic Versioning

Here is a table from the official NPM document,

Add some Chinese translation.

Code status Stage Rule Example version
1 First Release This is the First release New product Start with 1.0.0 1.0.0
2 Fixes Backward compatible Bug modified Patch release Releases a Patch update Increment the third digit 1.0.1
3 Backward Compatible new features Added new features for Backward compatibility Minor Release Releases Minor version updates Increment the middle digit and reset last digit to zero Increment the middle digit and reset last digit to zero 1.1.0
4 Changes that break backward compatibility Major release Releases Major version updates Increment the first digit and reset middle and last digits to zero 2.0.0

1 is the first release, and 2, 3 and 4 are patch/minor/major respectively.

7.2 Manually Modify the Version and Release it

data-struct-js/pakcage.json

{
  "version": "1.0.1"
}
Copy the code
npm publishs
Copy the code

7.3 Automatically Adding the Release Number

NPM version <update_type> <update_type> is:

  • Patch 0.0. *
  • Major *. 0.0
  • minor 1.*.0
npm version patch

npm publish
Copy the code

The above commands,

Is to version our packages semantically,

Automatically change the version number and then publish.

Other 8.

8.1 Modifying NPM Initialization Information

Run the following command to modify the default initialization content

> npm set init.author.email "[email protected]"
> npm set init.author.name "example_user"
> npm set init.license "MIT"
Copy the code

8.2 about the scoped/unscoped

Remember the babel-related packages we used above,

@babel/cli
@babel/core
@babel/preset-env
Copy the code

You’ll notice that in this format,

It’s not the same as installing the package we developed this time

npm install @babel/cli

npm install data-struct-js
Copy the code

So this @scopename is the limit of scoped,

For example, the package name is @codermonkey/data-struct-js

Because private packages are charged, the name can only be set to public,

Therefore, the following parameters must be added when publishing:

npm publish --access public
Copy the code

To publish is:

@yourscope/packagename

1.0.0 · Public · Published… ago

Scope is used to associate a series of packages,

Each user and organization has its own Scope,

We mentioned earlier that distribution packages cannot have the same name,

In fact, if I had the same name,

It should be ok as long as it is not in the same Scope.

I don’t know if I’m going to violate the rule for similar package names but there are slightly similar package names,

Our launch was a success

Scope name can be specified at login time:

npm login --registry=http://reg.example.com --scope=@myco
Copy the code

You can also configure the scope of the specified source in config:

npm config set @myco:registry http://reg.example.com
Copy the code

For more details about Scope, please refer to the official website:

docs.npmjs.com/misc/scope

* Note: This article refers to the NPM official website documentation