angular - 在 ng-packagr 构建中包含 json 文件
问题描述
我想将 json 文件导入我的 Angular 5 应用程序,然后构建一个库。我可以通过包含此代码来完成第一部分
declare module "*.json" {
const value: any;
export default value;
}
to typings.d.ts
,但是当我尝试构建它时,它失败并出现错误
Cannot find module '../../assets/locale-en.json'.
有什么办法解决吗?
解决方案
最后,我只是编写了将json
文件转换为ts
文件的脚本,并将其添加到用于 packagr build in 的脚本命令中package.json
。
包.json
scripts: {
"packagr": "node ./scripts/update-component-lib-locale-json.js && ng-packagr -p ng-package.json && rm -rf lib/node_modules && rm lib.tgz"
}
脚本文件
#!/usr/bin/env node
var fs = require('fs');
var Mustache = require('mustache');
var locales = [
'en',
];
/**
* Updates the component library's locale JSON with the shared locale JSON
* of the parent project.
*
* NOTE: This has been implemented as a workaround for not being able to
* dynamically load the shared locale JSON file in the component library's
* `locale-<locale>.ts` file. This seems to be a limitation of `ng-packagr` and
* could be resolved in future releases, or by someone smarter than me ;)
*
* @param {string} locale - A two-character locale string (e.g. 'en').
*/
var updateComponentLibLocaleJSON = function (locale) {
locale = locale.toLowerCase().trim();
// Location of the component locale definition file for this locale (required by `ng-packagr`).
var componentLibLocaleJSONPath = './src/components/locale-' + locale + '.ts';
// Location of the generic locale definition file Mustache template.
var componentLocaleJSONTemplatePath = './src/components/locale.ts.mustache';
// Location of the shared locale JSON file for this locale.
var sharedLocaleJSONPath = './src/assets/locale-' + locale + '.json';
// Read the shared JSON for this locale, render the Mustache template with
// that JSON and save the output to the component lib's locale JSON file for
// this locale.
var sharedLocaleJSON = fs.readFileSync(sharedLocaleJSONPath).toString();
var componentLocaleJSONTemplate = fs.readFileSync(componentLocaleJSONTemplatePath).toString();
var updatedComponentLocaleJSON =
Mustache.render(componentLocaleJSONTemplate, { localeJSON: sharedLocaleJSON });
fs.writeFileSync(componentLibLocaleJSONPath, updatedComponentLocaleJSON);
};
for (var i = 0; i < locales.length; i++) {
updateComponentLibLocaleJSON(locales[i]);
}
推荐阅读
- r - 使用 geom_text 在 ggplot2 中的单个方面注释文本
- jquery - 让 Jquery 和 Bootstrap 与 Rails 6 一起工作
- python - 从python中的列表中有效地删除也在给定列表中的元素
- matlab - 在 MATLAB GUI 中的选择之间重置弹出菜单
- python - 以递归方式评估 json 的优雅方法
- vbscript - 是否有一个函数或命令可用于在我的代码中调用默认浏览器
- azure-devops - Azure DevOps:用户没有完成此操作的权限。你需要有'AddPackage'
- c# - 如何让本地数据库在客户的 PC 上工作
- elm - 用于生成变量和函数的 Elm 语法:如何区分?
- websocket - 我们可以在云中托管一个主机 websocket 服务器作为代理/中继服务器来重定向来自本地网络的 websocket 流量吗