Repository navigation
Replies: 1 comment
|
There are two separate parts here: TypeScript needs a declaration for the import, and the test runtime needs a way to read the HTML. For CommonJS Mocha tests, I verified this small setup: // html.d.ts
declare module "*.html" {
const html: string;
export default html;
}Make sure ts-node loads that declaration. For a minimal test project, my {
"compilerOptions": {
"module": "CommonJS",
"target": "ES2020",
"strict": true,
"esModuleInterop": true
},
"ts-node": { "files": true },
"include": ["component.ts", "html.d.ts"]
}Use your actual source/test paths in A small preloader can supply the runtime part: // register-html.cjs
const fs = require("node:fs");
require.extensions[".html"] = (module, filename) => {
module.exports = fs.readFileSync(filename, "utf8");
};npx mocha --require ts-node/register --require ./register-html.cjs test.cjsFor example, Limit: I tested Node 24.18.0, ts-node 10.9.2, TypeScript 5.9.3 and Mocha 11.8.0: without the declaration I got TS2307; adding only the declaration reached a runtime AI assistance: written with OpenAI Codex; the example and both failure cases were run locally. |
Uh oh!
There was an error while loading. Please reload this page.
Hi there, I'm trying to setup
ts-nodewith HTML files imported as a string like this:import template from "./component.html";Just for context: my application is built using webpack, which has
html-loaderplugin, but when I try to setup unit tests (with mocha), I can't use that loader, so I get this error:error TS2307: Cannot find module './component.html' or its corresponding type declarations.Any help greatly appreciated!
All reactions