angrykoala
angrykoala

Reputation: 4064

Can't import ".html" file in Typescript using Parcel

I'm trying to setup a simple project using Typescript and Parcel.

Within this project, I'm trying to import a .html file (or, more accurately, its path) from a .ts:

import html from "../renderer/index.html";
console.log(html); // file:///home/foo/bar/dist/main/renderer.1c7e1d82.html

As mentioned in several places, in order for this to work I added the following declaration file html.d.ts:

declare module '*.html' {
  const value: string;
  export default value
}

And my full tsconfig.json:

{
    "compilerOptions": {
        "outDir": "dist",
        "module": "commonjs",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": false,
        "strict": true,
        "esModuleInterop": true,
    },
    "files": [
        "src/main/main.ts"
    ],
    "include": ["@types"]
}

The configuration appears to be correct, as my IDE seems to recognise the import above, and running tsc doesn't fail and yields the expected result (require("../renderer/index.html")).

However, when trying to bundle with Parcel (parcel build main.ts). While the compilation itself works as expected, with the import being substituted by new URL("renderer.1c7e1d82.html", "file:" + __filename).toString(); It fails to recognise the d.ts file, as the following warning is thrown:

@parcel/transformer-typescript-types: Cannot find module '../renderer/index.html' or its corresponding type declarations.

  /home/angrykoala/Desktop/scratchpad/gaucho2/src/main/main.ts:9:18
     8 | 
  >  9 | import html from "../renderer/index.html";
  >    |                  ^^^^^^^^^^^^^^^^^^^^^^^^^ Cannot find module '../renderer/index.html' or its corresponding type declarations.
    10 | console.log(html)
    11 | 

As per the documentation, my .pretierrc is set to use tsc:

{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.{ts,tsx}": ["@parcel/transformer-typescript-tsc"]
  }
}

And yet, it fails to take into account files or include parameters from tsconfig. Any other permutation I've tried (such as removing files) had the same issue.

Upvotes: 2

Views: 852

Answers (1)

rasmusmerzin
rasmusmerzin

Reputation: 71

Parcel string inlining is done using bundle-text: prefix.

import html from "bundle-text:../renderer/index.html";

Parcel automatically adds devDependency @parcel/transformer-inline-string.

More at https://parceljs.org/features/bundle-inlining.

I usually create a definition file global.d.ts which includes:

declare module "bundle-text:*" {
  const value: string;
  export default value;
}

And add line includes: ["**/*.ts"] to tsconfig.json.

EDIT:
More about tsconfig includes at https://www.typescriptlang.org/tsconfig#include.
Note it's important to include the definition file as well which is covered by pattern "**/*.ts".

Upvotes: 3

Related Questions