An external module without an import statement in Typescript

When you add instructions importto your Typescript file, this file is considered an external module. So this is not a problem:

File.1.ts

import { Type } from '...';
let whatever = 123;
...

File.2.ts

import { Type } from '...';
let whatever = 234;
...

So it works. But at the moment when these two statements are deleted import, these files are no longer considered modules, and both variables with the same name become global, interfering with each other.

Question

How to force modulate a source file that does not have any import statements?

+4
source share
2 answers

It takes importor exportsomething. I suggest exporting the value undefined:

export let undefined;

.

+2

hacky, ...

:

,
 
  ,
 
  , tsc

...
 ..pass
 ... /

... - ?

// file: notamoduleA.ts:
let x = "x";
(global as any).x = x;

// file: notamoduleB.ts:
let x = "y";
(global as any).x = x;

?

// file: index.ts:

import * as ts from "typescript";
import * as fs from "fs";

eval(
    ts.transpileModule(
        fs.readFileSync(
            "./external/notamoduleA.ts", "utf8")+
             "\n export = {name: 'A'}",{
                 // options ...
             }             
    ).outputText
);

console.log((global as any).x);

eval(
    ts.transpileModule(
        fs.readFileSync(
            "./external/notamoduleB.ts", "utf8")+
             "\n export = {name: 'B'}",{
                 // options ...
             }             
    ).outputText
);

console.log((global as any).x);

,
  script ?

0

Source: https://habr.com/ru/post/1664657/


All Articles