NPM, this is enough

Time:2020-10-23

preface

It’s been studying recentlynpmComponent release, encountered some related problems, is to sort out.

Contents involved

  • package.json Document introduction
  • The function and configuration of. Npmrc
  • Public network NPM component Publishing

package.json

summary

package.json Defined in the current projectNPM packageAnd some configuration information of the project (project name, version, description, developer, license, etc.).

When it comes to package manager, you will encounteryarnandnpmThe problem of selectivity. I like ityarn
Yes, have a lookgithubOpen source projects on, such asvueUnder the projectyarn.lockDocuments, from which I guessyarnMaybe it’s more popular, and so am I in everyday useyarnIt’s used a lot.

When wenpm installoryarn installAccording to thepackage.jsonResolve the dependencies between dependent packages, and then configure thenpm registry.npmrcYou can configure the correspondingregistry)Search the address and download the package.

We canyarn.lockorpackage-lock.jsonSee where packages are downloaded from and dependencies.

Exclude when submitting codenode_modulesDirectory, but submityarn.lockorpackage-lock.jsonTo lock the version of the project dependent package. And don’t change it manually when upgrading the packagepackage.jsonTo use the commandyarn upgradeornpm upgrade Upgrade.

npm initoryarn initCan be generated package.json 。

{
    "name": "@mflyyou/npm-description",
    "version": "0.1.0",
    "private": true,
    "Author": Zhang Panqin,
    "license": "MIT",
    "main":"index.js",
    "keywords": [
        "NPM search keywords"
    ],
    "publishConfig": {
        "registry": "https://registry.npmjs.com/"
    },
    "repository": {
        "type": "git",
        "url": " http://git.com/ Project git address“
    },
    "files": [
        "dist",
        "src"
    ],
    "bugs": {
        "url": "http://localhost:8080//issues",
        "email": "[email protected]"
    },
    "contributors": [
        {
            "name": "zhangpanqin",
            "email": "[email protected]"
        }
    ],
    "scripts": {
        "dev": "sh ./build/build.sh",
        "npm-version": "npm -v",
        "serve": "vue-cli-service serve"
    },
    "dependencies": {
        "vue": "^2.5.21"
    },
    "devDependencies": {
        "@vue/cli-plugin-babel": "^3.3.0"
    },
    "peerDependencies":{}
}

package.json Field introduction

name

nameField as the name of the project. For example, a component in Vue@vue/cli-plugin-babelThe front one@vueIn fact, the scope of the current package is the namespace. We can base it onscopeConfigure some private packagesregistrySo that some packets come from a specific address.

registry=https://registry.npm.taobao.org/
@pay-plugin:registry=https://npm.udolphin.com

version

npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease [--preid=<prerelease-id>] | from-git]

'npm [-v | --version]' to print npm version
'npm view <pkg> version' to view a package's published version
'npm ls' to inspect current package/dependency versions

“Version”: “0.1.0”, corresponding tomajor-minor-patch

#Update the location of major, the rest are 0
npm version major 

#Update the position of minor, major remains unchanged, and the rest are 0
npm version minor 

#Update the location of the patch and leave the rest unchanged
npm version patch
  • Major corresponds to a large iteration. For example, Vue 3.0 TS is renewed. New functions are added and major version number is updated
  • Minor corresponding to small version iteration, update the version number of minor in case of modification or function addition compatible with old version API
  • Patch corresponds to the revision number, which is usually modified when a bug is fixed

When your project needs to be released, version must be different from the previous version, otherwise the release will not succeed.

private

Indicates whether the current package is privatetrueThe package cannot be published.

main

Default index.js 。 Specify the JS to load when importing or requiring.

keywords

Keyword describing the current project, used to retrieve the current plug-in.

publishConfig

"publishConfig": {
    "registry": "https://registry.npmjs.com/"
}

Sometimes we are.npmrcOther configurationregistryFor example, Taobao image. When I install the dependency package, I want to install it from Taobao image. When publishing plug-ins, you want to publish them on the official website. You can go topublishConfigIs configured in.

files

Specifies the published dependent packages and included files. Some files will be ignored by default. You can also create. Npmignore in the root directory, ignoring some files.

NPM, this is enough

scripts

Configure some execution scripts. for instancenpm run devIt’s runningsh ./build/build.sh

"scripts": {
    //Running shell scripts
    "dev": "sh ./build/build.sh",
    "build": "npm -v",
    //After the build is successful, publish will be executed    
    "pub": "npm run build && npm publish"
}

dependencies

The development dependency of the project. Key is the module name and value is the version range. The dependencies here will be packaged when the project is packaged.

Fly NPM address

Fly NPM and fly use NPM have been released.

Notice, there’s a pit here, too. For example, I have two plug-ins, fly NPM and fly use NPM. Dependencies in fly use NPM depend on fly NPM. I introduced fly use NPM in my Vue project development. I can be directimport fly-use-npmThe project can run normally. But when youimport fly-npmAn error is reported for project resolution dependencies. Because only dependencies introduced in the current project can be imported.

<template>
    <div>
        <button @click="clickTest">
            test
        </button>
    </div>
</template>
<script>
//Fly NPM can only be imported if it is introduced in the current my Vue project dependencies
//import flyNpm from 'fly-npm';    
import flyUseNpm from 'fly-use-npm';

export default {
    name: 'TestPlugin',
    methods: {
        clickTest() {
            flyUseNpm();
        },
    },
};
</script>

devDependencies

To develop dependencies, you don’t package them when you package them. Like what we usebabel webpakWhen the related plug-ins are packaged, they will not be packed in.

peerDependencies

Before we do this, let’s understand what the tree dependency of NPM means.

I created a Vue project my Vue relies on fly use NPM (it relies on fly NPM 1.0.0) and fly NPM (2.0.0), as you can see in our project.

Whenmy-vueNo introductionfly-npm 2.0.0At the same time,my-vue/node_modules/fly-npm0.0.

NPM, this is enough

When we introducefly-npm 2.0.0The dependency diagram is shown in the figure above, which is called tree dependency.

Here’s the test introductionfly-npm 2.0.0After that.

<template>
    <div>
        <button @click="clickTest">
            test
        </button>
    </div>
</template>
<script>
import flyUseNpm from 'fly-use-npm';
import flyNpm from 'fly-npm';

export default {
    name: 'TestPlugin',
    methods: {
        clickTest() {
            //Print 2.0.0
            console.log('fly-npm', flyNpm);
            //1.0.0 was used
            flyUseNpm();
        },
    },
};
</script>

From the above, we can see that there are two fly NPM packages in a project. In this way, the packing volume will increase accordingly. In order to solve this problem, thepeerDependencies

Create the Vue project my Vue, which relies on fly use NPM (4.0.0, itspeerDependenciesIt is fly NPM 1.0.0).

peerDependenciesThe added dependency package will not be automatically installed (yarn 1.22.0, NPM 6.13.7 of the test).

When I was in my Vue projectyarn installBecause there was no introductionfly-npmIt will report an error.

When I introduced it into the projectfly-npm 2.0.0The installation will display a warning message under the current project.

warning ” > [email protected]″ has incorrect peer dependency “[email protected]”。

This is what happens when you develop a component that depends on the version of a particular package.

// fly-use-npm
import flyNpm from 'fly-npm';
const obj = () => {
    console.log ('the referenced fly NPM version is:', flyNpm.version );
    if (flyNpm.version > 1) {
        Throw new error ('version greater than 1 ');
    }
}
export default obj;

For scenario simulation, the latest package of fly NPM is 2.0.0, which is a major version upgrade. There may be something incompatible with 1.0.0. So I recommend (peer dependencies) 1.0.0 in fly use NPM. When I use fly NPM 2.0.0 in practice, I find that a function dependent on fly NPM 2.0.0 reports an error. I need to think about whether the dependency package is incompatible.

However, if you want to use fly NPM 2.0.0, you can only submit a PR compatible fly NPM or fly use NPM.

This situation is rarely encountered. The general version upgrade will be compatible with the previous functions, and you don’t have to pay too much attention to such problems.

In general, we rarely encounter such problems.githubPopular libraries are rarely usedpeerDependencies

.npmrc

package.jsonWhere do I install the dependent packages in? . npmrc can configure where the dependency package is installed, or some other configuration of NPM.

. npmrc profile priority

  • Project Profile:/project/.npmrc
  • User profile:~/.npmrc
  • Global profile:/usr/local/etc/npmrc
  • NPM built in configuration file/path/to/npm/npmrc
#Get. Npmrc user profile path
npm config get userconfig

The. Npmrc file has the highest priority under the project. Each project can be configured with different images, and the configuration between projects does not affect each other. We can also specify the source of a particular scope.

with@thingjs-pluginThe starting package starts fromregistry=https://npm.udolphin.comDownload here, the rest to Taobao image download.

registry=https://registry.npm.taobao.org/
@thingjs-plugin:registry=https://npm.udolphin.com
NPM config set < key > < value > [- g-- global] // set the value of the configuration parameter key to value;
NPM config get < key > // get the value of the configuration parameter key;
NPM config delete < key > [- g-- global] // delete the parameter key and its value;
NPM config list [- l] // displays all configuration parameters of NPM;
NPM config edit // edit user profile
NPM get < key > // get the effective value of the configuration parameter key;
NPM set < key > < value > [- g-- global] // set the value of the configuration parameter key to value;

The user profile is not configured with – G

-G is configured to the global configuration file

NPM component publishing process

  • Go to NPM official website to apply for account number
  • Add an account to your computer
  • Develop your components, use webpack, Babel processing
  • Your NPM release

Application account number

Apply for an account on the official website to login and publish components.

Create in the root path of the project.npmrcConfiguration file, add the following.

#When installing the package, configure the aliimage
registry = https://registry.npm.taobao.org

staypackage.jsonConfigure the publishing source in.

"publishConfig": {
    "registry": "https://registry.npmjs.com/"
}

In this way, the download dependency package will be downloaded from Taobao image, and the released dependency package will be published to the NPM official website.

Add an account to your computer

Add account command official website description NPM addUser

# npm adduser [--registry=url] [[email protected]] [--always-auth] [--auth-type=legacy]

npm adduser  --registry=https://registry.npmjs.com/

Run the above command. Npmrc user profile generates the following

registry=https://registry.npmjs.com/
//registry.npmjs.com/:_authToken=xxx

Develop your components, use webpack, Babel processing

Due to the troublesome configuration of webpack and Babel, Vue cli scaffold is used for development

package.json

{
    "name": "@thingjs-ad/thingjs-app",
    "version": "0.1.1",
    "private": false,
    "scripts": {
        "serve": "vue-cli-service serve",
        "build": "vue-cli-service build --target lib --name thingjs-app ./src/index.js",
        "lint": "vue-cli-service lint",
        "pub": "npm run build && npm publish --access=public"
    },
    "main": "dist/thingjs-app.umd.min.js",
    "files": [
        "src",
        "dist"
    ],
    "devDependencies": {
        "@vue/cli-plugin-babel": "^4.2.0",
        "@vue/cli-plugin-eslint": "^4.2.0",
        "@vue/cli-service": "^4.2.0",
        "babel-eslint": "^10.0.3",
        "eslint": "^6.7.2",
        "eslint-plugin-vue": "^6.1.2",
        "vue-template-compiler": "^2.6.11"
    },
    "eslintConfig": {
        "root": true,
        "env": {
            "node": true
        },
        "extends": [
            "plugin:vue/essential",
            "eslint:recommended"
        ],
        "parserOptions": {
            "parser": "babel-eslint"
        },
        "rules": {}
    },
    "browserslist": [
        "> 1%",
        "last 2 versions"
    ]
}

Component content

NPM, this is enough

  • AA.vue
<template>
     <div>
         AA module
     </div>
</template>
<script>
export default {
    name:'AA'
};
</script>
  • index.js
import AA from './components/AA.vue';

const components = [AA];


//When calling Vue.use The install method is actually called. Vue.component  Register global components.

const install = function (Vue) {
    components.forEach(component => {
        Vue.component(component.name, component);
    });
};

if (typeof window !== 'undefined' && window.Vue) {
    install(window.Vue);
}

export default {
    version: '1.0.0',
    install,
    AA
}

Publishing components

npm publish --access=public

This article is written by Zhang Panqin’s blog. They are free to reprint and quote, but the author should be signed and the source of the article should be noted.

If you are reprinted to WeChat official account, please add the author’s official account number 2. WeChat official account name: Mflyyou

NPM, this is enough

Recommended Today

Redis design and implementation 4: Dictionary Dict

In redis, the dictionary is the infrastructure. Redis database data, expiration time and hash type all take the dictionary as the underlying structure. Structure of dictionary Hashtable The implementation code of hash table is as follows:dict.h/dictht The dictionary of redis is implemented in the form of hash table. typedef struct dictht { //Hash table array, […]