Webpack packages image and other resources and devserver configuration

Front end_ CV Engineer 2021-10-14 07:59:31

Package image resources

stay webpack.config.js Add the following configuration under the file

// Process image resources
test: /\.(jpg|png|gif)$/,
loader: 'url-loader',
options: {
// The size of the picture is less than 8kb, Will be base64 Handle
// advantage : Reduce the number of requests ( Reduce server pressure )
// shortcoming : The image will be bigger ( File requests are slower )
limit: 8 * 1024,

Through you npm Commands required for installation loader
npm i url-loader file-loader -D

Be careful : Through the above configuration, only the picture resources introduced in the style file can be packaged ; Can't handle html in img picture

Need to install html-loader, And add the following configuration

test: /\.html$/,
// Handle html Of documents img picture ( Responsible for the introduction img, To be able to be url-loader To deal with )
loader: 'html-loader',
problem : because url-loader By default es6 Modular analysis , and html-loader The introduction of the picture is commonjs
There's a problem with parsing :[object Module]; After packing html There will be problems with the introduction of pictures in the file
solve : close url-loader Of es6 modularization , Use commonjs analysis

close url-loader Of es6 modularization , Need to be in url-loader Configured options Add the following below

esModule: false,
The name of the packaged image resource will be in the form of hash value , Can pass name: '[hash:10].[ext]', Rename the packed picture
[hash:10] Take pictures of hash Before 10 position
[ext] Take the original extension of the file

Package other resources

For other resources ( except html/js/css Resource unexpected resource ), Resources such as fonts and icons

  Add the following , exclude css/js/html resources , adopt name Rename the resource file

exclude: /\.(css|js|html|less)$/,
loader: 'file-loader',
options: {
name: '[hash:10].[ext]'

devServer To configure

In the development environment , You usually use devServer Realize the process of automatic compilation

Development server devServer: For automation ( Automatic compilation , Open browser automatically , Refresh browser automatically ~~)
characteristic : Only compile and package in memory , There won't be any output

devServer The configuration is as follows

devServer: {
// Path after project construction
contentBase: resolve(__dirname, 'build'),
// start-up gzip Compress
compress: true,
// Port number
port: 3000,
// Open browser automatically
open: true

start-up devServer Instructions for :
npx webpack-dev-server
After startup, change the project code every time , It will automatically package and compile the project files

Please bring the original link to reprint ,thank
Similar articles