webpack notes

Posted by budz on Sun, 30 Jan 2022 06:01:45 +0100

Tips:

webpck official address: https://webpack.docschina.org/guides/getting-started/#basic-setup

nrm

nrm(npm registry manager) is an image source management tool of npm. Sometimes foreign resources are too slow. Using this tool, you can quickly switch between npm sources

nrm ls displays a list of all images

The asterisk indicates the image currently in use. 
npm -------- https://registry.npmjs.org/
  yarn ------- https://registry.yarnpkg.com/
  cnpm ------- http://r.cnpmjs.org/
* taobao ----- https://registry.npm.taobao.org/
  nj --------- https://registry.nodejitsu.com/
  npmMirror -- https://skimdb.npmjs.com/registry/
  edunpm ----- http://registry.enpmjs.org/
The function is: when you npm install When, the data package will be downloaded from the address of the asterisk.

cls clear screen

1 basic installation

mkdir webpack-demo
cd webpack-demo
npm init -y     Initialize project generation packge.json file(When you first npm After downloading the package, the package-lock.json,Record the download address information of the package)

Abbreviations for command line instructions

The npx command provided by node 8.2/npm version 5.2.0 and above can run the webpack binary file in the webpack package installed for the first time (i.e. / node_modules/.bin/webpack)

1. Webpack execution instruction

.\node_modules\.bing\webpack -v

Equivalent to npx webpack -v

Case test:

  webpack-demo
  |- package.json
  |- webpack.config.js
  |- src
    |- main.js
    |- dis
    
implement    npx webpack .\src\main.js -o \src\dist\boundle.js 
         pack main.js, Output to in the current directory dist Folders, generating bundle.js

Packaging instruction improvement

Add the concept of configuration file webpack config. js

Configure inlet and outlet

const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
};

Next, the instruction does not need to add input and output. The instructions are as follows

npx webpack

2 hot loading using plug-ins

Webpack dev server hot load

npm install --save-dev webpack-dev-server

webpack.config.js

  devServer: {
+    contentBase: './dist',
+  },

package.json

   "start": "webpack serve --open",

Now run npm start from the command line

Develop auxiliary plug-ins"devDependencies": {    "webpack-dev-server": "^3.11.2"  }  

Note: the packaged files are not put on disk, but on memory. http://localhost:8080/boundle.js You can see

Adjustment: index html

Directly reference the compiled file in memory. Benefits: faster access

Modify open port

"start": "webpack serve --open --port 3000"

Note: only one service can be opened for one port and cannot be repeated.

Packaging Optimization:

Project code, modify those codes, and package those codes

package.json

  "start": "webpack serve --open --port 3000 --hot"        Key instructions --hot

Or on webpack config. js

   devServer: {        contentBase: 'src/',        open:true,        port:3000,        hot:true      },

Both ways are OK. However, the second method is generally adopted.

3 loader

Function: loader is used to convert the source code of the module. Other resources unknown to webpack except js are processed

Case 1: css -loader

Problem solved: main Introducing css files into JS

main.js

import $ from "jquery"$(function(){    $("li:odd").css("backgroundColor","#fff")    $("li:even").css("backgroundColor","#B9F444")})import "./css/style.css"

All loader s should be installed first, then configured, and then used.

npm install --save-dev css-loader

webpack.config.js

module.exports = {  module: {    rules: [      {        test: /\.css$/,        use: [ 'style-loader', 'css-loader' ]      }    ]  }}

Check the configuration case on the official website and find that CSS loader also relies on style loader. So find the configuration item and install it again.

 npm install style-loader --save-dev

Start the project and find that there is no error.

Case 2: less -loader

Problem solved: main The style is imported into the JS file. So that the webpack can be parsed normally.

In the local css file, create a less file, and then introduce main JS.

Installation:

npm install --save-dev less-loader less

Two of the above instructions are installed, one is less and the other is less loader

// webpack.config.jsmodule.exports = {    ...    module: {        rules: [{            test: /\.less$/,            use: [{                loader: "style-loader" // creates style nodes from JS strings            }, {                loader: "css-loader" // translates CSS into CommonJS            }, {                loader: "less-loader" // compiles Less to CSS            }]        }]    }};

As we can see above, he uses three types of loader s for files ending in less.

After configuration, run

Others, such as pictures, are used in the same way as sass loader

4 use of plug-ins

Function: the requirements that cannot be handled by the loader are handled by the plug-in

Case: HtmlWebpackPlugin this plugin will generate an HTML5 file for you

install

npm install --save-dev html-webpack-plugin

to configure

var HtmlWebpackPlugin = require('html-webpack-plugin');var path = require('path');var webpackConfig = {  entry: 'index.js',  output: {    path: path.resolve(__dirname, './dist'),    filename: 'index_bundle.js'  },    plugins: [new HtmlWebpackPlugin(        {            template: 'src/index.html',              filename: 'index.html',        }    )],};

This will produce a file dist / index html:

<!DOCTYPE html><html>  <head>    <meta charset="UTF-8">    <title>webpack App</title>  </head>  <body>    <script src="index_bundle.js"></script>  </body></html>

Resolution:

Open the chrome debugging page to view the dom, as shown above. There is no index in the local directory_ bundle. JS, index created by HTML webpack plugin I didn't find it. as a result of:

According to the requirements of configuration items, the webpack dev server packages the index_bundle.js, index created by HTML webpack plugin HTML, put it in memory. It can be viewed in the browser, but not in the local directory.

5. Use of webpack integrated bootstrap

Check the official website of bootstrap and learn that it relies on jquery

Install jQuery

npm install jquery --save-dev

Install bootstrap

npm install bootstrap --save-dev

Introduce a concept: main js, CSS Less TTF font icons, etc. loader s can parse them one by one through regular matching. However, bootstrap jQuery is a separate plug-in. There are dependencies between plug-ins, which cannot be solved.

So we introduce webpack ProvidePlugin

The function of viewing the official website is to automatically load the module without having to import or require everywhere

To automatically load jquery, we can point both variables to the corresponding node module:

new webpack.ProvidePlugin({  $: 'jquery',  jQuery: 'jquery'}

Solution:
On webpack base. Conf.js header addition

var webpack = require('webpack')

Add after entry

  plugins: [      new webpack.ProvidePlugin({          "$": "jquery",          "jQuery": "jquery",          "window.jQuery": "jquery"      })  ]

Note: this case uses "bootstrap": "^ 3.4.1",

The font icon is used in bootstrap, and the loader must be set.

  {                test: /\.(ttf|eot|svg|woff|woff2)$/,                use: "url-loader",            },

Additional questions

babel.loader

This section, babel, is a separate note.

-----Tencent classroom - IT veterans video notes sorting

Topics: Vue Webpack