Why is --isolatedModules error fixed by any import?

后端 未结 3 1460
醉话见心
醉话见心 2020-12-13 08:14

In a create-react-app typescript project, I tried to write this just to test some stuff quickly:

// experiment.test.ts         


        
相关标签:
3条回答
  • 2020-12-13 08:36

    The correct way is to tell TypeScript what you want. If you don't want isolatedModules create tsconfig.json inside your test directory and add:

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "isolatedModules": false
      },
    }
    

    Adding "isolatedModules": true to the config and then cheating TypeScript checker by adding empty export {} smells bad code to me.

    0 讨论(0)
  • 2020-12-13 08:39

    Typescript treats files without import/exports as legacy script files. As such files are not modules and any definitions they have get merged in the global namespace. isolatedModules forbids such files.

    Adding any import or export to a file makes it a module and the error disappears.

    Also export {} is a handy way to make a file a module without importing anything.

    0 讨论(0)
  • 2020-12-13 08:42

    Let's try to check isolated modules. When I checked Google, there is no direct context of it.

    It basically means that you allow Typescript to compile modules in isolation.

    But it comes from Typescript and has something to do with Typescript preferring modules over namespaces.

    Modules also have a dependency on a module loader (such as CommonJs/Require.js) or a runtime which supports ES Modules. Modules provide for better code reuse, stronger isolation and better tooling support for bundling.

    Source 1

    Using a create-react-app typescript project, you should have installed typescript and ts-jest (or the create-react-app should handle the dependencies based on wether you ejected the app or not).

    Also ts-jest has some information about it:

    By default ts-jest uses TypeScript compiler in the context of a project (yours), with full type-checking and features. But it can also be used to compile each file separately, what TypeScript calls an ‘isolated module’. That’s what the isolatedModules option (which defaults to false) does.

    Source 2

    As soon as you use the export command you are creating a module out of what is being exported.

    If you are using ts-jest, you can add these settings without affecting your other modules, which the create-react-app will consist off.

    "ts-jest": {
      "isolatedModules": false
    }
    

    And checkout the ts-jest page (second source) for the pro's and con's.

    0 讨论(0)
提交回复
热议问题