TopDev

Cách tối ưu hóa cấu hình dự án React với CRACO như thế nào

minhu 📖 2 phút đọc

Việc tối ưu hóa cấu hình dự án React sử dụng CRACO (Create React App Configuration Override) giúp bạn tùy chỉnh webpack, babel, postcss… mà không cần eject. Dưới đây là cách tối ưu hóa cấu hình dự án React dùng CRACO theo từng mục tiêu cụ thể:



🔧 1. Cài đặt CRACO#

Nếu bạn chưa cài:

npm install @craco/craco --save

Rồi chỉnh sửa trong package.json:

"scripts": { "start": "craco start", "build": "craco build", "test": "craco test" }

Tạo file craco.config.js ở root của dự án.



🚀 2. Tối ưu hóa hiệu suất build (Webpack)#

` // craco.config.js const TerserPlugin = require('terser-webpack-plugin');

module.exports = { webpack: { configure: (webpackConfig) => { // Giảm kích thước bundle webpackConfig.optimization = { minimize: true, minimizer: [ new TerserPlugin({ terserOptions: { compress: { drop_console: true, // loại bỏ console.log trong production }, }, }), ], }; return webpackConfig; }, }, }; `



🎨 3. Tùy chỉnh Babel (hỗ trợ Decorators, Plugins, v.v.)#

module.exports = { babel: { plugins: [ ['@babel/plugin-proposal-decorators', { legacy: true }], ['@babel/plugin-proposal-class-properties', { loose: true }], ], }, };



🌈 4. Tùy chỉnh Tailwind CSS (nếu dùng)#

module.exports = { style: { postcss: { plugins: [require('tailwindcss'), require('autoprefixer')], }, }, };



🧠 5. Alias để dễ import (ví dụ: @components)#

` const path = require("path");

module.exports = { webpack: { alias: { "@components": path.resolve(__dirname, "src/components/"), "@utils": path.resolve(__dirname, "src/utils/") } } }; `

Sau đó, bạn có thể: import Button from '@components/Button';



📦 6. Tách mã (code splitting)#

React đã hỗ trợ sẵn qua React.lazy()Suspense. Kết hợp với cấu hình Webpack tốt sẽ giúp hiệu quả hơn.

const LazyComponent = React.lazy(() => import('./components/LazyComponent'));



📁 7. Bỏ source map trong Production để bảo mật và giảm dung lượng#

module.exports = { webpack: { configure: (webpackConfig) => { if (process.env.NODE_ENV === 'production') { webpackConfig.devtool = false; } return webpackConfig; }, }, };



📊 8. Phân tích bundle#

npm install source-map-explorer --save-dev

"scripts": { "analyze": "source-map-explorer 'build/static/js/*.js'" }



✅ Tổng kết:#

Tùy theo mục tiêu tối ưu (hiệu suất, bảo mật, cấu trúc import, build nhỏ gọn…), bạn có thể kết hợp nhiều cách trên. CRACO rất linh hoạt và phù hợp khi bạn không muốn eject khỏi CRA.



Nếu bạn muốn, mình có thể giúp bạn viết sẵn file craco.config.js tối ưu chuẩn cho production. Bạn đang dùng Tailwind, TypeScript hay thư viện nào đặc biệt không?

Bài liên quan trong #ReactJS

✓ Đã sao chép link