webpack+vue搭建后续,生成html,css文件剥离,清除多余文件

本文介绍了如何使用webpack+vue搭建项目,包括使用html-webpack-plugin生成HTML,通过extract-text-webpack-plugin剥离CSS文件,以及利用clean-webpack-plugin删除多余文件,确保每次编译仅保留最新版本的资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、安装html-webpack-plugin

cnpm install --save-dev html-webpack-plugin

 

将原来的index.html改成index.tmpl.html,并移除里面的script标签。

webpack.config.js引入并配置

const htmlWebpackPlugin = require('html-webpack-plugin');

plugins: [
        new htmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.tmpl.html',
			minify: {
				removeAttributeQuotes: true // 移除属性的引号
			}
        })
    ]

 

执行webpack --mode development,dits目录下就生成了编译好的index.html文件。

顺便output选项在原来基础上加上hash或chunkhash,推荐chunkhash,用来清缓存

output: {
    path: __dirname + "/dist",//打包后的文件存放的地方
    filename: "bundle-[chunkhash].js",//打包后输出文件的文件名
	publicPath: 'dist/'
  },

 

 

2、安装extract-text-webpack-plugin

cnpm install extract-text-webpack-plugin@next

因为与webpack4的兼容性问题,后面得加上@next,或者推荐使用mini-css-extract-plugin,但没有找到从vue文件剥离css的配置,暂时还使用老的插件

针对vue文件进行配置

const ExtractTextPlugin = require('extract-text-webpack-plugin');

          {
   				test: /\.vue$/, 
				loader: 'vue-loader',
				options: {
                    loaders: {
                        css: ExtractTextPlugin.extract({
                            use: ['css-loader'],
                            fallback: 'vue-style-loader' 
                        })
                    }
				}	
			}

new ExtractTextPlugin('[name]-[chunkhash].css')

执行webpack --mode development,dits目录下就生成了剥离出来的css文件

3、使用了hash,每次编译都会生成不同的文件,为了删除多余的文件,引入clean-webpack-plugin插件

cnpm install --save-dev clean-webpack-plugin
const CleanWebpackPlugin = require("clean-webpack-plugin");

new CleanWebpackPlugin('dist/*.*', {
			root: __dirname,
			verbose: true,
			dry: false
		})

执行webpack --mode development,dits目录下之前生成的文件已删除,只保留当前版本的文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值