打包出口文件加入hash值防止瀏覽器緩存
output: {
filename: "js/[name].[chunkhash].js",
}
安裝CleanWebpackPlugin
代碼開(kāi)發(fā)過(guò)程中,打包前先清除原打包成的dist文件夾级历,防止打包好的js文件一直累積夕冲。
命令行輸入并執(zhí)行:npm install --save-dev clean-webpack-plugin
配置webpack.prod.conf.js(3.0版本之后寫(xiě)法略有不同,插件會(huì)根據(jù)我們的配置文件的output自動(dòng)去刪除出口文件夾下的文件)
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
..
module.exports = merge(baseWebpackConfig, {
plugins: [
new CleanWebpackPlugin()
]
})
熱加載模塊
命令行輸入并執(zhí)行: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"
// 源錯(cuò)誤檢查
devtool: 'inline-source-map',
output: {
filename: "js/[name].[hash].js", //熱更新(HMR)不能和[chunkhash]同時(shí)使用
},
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, //開(kāi)啟
https: false,
noInfo: true,
open: true,
proxy: {}
}
});
在package.json scripts屬性添加開(kāi)發(fā)模式
"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",
},
運(yùn)行npm run dev瀏覽器打開(kāi)頁(yè)面顯示即代表配置成功瞻颂。
加載css和less
css加載模塊
命令行輸入并執(zhí)行:npm install style-loader css-loader postcss-loader autoprefixer --save-dev
less加載模塊
命令行輸入并執(zhí)行: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",//自動(dòng)加前綴
options: {
plugins: [
require('autoprefixer')({
overrideBrowserslist: ['last 10 version']
})
]
}
},
{ loader: "less-loader" }
]
}
可以在src目錄下新增index.less,加入樣式豺谈,在index.js中導(dǎo)入 import './index.less';
h1{
color: red;
}
運(yùn)行服務(wù)若成功修改樣式代表配置成功。
sass的引入方式同less蘸朋。
加載圖片和字體
命令行輸入并執(zhí)行: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/
}
至此核无,就能進(jìn)行簡(jiǎn)單的項(xiàng)目開(kāi)發(fā)了扣唱。