我想将 json 文件导入我的 Angular 5 应用程序,然后构建一个库。我可以通过包含此代码来完成第一部分
declare module "*.json" {
const value: any;
export default value;
}
to typings.d.ts
,但是当我尝试构建它时,它失败并出现错误
Cannot find module '../../assets/locale-en.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]);
}
尝试更换
import * as locale from '../../assets/locale-en.json';
和
const locale = require('../../assets/locale-en.json');
在你的 tsconfig.lib.json
{
"compilerOptions": {
...
"declaration": false,
...
}