typescriptes6-modulestypescript-module-resolution

Trying to understand how "module" & "moduleResolution" differ,


I fail to understand why there is both a "module" & "moduleResolution" setting.

I have always thought of a module, as being nothing more than a specification (and/or standard) that defines the way that software-packages "resolve", and are "resolved-by", other software packages that adhere to the same specification (and/or standard).

Maybe that is an accurate perception, maybe not, either way, I don't see any reason for configuring the module type, and the moduleResolution separately. I am not criticizing TypeScript here, I know with 100% certainty, that I am the one lacking, not TypeScript. I am just trying to get a fundamental understanding for how to configure my TypeScript projects.


  1. What is the difference between "module" & "moduleResolution"?

  2. How does the tsconfig.json setting module affect the modules (or packages) being imported by a project? And what impact does it have on the JavaScript that is transpilled and emitted by the TypeScript compiler tsc?

  3. How does the tsconfig.json setting moduleResolution affect the modules (or packages) being imported by a project? And what impact does it have on the JavaScript that is transpilled and emitted by the TypeScript compiler tsc?


Solution

  • moduleResolution determines the algorithm used for finding/resolving modules e.g. looking in node_modules or searching relative paths

    module determines the type of import/export used -

    // CommonJS
    const zip = require("./ZipCodeValidator");
    
    // ES2020
    import { valueOfPi } from "./constants";
    

    For module node12/nodenext

    node12/nodenext (nightly builds) Available in nightly builds, the experimental node12 and nodenext modes integrate with Node’s native ECMAScript Module support. The emitted JavaScript uses either CommonJS or ES2020 output depending on the file extension and the value of the type setting in the nearest package.json. Module resolution also works differently. You can learn more in the handbook

    The docs are a bit behind for node16 but they're being updated