section-4 Webpack actual configuration examples to explain

4-1 Library of packaging

In addition to packaged application code, webpack can also be used to package JavaScript library
previous steps consistent with the ordinary packaged project, first npm init -yinitialize the folder, this file will help us become node_module

// package.json
{
  "name": "library",
  "version": "1.0.0",
  "description": "",
  "main": "./dist/library.js",  // 入口文件是打包后的dist目录下的library.js文件
  "scripts": {
    "build": "webpack"
  },
  "author": "yose",
  "license": "MIT",
  "dependencies": {
    "lodash": "^1.0.0",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  }
}

Create a library named library, there are some methods of calculation and string processing

// webpack.config.js
const path = require('path');

module.exports = {
    mode: "production",
    entry: './src/index.js',
    externals: ["lodash"],    // 打包的时候忽略lodash,业务上加载lodash,但是必须将lodash命名为lodash
    // externals: {
    //     lodash: {
    //         root: '_',          // 全局script标签变量定义为“_”
    //         commonjs: 'lodash'  // 如果这个库在commonjs环境下使用,
    //     }
    // },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'librart.js',
        library: 'root',   // 挂载在全局library变量上,一般写root,让该库可以通过script标签加载
        libraryTarget: 'umd'  // 通用库,兼容commonjs,seajs等语法
    }
}
// math.js
export function add(a, b){
    return a + b;
}

export function minus(a, b){
    return a - b;
}

export function multiply(a, b){
    return a * b;
}

export function division(a, b){
    return a / b;
}

// string.js
import _ from 'lodash';

export function join(a, b) {
    return _.join([a, b], " ");
}
// index.js
import * as math from './math';
import * as string from './string';

export default {math, string};

After the implementation of the development npm adduser, after enter the account password, the Executive npm publishwill be able to add their own items to the warehouse up npm
lack of ability, I can not yet reached capacity-create the wheel, so this will not go into, you can point to

4-2 PWA packaging configuration

PWA is Progressive Web App abbreviation, that is, progressive enhancement WEB applications.
To build pwa, but use workboxl to simplify our series of operations
to perform npm i workbox-webpack-plugin -Sthe installation
because we only need to use online environment pwa, so we only change webpack.prod.js

const WorkboxPlugin = require('workbox-webpack-plugin');

plugins: [
    new WorkboxPlugin.GenerateSW({  // serviceWorker
        clientsClaim: true,
        skipWaiting: true
    })
]
// index.js
console.log("this is a pwa");

if('serviceWorker' in navigator){
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/service-worker.js')
            .then(registration => {  // 注册成功返回值
                console.log('service-worker registed');
            }).catch(error => {
                console.log('service-worker registed error');
            })
    })
}

Here To verify that they need to use to simulate the http-server, front vue said that there is no longer here to say again, you can own Baidu, anyway, it is very simple. For convenience here to join a start-server command on the command line (remember to first execute webpack pack local files, because there will be direct service to open in the dist directory)

// package.json
"scripts": {
    "start-server": "http-server dist"
}

Run the local server, and boot normally access the page, then the implementation of the console.log page, turn off the local service and continue to visit, although this time the service has been shut down, but there is no implementation of the console.log still able to normal
due to the open http- server does not automatically recognize index.html, so remember the browser address plus /index.html, such as full address: http://127.0.0.1:8080/index.html

4.3 TypeScript packaging configuration

Because not learned typeScript, do not read this section first, otherwise the record do not know, skip

4.4 WebpackDevServer achieve forward the request

Vue direct reference to this section, that is the route forward, in fact, spoke of the front, there is no longer duplicate records. In fact, use devServe
Proxy, the specific parameters will look at the official website of the
bottom is actually using WebPACK-dev-Middleware , so it needs to be read

4.5 WebpackDevServer single-page application to solve the routing problem

For this type of progressive front-end development framework for Vue, in order to build SPA (single-page application), it is necessary to introduce front-end routing system, which is the meaning of existence Vue-router. Core front-end routes, is that while not changing the view request to the backend.
Routing is achieved by two methods, one is the hash, the other is History
hash, what we usually anchor, hash although appears in the URL, but will not be included in the HTTP request to the backend no impact, thus changing the hash will not reload the page
history, use of HTML5 History Interface in new pushState () and replaceState () method. history mode, there will be 404 cases, and therefore need to be configured in webpack
history is devServer need to use the historyApiFallback , most of the documentation to understand the look, there is a point to note, to which the path is not with. , which is the to: './dist/list'need to write to: '/dist/list'
about the vue vue-router configuration, you can also refer to the article: vue-router (routing) detailed tutorial

4.6 & 4.7 ESLint configuration of the webpack

About pain on ESLint and ESLint use only experienced students can understand (the code written, eslint pass, code format has been changed). vscode eslint also supports plug for restraining the code written specification, where they talk in ESLint webpack

4.8 ~ 4.11 webpack performance optimization

  1. Keep pace with technological iteration (Node, npm, Yarn)
  2. Application Loader on as few modules
  3. Plugin as lean as possible and to ensure reliable (to use as recommended by the official website of plug-ins)
  4. Reasonable resolve configuration parameters (module.exports the resolve, documents field is omitted, automatic search)
// 比如下面这些,需要合理使用
module.exports = {
    resolve: {
        extensions: ['.js', '.jsx'],
        mainFiles: ['index', 'child'],  //直接在引入文件的时候只写路径,让wenpack自动帮我们搜索名为index或child的文件
        alias: {  // 别名
            child: path.resolve(__dirname, '../src/child')  // 这里直接将组件起别名
        }
    }
}
  1. Packing speed increase using DllPlugin

Reproduced in: https: //www.jianshu.com/p/d6548ed68407

Guess you like

Origin blog.csdn.net/weixin_34129696/article/details/91154708