Webpack manual construction and its introduction

webpack is a static resource packaging tool (required for the front end)

  • Features of webpack

    js relies on packaging and integration
    Some pre-processed sass, less can be compiled and converted in the environment,
    js, html, image resources can be compressed and optimized

  • The core of webpack

  1. entry entry file
    // the core js file of the file
  2. output export file
    // packaged dist folder
  3. pligin plugin
    // Various plugins
  4. loader converter
    // convert the file to the file type we want
  5. dev-serve server
    // Let our webpack run locally to build a server
  6. modo mode
    // can switch development environment and production environment

Webpack manual construction steps

  1. Confirm whether there is webpack -v in the current environment. If there is no npm i webpack -g download to the local
  2. In the folder that you want to be a package file, but the folder name cannot be Chinese, use npm init -y to initialize a package.json
  3. Create a src, create an index.html under src
    Insert picture description here
  4. Create a main.js in src as the main development file, perform dom operations in it, and manipulate the root div in html
    Insert picture description here
  5. Bale

Create a webpack.config.js

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

Run the webpack command to pack

  1. You can use packaged hot start so you do not need to pack every time you modify the
    establishment of a local server cnpm webpack-dev-server -D i
    download dependent cnpm i node-sass sass-loader style-loader css-loader -D
    configuration commands in package.json
    added
"dev": "webpack-dev-server --open --port 8888 --contentBase src --hot"

Insert picture description here
npm run dev run

  1. Parse scss file

Configure in webpack.config.js

module: {
        rules: [
            //解析.scss文件,对于用 import 或 require 引入的sass文件进行加载,以及...声明的内部样式进行加载            
            {
              test: /\.scss$/,
              use:['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    }
  1. Introduce jquery

download npm i jquery --save

 import $ from 'jquery'
 // 对#root的样式进行改变
 $("#root").css({color:"red",backgroundColor:"green"})
  1. Automatically generate html page

Download dependent on cnpm i html-webpack-plugin -D
the configuration webpack.config.js

// 插件
plugins:[
    new htmlWebpackPlugin({
        filename:"index.html",
        template:path.join(__dirname,'index.html')
    })
],

Get the index.html template to the same level as src

After configuration, you can package and run again

Guess you like

Origin blog.csdn.net/t5_5_5_5_5_7_7/article/details/109746176
Recommended