preface

Recently, I was writing a front-end tool library. I started to build it with Webpack, but accidentally found the introduction of Rollup and found rollop meets my needs more. This article describes building a simple version of the JS library using rollup.

demand

Code level 1. Preparation: SUPPORT ES6 syntax (support asynchronous) requirements for parameter transmission 2. Submit: Submit code with specifications 3. Test: Code test – unit test 4. Note: generate corresponding documentation. Use: used by mainstream browsers; Obviously, webPack is the first thing that comes to mind when packaging, but IN practice I found a packaging framework that is more suitable for my needs, namely Rollup. Here’s a look at the differences. Both Webpack and Rollup require a configuration file that specifies entries, outputs, plug-ins, etc

webpack rollup
Relative paths If not, use path.resolve support

That’s just one of the simple differences, but let’s look at a few more

When we open a web page, as shown in the picture above, the page will not display until it has loaded relevant resources (eg:js, images). The smaller the volume of resources we need to load, of course, the shorter the time we open the page. Tree-shaking is one way to reduce the size of the resources we need. It reduces the amount of code we don’t use in our projects, reducing the amount of time it takes to open pages.

tree.png

Let’s look again at the webPack and rollup package for the same code

Same code webpack rollup
The execution time 71ms 17ms
The file size 389KB 262KB

The main reason for this is that Rollup uses tree-shaking, takes advantage of es6 module features, and forces Mudle to do static analysis and remove useless code during the Uglify phase. As for what the ES6 specification is, here it is:

  • Can only appear as statements at the top level of a module (import and export statements can only appear at the top level of code)

  • Import modules can only be string variables, not strings and variables

  • Imported modules cannot be modified

// let STR = 'can only appear as a statement at the top level of the module '; import { sum} from 'util' ; Import {'s'+'um'} from 'util'; Import {sum} from 'util' sum=1; // Syntax Error : 'a' is read-only;Copy the code

3. Real-time loading of Webpack: use webpack-dev-server rollup: rollup-plugin-serve+rollup-plugin-livereload. Webpack loads more customizations in real time, such as adding middleware and specifying the files to run with. Check out more comparisons. To sum up: Webpack ecosystem rich (more complete documentation, rich plugin library) Split code, load on demand Using plugin support tree-shaking(WebPack 2 +) Webpack generates a lot of extra code, Large package files slow execution weak readability applicable CSS HTML static resources handling complex code split merge or application rollup plugin ecology relatively weak put all resources in one place, Tree -shaking the size of a package does not generate extra code, it is faster, it is more readable. Rollup is more compatible with the base library. Just implement the usual JS method –rollup 2. Syntax: support type –TypeScript 3. Specification: Coding specification –ESLint&Prettier 4. Commit: Submission required –Husky&commitlint 5. Quality: Test Case – JEST begins our project construction

Initialize the project a. Create a folder rollup-demo B.npm init -y Initialize the project c. NPM I rollup rollup-plugin-clear -d D Create the entry file SRC /main.js


function fun1(){
  
  function fun2(){
    return 'no'
  }
 return 'yes'
}
fun1()
console.log(fun1())
function Useless(){
  console.log(1111)
}

Copy the code

E. Create rollup.config.js in the root directory

'use strict';
import clear from 'rollup-plugin-clear';
export default {
  input: 'src/main.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'umd', //打包文件格式
  },
  plugins: [
    clear({targets: ['dist']}), //清除dist目录
  ],
};

Copy the code

F. Add commands under package

 "build": "rollup -c rollup.config.js",

Copy the code

Run NPM run build; A simple rollup package project is complete.

The use of ts

Why ts? Ts is statically typed, js is dynamically typed; Static typing is friendly to reading code; At the same time, IDE provides a large number of convenient support and TS syntax check and code prompt automatic completion for developers to improve efficiency, convenient reconstruction and so on. Of course, TypeScript only provides type annotations for ways of using JavaScript that already exist in JavaScript. All development patterns that can be used in TypeScript must already exist in JavaScript. Rollup-plugin-typescript2: rollup-plugin-typescript2: rollup plugins that compile typescript

npm i rollup-plugin-typescript2 typescript -D

Copy the code

B. a rollup. Config. Js configuration

rollup.config.js
import ts from "rollup-plugin-typescript2";
export default {
    input: "./src/main.ts",
    plugins: [
        ts({
            useTsconfigDeclarationDir: true
        }),
    ]
}

Copy the code

UseTsconfigDeclarationDir: generate the statement specified file storage directory. C. configure tsconfig. Json

{" compilerOptions ": {" target" : "es5", "the module" : / / compile target "es2015," / / "lib" module type: [" ES2015 ", "ES2016 "," ES2017 "],// Import library type definitions "strict": true,// strict mode "sourceMap": true,// generate definition sourceMap" strictNullChecks": // Null and undefined are not allowed to be assigned to variables of other types. (.d.ts) "noUnusedLocals": true, // [//typeRoots specifies the default type declaration file lookup path. The default is node_modules/@types" node_modules/@types"]}}Copy the code

ESLint & Prettier

ESLint refers to code syntax quality rules, Prettier to formatting rules. ESLint is a plug-in javascript code detection tool that can be used to check for common javascript code errors, as well as code style checking, so that we can specify a set of ESLint configurations to our liking and then apply them to the projects we’re writing. In order to realize the implementation of the auxiliary coding specification, effectively control the quality of the project code.

Prettier is a code formatting tool. It enforces a consistent style by parsing the code and reprinting it using its own rules, taking into account maximum lines, and wrapping the code when necessary. Supports JavaScript, Flow, TypeScript, CSS, SCSS, Less, JSX, Vue, GraphQL, JSON, Markdown, etc. While detecting potential problems in your code, you can also unify your team’s code style, which can lead to high quality code that increases productivity.

A. Install dependencies

  • Eslint: The esLint core library, responsible for scheduling the entire ESLint

  • @typescript-eslint/parser: A parser for ESLint that parses typescript to check and standardize typescript code

  • @typescript-eslint/eslint-plugin: The ESLint plugin that contains various specifications for checking typescript code

  • Prettier: prettier core library

  • Eslint-config-prettier: Resolves the conflict between the style specification in ESLint and the style specification in Prettier by taking the style specification of Prettier as the standard

  • Eslint-plugin-prettier: To use the specification for prettier as the ESLint specification

npm i eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-config-prettier eslint-plugin-prettier -D

Copy the code

B. create. Eslintrc. Js

module.exports = {
    root: true,
    parser: '@typescript-eslint/parser',
    parserOptions: {
        ecmaVersion: 2019,
        sourceType: 'module', 
   },
       extends: [
        'plugin:@typescript-eslint/recommended',
        'prettier/@typescript-eslint',
        'plugin:prettier/recommended',
    ],
    env: {
        es6: true,
        node: true,
    },
  
    rules: {
        "no-undef": "error",
        "eqeqeq": "error",
          "no-console": "error"
    },
};


Copy the code

C. create prettierrc. Js


module.exports = {
    arrowParens: 'avoid',
    bracketSpacing: false,
    endOfLine: 'lf',
    jsxBracketSameLine: false,
    jsxSingleQuote: false,
    printWidth: 100,
    proseWrap: 'preserve',
    semi: true,
    singleQuote: true,
    // tabWidth: 4,
    useTabs: false,
    trailingComma: 'es5',
 
};


Copy the code

Commit code specifications Husky & Lint-Staged & Commitlint

Husky is a Git hook helper that performs operations when a Git file state changes. Husky prevents non-standard code from being committed, pushed, merged, and so on

Lint-staged documents can be detected when submitted for change and manipulated with a series of commands, such as Prettier, to fix nonconforming code.

Git commit -m ‘XXXXX’ git commit -m ‘XXXXX’ git commit -m ‘XXXXX’ git commitlint Git commit -m ‘add ESLint ‘is a non-compliant commit because it does not add the corresponding commit type category, which should be chore (Build process or Helper changes) A. Install dependencies

  • Husky: Git hook aid

  • Lint-staged: Monitor changed files and execute commands

  • @commitlint/cli: Commitlint core tool library

  • @commitlint/ config-Conventional: Some commitlint rules are preset

npm i husky lint-staged -D
npm i @commitlint/cli @commitlint/config-conventional -D


Copy the code

B. create huskyrc. Js

module.exports = { hooks: { 'commit-msg': 'commitlint -e $HUSKY_GIT_PARAMS', 'pre-commit': 'Lint-passage ',// Execute commands from Lint-Passage in the pre-commit stage. }};Copy the code

C. create a lint – staged. Config. Js

module.exports = {
  '{src,test}/**/*.ts': [
    'npm run lint',
    'git add'
  ]
};


Copy the code

D. create commitlint. Config. Js

Module. Exports = {extends: ["@commitlint/config-conventional"], rules: {// export = {commitlint/config-conventional"], rules: { [2, 'always', ['upper-case']] } };Copy the code

Jest tests JEST is a JavaScript test library for creating, executing, and building test cases. Can install and use it in any project, such as the Vue/React/presents/Node/TypeScript, etc. To summarize, Jest has the following advantages:

  • Test cases are executed in parallel, more efficiently

  • Powerful Mock functionality

  • Built-in code coverage checking, no need to introduce additional tools

  • JSDOM integration enables direct DOM related testing

  • Out of the box, little extra configuration is required

  • The ES Module Import code can be tested directly

  • There is a snapshot test function to test the UI of frameworks such as React

A. Install dependencies

  • Jest: Integration testing framework

  • @types/jest: A type definition package for Jest that is required to use jest in typescript environments

  • Ts-jest: A conversion tool for testing typescript code

npm i jest @types/jest ts-jest -D

Copy the code

B. create a jest. Config. Js

Module. Exports = {/ / test directory roots: [' < rootDir > / test '], / / for ts TSX file using ts - to test run the transform jest: {' (ts | TSX) ': 'ts-jest',}, // testEnvironment testEnvironment: 'node', // test file matching testRegex: '(/ __tests__ /. * | \ \. (test | spec)) \ \. (ts | TSX | js) $', collectCoverage: true, / / not included in the coverage of coveragePathIgnorePatterns: ['/node_modules/', '/test/'], // coverageThreshold: {global: {branches: 90, functions: 95, lines: 95, statements: 95, }, }, };Copy the code

C. Create test/main.test.ts in the root directory

import Sum from '.. /src/main' test('sum is right', () => { expect(Sum(1, 2)).toBe(10); });Copy the code

D.package. json with new script instruction “test”: “jest”

conclusion

This article explains the difference between WebPack and Rollup, uses ROLLup to build a simple JS library, uses TS, ESLint, and Prettier codes, commits code, and jEST to ensure code quality. The code has been uploaded to Github. Github.com/turning1998…