我想将json文件导入我的Angular 5应用程序,然后构建一个lib。我可以通过包含此代码来完成第一部分
declare module "*.json" {
const value: any;
export default value;
}
到typings.d.ts
,但是当我尝试构建它时,它会失败并显示错误
Cannot find module '../../assets/locale-en.json'.
有什么方法可以解决吗?
答案 0 :(得分:2)
最后,我只是编写了将json
文件转换为ts
文件的脚本,并将其添加到脚本命令中,以便在package.json
中进行packagr构建。
package.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]);
}
答案 1 :(得分:0)
尝试更换
import * as locale from '../../assets/locale-en.json';
使用
const locale = require('../../assets/locale-en.json');
在您的tsconfig.lib.json
中{
"compilerOptions": {
...
"declaration": false,
...
}