Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Webpack 将原始文件作为字符串导入_Webpack - Fatal编程技术网

Webpack 将原始文件作为字符串导入

Webpack 将原始文件作为字符串导入,webpack,Webpack,在一个类型脚本项目中,我有一些原始文本文件要作为字符串导入,这些文件应该捆绑在最终的js文件中 我在我的项目中使用Webpack5.21 假设我的源文件中有: app.ts 模板\index.ts 模板\somefile.tmpl.html 我希望从我的app.ts文件中能够像这样导入: import {somefile } from './templates' somefile应该是包含tmpl.html文件原始内容的字符串 以下是我尝试过的: 在我的webpack.config.ts

在一个类型脚本项目中,我有一些原始文本文件要作为字符串导入,这些文件应该捆绑在最终的js文件中

我在我的项目中使用Webpack5.21

假设我的源文件中有:

  • app.ts
  • 模板\index.ts
  • 模板\somefile.tmpl.html
我希望从我的app.ts文件中能够像这样导入:

import {somefile } from './templates'
somefile
应该是包含tmpl.html文件原始内容的字符串

以下是我尝试过的:

  • 在我的webpack.config.ts文件中,我添加了以下规则:

          {
              test: /\.tmpl\.html$/i,
              type:'asset/source',
              exclude: /node_modules/,
          }
    
我还添加了一个解析扩展:

resolve: {
    extensions: ['.tsx', '.ts', '.js', '.tmpl.html'],
},
在我的
templates\index.ts
文件中,我尝试了:

import somefile from './somefile.tmpl.html'

export default {
    somefile
}
但是,当我从命令行调用
webpack
时,我得到:

[tsl] ERROR in C:\Code\myproject\src\templates\index.ts(4,23)
  TS2307: Cannot find module './somefile.tmpl.html' or its corresponding type declarations.
少了什么


PS:我的背景是一个定制构建系统,它接受一些typescript文件,并在独立的JSF文件中转换它们。我不是正在运行的web应用。

此错误与Typescript有关,它无法识别
.html
模块

您需要添加一个
d.ts
文件,该文件将包含

//global.d.ts
声明模块'*.tmpl.html'{
常量值:字符串;
导出默认值;
}
//tsconfig.json
{
编译器:{
...
},
包括:[“path/to/global.d.ts”]
}

您能澄清最后一部分吗?我应该在tsconfig.json文件中添加什么?编辑了我的回答它现在编译没有错误。但是,在输出的javascript包中,我没有在源代码中获取字符串。您可能需要为这些文件应用原始加载程序。先前的测试破坏了编译。修复此问题后,我的设置会按预期在输出包中包含字符串。