Skip to content

TypeScript doesn't work with "type": "module" in package.json #239

@TimothyGu

Description

@TimothyGu

Running any postcss-cli command fails with

  • "type": "module" in package.json, and
  • TypeScript config file (postcss.config.ts)

Details

After support for .mjs was added in version 4 of this module, I expected ESM-mode TypeScript to work as well. Unfortunately, it does not.

The issue has to do with how TypeScript config files are loaded:

// Register TypeScript compiler instance
registerer = require('ts-node').register()
return require(configFile)

Using ts-node.register() / require() with "type": "module" is simply unsupported. See ts-node documentation.

Workaround

The ts-node documentation describes a valid workaround:

  • You have moved your project to ESM but still have a config file, such as webpack.config.ts, which must be executed as CommonJS
    • Solution: Configure a module type override. Docs

Indeed, if I include

  "ts-node": {
    "moduleTypes": {
      "postcss.config.ts": "cjs"
    }
  }

in tsconfig.json then the error goes away.

Error (Logs|Stacks)

https://gist.github.com/TimothyGu/e65fcba3fd759cd6fa2e415ed2047b77#file-readme-md

Reproduction (Code)

See https://gist.github.com/TimothyGu/e65fcba3fd759cd6fa2e415ed2047b77

$ git clone https://gist.github.com/e65fcba3fd759cd6fa2e415ed2047b77.git testdir
$ cd testdir
$ yarn
$ node_modules/.bin/postcss test.css

Environment

OS node npm/yarn package
Linux 5.17.15-1-MANJARO 18.3.0 yarn 1.22.19 postcss 8.4.14
postcss-cli 10.0.0
postcss-load-config 4.0.1
see yarn.lock

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions