webpack5 packs a TS library and publishes it to npm one-stop practical tutorial (with template code)

Article catalogue

preface

The current front-end wheels are bound to run away from webpack, rollup and other packaging tools. Webpack 5 has been out for a long time. Let's try it.

The article will create a TS library from scratch and upload it to npm. The dimensions are in the order of operation steps.

  1. Create a new project package json
  2. Install webpack and webpack cli
  3. Webpack cli init select configuration
  4. Default scheme of webpack5 resource packaging
  5. The ts declaration file is not generated and processed
  6. Publish package to npm

Note: the following are all synchronous replacement with yarn npm users.

1, Create a new project package json

Create a new project, which I call webpack5 TS lib boilerplate

Then create the project with the yarn init command

2, Install webpack and webpack cli

Install webpack and webpack cli into the project development dependency. The version I choose here is the latest version.

yarn add  webpack webpack-cli -D

3, Webpack cli init select configuration

Execute the following command:

yarn webpack-cli init

At this time, enter the select configuration mode and introduce the configuration one by one:

Select language

Which of the following JS solutions do you want to use? Which of the following JS solutions do you want to use?

Here we can use TS selection.

Whether to use webpack dev server

Do you want to use webpack-dev-server? (Y/n) Whether to use webpack dev server

Webpack dev server is mainly used to write example tests. It is convenient to watch. Enter Y here.

Create html in the warehouse

Do you want to simplify the creation of HTML files for your bundle? Do you want to simplify the creation of bundle HTML files?

html webpack plugin will automatically bind the packaged js file to the html file and give it to webpack for configuration.

Enter y, required

Is pwa required

Do you want to add PWA support? Do you want to add PWA support?

This is a third database, which does not need to be supported

Select the css preprocessor to use

Which of the following CSS solutions do you want to use? Choose css solution

I use less for this library

Will you use CSS styles in your project?

Will you be using CSS styles along with LESS in your project? Will you use CSS styles in your project?

Yes, it will be handled by your loader here

Use PostCSS

Will you be using PostCSS in your project? Use PostCSS

postcss can preprocess css through the plug-in mechanism, which is selected here.

Do you want to add global css

Do you want to extract CSS for every file? Do you want to extract CSS for each file?

Not yet. Some configurations are OK

Select package manager

Pick a package manager Select package manager

Used to yarn

Overview configuration

Finally, overwrite the package json

4, webpack generate configuration Preview

Overall Catalog:

Automatically generated

  • tsconfig
  • postcss.config
  • webpack.config

Focus on webpack config

webpack.config

// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

const isProduction = process.env.NODE_ENV == "production";

const stylesHandler = "style-loader";

const config = {
  entry: "./src/index.ts",
  output: {
    path: path.resolve(__dirname, "dist"),
  },
  devServer: {
    open: true,
    host: "localhost",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html",
    }),

    // Add your plugins here
    // Learn more about plugins from https://webpack.js.org/configuration/plugins/
  ],
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/i,
        loader: "ts-loader",
        exclude: ["/node_modules/"],
      },
      {
        test: /\.less$/i,
        use: [stylesHandler, "css-loader", "postcss-loader", "less-loader"],
      },
      {
        test: /\.css$/i,
        use: [stylesHandler, "css-loader", "postcss-loader"],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
        type: "asset",
      },

      // Add your rules for custom modules here
      // Learn more about loaders from https://webpack.js.org/loaders/
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
};

module.exports = () => {
  if (isProduction) {
    config.mode = "production";
  } else {
    config.mode = "development";
  }
  return config;
};

Configuration content:

  • HtmlWebpackPlugin
  • ts-loader
  • style-loader
  • css-loader
  • postcss-loader
  • less-loader

Resource allocation policy:

{
        test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
        type: "asset",
},

Now, webpack will automatically select between resource and inline according to the default conditions: files less than 8kb will be regarded as inline module type, otherwise they will be regarded as resource module type.

tsconfig

tsconfig is only the basic configuration

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "allowJs": true
  },
  "files": ["src/index.ts"]
}

5. The ts declaration file is not generated and processed

Modify code

export interface StudentProps {
  name:string,
  class:string
}

class Student {
  name:string
  class:string
  constructor(std:StudentProps) {
    this.name = std.name
    this.class = std.class
  }
}

export default Student

Generate dist

Execute the script generated by default

"scripts": {
    "build": "webpack --mode=production --node-env=production",
    "build:dev": "webpack --mode=development",
    "build:prod": "webpack --mode=production --node-env=production",
    "watch": "webpack --watch",
    "serve": "webpack serve"
  }
yarn build

No ts declaration file found after compilation

Configure tsconfig to generate a declaration file

We need to declare the file and distribute it with dist, so we need to configure tsconfig

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/",// Package to directory
    "sourceMap": false,// Generate sourceMap (for browser debugging)
    "noImplicitAny": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "declaration": true,// Generate declaration file
    "declarationDir": "./dist/types/",// Declare where files are packaged
    "declarationMap": false,// Whether to generate declaration file and map file (for debugging)
    "moduleResolution": "node",
    "module": "esnext",
    "target": "es5",// Target language converted into
    "baseUrl": "./",
    "types": [
      "node"
    ],
    "typeRoots": [
      "./node_modules/@types"
    ],
    "lib": [
      "dom",
      "es2015"
    ],
    "jsx": "react",
    "allowJs": false
  },
  "include": [
    "src/**/*.ts",
    "typings.d.ts",
  ],// Files to package
  "exclude": [
    "node_modules",
    "*.test.ts"
  ]
}

Then execute the packaging command, and the generated results are as follows:

Publish package to npm

Specify npm package upload content

Modify package JSON modify main and files and add the types field.

The specific configuration is as follows:

{
  "name": "webpack5-ts-lib-boilerplate",
  "version": "1.0.0",
  "description": "My webpack project",
  "author": "ZY",
  "license": "MIT",
  "main": "./dist/main.js",
  "types": "./dist/types/index.d.ts",
  "files": [
    "dist"
  ],
  "devDependencies": {
    "@webpack-cli/generators": "^2.4.1",
    "autoprefixer": "^10.4.2",
    "css-loader": "^6.5.1",
    "html-webpack-plugin": "^5.5.0",
    "less": "^4.1.2",
    "less-loader": "^10.2.0",
    "postcss": "^8.4.5",
    "postcss-loader": "^6.2.1",
    "prettier": "^2.5.1",
    "style-loader": "^3.3.1",
    "ts-loader": "^9.2.6",
    "typescript": "^4.5.4",
    "webpack": "^5.66.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.7.3"
  },
  "scripts": {
    "build": "webpack --mode=production --node-env=production",
    "build:dev": "webpack --mode=development",
    "build:prod": "webpack --mode=production --node-env=production",
    "watch": "webpack --watch",
    "serve": "webpack serve"
  }
}

Package upload

Switch npm source to public. If you don't log in when you execute npm publish, remember to log in. This is not wordy here.

After publishing successfully, you can view the address:

https://www.npmjs.com/package/webpack5-ts-lib-boilerplate

ending

github code warehouse: https://github.com/Template-FE/webpack5-ts-lib-boilerplate

Added by Topshed on Wed, 09 Mar 2022 05:55:35 +0200