|
| 1 | +import chokidar from 'chokidar'; |
| 2 | +import path from 'path'; |
| 3 | +import { NextConfig } from 'next'; |
| 4 | +import { LangPair, translateLocaleFolder } from '@aexol/dev-translate-core'; |
| 5 | + |
| 6 | +export type DevTranslateOptions = { |
| 7 | + apiKey: string; |
| 8 | + folderName: string; |
| 9 | + lang: LangPair['lang']; |
| 10 | + localeDir: string; |
| 11 | +}; |
| 12 | + |
| 13 | +const setupFileWatcher = async (opts: { |
| 14 | + apiKey: string; |
| 15 | + folderName: string; |
| 16 | + lang: LangPair['lang']; |
| 17 | + localeDir: string; |
| 18 | +}) => { |
| 19 | + const { apiKey, folderName, lang, localeDir } = opts; |
| 20 | + const directoryToWatch = path.join(process.cwd(), localeDir, opts.folderName); |
| 21 | + const translate = async () => { |
| 22 | + const result = await translateLocaleFolder({ |
| 23 | + srcLang: { |
| 24 | + folderName, |
| 25 | + lang, |
| 26 | + }, |
| 27 | + apiKey, |
| 28 | + cwd: process.cwd(), |
| 29 | + localeDir, |
| 30 | + }); |
| 31 | + console.log(JSON.stringify(result, null, 2)); |
| 32 | + }; |
| 33 | + const watcher = chokidar.watch(directoryToWatch, { |
| 34 | + persistent: true, |
| 35 | + }); |
| 36 | + |
| 37 | + watcher.on('change', (filePath: string) => { |
| 38 | + console.log(`File changed: ${filePath}`); |
| 39 | + translate(); |
| 40 | + }); |
| 41 | + |
| 42 | + watcher.on('add', (filePath: string) => { |
| 43 | + console.log(`File added: ${filePath}`); |
| 44 | + translate(); |
| 45 | + }); |
| 46 | + |
| 47 | + watcher.on('unlink', (filePath: string) => { |
| 48 | + console.log(`File removed: ${filePath}`); |
| 49 | + translate(); |
| 50 | + }); |
| 51 | + |
| 52 | + console.log(`Watching for file changes in ${directoryToWatch}`); |
| 53 | +}; |
| 54 | + |
| 55 | +// Plugin function to be used in next.config.js |
| 56 | +export function withDevTranslate(nextConfig: NextConfig = {}, options: DevTranslateOptions): NextConfig { |
| 57 | + setupFileWatcher(options); |
| 58 | + return { |
| 59 | + ...nextConfig, |
| 60 | + webpack(config, options) { |
| 61 | + // Optionally, customize the webpack configuration |
| 62 | + |
| 63 | + // Don't forget to include other plugins' webpack modification |
| 64 | + if (typeof nextConfig.webpack === 'function') { |
| 65 | + return nextConfig.webpack(config, options); |
| 66 | + } |
| 67 | + |
| 68 | + return config; |
| 69 | + }, |
| 70 | + }; |
| 71 | +} |
0 commit comments