【问题标题】:Import .html file as a string in nestjs在nestjs中将.html文件作为字符串导入
【发布时间】:2021-03-07 09:14:27
【问题描述】:

我希望能够在 NestJS 应用程序中将 .html 文件作为字符串模板导入。 为了满足 TypeScript,我像这样创建了 text.d.ts:

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

并将其导入到这样的文件中:

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

TypeScript 没有任何抱怨。但是,当我尝试运行 应用程序我收到以下错误:

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

如何解决这个错误?

提前致谢。

【问题讨论】:

  • 您是否尝试使用相对路径而不是这个绝对路径'src/templates/test!text'
  • @MicaelLevi 在导入中路径是相对的。

标签: nestjs


【解决方案1】:

可能是因为您从dist/ 文件夹运行编译代码,而.html 文件没有从src/ 复制。

如果是这样,您需要将这些行添加到nest-cli.json"compilerOptions" 部分):

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

(基于https://stackoverflow.com/a/61673191/1760643的回答,见NestJS docs about assets copying

更新import 也不适合我。

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');
    };
}

目标文件:

import requireAsPlainTextConstructor from 'requireAsPlainTextConstructor';

const requireAsPlainText = requireAsPlainTextConstructor(__dirname);
const myHtml = requireAsPlainText('my.html');

【讨论】:

    【解决方案2】:

    你已经写了“test!text”,我认为它应该是“test.txt”(因为我认为你已经将它保存为项目中的文本文件并导入为 RAW 并使用)。

    【讨论】:

    • 你好。谢谢你的回答。不幸的是,错误是一样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2012-02-22
    • 2016-08-07
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    相关资源
    最近更新 更多