current position:Home>Learn about the use of webpcak in Vue
Learn about the use of webpcak in Vue
2021-08-27 00:14:51 【yuobey】
One , know webpack
Webpack It's a packaging modularity JavaScript Tools for , stay Webpack All the documents in are modules , adopt Loader Convert files , adopt Plugin Inject the hook , Finally, output the file composed of multiple modules .Webpack Focus on building modular projects .
In fact, it's a packing tool that's a little overqualified , I personally think it's a set of front-end Automation 、 modularization 、 A scalable system that integrates components , You can do a series of configuration and installation according to your own needs , Finally you need to achieve the functions and packaging output .
All the documents :JavaScript、CSS、SCSS、 picture 、 Templates , stay Webpack They're all modules in their eyes , The advantage of this is that it can clearly describe the dependencies between the modules , To facilitate Webpack Combine and package modules . after Webpack To deal with , Finally, it will output the static resources that the browser can use .
stay Vue In the project ,webpack It's important , For example, pack and compress 、 Load asynchronously 、 Modular management and so on .
Two ,webpack Use
1. vue-cli 2.x And vue-cli 3.x The difference of
If used vue-cli 2.x, Then you should know that the directory it builds will contain the corresponding webpack The configuration file , But in vue-cli 3.x But you don't see one about webpack Configuration file for ,cli 3.x Provides an out of the box mode , That is, you don't need to configure webpack You can run the project , And it provides a vue.config.js Files to satisfy the developer's encapsulation of webpack Extension and modification of default configuration . Pictured (cli-3.xx To configure ):
cli 2.xx Configuration file diagram
The comparison shows that cli 3.x Remove all kinds of complicated configuration files , Unified into a separate file, allowing developers to expand the configuration of the project alone .
2. vue.config.js Configuration of
Through the comparison above , We can see clearly vue.config.js Configuration item structure of , The built project does not have this configuration file by default , Then you need to create it manually at the root . The functions and uses of common configuration items :
(1). baseurl
We go through vue-cli 3.x Successfully built and opened in browser http://localhost:8080/
Show the front page of the project . If you want to add a secondary directory to the project address now , such as :http://localhost:8080/vue/
, So we need to vue.config.js Internal configuration baseurl This one ( from Vue CLI 3.3 It has been abandoned , Please use publicPath
):
// vue.config.js
module.exports = {
...
baseUrl: 'vue',
...
}
Copy code
What has changed is webpack In profile output Of publicPath
term , At this time, when you restart the terminal and open the page again, our home page url It's going to take the form of a secondary directory .
(2). outputDir
If you want to package and output the built files to output Under the folder ( The default is dist Folder ), You can configure :
// vue.config.js
module.exports = {
...
outputDir: 'dist', // Default dist
...
}
Copy code
And then run the command npm run build
For packaging output , You will find that projects and directories will create dist Folder , It's actually changed webpack Configuration in progress output Under the path
term , Modified the output path of the file .
(3).productionSourceMap
This configuration item is used to set whether to build a build for the production environment source map, In general, in order to quickly locate the error information in the production environment , We'll all turn on source map:
// vue.config.js
module.exports = {
...
productionSourceMap: true,
...
}
Copy code
The configuration will change webpack in devtool
The value of the item source-map
.
Turn on source map after , We package the output file with js Corresponding .map file , Its use can refer to :JavaScript Source Map Detailed explanation
(4). devServer
vue.config.js It also provides devServer Item is used to configure webpack-dev-server act , So that we can configure the local server accordingly , We run... On the command line npm run serve
The corresponding order vue-cli-service serve
In fact, it is based on webpack-dev-server Open a local server , The common configuration parameters are as follows :
// vue.config.js
module.exports = {
...
devServer: {
open: true, // Do you want to open the browser page automatically
host: '0.0.0.0', // Specify to use a host. The default is localhost
port: 8080, // Port address
https: false, // Use https Provide services
// proxy: null, // string | Object Agent settings Generally handle cross domain request forwarding
proxy: {
'/repos': { // Match to /repos character string Auto forward to target Address
target: 'https://api.github.com', // Forwarding address
changeOrigin: true
// pathRewrite: {'^/api': ''} // Rewrite address
}
},
// Provides the ability to execute custom middleware before other middleware inside the server
before: app => {
// `app` It's a express example
}
}
...
}
Copy code
(5). chainWebpack
chainWebpack Configuration items allow us more granular control webpack Internal configuration , It integrates webpack-chain This plugin , This plug-in allows us to use chain operations to modify the configuration , such as :
// Used to do the corresponding merge processing
const merge = require('webpack-merge');
module.exports = {
...
chainWebpack: (config) => {
config.module.rules.delete('svg') // a key : Delete the process in the default configuration svg,
config.resolve.alias
.set('@', resolve('src'))
.set('~lib', resolve('src/common'))
.set('~com', resolve('src/components'))
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons')) // Handle svg Catalog
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
// To configure rules The rule is url-loader value
config.module
.rule('images')
.use('url-loader')
.tap(options =>
merge(options, {
limit: 5120,
})
)
},
...
}
Copy code
We can modify the above operations successfully webpack in module Configuration in item rules The rule is url-loader value , Put it limit The limit was changed to 5M, Configuration rules by icons Of svg-sprite-loader value Use The modified webpack The configuration code is as follows :
{
...
module: {
rules: [
{
/* config.module.rule('images') */
test: /.(png|jpe?g|gif|webp)(?.*)?$/,
use: [
/* config.module.rule('images').use('url-loader') */
{
loader: 'url-loader',
options: {
limit: 5120,
name: 'img/[name].[hash:8].[ext]'
}
}
]
}
]
}
...
}
Copy code
What we need to pay attention to here is that we use webpack-merge This plugin , This plug-in is used to do webpack Configuration merge , such options Other values below will not be overridden or changed . About webpack-chain The use of can refer to its github Official address :github.com/mozilla-neu…, It provides operations similar to JavaScript Set and Map The way , And a series of shorthand methods .
(6). configureWebpack
In addition to the above use chainWebpack To change webpack Outside of the internal configuration , We can also use configureWebpack To make changes , The difference between the two is chainWebpack It's chain modification , and configureWebpack More likely to replace and modify the whole . The sample code is as follows :
// vue.config.js
module.exports = {
...
// config The parameters are parsed webpack To configure
configureWebpack: config => {
// config.plugins = []; // This will directly plugins empty
// Use return An object will pass through webpack-merge A merger ,plugins Not empty
return {
plugins: []
}
}
...
}
Copy code
configureWebpack Can be an object directly , It can also be a function , If it is an object, it will directly use webpack-merge Merge it , If it's a function , You can use it directly config Parameters to modify webpack Configuration in , Or return an object to do merge Handle .
You can run... In the project directory vue inspect
To see your revised webpack Full configuration , Of course, you can also narrow down the scope of the review , such as :
# Only view plugins The content of
vue inspect plugins
Copy code
The above explains vue.config.js Some commonly used configuration item functions in , The specific configuration implementation needs to be combined with the actual project , The complete configuration items can be viewed :vue.config.js
3、 ... and , other
-
filenameHashing : By default , Generated static resources contain in their filenames hash In order to better control the cache . However , It also requires index Of HTML Be being Vue CLI Automatically generated . If you can't use Vue CLI Generated index HTML, You can set this option to
false
To turn off the file name hash . -
pages: stay multi-page Build applications in mode . Every “page” There should be a corresponding JavaScript Entrance file . Its value should be an object , Object's key It's the name of the entrance ,value yes :
One designated
entry
,template
,filename
,title
andchunks
The object of ( exceptentry
It's all optional );One specifies its
entry
String .module.exports = { pages: { index: { // page Entrance entry: 'src/index/main.js', // Template source template: 'public/index.html', // stay dist/index.html Output filename: 'index.html', // When using title Option , // template Medium title The label needs to be <title><%= htmlWebpackPlugin.options.title %></title> title: 'Index Page', // The blocks included in this page , By default, it contains // The extracted universal chunk and vendor chunk. chunks: ['chunk-vendors', 'chunk-common', 'index'] }, // When using the entry only string format , // The template will be derived as `public/subpage.html` // And if it can't be found , Just go back to `public/index.html`. // The output filename is derived as `subpage.html`. subpage: 'src/subpage/main.js' } } Copy code
-
css
css: { modules: true, sourceMap:true, // Is it CSS Turn on source map. Set to `true` Later it may affect the performance of the build . loaderOptions: { css: { localIdentName: '[name]-[hash]', camelCase: 'only' } } } Copy code
css.modules By default , Only
*.module.[ext]
The end of the file will be regarded as CSS Modules modular . Set totrue
After that, you can remove... From the file name.module
And will all*.(css|scss|sass|less|styl(us)?)
The document is regarded as CSS Modules modular .css.loaderOptions:
towards CSS dependent loader Delivery options . for example : ``` module.exports = { css: { loaderOptions: { css: { // The options here are passed to css-loader }, postcss: { // The options here are passed to postcss-loader } } } } ``` Copy code
copyright notice
author[yuobey],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827001448395j.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich