Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript compiler can't skip imported js file

I've just started typescript with angular2 and I've run into the following problem. I started with the angular2 quickstart project and it worked fine, until I tried to import a plain javascript file. I am using the import statement as follows

import * as myModule from './mymodule.js';

Also I added the allowJs: true to the tsconfig.json file to accept the javascript file as an import. The following error is given by the compiler:

error TS5055: Cannot write file '.../mymodule.js' because it would overwrite input file.

As far as I understand the typescript compiler should not compile this file, because it is already in javascript, but for some reason I cannot exclude this from compilation.

I tried adding the file to the exclude: [] array in tsconfig.json, but because it is imported in one of my .ts files this is not taken into consideration (at least that's what I understood from the typescript docs).

My question is how can I compile my project with that file included? Is there a setting that I'm missing? Or something wrong with my approach?

Any help or advice is appreciated as this is starting to drive me crazy

Additional info

I'm using the following tsconfig file:

{
   "compilerOptions": {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": [ "es2015", "dom" ],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
   }
}

I'm building my project running the

npm run build

from a console. Which is a script in the package.json file that looks like this:

"scripts": {
   "build": "tsc -p src/",
...

After the modifications suggested by @Seamus below, the same error happens.

But

if I just run in the console

tsc -p src/

The error I get is different:

error TS7016: Could not find a declaration file for module 'mymodule'

This looks like it find the module, if I do it manually, but then the question is, why does it not work with the npm run build? Is it doing something differently?

like image 352
zolipapa Avatar asked Mar 13 '17 13:03

zolipapa


1 Answers

The compiler option allowJs will:

Allow JavaScript files to be compiled.

For commonjs you will need a module declaration like this:

mymodule.d.ts

declare module "mymodule";

And in your source where you import:

/// <reference path="mymodule.d.ts"/>
import * as myModule from 'mymodule';

See "Working with Other JavaScript Libraries" in the documentation.

like image 193
Seamus Avatar answered Sep 30 '22 12:09

Seamus