Getting started with Webpack (notes)

1. The difference between gulp and webpack

  1. Gulp puts more emphasis on the automation of front-end processes, and modularity is not its core.
  2. Webpack puts more emphasis on modular development and management, and functions such as file compression and merging, preprocessing, etc., are additional functions.

2. Installation

webpack depends on the node environment, node needs to use npm (package management tool) to manage packages

3. Packaging

webpack ./src/main.js ./dist/bundle.js

  1. Setting the webpack.config.js file can simplify the command line execution statement
const {
    
     dirname } = require('path');
const path = require('path');//引入node中的path
module.exports = {
    
    
    entry: './src/main.js',
    output: {
    
    // 必须是一个对象,并且里面有两个值
    
        //path: './dist', //只能是绝对路径,动态获取,所以这种写法是错误的
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
    },
}
  1. Setting the script in package.json can simplify the commands and has the advantages.
    Insert picture description here

For example: executing npm run build will find the "command" corresponding to the build for execution.

And when this command is executed, it will be found locally first

If cmd is executed directly, then the global package is used

{
    
    
    "name": "meetwebpack",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    
    
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack"
    },
    "author": "",
    "license": "ISC"
}

Development dependency (–save-dev)

npm install [email protected] --save-dev

    "devDependencies": {
        "webpack": "^3.6.0"
    },

Project dependency

    "dependencies": {

    }

4. loader

Webpack is used to care for the js code we write, and webpack will automatically handle the dependencies between js.

But during development, we also need to load css, pictures, convert ES6 or Typescript to ES5 code, convert scss to css, convert jsx and .vue files to js files, etc.

This requires the loader:

! ! ! ! Learn to check documents! ! ! !

Chinese document
https://www.webpackjs.com/Foreign
document
https://webpack.js.org/

    "devDependencies": {
    
    
        "babel-core": "^6.26.3",
        "babel-loader": "^7.1.5",
        "babel-preset-es2015": "^6.24.1",
        "css-loader": "^3.3.0",
        "file-loader": "^1.1.1",
        "less": "^4.1.0",
        "less-loader": "^2.2.3",
        "style-loader": "^1.2.1",
        "url-loader": "^1.1.1",
        "webpack": "^3.6.0"
    }

After checking the documentation, install various loaders and configure the webpack.config.js file

const {
    
     dirname } = require('path');
const path = require('path');
module.exports = {
    
    
    entry: './src/main.js',
    output: {
    
    
        //path: './dist', //只能是绝对路径,动态获取
        // path: path.resolve(__dirname, 'dist'),
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: 'dist/'
    },
    module: {
    
    
        rules: [{
    
    
            test: /\.css$/,
            //css-loader只负责将css文件进行加载
            //style-loader负责将样式添加到DOM中
            //要在main.js中将.css文件引入
            //使用多个loader时,是从右向左读
            use: ['style-loader', 'css-loader']
        }, {
    
    
            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
            }]
        }, {
    
    
            // DOS只允许后缀名为三个htm,jpg == html,jpeg
            test: /\.(png|jpg|gif|jpeg)$/,
            use: [{
    
    
                loader: 'url-loader',
                options: {
    
    
                    // 当加载的图片,小于limit时,会将图片编译成base64字符串形式。
                    // 当加载的图片,大于limit时,需要使用file-loader模块进行加载。
                    limit: 13000,
                    // 给name加上[]是还原图片原本的名字,不加就都叫name.jpg
                    // extension
                    name: 'img/[name].[hash:8].[ext]',
                }
            }]
        }, {
    
    
            test: /\.js$/,
            // 排除 
            exclude: /(node_modules|bower_components)/,
            use: {
    
    
                loader: 'babel-loader',
                options: {
    
    
                    // presets: ['@babel/preset-env']
                    presets: ['es2015']
                }
            }
        }],
    }
}

The dependent css file or less file should be quoted in main.js to make contact.
Insert picture description here

5. Node configuration vue environment

npm install --save vue

Then it can be used by importing it in main.js,
Insert picture description here
but it will report an error! ! !
Insert picture description here
the reason

  1. runtime-only -> There can be no template in the code (apps mounted by the vue instance are also considered templates)
  2. runtime-compiler -> There can be a template in the code, because a compiler can be used to compile the template

Solution:
configure a resolve in webpack.config.js
Insert picture description here

6. The relationship between el and template

If you set the template attribute in the vue instance, then vue will replace #app with the things in the template

If the template is set in the vue instance:
Insert picture description here
#app is replaced when the page is displayed:
Insert picture description here
if there is no template attribute:
Insert picture description here

Single page multiple application
SPA (simple page web application)

7. Use of vue files

  1. First, let webpack be able to parse the .vue file, and you need to install a loader

(Analyze vue, compile vue template)

npm install vue-loader vue-template-compiler --save-dev

  1. Configure the webpack.config.js file
    Insert picture description here
    resolve: {
    
    
        // 别名
        alias: {
    
    
            "vue$": 'vue/dist/vue.esm.js'
        }
    },
  1. A .vue file is a component.
    Insert picture description here
  2. App.vue index of files can be <div id="app"></div>replaced
    Insert picture description here
  3. There are three modules in the .vue file, as follows:
    Insert picture description here
    template, script, style
<template>
    <div>
        <p class="title"></p>
        <button @click="btnclick">{
   
   {message}}</button>
        <p>{
   
   {name}}</p>
        <Cpn></Cpn>;
    </div>
</template>

<script>
    import Cpn from "./Cpn.vue";
    export default {
     
     
        name: "App",
        data() {
     
     
            return {
     
     
                message: '你好啊',
                name: 'perry',
            }
        },
        methods: {
     
     
            btnclick() {
     
     
                console.log("message");
            }
        },
        components:{
     
     
            Cpn,
        }
    }
</script>

<style scoped>
    .title{
     
     
        color: red;
    }
</style>

8. Know the plugin

1. What is plugin
  1. plugin (plug-in), which means to extend an existing framework.
  2. The plug-ins in webpack are various extensions to the existing functions of webpack, such as packaging optimization, file compression, and so on.
2. The difference between loader and plugin
  1. Loader is mainly used to convert certain types of modules, it is a converter.
  2. Plugin is a plug-in, it is an extension to webpack itself, is an expander.
3. How to use plugin
  • List item
  1. Step 1: Install the plugin that needs to be used through npm (some webpack already built-in plugins do not need to be installed)
  2. Step 2: Configure the plug-in in the plugin in webpack.config.js.
4. Use of BannerPlugin

We want to add a copyright notice to the file.

The name of the plug-in is BannerPlugin, which belongs to webpack's own plug-in.

  1. Configure webpack.config.js file
    Insert picture description here
    plugins: [
        // 横幅plugin的使用
        new webpack.BannerPlugin('最终版权归我所有')
    ]
  1. After the program is repackaged, the header of the packaged file will have the copyright information you set
    Insert picture description here
5. Package html plugin plug-in (HtmlWebpackPlugin)

Currently, our index.html file is stored in the root directory of the project.

  1. We know that when the project is actually released, the content in the dist folder is released, but if there is no index.html file in the dist folder, then the packaged js and other files will be meaningless.
  2. Therefore, we need to pack the index.html file into the dist folder, this time you can use the HtmlWebpackPlugin plug-in

What can he do?

  1. Automatically generate an index.html file (you can specify a template to generate)
  2. Automatically insert the packaged js file into the body through the script tag

Install the HtmlWebpackPlugin plugin

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

Using plugins, modify the content of the plugins section in the webpack.config.js file as follows:

  1. The template here indicates what template to generate index.html according to
  2. In addition, we need to delete the publicPath attribute previously added in output
  3. Otherwise the src in the inserted script tag may be problematic
    Insert picture description here
        new HtmlWebpackPlugin({
    
    
            template: 'index.html',
        })
6. js compressed plugin (uglifyjs)
  1. Install uglifyjs-webpack-plugin version number to specify 1.1.1, consistent with CLI2

npm install [email protected] --save-dev

  1. Modify the webpack.config.js file and use the plug-in:
    Insert picture description here

9. Set up a local server

webpack provides an optional development server. This local server is based on node.js to build an internal express framework, which can achieve what we want to let the browser automatically refresh and display our modified results.

installation:

npm install --save-dev [email protected]

Devserver is also used as an option in webpack. The option itself can be set with the following attributes:

  1. contentBase: Which folder to provide local services for, the default is the root folder, we need to fill in here./dist
  2. port: port number
  3. inline: real-time page refresh
  4. historyApiFallback: In SPA (simple web page application) pages, rely on the history mode of HTML5

The webpack.config.js file configuration is modified as follows

Insert picture description here

    devServer: {
    
    
        contentBase: './dist',
        inline: true,
    }

Then add script to package.json (–open is to open the web page directly after execution)
Insert picture description here

 "dev": "webpack-dev-server --open"

10. Configuration extraction in the development phase

Since some of the things in webpack.config.js are used in the development phase and some are used in the production phase, we need to separate them.

For example, webpack.dev-server is the configuration used in the development phase, and uglifyjs-webpack-plugin is the configuration used in the production phase. We try to separate him

  1. We create a build folder in the same directory as index.html, in which all configuration files are placed
    Insert picture description here
  2. Create three js files
  • Place the configuration needed in the development phase in dev.config.js
  • Place the configuration required for the production phase in production.config.js
  • It is used in base.config.js
  1. Merge it with webpack-merge

npm install [email protected]

Insert picture description here
Insert picture description here

  1. Configure the script in the package.json file

Let the production.config.js be found when the npm run build command is
executed Let the dev.config.js be found when the npm run dev command is executed
Insert picture description here

    "scripts": {
    
    
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack --config ./build/production.config.js",
        "dev": "webpack-dev-server --open --config ./build/dev.config.js"
    },

After this, the webpack.config.js in the index.html directory can be deleted

That's an entry point~

Guess you like

Origin blog.csdn.net/weixin_45773503/article/details/113028906