Sunday, 23 April 2017

How to import javascript file in ionic2 project?

After two days of wrestling with this, could someone please explain to me how can I include a javascript file properly into an ionic application?

I have an UMD compatible javascript library (let's call it foo.js) that I would like to import in one of my directives. foo.js is not available on npm so I cannot install it.

I created a definition file for it foo.d.ts but if I import it I get the following error:

// file: foo.d.ts
declare module 'foo' { export function bar(): void; };

Inside my directive I would like to import it like this:

// file: mydir.directive.ts
import * as foo from 'foo';
// ...
ngAfterContentInit() {
    foo.bar();
}

Runtime error: Cannot find module 'foo'

If I simply reference my file in the index.html as a script and use it as a global variable (which should be my last resort) then the typescript compiler shouts that foo is not defined.

I've read the typescript module resolution docs, saw a lot of blog post about how to import third party libraries from node_modules, but I must be missing something trivial here...

My tsconfig file looks like this:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}



via zolipapa

No comments:

Post a Comment