Build component library from 0 to 1

Posted by Gokul on Tue, 08 Feb 2022 05:50:32 +0100

brief introduction

From implementing the basic architecture of the project - > supporting multi specification packaging - > implementing on-demand loading - > publishing npm packages, take you to build component libraries from 0 to 1.

Construction project

  • Initialize project directory
mkdir lyn-comp-lib && cd lyn-comp-lib && npm init -y
  • New packages directory

packages directory is the component directory. A folder of a component is a unit, and a folder is a component

mkdir packages
  • New / SRC / index js

/src/index.js as the packaging entry of the commonjs specification

mkdir src && cd src && touch index.js
  • Create a new webpack common. js

webpack configuration file of commonjs specification

touch webpack.common.js
  • Create a new webpack umd. js

webpack configuration file of umd specification

touch webpack.umd.js
  • Create a new publish sh

Responsible for building projects and publishing npm packages

touch publish.sh
  • Install webpack and webpack cli
npm i webpack webpack-cli -D

Project directory structure

Start coding

At present, we only want to verify the architecture design, so we will only write some simple demo s

assembly

Create two directories in the packages directory as the component directory

In fact, this directory structure refers to the element UI component library to prepare for on-demand loading

  • /packages/hello/src/index.js
// hello function
export default function hello (msg) {
    console.log('hello ', msg)
}
  • /packages/log/src/index.js
// log function
export default function log (str) {
    console.log('log: ', str)
}

Import and export components

At / SRC / index JS to uniformly import and export the components in the project

// When the component becomes large, this part can be generated automatically, and the element UI is generated automatically
import hello from '../packages/hello/src/index'
import log from '../packages/log/src/index'

export default {
    hello,
    log
}

Writing a webpack configuration file

  • /webpack.common.js
const path = require('path')

module.exports = {
    entry: './src/index.js',
    // The purpose of using developer mode is to debug for a while. In actual development, it can be changed to production
    mode: 'development',
    output: {
        path: path.join(__dirname, './lib'),
        filename: 'lyn-comp-lib.common.js',
        // commonjs2 specification
        libraryTarget: 'commonjs2',
        // Replace the window object in the bundle with this, otherwise it will report window is not defined
        globalObject: 'this',
        // Without this configuration item, the component will be mounted under the default attribute, and comp default. XXX is inconvenient to use in this way
        libraryExport: 'default'
    }
}
  • /webpack.umd.js
const path = require('path')

module.exports = {
    // This part can be generated automatically during actual development, and the element UI method can be adopted
    // On demand loading requires that the entry be configured as a multi entry mode, with one entry for each component
    entry: {
        log: './packages/log/src/index.js',
        hello: './packages/hello/src/index.js'
    },
    mode: 'development',
    output: {
        path: path.join(__dirname, './lib'),
        filename: '[name].js',
        // umd specification
        libraryTarget: 'umd',
        globalObject: 'this',
        // The global variables exposed by the component library can be used, for example, when the bundle is introduced through script
        library: 'lyn-comp-lib',
        libraryExport: 'default'
    }
}

package.json

{
    "name": "@liyongning/lyn-comp-lib",
    "version": "1.0.0",
    "description": "Build component library from 0 to 1",
    "main": "lib/lyn-comp-lib.common.js",
    "scripts": {
        "build:commonjs2": "webpack --config webpack.common.js",
        "build:umd": "webpack --config webpack.umd.js",
        "build": "npm run build:commonjs2 && npm run build:umd"
    },
    "keywords": ["Component library", "0 To 1"],
    "author": "Li Yong Ning",
    "files": [
      "lib",
      "package.json"
    ],
    "repository": {
      "type": "git",
      "url": "https://github.com/liyongning/lyn-comp-lib.git"
    },
    ...
}

explain

  • name

    Add your own npm account name before the package name and adopt the npm scope method. The organization of the package directory is different from that of ordinary packages, and it can effectively avoid conflicts with others' package names

  • main

    Tell the user where to load the component library (import Hello from '@ liyongning / Lyn comp lib')

  • script

    Build command

  • files

    When publishing the npm package, tell the publisher to upload only the files and directories specified in files to the npm server

  • repository

    The code warehouse address and options are not mandatory. You can have none, but they are generally provided and shared with others

Build the publish script publish sh

shell script, which is responsible for building the component library and publishing the component library to npm

#!/bin/bash

echo 'Start building component library'

npm run build

echo 'The component library has been built and is now released'

npm publish --access public

README.md

A project must have fewer files, readme MD is responsible for telling others how to use our component library

Build and publish

At this step, not surprisingly, the goal set at the beginning is about to be completed. Next, execute the script, build and publish the component library. Of course, you should have your own npm account before publishing

sh publish.sh

If no error is reported during the execution of the script, and the following contents appear at the end, it means that the npm package is published successfully, and you can go npm official website see

...
npm notice total files:   5                                       
npm notice 
+ @liyongning/lyn-comp-lib@1.0.0

test

Next, we create a new test project to actually use the component library just released to verify whether it is available and whether it meets our expected goals

New project

  • Initialize project directory
mkdir test && cd test && npm init -y && npm i webpack webpack-cli -D && npm i @liyongning/lyn-comp-lib -S

Check the log or package JSON will find that the component library has been installed successfully, and the next step is to use it

  • New / SRC / index js
import { hello } from '@liyongning/lyn-comp-lib'
console.log(hello('lyn comp lib'))
  • structure
npx webpack-cli --mode development

In the / dist directory, the packaged file mian.com will be generated JS, and then create a new index in the / dist directory HTML file and introduce main JS, and then open the console in the browser, and you will find the following output:

  • Load on demand

We are at / SRC / index JS only introduces and uses the hello method in main JS, you can find both hello function and log function, which indicates that it is now fully imported. Next, load on demand according to the configuration of the usage document (README.md)

It can also be seen from this figure that the introduction is the package of commonjs, not ". / node_modules / @ liyongning / Lyn comp lib / lib / hello.js

  • Load on demand according to the usage document configuration of the component library

Install Babel plugin component

Install Babel loader, @ babel/core

npm install --save-dev babel-loader @babel/core
// webpack.config.js
const path = require('path')

module.exports = {
  entry: './src/index.js',
  mode: 'development',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'main.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  }
}

Install @ Babel / preset env

{
  "presets": ["@babel/preset-env"],
  "plugins": [
    [
      "component",
      {
        "libraryName": "@liyongning/lyn-comp-lib",
        "style": false
      }
    ]
  ]
}
  • Configure package JSON script

{
...
scripts: {

"build": "webpack --config webpack.config.js"

}
...
}

* Execute build command

npm run build

* Repeat step 4 above, and you will find that the packaged file has only `hello function`,No, `log function`

![](https://gitee.com/liyongning/typora-image-bed/raw/master/202202071719323.jpg)

And the actual package size is also small

**OK,Goal complete!! If you have any questions, you are welcome to ask questions and make common progress**

## link

* [Component library column](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzA3NTk4NjQ1OQ==&action=getalbum&album_id=2259813235891863559#wechat_redirect)

- [github](https://github.com/liyongning/lyn-comp-lib.git)



Thank you for your:**give the thumbs-up**,**Collection**and**comment**,I'll see you next time.

---

**When learning becomes a habit, knowledge becomes common sense**,Scan code concerns WeChat official account, learn and progress together. The article has been included in [github](https://github.com/liyongning/blog), welcome to Watch and Star.

Topics: Javascript Front-end npm