打包出口文件加入hash值防止浏览器缓存
output: {
filename: "js/[name].[chunkhash].js",
}
安装CleanWebpackPlugin
代码开发过程中,打包前先清除原打包成的dist文件夹,防止打包好的js文件一直累积。
命令行输入并执行:npm install --save-dev clean-webpack-plugin
配置webpack.prod.conf.js(3.0版本之后写法略有不同,插件会根据我们的配置文件的output自动去删除出口文件夹下的文件)
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
..
module.exports = merge(baseWebpackConfig, {
plugins: [
new CleanWebpackPlugin()
]
})
热加载模块
命令行输入并执行:npm install --save-dev webpack-dev-server
在webpack.dev.conf.js填入配置信息
const path = require('path');
const merge = require('webpack-merge'); //合并
const baseWebpackConfig = require('./webpack.base.conf');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = merge(baseWebpackConfig, {
mode: 'development', //webpack4新增mode,"production" | "development" | "none"
// 源错误检查
devtool: 'inline-source-map',
output: {
filename: "js/[name].[hash].js", //热更新(HMR)不能和[chunkhash]同时使用
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
minify: {
removeComments: true, // 移除HTML中的注释
collapseWhitespace: true, // 删除空白符与换行符
},
}),
// 热更新
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
port: 3000,
contentBase: path.join(__dirname, "dist"),
compress: true,
historyApiFallback: true,
hot: true, //开启
https: false,
noInfo: true,
open: true,
proxy: {}
}
});
在package.json scripts属性添加开发模式
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"build": "webpack --config build/webpack.prod.conf.js",
},
运行npm run dev浏览器打开页面显示即代表配置成功。
加载css和less
css加载模块
命令行输入并执行:npm install style-loader css-loader postcss-loader autoprefixer --save-dev
less加载模块
命令行输入并执行:npm install less less-loader --save-dev
webpack.base.conf.js 配置
{
test: /\.css$/,
use: ['style-loader', 'css-loader',],
},
{
test: /\.less$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{
loader: "postcss-loader",//自动加前缀
options: {
plugins: [
require('autoprefixer')({
overrideBrowserslist: ['last 10 version']
})
]
}
},
{ loader: "less-loader" }
]
}
可以在src目录下新增index.less,加入样式,在index.js中导入 import './index.less';
h1{
color: red;
}
运行服务若成功修改样式代表配置成功。
sass的引入方式同less。
加载图片和字体
命令行输入并执行:npm install file-loader url-loader --save-dev
webpack.base.conf.js 配置
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'url-loader',
options: {
publicPath: '/',
name: "images/[name].[ext]",
limit: 1000
}
}]
},
{
test: /\.(woff|svg|eot|woff2|tff)$/,
use: 'url-loader',
exclude: /node_modules/
}
至此,就能进行简单的项目开发了。