【发布时间】:2020-11-11 22:11:48
【问题描述】:
喂,
我是 webpack 的新手,经过艰苦的学习,我知道我什么都不知道 :-)。
我正在使用 React,我有 2 个问题:
- 如何在浏览器中运行我的构建版本,以进行灯塔测试。目前我正在使用 npm run dist(在 package.json 下面)。这是可行的,但我觉得这不是正确的方法,我的 dist 文件夹被删除了。如果我使用 npx create-react-app 我可以为此使用 serve -s build。
- 如果我进行 Lighthouse 性能测试,我会得到“启用文本压缩”。所以我安装了 compression-webpack-plugin 和 brotli-webpack-plugin。我现在在 dist 文件夹中有 br 和 gz 文件,但在 HTTP 响应标头中我没有得到 Content-Encoding: br or gzip 并且 lighthouse 仍然为此责备我。
package.jsong
"scripts": {
"start": "webpack-dev-server --config webpack.dev.js --open --progress --colors --hot",
"dist": "webpack-dev-server --config webpack.prod.js --open --mode production",
"build": "webpack --config webpack.prod.js"
}
webpack.common.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: {
main: "./src/index.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: {
attributes: true
}
}
]
},
{
test: /\.(svg|png|jpg|gif|webp|jpeg)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
webpack.dev.js
var path = require("path");
const { merge } = require("webpack-merge");
const common = require("./webpack.common");
module.exports = merge(common, {
mode: "development",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js",
publicPath: "/"
},
devServer: {
historyApiFallback: true,
contentBase: "./dist"
}
});
webpack.prod.js
var path = require("path");
const { merge } = require("webpack-merge");
const common = require("./webpack.common");
const CompressionPlugin = require("compression-webpack-plugin");
const BrotliPlugin = require("brotli-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = merge(common, {
mode: "production",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].[hash].bundle.js"
},
devtool: "source-map",
performance: {
hints: false
},
optimization: {
splitChunks: {
chunks: "all"
},
minimizer: [
new TerserPlugin({
parallel: true,
cache: true,
sourceMap: true
})
]
},
plugins: [
new CompressionPlugin({
filename: "[path].gz[query]",
algorithm: "gzip",
test: /\.(js|html|svg)$/,
threshold: 8192,
minRatio: 0.8
}),
new BrotliPlugin({
asset: "[path].br[query]",
test: /\.(js|html|svg)$/,
threshold: 10240,
minRatio: 0.8
})
]
});
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": [["@babel/transform-runtime"]]
}
感谢您的帮助。
【问题讨论】:
标签: reactjs webpack performance-testing lighthouse