It’s Friday, why don’t you make yourself a meal? Thinking about the next day when you don’t have to go to work, you feel like taking off. So write an article before you leave work.

Knowledge:

  • A library about front-end log printing. NPM address
  • This article (in detail) explains how a canonical NPM package should be distributed
  • How to use Webpack to package common class libraries, compatible with different environments, different scenarios.

Daily log debugging is very basic, console.log is something we use every day, one day I saw a friend’s project log like this.

So I can’t help but think…?

**console.log(info,’=========’) is often used in daily development.

I decided to wrap console.log to make it easier to debug, so I was ready to release an NPM package for future use.

So, by the way, here is a detailed description of how an NPM package works.

How to distribute an NPM package


Let’s start with NPM

As we all know, the current state of the front end looks like this:

Node_modules is what front-end development is all about right now. Front-end engineering gives birth to this product, which makes the front end grow very quickly, but it also gives rise to a project that sometimes has very large Node_modules. If it’s Windows, Sometimes delete a node_modules folder needs to be particularly long time, thus it can be seen, this huge, of course, get to the point, you know we are in the development process of each package is stored in the web site of NPM, here, you can search to the package, all used in your development process, therefore, When you sometimes have problems downloading dependencies, check out the author’s documentation here. If we want to publish a package, naturally we should register an account on this website first, which is skipped here.

Initialize a project

I named my bag Sn-Console, if you like, because of my English name (SNine). So the first step is NPM init, and then press Enter, and we’ll see how that works in pakeage.json.

{
  "name": "log".// The name of the package you want to publish
  "version": "1.0.0".// The version number you want to release
  "description": "".// A brief description of your package
  "main": "index.js".// Your project entry file
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "".// Author name
  "license": "ISC" // License the code, whether open source is allowed to use such and such a protocol.
}
Copy the code

The initialized project is such a base page, which we refine one by one:

1: Preparation

Js file. This is the entry specified in package.json. This is the code entry. This is important, especially for component libraries. When you want to modify the code of a component library that you are using in node_modules, the first thing you need to do is look at node_modules and go to main. Go to the entry file of the component library, which is the entry file of your project, and create a SRC folder. For the code we’re going to write, we’ll put the rest of the code in SRC.

Here is a simple case to introduce in detail how to package a standard NPMJS public library.

We know that a common library, whether you are a UI library or a feature library, is intended to be used by others, so we need to meet some basic requirements:

  • Distinguish between development and production environments
  • To conform to different norms
  • Users should be able to choose their preferred methods to use

So we can see that we need to use Webpack, of course, the first thing is to download Webpack, since Webpack has been updated to 5, many new features are not particularly clear, so I will directly download the version of 4 here.

npm i webpack@4.44. 0 webpack-cli@3.312. -D
Copy the code
  1. After downloading this file, create webpack.config.js in the root directory. Those who have used Webpakc will know that this is the webpack configuration file.
  2. Also go to pakeage.json and create a script command for packaging
{
  "name": "sn-console"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack" // Create a new command, NPM run build
  },
  "author": ""."license": "ISC"."devDependencies": {
    "webpack": "^ 4.44.0"."webpack-cli": "^" 3.3.12}}Copy the code

2: encapsulates the log library

Basic work done, here is the encapsulation, in order to tell you a more detailed, here for you to expand some knowledge:

Let’s start with a basic webPake configuration,

module.exports = {
    entry: './src/index.js'.output: {}}Copy the code

There is nothing to configure here, see how webpakc is packaged by default.

To make things easier for you, let’s just write a simple method to make things easier for you. Let’s write a method inside SRC /index, which is also very simple:

export default function add(a, b){
    return a + b;
}
Copy the code

We write an addition function export, and then we execute NPM run build to save the package and see if we can find a dist directory. The packaged file is called main.js and it is compressed, which is obviously not what we expected. First we want to package two files, one for the development environment. One is the production environment, so how to solve this problem, of course, is to configure webpakC.

module.exports = {
    entry: {
        "addNumber": './src/index.js'."addNumber.min": './src/index.js',},output: {
        filename: "[name].js".library: "addNumber".libraryTarget: "umd",}}Copy the code

AddNumber and addNumber.min can be packaged separately in dist. So, is our problem solved? After open the two files, we found that the two files are compressed, it obviously doesn’t meet our expectations, although there are two files, but we hope to have an uncompressed used in the development environment, so we need to continue configuration, we know that in webpake configuration mode parameters is used to configure the environment, but can only specify one environment, So we disabled it directly and introduced a compressed plugin to solve the problem. We also downloaded the 4.x version of the plugin.

npm install terser-webpack-plugin@4.2. 0 -D
Copy the code

Then look at the WebPack configuration

const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
    entry: {
        "addNumber": './src/index.js'.To export two files, we specify two exits
        "addNumber.min": './src/index.js',},output: {
        filename: "[name].js".// Write this as multiple files
        library: "addNumber".// The name of the packing library
        libraryTarget: "umd".// Define the specification, package the target option of the library, Umds include var, assign, this, window, global, CommonJS, CommonJs2, CommonJsmodule, AMD, UMD, umD2, jSONP The default value is var
    },
    mode: "none".// Since only one environment can be specified, we close it and use the plugin to implement it
    optimization: { // This field is very powerful, we do webpack code split, shake, tree shake, etc use this field
        minimize: true.// Start the plug-in
        minimizer: [new TerserPlugin({
            test: /\.min.js/  // Provide a regex to compress objects that have min.js}}})]Copy the code

So you can actually pack, and he did,

  1. Package up two environments to develop and produce compressed and uncompressed functionality,
  2. Using UMD specification packaging, when used, it contains multiple standards, no matter esModel or commonJs and other environments can be used normally, so this is also a recommended way to package the public library. In this way, no matter you are import or require, you can get it. Is it convenient?

3: Test our library

In general, if you’re testing a formal library, of course it’s good to write test cases, but the example I’m going to give you today is very simple, let’s write an HTML import, let’s create an index.html in a directory and import a packaged file to test, When we exposed a library as addNumber in the WebPack configuration, we printed it directly:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script src="./dist/sn-console.js"></script>
    <script>
        console.log(addNumber)
    </script>
</body>
</html>
Copy the code

We imported and printed the results: guess what?

Open the console and see?

We found that it was actually a Module. How do you want me to use it? Open it and have a look. Our method is found in default, so we print a new method. Default (99,1)) console.log(addnumber.default (99,1)); How do you solve it? LibraryExport :”default”. Add this configuration to output to indicate that the output is the default value. If you do not specify this configuration, we export a module. Default is exported and can be used directly. At this point, our packaging environment is over.

What do I need to do next?

4: Environment differentiation, development/production

At this point, we find that the packaged file is under dist, and the entry of our package.json is index.js, so what do we need to do? Of course, it is very simple. Add the compressed and uncompressed files under Dist in index via environment differentiation.

"use strict"
if(process.env.NODE_ENV === 'production') {module.exports = require('./dist/sn-log.min')}else{
    module.exports = require('./dist/sn-log')}Copy the code

That’s it. We have a canonical NPM package that can be introduced in different environments, in different ways, and that distinguishes between the two.

5: Add package.json

Once the package is ready to publish, let’s go back to the beginning and complete the contents of package.json, which has many parameters.

{
  "name": "sn-console".// The package name to publish
  "version": "1.0.0".// Release package version number
  "description": "Beautiful and effective console printing about JS".// A short description of the package
  "main": "index.js".// Specify the project entry file
  "scripts": { / / script script
    "test": "echo \"Error: no test specified\" && exit 1"."dev": "webpack"
  },
  "keywords": [ // Keywords, enter these keywords on the NPM website to search for your package
    "console"."snine"."log"]."author": "Snine".// The author of this package can write his own name
  "license": "ISC".// Open source protocols supported by the current package
  "repository": { // Useful for component libraries. Ask the component library user to find your code library address. This configuration item takes effect directly on the NPM home page of the component library
    "type": "git"."url": "git+https://github.com/xxxxxxxxxx"
  },
  "devDependencies": { // Develop dependencies
    "terser-webpack-plugin": "^ 4.2.0"."webpack": "^ 4.44.0"."webpack-cli": "^" 3.3.12}}Copy the code

We can add the package name, version number definition, description package, keywords, author, protocol and so on. Of course, there are many other things that can be added here. If you need it, you can check it by yourself.

  • In fact, it is best not to put things like packaging tools that we used above in the development dependency, do not put test tools, code converters or packaging tools, etc., here, affect the size.

6: Write readme.md

Readme. md is the package specification, this is to create the file in the root directory, and write the specification inside.

If you upload code to Github, you need.gitignore to keep useless files from being uploaded. If you upload code to NPM, you need to create.npmignore.

All right: we’re all set now.

7: Release to NPM market

Publishing to the NPM marketplace generally requires only two steps, login and publish

  1. npm loginThen enterNPM web siteTo log in
  2. npm publishJust publish.

The source of NPM is a foreign source, and we actually switch to other sources in order to speed up our daily life. Therefore, before releasing, we need to cut back to the original source of NPM. npm config **set** registry=http://registry.npmjs.org

  • Of course, for your convenience, I have prepared an SH script for you to upload with one click.

We create a file publish.sh in the root directory

#! /usr/bin/env bash
npm config get registry 
npm config set registry=http://registry.npmjs.org
echo 'Please login :'
npm login # login
echo '===========publish=========='
npm publish # release
npm config set registry=http://registry.npm.taobao.org
echo 'Publish complete'
exit
Copy the code

Just type sh. /publish.sh in terminal and enter your account and password email to publish. A successful launch would look something like this:

All right, when we’re done. NPM will have an email sent to you, then log on to the website to see the package you posted, then go to try, a full specification of the NPM public library is complete.

sn-console

Let’s go back to the beginning. Based on the above problems, we have encapsulated such a public library, the purpose is to make daily debugging more convenient, take a look at use;

  • npm install sn-console --save
  • import ‘sn-console’

Since console itself is a global object, we simply mount the exported log onto the window. Let’s see how it works. In fact, it allows us to print the log in color font and label it so that we can see our printed log more quickly. I’ve exported an object called log, and we can just print the object and look at the methods inside, or you can just call the log.help() method and we’ll talk about that in detail. It can be called from inside the code or directly from the console, since we’ve already mounted the Window.

  • Based on using
  1. Log is an object that provides, respectively,log.info().log.primary.log.success.log.warning.log.danger()For these methods, you can print a log with a label header to see the effect
let arr = [
            {
                name: 'SNine'.age: 22
            },
            {
                name: 'Joe'.age: 28
            }
        ]
  log.info(arr)
  log.success(arr)
  log.primary(arr)
  log.warning(arr)
  log.danger(arr)
Copy the code

He would print a color label, think about, all black from a little green, if we can print the log saw himself, of course, if too much green, we would take the eye, so the label head also can change of course, we only need to pass into the second parameter, will change his tag name, to give it a try

log.info(arr,'This is the tag head I changed myself.')
log.success(arr,'This is the tag head I changed myself.')
log.primary(arr,'This is the tag head I changed myself.')
log.warning(arr,'This is the tag head I changed myself.')
log.danger(arr,'This is the tag head I changed myself.')
Copy the code

  • Print pictures

Open the console of some websites, we will find that some websites have pictures that welcome you, so I also provide a **log.img()** method can be used to print pictures, need to pass in a link, just find one in Baidu.

        log.img('https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2969235134, 11 & gp = 0. 2098148338 & FM = JPG')

Copy the code

  • Print a dividing line

The line (), sometimes their console. The log (‘ — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — ‘) such a line to log more apparent, better looking, and invoke this method directly here will print out a line, I’m not going to do the demo.

  • Clearing Other Logs

Log. Clear () : log. Clear () : log. Clear () : log.

  • Print out a welcome ripple and see the effect,

Can print out such effect, of course, pure entertainment, for their own website custom a special label is also of course very interesting, this function is not perfect, because the text into such code interface has not been developed by others, so it can not be customized, behind can be added.

  • Print out a copyright message and see what it looks like

Is it cool to print such a message on your own website? Of course, this is not perfect, later I will turn all the content into a custom way, more convenient, add a copyright for your website.

  • Check the performance of your web pages

Performance () is an API that allows you to query the performance of your web page. It is very simple to do this by calling log.performance(). Do your own research.

  • Intercept the console log

If you want to intercept console.log, just call log.clearAll and you’ll find that all the console logs disappear. Then we are happy to use their own log library to print their own log, no longer need to be disturbed by others, of course, remember to delete this method after use, or I do not guarantee that your teammates tomorrow will not hit people (manual dog head), at the same time, this method can also be used to judge the environment, Starting this method at production time will also make all the console disappear, although it can be removed at packaging time, but this is also an easy way to implement.

conclusion

We often lose our own learning direction in the work, often thinking about our own learning direction, how to learn, how to be effective, according to me before, it is better to build their own wheels, release some of their own public library, the next time to implement a certain function, will be able to know, know why. Found detailed baidu to NPM release tutorials are varied but not detailed enough, so free to write a detailed introduction, I hope to help you, of course, creation is not easy, to help you, help me point a like it.