-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvite.config.js
68 lines (56 loc) · 2.08 KB
/
vite.config.js
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
import { defineConfig } from 'vite';
import { resolve } from 'path';
import fs from 'fs';
import sass from 'sass';
import { exec } from 'child_process';
function compileSass() {
try {
const srcPath = resolve(__dirname, 'src/main.scss');
const distDir = resolve(__dirname, 'dist/');
const distPath = resolve(distDir, 'index.css');
console.log(`Compiling Sass from ${srcPath} to ${distPath}`);
// Compile Sass to CSS
const result = sass.renderSync({
file: srcPath,
outputStyle: 'compressed', // Compressed CSS output
});
// Ensure the dist directory exists
fs.mkdirSync(distDir, { recursive: true });
// Write the output CSS to the dist folder
fs.writeFileSync(distPath, result.css);
console.log('Sass compiled and CSS updated successfully.');
} catch (error) {
console.error('Sass compilation error:', error);
}
}
function viteSassWatcher() {
let serverRestarting = false;
return {
name: 'vite-sass-watcher',
apply: 'serve',
configureServer(server) {
// Watch for changes in the src directory
server.watcher.add(resolve(__dirname, 'src'));
server.watcher.on('change', (file) => {
if (file.endsWith('.scss') && !serverRestarting) {
console.log(`File changed: ${file}`);
compileSass();
serverRestarting = true;
console.log('Restarting Vite server to refresh changes...');
// Programmatically restart the server after a delay to ensure CSS is saved
setTimeout(() => {
serverRestarting = false;
exec('npx vite');
server.close(); // Close the existing server instance
}, 500);
}
});
},
buildStart() {
compileSass(); // Compile once at the start
}
};
}
export default defineConfig({
plugins: [viteSassWatcher()],
});