问题
I want to import json file into my Angular 5 app and then build a lib. I can do the first part by including this code
declare module "*.json" {
const value: any;
export default value;
}
to typings.d.ts
, but when I try to build it it fails with error
Cannot find module '../../assets/locale-en.json'.
Any way to fix it?
回答1:
In the end I just wrote script to convert json
file to ts
file and added it to script command for packagr build in package.json
.
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"
}
dcript file
#!/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]);
}
回答2:
Try replacing
import * as locale from '../../assets/locale-en.json';
with
const locale = require('../../assets/locale-en.json');
In your tsconfig.lib.json
{
"compilerOptions": {
...
"declaration": false,
...
}
来源:https://stackoverflow.com/questions/50369248/include-json-file-in-ng-packagr-build