开发环境
const webpack = require("webpack");
const path = require('path')
module.exports = {
entry: "./src/0707/reactDemo.js",
output: {
filename: '[name]_dist.js',
path: path.resolve(__dirname, 'dist3'),
},
mode: 'development',
devtool: 'source-map',
module: {
rules: [
{
test:/.js$/,
use: 'babel-loader',
},
{
test: /.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test:/.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
{
test: /.(png|jpg|gif|jpeg)$/,
use: 'file-loader'
},
{
test: /.(png|jpg|jpeg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 10240 * 10
}
}
},
{
test: /.(woff|woff2|eot|ttf|otf)$/,
use: 'file-loader'
}
],
},
devServer: {
contentBase: './dist3',
hot: true
}
}
生产环境
const webpack = require("webpack");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');
module.exports = {
entry: "./src/0707/reactDemo.js",
output: {
filename: '[name]_[chunkhash:8].js',
path: path.resolve(__dirname, 'dist3'),
},
mode: 'production',
optimization: {
minimizer: [
new CssMinimizerPlugin(),
'...'
]
},
module: {
rules: [
{
test:/.js$/,
use: 'babel-loader',
},
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test:/.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'less-loader'
]
},
{
test: /.(png|jpg|gif|jpeg)$/,
use: {
loader: 'file-loader',
options: {
name: '[name]_[hash:8].[ext]'
}
}
},
{
test: /.(png|jpg|jpeg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 10240 * 10
}
}
},
{
test: /.(woff|woff2|eot|ttf|otf)$/,
use: 'file-loader'
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html'),
filename: 'index2.html',
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: true
}
})
]
}
参考webpack视频讲解:进入学习
自动添加CSS前缀
- 使用postcss-loader + autoprefixer
- 添加postcss.config.js 新版本直接在webpack配置文件里添加会报错,所以需要写到一个独立的配置文件里
module.exports = {
plugins: [
require('autoprefixer')({
overrideBrowserslist: ['last 2 version', '>1%', 'ios 7']
})
]
}
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader'
]
},
移动端适配 css px自动转rem
- 使用手淘lib-flexible 动态计算font-size
// 将lib-flexible静态内联到html上,因为要最先执行计算
// 在头部加入如下代码
// 使用了raw-loader,相当于在对应的位置是插入字符串
// 需注意raw-loader新老版本引入的差异