-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-vue-i18n.js
More file actions
executable file
·130 lines (106 loc) · 3.76 KB
/
generate-vue-i18n.js
File metadata and controls
executable file
·130 lines (106 loc) · 3.76 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
#!/usr/bin/env node
/**
* Script to automatically generate vue-i18n.d.ts TypeScript definitions
* based on the structure of src/locales/en.json.
*/
import fs from "fs"
import path from "path"
import { fileURLToPath } from "url"
// Get current directory for ES modules.
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// File paths.
const EN_JSON_PATH = path.join(__dirname, "src", "locales", "en.json")
const VUE_I18N_DEFS_PATH = path.join(__dirname, "src", "vue-i18n.d.ts")
/**
* Convert a JSON object structure to TypeScript interface properties.
* @param {any} obj - The JSON object to convert.
* @param {number} indent - Current indentation level.
* @returns {string} TypeScript interface properties.
*/
function jsonToTypeScript(obj, indent = 0) {
const indentStr = " ".repeat(indent)
if (typeof obj === "string") {
return "string"
}
if (Array.isArray(obj)) {
// Handle arrays (shouldn't occur in locale files, but just in case).
return "string[]"
}
if (typeof obj === "object" && obj !== null) {
const entries = Object.entries(obj)
const properties = entries.map(([key, value]) => {
if (/^\d/.test(key)) {
key = '"' + key + '"'
}
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
// Nested object.
const nestedContent = jsonToTypeScript(value, indent + 1)
return `${indentStr}${key}: {\n${nestedContent}\n${indentStr}}`
} else {
// Simple property.
return `${indentStr}${key}: string`
}
})
return properties.join("\n")
}
return "string"
}
/**
* Generate the complete vue-i18n.d.ts file content.
* @param {Object} localeData - The parsed locale JSON data.
* @returns {string} Complete TypeScript definition file content.
*/
function generateTypeScriptDefinitions(localeData) {
const interfaceContent = jsonToTypeScript(localeData, 2) // Start with 2-level indentation for proper formatting.
return `/**
* AUTOMATICALLY GENERATED FILE - DO NOT EDIT MANUALLY
*
* This file is auto-generated by generate-vue-i18n.js script based on src/locales/en.json.
* To update this file, modify src/locales/en.json and run: npm run generate-vue-i18n.
*/
// This empty export makes TypeScript treat this file as a module.
export {}
declare module "vue-i18n" {
export interface DefineLocaleMessage {
${interfaceContent}
}
}
`
}
/**
* Main function to read en.json and generate vue-i18n.d.ts.
*/
function main() {
try {
console.log("🔍 Reading en.json file...")
// Check if en.json exists.
if (!fs.existsSync(EN_JSON_PATH)) {
console.error(`❌ Error: ${EN_JSON_PATH} not found!`)
process.exit(1)
}
// Read and parse en.json.
const rawData = fs.readFileSync(EN_JSON_PATH, "utf8")
const localeData = JSON.parse(rawData)
console.log("✅ Successfully parsed en.json")
console.log("🛠️ Generating TypeScript definitions...")
// Generate TypeScript definitions.
const typeScriptContent = generateTypeScriptDefinitions(localeData)
// Write to vue-i18n.d.ts.
fs.writeFileSync(VUE_I18N_DEFS_PATH, typeScriptContent, "utf8")
console.log("✅ Successfully generated vue-i18n.d.ts")
console.log(`📁 Written to: ${VUE_I18N_DEFS_PATH}`)
// Validate the generated file.
if (fs.existsSync(VUE_I18N_DEFS_PATH)) {
const generatedSize = fs.statSync(VUE_I18N_DEFS_PATH).size
console.log(`📊 Generated file size: ${generatedSize} bytes`)
console.log("🎉 Generation completed successfully!")
}
} catch (error) {
console.error("❌ Error generating vue-i18n.d.ts:", error.message)
process.exit(1)
}
}
// Run the script if executed directly.
main()
export { generateTypeScriptDefinitions, jsonToTypeScript, main }