|
1 | 1 | 'use server'; |
2 | 2 |
|
3 | | -import { readFileSync, appendFileSync } from 'fs'; |
4 | | -import { isServer, get } from './helper'; |
| 3 | +import { readFileSync, appendFileSync, mkdirSync, existsSync } from 'fs'; |
| 4 | +import { isServer } from './helper'; |
| 5 | +import { join, dirname } from 'path'; |
| 6 | + |
| 7 | +function findNextJsProjectRoot(startPath: string): string | null { |
| 8 | + let currentPath = startPath; |
| 9 | + for (let i = 1; i <= 6; i++) { |
| 10 | + if ( |
| 11 | + existsSync(join(currentPath, 'package.json')) && |
| 12 | + (existsSync(join(currentPath, 'next.config.js')) || existsSync(join(currentPath, 'next.config.mjs'))) |
| 13 | + ) { |
| 14 | + return currentPath; |
| 15 | + } |
| 16 | + currentPath = dirname(currentPath); |
| 17 | + } |
| 18 | + return null; |
| 19 | +} |
5 | 20 |
|
6 | 21 | export const buildIn = (styleSheet: string, global?: string) => { |
7 | | - const styleFilePath = get.dir(__dirname, '../../core/styles/style.module.css'); |
8 | | - const globalFilePath = get.dir(__dirname, '../../core/styles/global.css'); |
| 22 | + const currentDir = __dirname; |
| 23 | + const projectRoot = findNextJsProjectRoot(currentDir); |
| 24 | + |
| 25 | + if (!projectRoot) { |
| 26 | + console.error('Next.js project root not found'); |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + const srcDir = join(projectRoot, 'src'); |
| 31 | + let stylesDir: string; |
| 32 | + |
| 33 | + if (existsSync(srcDir)) { |
| 34 | + stylesDir = join(srcDir, 'styles'); |
| 35 | + } else { |
| 36 | + stylesDir = join(projectRoot, 'styles'); |
| 37 | + } |
| 38 | + |
| 39 | + const styleFilePath = join(__dirname, '../../core/styles/style.module.css'); |
| 40 | + const globalFilePath = join(stylesDir, 'typedcssx-global.css'); |
| 41 | + |
9 | 42 | const filePath = global === '--global' ? globalFilePath : styleFilePath; |
10 | 43 | const message = global === '--global' ? ' ✅ Generating global static css \n' : ' ✅ Generating module static css \n'; |
11 | 44 |
|
| 45 | + if (!existsSync(stylesDir)) { |
| 46 | + mkdirSync(stylesDir, { recursive: true }); |
| 47 | + } |
| 48 | + |
12 | 49 | if (isServer) { |
13 | 50 | try { |
14 | | - const cssData = readFileSync(filePath, 'utf-8'); |
15 | | - if (!cssData.includes(styleSheet)) { |
| 51 | + if (existsSync(filePath)) { |
| 52 | + const cssData = readFileSync(filePath, 'utf-8'); |
| 53 | + if (!cssData.includes(styleSheet)) { |
| 54 | + appendFileSync(filePath, styleSheet, 'utf-8'); |
| 55 | + console.log(message + styleSheet); |
| 56 | + } |
| 57 | + } else { |
16 | 58 | appendFileSync(filePath, styleSheet, 'utf-8'); |
17 | 59 | console.log(message + styleSheet); |
18 | 60 | } |
19 | 61 | } catch (error) { |
20 | | - console.log('write error'); |
| 62 | + console.error('Error writing to file:', error); |
| 63 | + console.error('Stack trace:', error); |
21 | 64 | } |
22 | 65 | } |
23 | 66 | }; |
0 commit comments