webpack从入门到精通----(二)热重载及html插件

第三课

webpack-dev-server

  1. 安装
    yarn add webpack-dev-server -D
  2. 启动
    npx webpack-dev-server
  3. 配置 webpack
module.exports = {
    devServer: { // 开发服务器的配置
        port: 3000, // 启动端口
        progress: true, // 滚动条
        contentBase: './build', // 启动服务的路径
        compress: true, //压缩
    },
    entry: './src/index.js', //入口
    ...
}
  1. 修改 package.json文件
"script": {
    "dev": "webpack-dev-server"
}

webpack-plugin

  1. 安装插件
    yarn add html-webpack-plugin -D
  2. webpack.config.js中引入和使用插件
let HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    ...,
    plugins: [ // 数组 放着所有的webpack插件
        new HtmlWebpackPlugin({
            template: './src/index.html', // 打包的模板路径
            filename: 'index.html', // 打包之后的文件名
            minify: { // 格式化html文件
                removeAttributeQuotes: true, // 去除掉双引号
                collapseWhitespace: true // 变成1行
            },
            hash: true // 会在 js后面加上 [? + 哈希]
        })
    ],
    output: {
        ...,
        filename: 'index.[hash:8].js' // 这个地方也是在名字上加上哈希 后面的:8表示8位
    }
}

最终webpack.config.js

let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    devServer: { // 开发服务器的配置
        port: 3000, // 启动端口
        progress: true, // 滚动条
        contentBase: './build', // 启动服务的路径
        compress: true //压缩
    },
    mode: 'development', // 模式 默认两种 production(会压缩js文件) development
    entry: './src/index.js', //入口
    output: { // 出口
        filename: 'bundle.[hash:8].js', // 打包后的文件名 [hash:8] 只显示8位的hash文件
        path: path.resolve(__dirname, 'build') // 路径必须是一个绝对路径
    },
    plugins: [ // 数组 放着所有的webpack插件
        new HtmlWebpackPlugin({
            template: './src/index.html', // 打包的模板路径
            filename: 'index.html', // 打包之后的文件名
            minify: {
                removeAttributeQuotes: true,
                collapseWhitespace: true
            },
            hash: true
        })
    ]
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值