-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
328 lines (315 loc) · 12.1 KB
/
vite.config.ts
File metadata and controls
328 lines (315 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import mdx from '@mdx-js/rollup'
import tsconfigPaths from 'vite-tsconfig-paths'
import path from "path"
import tailwindcss from "@tailwindcss/vite"
import { TanStackRouterVite } from '@tanstack/router-vite-plugin'
import fs from 'fs'
import { compression as viteCompression } from 'vite-plugin-compression2'
// Nội dung robots.txt mặc định
const defaultRobotsTxt = `# PHPure Documentation Website - robots.txt
# Cho phép tất cả robot truy cập vào tất cả các trang
User-agent: *
Allow: /
# Đảm bảo Googlebot mobile có thể truy cập
User-agent: Googlebot-Mobile
Allow: /
# Đường dẫn đến sitemap
Sitemap: https://phpure.netlify.app/sitemap.xml
# Disallow một số đường dẫn không hữu ích cho người dùng (nếu có)
# Disallow: /assets/
# Disallow: /.git/
# Disallow: /node_modules/
`;
// https://vite.dev/config/
export default defineConfig({
plugins: [
// Plugin để đảm bảo React được khởi tạo sớm trong quá trình tải
{
name: 'ensure-react-initialized',
enforce: 'pre',
transformIndexHtml(html) {
return html.replace(
'</head>',
`<script>
// Very early React initialization - basic shell to prevent errors
window.React = window.React || {};
window.React.Children = window.React.Children || {
map: function(children, func, context) { return Array.isArray(children) ? children.map(func, context) : []; },
forEach: function(children, func, context) { Array.isArray(children) && children.forEach(func, context); },
count: function(children) { return Array.isArray(children) ? children.length : 0; },
only: function() { return null; },
toArray: function(children) { return Array.isArray(children) ? children : []; }
};
window.react_production = window.react_production || {};
window.react_production.jsx = window.react_production.jsx || function() { return null; };
window.react_production.jsxs = window.react_production.jsxs || function() { return null; };
window.react_production.Fragment = window.react_production.Fragment || Symbol('Fragment');
console.debug('[Vite Plugin] Created enhanced React and react_production objects');
</script>
</head>`
);
}
},
react({
// Improve React performance with automatic babel optimizations
babel: {
plugins: [
['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }]
]
},
// Ensure consistent React version
jsxRuntime: 'automatic',
}),
mdx({
providerImportSource: '@mdx-js/react',
}),
tsconfigPaths(),
TanStackRouterVite(),
tailwindcss(),
// Cải thiện cấu hình nén - sử dụng cả gzip và brotli với mức nén cao hơn
viteCompression({
algorithm: 'gzip',
exclude: [/\.(br)$/, /\.(gz)$/],
threshold: 1024, // Giảm ngưỡng xuống 1KB để nén nhiều file hơn
compressionOptions: {
level: 9, // Mức nén cao nhất cho gzip
},
deleteOriginalAssets: false, // Giữ lại file gốc
filename: '[path][base].gz',
}),
viteCompression({
exclude: [/\.(br)$/, /\.(gz)$/],
threshold: 1024, // Giảm ngưỡng xuống 1KB
algorithm: (buf) => import('zlib').then(zlib => zlib.brotliCompressSync(buf, {
params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11 }
})),
filename: '[path][base].br',
deleteOriginalAssets: false,
}),
// Plugin phục vụ robots.txt trong môi trường phát triển
{
name: 'serve-robots-txt',
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url === '/robots.txt') {
const publicRobotsPath = path.join(__dirname, 'public/robots.txt');
if (fs.existsSync(publicRobotsPath)) {
// Phục vụ file robots.txt từ thư mục public nếu có
const content = fs.readFileSync(publicRobotsPath, 'utf-8');
res.setHeader('Content-Type', 'text/plain');
res.end(content);
} else {
// Phục vụ nội dung mặc định nếu không có file
res.setHeader('Content-Type', 'text/plain');
res.end(defaultRobotsTxt);
}
return;
}
next();
});
}
},
// Plugin tạo file SEO khi build
{
name: 'generate-seo-files',
closeBundle: async () => {
try {
// Tạo sitemap.xml
const { generateSitemap } = await import('./src/utils/generateSitemap');
generateSitemap();
// Kiểm tra xem có file robots.txt từ public/ không (nếu không, tạo mới)
const distRobotsPath = path.join('dist', 'robots.txt');
if (!fs.existsSync(distRobotsPath)) {
console.log('Không tìm thấy robots.txt từ thư mục public, tạo mới...');
fs.writeFileSync(distRobotsPath, defaultRobotsTxt);
console.log('Robots.txt đã được tạo');
} else {
console.log('Sử dụng robots.txt từ thư mục public');
}
} catch (error) {
console.error('Lỗi khi tạo file SEO:', error);
}
}
},
// Inject React initialization script
{
name: 'inject-react-globals',
transformIndexHtml(html) {
return html.replace(
'</head>',
`<script>
// Very early React initialization - basic shell to prevent errors
window.React = window.React || {};
window.React.Children = window.React.Children || {};
window.ReactDOM = window.ReactDOM || {};
// Minimal initialization to prevent undefined errors
if (!window.React.createElement) {
window.React.createElement = function() { return null; };
window.React.Fragment = Symbol('Fragment');
}
</script>
</head>`
);
},
},
// Plugin that injects a script to fix the react_production is undefined error
{
name: 'fix-react-production',
transformIndexHtml(html) {
return html.replace(
'</head>',
`<script>
// Ensure react_production exists to prevent the "react_production is undefined" error
// Đặt script này trực tiếp trong HTML để đảm bảo nó chạy sớm nhất có thể
(function() {
// Khởi tạo React Production ngay lập tức
window.react_production = window.react_production || {
Fragment: Symbol('Fragment'),
jsx: function() { return null; },
jsxs: function() { return null; },
createElement: function() { return null; }
};
// Tạo proxy để tự động tạo các thuộc tính không xác định
window.react_production = new Proxy(window.react_production, {
get: function(target, prop) {
// Nếu thuộc tính không tồn tại, tạo một hàm giả
if (target[prop] === undefined) {
if (typeof prop === 'string') {
console.warn('[React Init] Accessing undefined property: ' + prop);
return function() { return null; };
}
}
return target[prop];
}
});
console.log("[Vite Plugin] Created enhanced react_production object");
})();
</script>
</head>`
);
}
},
// Browser-specific fixes cho Firefox
{
name: 'firefox-specific-fixes',
transformIndexHtml(html) {
return html.replace(
'</head>',
`<script>
// Firefox-specific fixes for react_production
(function() {
// Firefox thường có vấn đề với thứ tự tải module, khiến react_production bị undefined
// Sử dụng MutationObserver để khắc phục sự cố khi DOM thay đổi
if (typeof MutationObserver === 'function') {
var observer = new MutationObserver(function(mutations) {
if (!window.react_production) {
// Nếu react_production bị reset thành undefined, tạo lại nó
console.warn('[Firefox Fix] Detected react_production is undefined, restoring');
window.react_production = window.react_production || {};
window.react_production.jsx = function() { return null; };
window.react_production.jsxs = function() { return null; };
window.react_production.Fragment = Symbol('Fragment');
}
});
// Theo dõi các thay đổi trong DOM
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
// Ngừng quan sát sau 10 giây để tránh ảnh hưởng đến hiệu suất
setTimeout(function() {
observer.disconnect();
}, 10000);
}
})();
</script>
</head>`
);
}
}
],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
dedupe: ['react', 'react-dom'], // Ensure only one copy of React is used
},
build: {
// Use the most conservative minification option
minify: process.env.NODE_ENV === 'production' ? 'terser' : false,
terserOptions: {
compress: {
drop_console: false, // Keep console logs during debugging
drop_debugger: false,
pure_getters: false,
keep_classnames: true,
keep_fnames: true, // Keep function names to avoid minification issues
passes: 1, // Use minimal passes
sequences: false, // Be conservative with optimizing sequences
},
mangle: {
keep_classnames: true,
keep_fnames: true, // Important to keep function names for React
module: false, // Don't mangle module-specific code
properties: false, // Don't mangle property names
},
format: {
comments: 'some', // Keep some comments
ecma: 2015, // Safer target
},
},
rollupOptions: {
// Explicitly list React as an external dependency to avoid duplication
external: [],
output: {
manualChunks: {
'vendor': [
'react',
'react-dom',
'react-dom/client',
'scheduler'
],
'ui-vendor': [
'@tanstack/react-router',
'framer-motion',
'i18next',
'react-i18next'
],
'syntax': ['react-syntax-highlighter'],
},
inlineDynamicImports: false,
// More predictable chunk naming for better imports
entryFileNames: 'assets/[name].js',
chunkFileNames: 'assets/[name].[hash].js',
assetFileNames: 'assets/[name].[ext]',
},
},
// Use source maps during development only
sourcemap: process.env.NODE_ENV !== 'production',
target: 'es2015', // Use a more conservative target for wider compatibility
commonjsOptions: {
include: [/node_modules/],
transformMixedEsModules: true, // Important for React
}
},
define: {
// Define global constants to help with React's process.env checks
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
// Ensure React's development checks are properly disabled in production
__DEV__: process.env.NODE_ENV !== 'production',
},
// Optimization options
optimizeDeps: {
include: ['react', 'react-dom', 'react-dom/client'],
esbuildOptions: {
define: {
global: 'globalThis' // Fix issues with global in some packages
},
// Less aggressive optimizations
treeShaking: false,
minify: false,
}
},
})