AdMer
AdMer

Reputation: 558

Parcel typescript module augmentation

I'm trying to ship a lib that uses typescript module augmentation with Parceljs but it doesn't seem to bundle those module augmentations. I'm not able to use the properties in the project that import the lib generated with Parcel.

{
  "name": "my-library",
  "version": "1.0.0",
  "source": "src/index.js",
  "main": "dist/main.js",
  "module": "dist/module.js",
  "types": "dist/types.d.ts",
  "devDependencies": {
    "parcel": "latest"
  }
}

Example that I try to ship with Parcel and Typescript augmentation.

import { Components, createTheme, PaletteOptions } from '@mui/material/styles';

declare module '@mui/material/styles' {
  interface Palette {
    ternary: Palette['primary'];
    quaternary: Palette['primary'];
    gridColor: string;
    logoColor: string;
  }
  interface PaletteOptions {
    ternary?: PaletteOptions['primary'];
    quaternary?: PaletteOptions['primary'];
    gridColor?: string;
    logoColor?: string;
  }
}

export const defaultTheme = createTheme();

My exported defaultTheme that comes from the lib built with Parcel won't be shipped with additional properties that I defined here. I would like them to be available.

Upvotes: 0

Views: 185

Answers (1)

Andrew Stegmaier
Andrew Stegmaier

Reputation: 3777

Unfortunately, it looks like this is a bug in parcel.

Update (2021-11): This PR to fix this bug was accepted. The fix is available in version 2.0.0-nightly.296 and later (link), and should also ship in the next release of @parcel/transformer-typescript-types after 2.0.1. If you're using version 2.0.1 or earlier, read on for a workaround.

You can work around the issue by using tsc to generate the .d.ts files for your project. Here's how you would do that:

  1. Make sure your package.json is configured to tell parcel to output files with the same name as the root source file (e.g. if the root source file is /src/index.ts, make sure that you have "main": "dist/index.js" in your package.json)
  2. Add a tsconfig.json with the following contents:
    {
      "compilerOptions": {
        "rootDir": "./src",
        "declaration": true,
        "emitDeclarationOnly": true,
        "outFile": "./dist/index.js",
      }
    }
    
  3. Add a command to your build step that deletes the .d.ts file generated by parcel, and creates a new one with tsc. E.g. parcel build becomes parcel build && rimraf dist/index.d.ts && tsc

I know this isn't pretty, but hopefully it will unblock you.

Here's a repo where you can see an example of both the bug and the workaround.

Upvotes: 1

Related Questions