• Code store address

NPM register login

  • Prerequisite: Switch to the corresponding NPM source
  1. npm logout
  2. npm login
  3. Enter your account, password, and email address in sequence
  4. Publish NPM publish NPM publish
  • NPM may be encountered at release timeThe problem
    1. Source of error
    2. The package name repetition
    3. Make changes before each releasepackage.jsonMust be greater than the previous version number
  • NPM link Local debugging: To prevent frequent packet sending caused by debugging, you can use NPM link to proxy the NPM package to the local debugging.
    1. Enter the source directory to executenpm link
    2. Enter the use directory that is sample code executionNPM link [package name], and you can use it directly in the sample codeimport xxx from 'xxx'Debug it

Webpack TS Babel and other package configuration file writing

This article is pretty comprehensive, except it doesn’t introduce typescript

  • When you write this article"Webpack" : "^ 4.41.6",The main process is recorded below. The final directory structure is shown below
    |____babelrc / / the Babel configuration
    |____config  / / webpack configuration├ ─ ─ webpack. Base. Js// Public configuration├ ─ ─ webpack. Dev. Config. Js// Development environment configuration└ ─ ─ webpack. Prod. Config. Js// Package the distribution environment configuration
    |____example // Debug directory for the development environment
    |____node_modules 
    |____README.md
    |____yarn.lock
    |____public // Create the index.html template for the debug environment
    |____.gitignore
    |____package.json
    |____lib // Package directory
    |____tsconfig.json / / ts configuration
    |____postcss.config.js / / postcss configuration
    |____src // Component source code
    |____.npmignore // Specify the files and folders to ignore when publishing NPM
    Copy the code
  1. mkdir learnnpm & cd learnnpm & npm init, fill in the information in turn as prompted, and then generatepackage.json
  2. Install dependencies in sequence
    1.Install webpack-related dependencies: yarn add webpack webpack-cli webpack-dev-server webpack-merge -d Related plug-ins: yarn add webpack webpack-cli webpack-dev-server webpack-merge -d clean-webpack-plugin html-webpack-plugin mini-css-extract-plugin2.Install react related yarn add react react-dom3.Install Babel related yarn add @babel/cli @babel/core @babel/preset-env @babel/preset-react babel-loader @babel/plugin-proposal-class-properties @babel/plugin-proposal-object-rest-spread -D4. Installtypescript ts-loader fork-ts-checker-webpack-plugin5. Installationcssrelatedstyle-loader css-loader postcss-loader less less-loader
       url-loader file-loader
       autoprefixer
    Copy the code
    • Complete the above stepspackage.json .babelrc webpack.config.js postcss.config.jsRelevant content is as follows
    {
        // ...
        "main": "lib/index.js".// Package the entry address
        "scripts": {
            "start": "webpack-dev-server --config config/webpack.dev.config.js"."build": "webpack --config config/webpack.prod.config.js"."pub": "npm run build && npm publish" / / release NPM
        },
        // ...
        "dependencies": {
            "react": "^ 16.12.0"."react-dom": "^ 16.12.0"
        },
        "devDependencies": {
            "@babel/cli": "^ 7.8.4"."@babel/core": "^ 7.8.4"."@babel/preset-env": "^ 7.8.4"."@babel/preset-react": "^ 7.8.3"."@babel/plugin-proposal-class-properties": "^ 7.8.3"."@babel/plugin-proposal-object-rest-spread": "^ 7.8.3"."@types/react": "^ 16.9.19".// the related library types file required by ts
            "@types/react-dom": "^ 16.9.5"."@types/react-router-dom": "^ 5.1.3"."autoprefixer": "^ 9.7.4." "."babel-loader": "^ 8.0.6"."clean-webpack-plugin": "^ 3.0.0"."css-loader": "^ 3.4.2." "."fork-ts-checker-webpack-plugin": "^ 0.5.2".// Ts validation webPack plugin
            "html-webpack-plugin": "^ 3.2.0"."less": "^ 3.11.1." "."less-loader": "^ 5.0.0"."mini-css-extract-plugin": "^ 0.9.0".// Remove the CSS plug-in
            "postcss-loader": "^ 3.0.0"."style-loader": "^ 1.1.3." "."ts-loader": "^ 6.2.1." "."typescript": "^ 3.7.5." "."url-loader": "^ 3.0.0"."webpack": "^ 4.41.6"."webpack-cli": "3.3.7"."webpack-dev-server": "^ 3.10.3"."webpack-merge": "^ 4.2.2." "
        },
        "browserslist": [ Postcss Configuration used by autoprefixer
            "iOS >= 6"."Android >= 4"."IE >= 9"]}Copy the code
    • .babelrc
    {
        "presets": [
            "@babel/preset-env"."@babel/preset-react",]."plugins": [
            "@babel/plugin-proposal-class-properties"."@babel/plugin-proposal-object-rest-spread"]}Copy the code
    • .postcss.config.js
    / / https://segmentfault.com/a/1190000008030425 postcss configuration reference
    module.exports = {
        plugins: [
            require('autoprefixer') ({/ *... options */}})]Copy the code
    • webpack.base.js
    const path = require('path');
    
    module.exports = {
        module: {
            rules: [{test: /\.(js|jsx)$/.use: "babel-loader".exclude: /node_modules/
                },
                {
                    test: /\.(ts|tsx)$/.use: [
                        "babel-loader", 
                        {
                            loader: 'ts-loader'.options: {
                                // Turn off type checking, i.e., just do translation, and leave type checking to fork-ts-checker-webpack-plugin in another thread
                                transpileOnly: true}}].exclude: /node_modules/
                },
                {
                    / / CSS/less parsing
                    test: /\.(less|css)$/.use: [
                        'style-loader'."css-loader"."postcss-loader"."less-loader"],}, {//
                    test: /\.(png|jpg|gif)$/.include: path.resolve(__dirname, ".."."src"),
                    use: ["url-loader? limit=8192&name=assets/image/[name].[hash:4].[ext]"] {},// File and font parsing
                    test: /\.(eot|woff|svg|ttf|woff2|otf|appcache|mp3|mp4|pdf)(\? | $) /.include: path.resolve(__dirname, ".."."src"),
                    use: ["file-loader? name=assets/font/[name].[hash:4].[ext]"]},]},resolve: {
            // The suffix name is automatically completed
            extensions: [".ts".".tsx".".js".".jsx".".less".".css"]}};Copy the code
    • webpack.dev.config.js
    const path = require('path');
    const merge = require('webpack-merge');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const baseConfig = require('./webpack.base.js');
    
    const devConfig = {
        mode: 'development'.// Development mode
        entry: path.join(__dirname, ".. /example/src/app.js"), // Project entry, handle resource file dependencies
        output: {
            path: path.join(__dirname, ".. /example/src/"),
            filename: "bundle.js".// When using webpack-dev-sevrer to start the development service, bundle.js is not actually generated in the 'SRC' directory. The packaged file is in memory, but it does not affect our use.
        },
        module: {
            rules: []},plugins: [
            new HtmlWebpackPlugin({
                title: 'learn npm'.filename: "index.html".template: "./public/index.html".inject: true,})],devServer: {
            contentBase: path.join(__dirname, '.. /example/src/'),
            compress: true.port: 3001.// Start the service on port 3001
            // open: true // Automatically opens the browser}};module.exports = merge(devConfig, baseConfig);
    Copy the code
    • webpack.prod.config.js
    const path = require('path');
    const merge = require('webpack-merge');
    const baseConfig = require('./webpack.base.js');
    // const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // Use to package the component's CSS into a separate output file in the 'lib' directory
    const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    
    const prodConfig = {
        mode: 'production'.entry: path.join(__dirname, ".. /src/index.tsx"),
        output: {
            path: path.join(__dirname, ".. /lib/"),
            filename: "index.js".libraryTarget: 'umd'.// Use common module definitions
            libraryExport: 'default'.// Compatible with ES6 module system, CommonJS and AMD module specifications
        },
        module: {
            rules: [
                // I didn't do CSS extraction on the package, so I commented it
                / / {
                // test: /\.css$/,
                // loader: [MiniCssExtractPlugin.loader, 'css-loader?modules'],
                // },]},plugins: [
            // new MiniCssExtractPlugin({
            // filename: "main.min. CSS "// the extracted CSS filename
            // }),
            new CleanWebpackPlugin(),
        ],
        externals: { // Define external dependencies to avoid packing react and react-dom
            react: {
                root: "React".commonjs2: "react".commonjs: "react".amd: "react",},"react-dom": {
                root: "ReactDOM".commonjs2: "react-dom".commonjs: "react-dom".amd: "react-dom",}}};module.exports = merge(prodConfig, baseConfig); 
    Copy the code
    • Tsconfig. json I have turned off the TS mandatory type verification ts configuration details, configuration, TS learning
    {
        "compilerOptions": {
            "target": "es6"."experimentalDecorators": true."strictNullChecks": false."module": "ESNext"."moduleResolution": "node"."jsx": "react"."noUnusedParameters": false."noUnusedLocals": false."esModuleInterop": true."allowSyntheticDefaultImports": true."skipLibCheck": true."noImplicitAny": false."noImplicitReturns": false."noFallthroughCasesInSwitch": false."alwaysStrict": false."strict": false."strictBindCallApply": false."strictPropertyInitialization": false."types": [
                "react"."react-dom"."node"].// "baseUrl": "src",
            // This is equivalent to webpack alias
            // "paths": {
            // "src/*": [
            / / "*"
            / /]
            // }
        },
        "include": [
            "src/"]."exclude": [
            "node_modules"."dist"]."compileOnSave": false
    }
    Copy the code

Ts and Babel

The Babel TS used in the above configuration works as TSX -(TS-Loader) -> ES6 -(babel-loader) -> ES5, which is the TS-Loader branch of this project

  • The master branch of my project does not use the methods described in the above article. Instead, I compile source TSX directly into ES5 using the TSC compiler (using tsconfig.json configuration). The target of tsconfig.json is set to ES5, and it works fine after being introduced

Ts and Babel work together in several ways

  • Refer mainly to these Webpack translations of Typescript existing solutions

  • To sum up, there are roughly the following two schemes

  1. ts-loader + babel-loader
`ts-loader + tsc + tsconfig.json`Process TSX to ES6`babel-loader + babelrc`Connect to es6 as per`@babel/presents-env`Handling for ES5 code voiceover:`ts-loader``new ForkTsCheckerWebpackPlugin`Cooperate with WebPack4`happypack`The function is also small, so it is not used as the above configurationCopy the code
  1. babel7 + @babel/preset-typescript
    • Configure TypeScript support in Babel 7
    • With two small optimizations, Webpack speeds fly up
Introducing @ Babel/preset - typescript, Webpack configuration js, JSX, TS, TSX are all handled by Babel-loader. In addition, a TSC service is started to check the code type TSC --watch (package.json) NPM script,Copy the code
Each of these approaches ends up converting only the higher ES syntax or TypeScript to ES5 syntax, but not the API
  • Syntax: let, const, class, Decorator
  • API: includes, Object.assign, array. from, Promise, async await
  • Grammar by@babel/preset-envThe related configuration is escaped
  • API by@babel/polyfill@babel/runtimeand@babel/plugin-transform-runtime

  • Update: TSC compiler seems to be able to take polyfill, Zhihu question/TS-Polyfill

  • There's a question I don't have an answer to right now, okay?
    Do you need to polyfill NPM packages or UI component libraries like the ones we wrote? I'll leave it to the user, the host environment`antd-mobile`After packing the file, found like`Promise, Object.assign`I didn't do polyfillCopy the code

Babel related -@babel/polyfill, @babel/preset-env, @babel/ plugin-transform-Runtime

  • Refer to the article
  1. Babel Learning Series 1-Babel History
  2. Babel Learning Series 2-Babel design, composition
  3. Babel Learning Series 3- Babel-Preset,babel-plugin
  4. Babel Learning Series 4- Polyfill and Runtime Differences (must see)
  5. Does Babel compile or ES 6? Do you have to go to Polyfill?
  6. This site allows you to stop “blind matching” front end toolchain
  7. www.tangshuang.net/7427.html
  • Dynamic polyfill schemes are mainly based on@babel/preset-envuseBuiltInTo determine the
  • @babel/babel-polyfillThe entire application is introduced globally to simulate the complete ES6+ environment
  • @babel/babel-runtime @babel/babel-plugin-transform-runtimeDeveloping frameworks, libraries such as Vue, provides a sandbox environment that does not pollute the prototype chain, which mainly provides reference assistance for the former and reduces the code volume