Include json file in ng-packagr build

别来无恙 提交于 2021-02-18 18:09:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!