search
HomeWeb Front-endJS Tutorialvue study notes (1)--webpack study

vue study notes (1)--webpack study

Mar 31, 2018 am 10:11 AM
webnotes

Before learning vue, first learn the front-end packaging tool-webpack. This article shares the learning about webpack. Friends who are interested can take a look.

Recently, vue has been used in the project, and I have been hearing about its name for a long time. , but I know very little about it, so I took this opportunity to learn about vue.
Before learning vue, I first learned the front-end packaging tool-webpack, which is currently a very excellent and widely used packaging tool. Follow the official webpack tutorial to learn, but the official tutorial is currently based on webpack3, and the actual use is webpack4. There are some big differences at present, and I have also made some summaries. I will make a simple record here to facilitate future review and study.

一webpack concept

Webpack is a static compilation tool (pre-compilation) [static module bundle], which is different from seaJs and requireJS (online compilation), similar to the difference between javac and jit
Several concepts in webpack

  • Entry

## Entry file, webpack compiled entry, webpack searches all The dependent root will eventually associate all dependencies

  • output

Edit result (bundles) output location , and how to name the output results, etc.

  • loader

  • ##webpack is used to process various files, loader can process and use All files introduced by import (theoretically). The loader needs to be configured in module.rules. It has two required attributes: test (which files to process) and use (which loader to use). If the configuration is wrong, webpack will report an error

  • plugin

  • Plugin is used to handle various tasks. Its scope and role are larger than loader. When using it, you need to use require() to introduce it and add it to in plugins. If you use the plug-in multiple times for different purposes, you need to use new to initialize the plug-in

Separation of two environments

The webpack.DefinePlugin plug-in is used in webpack3 to achieve separation of different environments: development and production

new webpack.DefinePlugin({
    //许多 library 将通过与 process.env.NODE_ENV 环境变量关联,以决定 library 中应该引用哪些内容
     // 在webpack4中mode会自动设置该信息,废弃该配置
    "process.env.NODE_ENV": JSON.stringify("development")
})

Using this method in webpack4 is no longer valid, and you need to use the newly provided mode to specify different environments.

Mode is divided into development and production, and one must be set, otherwise an error message will be reported.

// 环境设置,webpack4必须有该值,使用该属性来设置不同的环境,目前有development和production两种,也可以使用:--mode development设置
// process.env.NODE_ENV会被该设置覆盖
mode:"development",

Three source map

Eval is used by default in webpack4, and the default settings can be changed by setting devtool: "inline-source-map". It is recommended to use "source-map" in the production environment

Four code separation

4.1 Separate CSS, etc.

Use the plugin extract-text-webpack-plugin to separate css and js separation. Official example:

https://doc.webpack-china.org...

The specific settings are as follows:

// 将CSS分离 https://doc.webpack-china.org/plugins/extract-text-webpack-plugin
const ExtractTextPlugin = require("extract-text-webpack-plugin");
//使用extractTextPlugin就不能在单独使用style-loader
config.module:{
     rules:[
      {
        test:/\.css$/,
        use : ExtractTextPlugin.extract({
            fallback : "style-loader",
            //这样使用会出现url()解析路径错误的问题
            //use : "css-loader"
            //使用该方式解决url()路径问题
            use:[
                {
                    loader:"css-loader",
                    options:{
                        //用于解决url()路径解析错误
                        url:false,
                        minimize:true,
                        sourceMap:true
                    }
                }
                ]
            })
        },  
    ]
}

4.2 Split the public module

Since CommonChunkPlugin has been replaced by webpack4 Deprecated, webpack4 recommends using SplitChunkPlugin to extract public modules. Since the webpack official website (https://webpack.js.org)..., the online information introduction is not very detailed. Based on the online search results, the separation of public modules has finally been achieved, but there are still many questions that have not been resolved. Still need to find relevant information.

You can refer to the official example: https://github.com/webpack/we...

The specific configuration is as follows:
There are two ways to use SplitChunkPlugin:

1. Optimization .splitChunks

optimization: {
        //提取公共模块,webpack4去除了CommonsChunkPlugin,使用SplitChunksPlugin作为替代
        //主要用于多页面
        //例子代码 https://github.com/webpack/webpack/tree/master/examples/common-chunk-and-vendor-chunk
        //SplitChunksPlugin配置,其中缓存组概念目前不是很清楚
        splitChunks: {
            // 表示显示块的范围,有三个可选值:initial(初始块)、async(按需加载块)、all(全部块),默认为all;
            chunks: "all",
            // 表示在压缩前的最小模块大小,默认为0;
            minSize: 30000,
            //表示被引用次数,默认为1
            minChunks: 1,
            //最大的按需(异步)加载次数,默认为1;
            maxAsyncRequests: 3,
            //最大的初始化加载次数,默认为1;
            maxInitialRequests: 3,
            // 拆分出来块的名字(Chunk Names),默认由块名和hash值自动生成;设置ture则使用默认值
            name: true,
            //缓存组,目前在项目中设置cacheGroup可以抽取公共模块,不设置则不会抽取
            cacheGroups: {
                //缓存组信息,名称可以自己定义
                commons: {
                    //拆分出来块的名字,默认是缓存组名称+"~" + [name].js
                    name: "test",
                    // 同上
                    chunks: "all",
                    // 同上
                    minChunks: 3,
                    // 如果cacheGroup中没有设置minSize,则据此判断是否使用上层的minSize,true:则使用0,false:使用上层minSize
                    enforce: true,
                    //test: 缓存组的规则,表示符合条件的的放入当前缓存组,值可以是function、boolean、string、RegExp,默认为空;
                    test:""
                },
                //设置多个缓存规则
                vendor: {
                    test: /node_modules/,
                    chunks: "all",
                    name: "vendor",
                    //表示缓存的优先级
                    priority: 10,
                    enforce: true
                }
            }
        }
    }

Second type: new webpack.optimize.SplitChunksPlugin

The specific configuration is the same as optimization.splitChunks
Five hot replacement

Use the following configuration to implement:

Use the following configuration in webpack3

//查看要修补(patch)的依赖,被optimization.namedModules代替,development模式下默认开启,显示模块的相对路径
new webpack.NamedModulesPlugin(),
// 热替换插件
new webpack.HotModuleReplacementPlugin(),

In webpack4, NamedModulesPlugin has been set as the default setting and will be automatically turned on in development mode. There is no need to configure this item

六treeshaking

webpack4 does not use Tree shaking in development mode and is only enabled in production mode. You can use uglifyjs-webpack-plugin to compress obfuscated code

7 Lazy loading

Use import() to introduce the required modules. This part is called in the method, not at the beginning of js.

It is recommended to use the lazy loading implementation that comes with vue, react and other frameworks




##

The above is the detailed content of vue study notes (1)--webpack study. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)