First, the use of Webpack

Install and configure WebPack in your project

  1. Run the NPM installwebpack webpack-cli-d command to install webpack-related packages
  2. In the project root directory, create a name namedwebpack.config.jsWebpack configuration file
  3. In the webPack configuration file, initialize the following basic configuration:
Module. exports = {mode: 'development' //mode used to initialize build mode (development-------; Production ---- Product release model)}Copy the code
  1. npm init -yGenerate package.json configuration file, add dev script under scripts node in configuration file as follows:
"Scripts ": {"dev": "webpack" // scripts under the script node, can be executed by NPM run}Copy the code
  1. Running in a terminalnpm run devCommand to start webpack for project packaging

Basic use of Webpack

1. Configure packing inlets and egress

Set the entry/exit js file by changing webpack.config.js as follows:

const path = require("path"); Module. exports = {mode:"development", // set file path entry: Path. The join (__dirname, ". / SRC/xx. Js "), / / set the export file output: {/ / set the path path: the path. The join (__dirname, ". / dist "), // set output filename filename:"bundle.js"}}Copy the code
2. Webpack automatically

A. Install the automatic packaging package: webpack-dev-server Enter NPM install webpack-dev-server -d

B. Modify the dev command in package.json as follows:

"scripts":{
   "dev":"webpack-dev-server"
}
Copy the code

C. Change the path of the imported JS file to: D. Run NPM run dev to package the package. Open the website to see the effect: http://localhost:8080

3. Configure the generation preview page

A. Install the default preview package: html-webpack-plugin Enter the command NPM install html-webpack-plugin -d NPM install clean-webpack-plugin

B. Modify the webpack.config.js file as follows:

/ / import packages
const HtmlWebpackPlugin = require("html-webpack-plugin");

// Remove dist without manually deleting the dist folder each time
const clearWebpackPlugin= require("clean-webpack-plugin"); 

// Create an object
const htmlPlugin = new HtmlWebpackPlugin({
    // Set the template file to generate the preview page
    template:"./src/index.html".// Set the name of the generated preview page. This file exists in memory and is not displayed in the directory
    filename:"index.html"
})

const  clearPlugin=new clearWebpackPlugin() // Delete dist without manually deleting the dist folder each time

Copy the code

C. Continue to modify the webpack.config.js file and add plugins:

module.exports = {
    ...
    plugins:[ htmlPlugin,clearPlugin ]
}
Copy the code

Parameters for automatic packaging

// configure package.json //--open automatically open browser after package completion, //--host configure IP address //--post configure port "dev": "Webpack-dev-server --open --host 127.0.0.1 --port 8888"Copy the code

Attention! To modify the configuration file, rerun the command: NPM run dev

Webpack loader

1. Use loader to package non-JS modules

In actual development, webpack can only package modules with.js suffix by default, and other modules with non-.js suffix cannot be processed by default. You need to call loader to package normally, otherwise an error will be reported!

1. Package and process the CSS file
  • runnpm i style-loader css-loader -DCommand to install the loader that processes CSS files
  • In the module -> rules array of webpack.config.js, add the loader rule as follows:
// Match rules for all third-party file modules
module: {rules:[
        { test:/\.css$/,use:['style-loader'.'css-loader']]}}//test indicates the matched file type. Use indicates the loader to be invoked
Copy the code

Pay attention to

  • The loader order specified in the use array is fixed
  • Multiple Loaders are invoked in the following order: from back to front
2. Pack and process less files
  • Run the NPM I less-loader less -d command
module:{
    rules:[
        { test:/\less$/,use:['style-loader','css-loader','less-loader'] }
    ]
}
Copy the code
3. Pack and process SCSS files
  • Run the NPM I sass-loader node-sass -d command
module: {rules:[
        { test:/\.scss$/,use:['style-loader'.'css-loader'.'sass-loader']]}}Copy the code
4. Configure postCSS to automatically add CSS compatible prefixes
  • Run the NPM I postcss-loader autoprefixer -d command
  • Create the postcss configuration file postcss.config.js in the project root directory and initialize the following configuration:
 const autoprefixer = requier('autoprefixer')    // Import the auto-prefix plug-in
module.exports = {
   plugins: [ autoprefixer ] // Mount the plug-in
}
Copy the code
  • In the module -> rules array of webpack.config.js, modify the loader rules in the CSS as follows:
module: {rules:[
        { test:/\.css$/,use:['style-loader'.'css-loader'.'postcss-loader']]}}Copy the code
5. Package the image and font files in the stylesheet
  • Run the NPM I url-loader file-loader -d command
module: {rules:[
        { 
            test:/\.jpg|png|gif|bmp|ttf|eot|svg|woff|woff2$/,
            use:'url-loader? limit=xxxx'}}]/ / which? The loader parameters followLimit specifies the size of an image, in bytes. Only images smaller than limit are converted to Base64 imagesCopy the code
6. Package advanced syntax in js files
  • NPM I babel-loader @babel/ core@babel/run-time -d
  • NPM i@babel /preset-env @bable/plugin- transform-runtime@babel /plugin-proposal-class-properties -d
  • In the project root directory, create the Babel configuration file babel.config.js and initialize it as follows:
module.exports = {
    presets: ['@babel/preser-env'].plugins: [ '@bable/plugin-tranform-runtime'.'@babel/plugin-proposal-class-properties']}Copy the code
  • In the module -> rules array of webpack.config.js, add the loader rule as follows:
module: {rules: [//exclude excludes the JS files in node_modules from babel-loader
        { test:/\.js$/,use:'babel-loader'.exclude: /node_modules/}}]Copy the code

Single file component —– filename. Vue (eg: app.vue)

1. Configure the loader for vUE components in Webpack
  • Run the NPM I vue-loader vue-template-compiler -d command
module.exports = {
    const VueLoaderPlugin = require('vue-loader/lib/plugin')
    module: {rules:[
            { test:/\.vue$/,use:'vue-loader'}},plugins: [// Other plug-ins
        new VueLoaderPlugin() 
    ]
}
Copy the code
2. Use VUE in webpack projects
  • Run NPM I VUe-s to install vUE
  • In the SRC ->index.js entry file, import the Vue constructor by importing Vue from ‘Vue’
  • Create a VUE instance object and specify the EL region to control
  • Render App components using the Render function
Import vue from 'vue' // 2. / app. vue' const vm = new vue ({// 3. Specify the page area that the vm instance controls el: '#app', // 4. Render: h=>h(App)})Copy the code


The use of Gulp

The steps of the building tool developed based on node platform are as follows:

  1. Run the NPM install gulp command to download the gulp library file
  2. Create the gulpfile.js file in the project root directory
  3. The file structure under the reconstruction project, SRC directory stores the source files, dist directory stores the built files
  4. Write tasks in the gulpfile.js file
  5. Execute the gulp task in the command tool

Methods provided by Gulp

  1. Gulp.task (): Creates a gulp task
  2. Gulp.src (): Gets the file to process
  3. Gulp.dest (): Output file
  4. Gulp.watch () : Monitors file changes
// const gulp = require('gulp'); /* Create a task using gulp.task(). */ gulp.task('first', Gulp.src ('./ SRC/CSS /index.css') // Output the processed file to the dist directory. Pipe (gulp.dest('dist/ CSS ')); });Copy the code

Enter the command NPM install gulp-cli -g gulp first

Gulp plug-in

(1) Download plugin: NPM install plugin name; Gulpfile.js: require(‘ plugin name ‘); (3) Call the plug-in

  1. Gulp-htmlmin: HTML file compression
  2. Gulp-less: less syntax conversion
  3. Gulp – csso: compress CSS
  4. Gulp-babel: JavaScript syntax conversion
  5. Gulp-uglify: Compression obfuscates JavaScript
  6. Gulp-file-include: includes public files
  7. Browsersync: Real-time browser synchronization
<! Const htmlmin = require('gulp-htmlmin'); // public files include const fileinclude = require('gulp-file-include'); Gulp.task ('htmlmin', () => {gulp.src('./ SRC /*.html') // Require ('gulp-file-include'); .pipe(fileinclude()) // collapseWhitespace (htmlmin({collapseWhitespace: true})).pipe(gulp.dest('dist'))});Copy the code
Const less = require('gulp-less'); // const csso = require('gulp-csso') gulp.task('cssmin', () = > {/ / gulp. SRC ('. / SRC/CSS / *. Less ') / / select the CSS files and CSS file directory of all less gulp. SRC (['. / SRC/CSS / *. Less ', Pipe (less()) // Zip the CSS code. Pipe (csso()) // output the result. Pipe (gulp.dest('dist/ CSS ')) });Copy the code
// const Babel = require('gulp-babel'); // const uglify = require('gulp-uglify') gulp.task('jsmin', () => {gulp.src('./ SRC /js/*.js'). [' @ Babel/env]})) / / compression code. The pipe (uglify ()), pipe (gulp. Dest (' dist/js')});Copy the code
Gulp.task ('copy', () => { gulp.src('./src/images/*') .pipe(gulp.dest('dist/images')) gulp.src('./src/lib/*') .pipe(gulp.dest('dist/lib')) });Copy the code
/ / build tasks gulp. Task (' my - tasks, gulp. Series (' htmlmin ', 'cssmin', 'jsmin', 'copy', () = > {}));Copy the code