Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 60 additions & 14 deletions bin/micro-template-serialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,28 +57,74 @@ for (let i = 0; i < args.length; i++) {
}
}
if (!outputFile || inputFiles.length === 0) {
console.error('Usage: micro-template-serialize <input1.tmpl> ... --output templates.js [--root <dir>]');
console.error('❌ Error: Missing required arguments');
if (!outputFile) console.error(' Missing --output flag');
if (inputFiles.length === 0) console.error(' No input template files specified');
console.error('\nUsage: micro-template-serialize <input1.tmpl> ... --output templates.js [--root <dir>]');
console.error('Use --help for more information');
process.exit(1);
}

// --- テンプレートファイル読み込み ---
console.log(`🔄 Processing ${inputFiles.length} template file(s)...`);
console.log(`📁 Root directory: ${rootDir}`);
console.log(`📄 Output file: ${outputFile}`);
console.log('');

const templates = {};
for (const file of inputFiles) {
for (let i = 0; i < inputFiles.length; i++) {
const file = inputFiles[i];
// id を rootDir からの相対パス(拡張子除く)にする
const relPath = path.relative(rootDir, file);
const id = relPath.replace(path.extname(relPath), '');
const source = await fs.readFile(file, 'utf-8');
templates[id] = { source };
source.replace(/<!--meta\.(\w+)=(.+?)-->/g, (match, key, value) => {
templates[id][key] = JSON.parse(value);
return ''; // Remove the comment
});
if (!templates[id].keys) {
console.warn(`Warning: Template "${id}" does not have keys defined. Please add <!--meta.keys=["key1", "key2"]--> in the template file.`);
templates[id].keys = [];

try {
const source = await fs.readFile(file, 'utf-8');
templates[id] = { source };

// メタデータの抽出
source.replace(/<!--meta\.(\w+)=(.+?)-->/g, (match, key, value) => {
templates[id][key] = JSON.parse(value);
return ''; // Remove the comment
});

if (!templates[id].keys) {
console.warn(`⚠️ Template "${id}" does not have keys defined. Please add <!--meta.keys=["key1", "key2"]--> in the template file.`);
templates[id].keys = [];
}

console.log(`✅ [${i + 1}/${inputFiles.length}] ${file} → ${id} (${templates[id].keys?.length || 0} keys)`);
} catch (error) {
console.error(`❌ Failed to read ${file}: ${error.message}`);
process.exit(1);
}
}

const code = serializeTemplates(templates);
await fs.writeFile(outputFile, code);
console.log(`Wrote: ${outputFile}`);
console.log('\n🔄 Compiling templates...');
const startTime = Date.now();
const code = serializeTemplates(templates, {
onProgress: ({ current, total, templateId, keys }) => {
console.log(` 📝 [${current}/${total}] Compiling template: ${templateId} (${keys} keys)`);
}
});
const endTime = Date.now();

console.log(`\n💾 Writing output file...`);
try {
await fs.writeFile(outputFile, code);
const stats = await fs.stat(outputFile);
const fileSize = (stats.size / 1024).toFixed(2);

console.log(`\n✨ Successfully generated template bundle!`);
console.log(`📄 Output: ${outputFile}`);
console.log(`📆 File size: ${fileSize} KB`);
console.log(`🕰️ Compilation time: ${endTime - startTime}ms`);
console.log(`📦 Templates included: ${Object.keys(templates).length}`);
console.log('');
console.log('Usage example:');
console.log(` import { extended as template } from './${path.basename(outputFile)}';`);
console.log(` const result = template('templateId', { key: 'value' });`);
} catch (error) {
console.error(`❌ Failed to write output file: ${error.message}`);
process.exit(1);
}
34 changes: 29 additions & 5 deletions lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,39 @@

import { template, extended } from './micro-template.js';

export function serializeTemplates(target) {
export function serializeTemplates(target, options = {}) {
template.get = id => target[id].source;
template.cache.clear();

let serialized = 'const compiled = {};\n';

for (const [id, entry] of Object.entries(target)) {
const timestamp = new Date().toISOString();
let serialized = `/**
* Auto-generated by micro-template-serialize
* Generated at: ${timestamp}
* DO NOT EDIT THIS FILE MANUALLY
*
* This file contains pre-compiled templates from micro-template.js
* Source: https://github.com/cho45/micro-template.js
*/

const compiled = {};
`;

const { onProgress } = options;
const entries = Object.entries(target);

for (let i = 0; i < entries.length; i++) {
const [id, entry] = entries[i];
const keys = entry.keys || [];
console.log(`Compiling template: ${id}`);

if (onProgress) {
onProgress({
current: i + 1,
total: entries.length,
templateId: id,
keys: keys.length
});
}

const func = extended(id, keys);
const compiled = func.compiled;
serialized += `compiled['${id}'] = ` + compiled.toString().replace(/\/\/#.*/g, '') + ';\n';
Expand Down