1- import { defineConfig , splitVendorChunkPlugin } from 'vite' ;
2- import react from '@vitejs/plugin-react' ;
3- import checker from 'vite-plugin-checker' ;
1+ import { defineConfig , splitVendorChunkPlugin } from "vite" ;
2+ import react from "@vitejs/plugin-react" ;
3+ import checker from "vite-plugin-checker" ;
4+ import legacy , { cspHashes } from "@vitejs/plugin-legacy" ;
5+ import { readFileSync , writeFileSync } from "fs" ;
6+ import path from "path" ;
7+
8+ function cspPlugin ( ) {
9+ return {
10+ name : "csp-plugin" ,
11+ closeBundle ( ) {
12+ // Path to the generated HTML file after build
13+ const htmlFilePath = path . resolve ( __dirname , "build/index.html" ) ;
14+
15+ // Read the HTML file content
16+ let htmlContent = readFileSync ( htmlFilePath , "utf-8" ) ;
17+
18+ const scriptHashes = cspHashes
19+ ? cspHashes . map ( ( id ) => {
20+ return `'sha256-${ id } '` ;
21+ } )
22+ : [ ] ;
23+
24+ // Create the CSP header
25+ const cspHeader = `default-src 'self'; script-src 'self' ${ scriptHashes . join (
26+ " "
27+ ) } `;
28+
29+ // Insert the CSP meta tag in the HTML <head> section
30+ htmlContent = htmlContent . replace (
31+ / < m e t a h t t p - e q u i v = " C o n t e n t - S e c u r i t y - P o l i c y " > / ,
32+ `<meta http-equiv="Content-Security-Policy" content="${ cspHeader } ">`
33+ ) ;
34+
35+ // Write the updated HTML back to the file
36+ writeFileSync ( htmlFilePath , htmlContent ) ;
37+
38+ console . log ( "CSP header added to HTML:" , cspHeader ) ;
39+ } ,
40+ } ;
41+ }
442
543export default defineConfig ( ( env ) => {
644 return {
@@ -23,12 +61,17 @@ export default defineConfig((env) => {
2361 } ,
2462 plugins : [
2563 react ( ) ,
26- env . mode !== 'test' && checker ( {
27- typescript : true ,
28- eslint : {
29- lintCommand : 'eslint --max-warnings=0 src' ,
30- } ,
64+ legacy ( {
65+ targets : [ 'edge 18' ] ,
3166 } ) ,
67+ cspPlugin ( ) ,
68+ env . mode !== 'test' &&
69+ checker ( {
70+ typescript : true ,
71+ eslint : {
72+ lintCommand : 'eslint --max-warnings=0 src' ,
73+ } ,
74+ } ) ,
3275 splitVendorChunkPlugin ( ) ,
3376 ] ,
3477 test : {
0 commit comments