webpack5打包图片

webpack加载图片

  • 下载file-loader
npm install --save-dev file-loader
  • index.html

<html>
  <head>
    <title>起步title>
    
  head>
  <body>
    
    <script src="bundle.js">script>
  body>
html>
  • index.js
    • 导入图片,并加载到也页面中
    • 需要注意的是,webpack默认无法识别图片资源,只能通过file-loader进行配置
import _ from 'lodash'
// 导入css文件
import './index.css'
// 导入照片
import mao from './mao.jpg'
function component() {
    var element = document.createElement('div');
  
    // Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.classList.add('hello');

    // 添加图片
    const img = new Image();
    img.src = mao;
    element.appendChild(img);

    return element;
  }
  
  document.body.appendChild(component());
  • webpack.config.js
    • 在modules中配置加载图片,详细看一以下代码
const path = require('path')

module.exports = {
    // 入口文件
    entry: './src/index.js',
    // 输出文件
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    // 配置loader
    module: {
        rules: [
            // style-loader和css-loader加载css文件
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            // file-laoder加载图片
            {
                test: /\.(jpg|png|jpeg|gif|svg)$/,
                use: ['file-loader']
            }
        ]
    }
}
  • package.json
{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "private": "true",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^5.0.0",
    "file-loader": "^6.1.1",
    "style-loader": "^2.0.0",
    "webpack": "^5.1.0",
    "webpack-cli": "^4.0.0"
  },
  "dependencies": {
    "lodash": "^4.17.20"
  }
}
  • npm run build
    webpack5打包图片_第1张图片
    webpack5打包图片_第2张图片

你可能感兴趣的:(webpack,webpack,webpack-cli)