![](/img/trans.png)
[英]How do I add WebPack polyfill to React App created with React Create App without ejecting?
[英]How to compress build files in create react app without ejecting?
我試圖弄清楚如何最好地優化我的構建文件並遇到了壓縮文本文件的概念,例如 js 和 css。從我遇到的每篇文章來看,要么假設您可以訪問 webpack 配置文件,要么您'已經被CRA開除了。 我不想。
所以我在我的 package.json 文件中添加了一個構建后腳本:
"scripts": {
"build": "npm run build --prefix client",
"prod-compress": "gzip client/build/static/js/*.js && gzip client/build/static/css/*.css",
這導致/client/build/static/js
和/client/build/static/css
文件夾如下所示:
然后我進入我的 app.js 文件並添加以下代碼:
app.get('*.js', function(req, res, next) {
req.url = req.url + '.gz';
res.set('Content-Encoding', 'gzip');
res.set('Content-Type', 'text/javascript');
next();
});
app.get('*.css', function(req, res, next) {
req.url = req.url + '.gz';
res.set('Content-Encoding', 'gzip');
res.set('Content-Type', 'text/css');
next();
});
如果我正確理解發生了什么,f/e /client/public/index.html
文件仍將引用常規.js
文件。 但是,當從服務器請求該文件時,它將使用.js.gz
文件進行響應。
如果您不介意添加新的依賴項,我建議您使用express-static-gzip它將自動為您的壓縮文件提供服務:
const express = require("express");
const expressStaticGzip = require("express-static-gzip");
const app = express();
const buildPath = path.join(__dirname, '..', 'build', 'static');
app.use("/", expressStaticGzip(buildPath);
您還可以通過傳遞選項 object 來選擇添加其他類型的壓縮,例如 brotli:
const buildPath = path.join(__dirname, '..', 'build', 'static');
app.use(
'/',
expressStaticGzip(buildPath, {
enableBrotli: true,
orderPreference: ['br', 'gz']
})
);
Brotli 為您提供比 gzip 更優化的文件,但並非所有瀏覽器都支持它。 值得慶幸的是,express-static-gzip 會根據用戶瀏覽器發送給它的Accept-Encoding/Content-Encoding
header 自動選擇要發送的正確文件。
如果你想使用 brotli,我建議你看看compress-create-react-app 。 它專為 React 應用程序而設計,但應該適用於任何文件。
免責聲明:我是 compress-create-react-app 的作者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.