如何用static-i18n动态设置HTML lang属性与base标签href值
解决static-i18n多语言文件的lang属性与base href配置问题
问题背景
使用static-i18n工具从含翻译键的模板生成多语言单文件着陆页,主语言(英文)文件输出到./dist/index.html,其他语言(如波兰语)输出到./dist/pl/index.html。需要实现:
- 为每个语言文件的
<html>标签设置对应lang属性值 - 主语言文件的
<base href>设为./,子目录语言文件设为../,确保资源加载正常 - 不修改现有翻译键(如
<div i18n>main.title</div>)的写法
解决方案:Post-Build脚本批量处理
通过编写Node.js脚本,在static-i18n生成文件后,自动遍历并修改目标文件的lang属性和base标签。
步骤1:在模板HTML中预留占位符
修改./src/index.html模板,为<html>的lang和<base>的href设置占位符(static-i18n不会处理这些内容,因为它们没有i18n属性):
<html lang="__LANG__"> <head> <meta charset="UTF-8"> <base href="__BASE_HREF__"> <!-- 其他头部内容 --> </head> <!-- 页面主体内容 -->
步骤2:编写Post-Build脚本
在项目根目录创建post-build.js脚本:
const fs = require('fs'); const path = require('path'); const distDir = './dist'; // 处理主语言文件(en) const mainIndexPath = path.join(distDir, 'index.html'); if (fs.existsSync(mainIndexPath)) { let content = fs.readFileSync(mainIndexPath, 'utf8'); content = content.replace('__LANG__', 'en').replace('__BASE_HREF__', './'); fs.writeFileSync(mainIndexPath, content); } // 处理子目录语言文件 const langDirectories = fs.readdirSync(distDir, { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name); langDirectories.forEach(langCode => { const langIndexPath = path.join(distDir, langCode, 'index.html'); if (fs.existsSync(langIndexPath)) { let content = fs.readFileSync(langIndexPath, 'utf8'); content = content.replace('__LANG__', langCode).replace('__BASE_HREF__', '../'); fs.writeFileSync(langIndexPath, content); } });
步骤3:配置npm脚本自动执行
修改package.json的scripts,添加postbuild脚本(npm会在build脚本执行完成后自动运行postbuild):
{ "scripts": { "build": "static-i18n --fixPaths false --selector [i18n] --useAttr false -o ./dist -l en -i en -i pl ./src", "postbuild": "node post-build.js" } }
运行验证
执行npm run build,static-i18n生成文件后,脚本会自动修改:
./dist/index.html:<html lang="en">、<base href="./">./dist/pl/index.html:<html lang="pl">、<base href="../">
这种方案完全不影响现有翻译键的使用逻辑,仅通过后续批量处理完成配置需求,适配Apache等简易文件服务器的部署场景。
内容的提问来源于stack exchange,提问作者Kamil Kiełczewski
相关产品推荐
相关产品推荐

