4

I would like to be able to import .html file as a string template in NestJS application. In order to satisfy TypeScript I created text.d.ts like this:

declare module "*!text" {
  const content: string;
  export default content;
}

and imported it in a file like this:

import html from 'src/templates/test!text';

There are no complains from TypeScript. However when I try to run the application I get the following error:

internal/modules/cjs/loader.js:905
  throw err;
  ^
    
Error: Cannot find module 'src/templates/test!text'

How to solve this error?

Thanks in advance.

fortunee
  • 3,852
  • 2
  • 17
  • 29
Georgi Naumov
  • 4,160
  • 4
  • 40
  • 62

2 Answers2

2

Maybe that's because you run compiled code from dist/ folder and .html files are not copied from src/.

If so, you need to add these lines into nest-cli.json ("compilerOptions" section):

    "assets": ["src/**/*.html"],
    "watchAssets": true,

(based on https://stackoverflow.com/a/61673191/1760643 answer, see NestJS docs about assets copying)

Upd: also import doesn't work for me.

Used this hack:

requireAsPlainTextConstructor.ts:

import fs from 'fs';
import path from 'path';

export default function requireAsPlainTextConstructor(dirname: string) {
    return (filePath: string) => {
        const filename = path.resolve(dirname, filePath);
        return fs.readFileSync(filename, 'utf8');
    };
}

Target file:

import requireAsPlainTextConstructor from 'requireAsPlainTextConstructor';

const requireAsPlainText = requireAsPlainTextConstructor(__dirname);
const myHtml = requireAsPlainText('my.html');
d9k
  • 1,476
  • 3
  • 15
  • 28
0

you have written "test!text" I think it should be "test.txt" ( as I think you have saved it as a text file in your project and importing as RAW and using).

Mubashir Jamali
  • 141
  • 3
  • 4