Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS1148 ~ How to "import" with --module: "none" and typescript 2.x

I'm currently working on a project with some legacy javascript. The application does not include a module loader, it just puts everything as a global into the window object. Touching the legacy code and including a module loader is sadly not a viable option for me.

I want to use typescript for my own code. I set the typescript compiler-option

module : "none"

in my tsconfig.json and I only used namespaces to organize my own code. Worked well so far.

.. until now:

import * as Rx from 'rxjs';
..
Rx.Observable.from(['foo',bar']);
...
// Results in TypeScript-Error: 
//   TS1148:Cannot use imports, exports, or module augmentations when '--module' is 'none'. 

With the "module-none" option set, you can't use import statements in your typescript.
How can you include external libs with this typescript setup?
Is it even possible?

What I tried so far (to include Rx from the RxJs-Library)

///<reference path="../node_modules/rxjs/Rx.d.ts" />
..
Rx.Observable.from(['foo',bar']);
...
// Results in TypeScript-Error -> TS2304:Cannot find name 'Rx'. 

In this Related Question, Kirill Dmitrenko sugested using an reference-tag, didn´t work for me.

I ended up with this construct.

declare const Rx: any;

Works, but you loose type-checks and intellisense :(

like image 768
J.Doe Avatar asked Jun 23 '17 23:06

J.Doe


People also ask

How do I import all modules into a directory in TypeScript?

To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .

How do I import items into TypeScript?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.

Does TypeScript support es2020?

TypeScript 3.8 supports es2020 as an option for module and target . This will preserve newer ECMAScript 2020 features like optional chaining, nullish coalescing, export * as ns , and dynamic import(...) syntax.


1 Answers

Create a global declaration for Rx which is the type of the RxJS exports, like so:

import * as RxJS from "rxjs";

declare global {
    const Rx: typeof RxJS;
}

export {};

Save it to a file (e.g. global.d.ts) and then add that to the include array of tsconfig.json.

like image 59
Oden Avatar answered Sep 30 '22 14:09

Oden