webpack4 配置
安装 webpack4
yarn add webpack webpack-cli -D
新建 webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "webpack demo project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack" // 增加
},
"author": {
"name": "wubh2012"
},
"license": "MIT",
"devDependencies": {
"webpack": "^4.39.2",
"webpack-cli": "^3.3.6"
}
}
使用 命令yarn build
或 npx run build
运行
处理 CSS, sass, 图片等资源
yarn add style-loader css-loader -D
yarn add node-sass sass-loader -D
yarn add file-loader -D
配置 webpack.config.js
{
test: /\.css|.scss|.sass$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: devMode,
},
},
'css-loader',
'sass-loader',
]},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
独立出css文件,并压缩
yarn add mini-css-extract-plugin -D
yarn add optimize-css-assets-webpack-plugin -D
yarn add cssnano -D
webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
plugins:[
// 独立css文件
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
}),
// 压缩css
new OptimizeCSSAssetsPlugin({
assetNameRegExp: /\.css\.*(?!.*map)/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
canPrint: true
})
]
配置热更新部署
yarn add html-webpack-plugin -D
yarn add clean-webpack-plugin -D
yarn add webpack-dev-server -D
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"start": "webpack-dev-server",
"build": "webpack"
},
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const APPDIR = 'src/';
module.exports = {
mode: 'development',
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, APPDIR, 'index.html'),
filename: 'index.html',
inject: 'body'
})
],
运行 yarn start
,然后用浏览器打开 localhost:8080
使用 babel 处理JS
yarn add @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/runtime babel-loader -D
// webpack.config 配置
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime']
}
}
}