1.安装依赖

注意:webpack5已经弃用看url-loader了,所以这里不需要安装。

2.准备三张图片

  • src\image\image1.jpg
  • src\image\image2.jpg
  • src\image\image3.jpg

3.index.html

src\index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <div id="box1"></div>
  9. <div id="box2"></div>
  10. <div id="box3"></div>
  11. <img src="./image/image1.jpg" alt="">
  12. <img src="./image/image2.jpg" alt="">
  13. <img src="./image/image3.jpg" alt="">
  14. </body>
  15. </html>

4.index.less

src\index.less

#box1 {
  width: 854px;
  height: 500px;
  background-image: url("./image/image1.jpg");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

#box2 {
  width: 854px;
  height: 500px;
  background-image: url("./image/image2.jpg");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

#box3 {
  width: 854px;
  height: 500px;
  background-image: url("./image/image3.jpg");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

5.index.js

src\index.js

import './index.less'

6.打包配置

6.1.普通图片

这里只是简单的加一个样式loder即可,但是这样编译之后,index.html文件中的图片是没有编译的。
webpack.config.js

const { resolve } = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        filename: 'built.js',
        path: resolve(__dirname, 'build')
    },
    module: {
        rules: [
            { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
        })
    ],
}

6.2.index.html中的图片

只需要指定html-lodaer即可。

npm i html-loader -D

webpack.config.js

const { resolve } = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
        filename: 'built.js',
        path: resolve(__dirname, 'build')
    },
    module: {
        rules: [
            { test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
            { test: /\.html$/, loader: 'html-loader' },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
        })
    ],
}