Common JS like imports in angular

810 views Asked by At

I have a package "citation-js", which uses commonJS style import

for using it in angular I installed @types/node and then added node in types array in tsconfig.app.json

    {
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["node"],
"resolveJsonModule": true
  },
  "files": ["src/main.ts", "src/polyfills.ts"],
  "include": ["src/**/*.d.ts"]
}

I started testing the package in app.component.ts by

  ngOnInit() {
    let example = new Cite("Q21972834");

    let output = example.format("bibliography", {
      format: "html",
      template: "apa",
      lang: "en-US",
    });

    console.log(output);
  }

After running I still get an error

ERROR in ./node_modules/@citation-js/plugin-ris/lib-mjs/spec/mixed.js
Module not found: Error: Can't resolve './additions' in '/home/inkant/citationjs/node_modules/@citation-js/plugin-ris/lib-mjs/spec'

So I looked into the package, which has

import ADDITIONS from './additions';

I notice that "./additions" is JSON file and not a JS module. Now what can I do to use this package.

To me it seems to be the difference in the imports between CommonJS and ES6 Modules.

1

There are 1 answers

0
mozpider On

I found the way to do directly import JSON into typescript. Please add the two suggested changes to you tsconfig.json / tsconfig.app.json file:

  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true
  }

citation-js package however has been developed with Browserify and does not like Typescript compiler. It does not play well with Webpack, which is the default bundler for Angular. So to use it with angular:

On the component I used window.require instead of an import or plain require again because I didn't want typescript trying to compile citation-js. I saw at the top of citation.js it included an implementation of require, which may be a browserify artifact. So bottomline is disable typescript compilation by including it in the assets