gpt4 book ai didi

typescript - 在编译时将文件导入为字符串

转载 作者:行者123 更新时间:2023-12-03 16:32:53 25 4
gpt4 key购买 nike

我正在使用Typescript和Webpack。是否可以在编译时将文件导入为字符串,所以我在运行时不需要该文件?



import text from "foo.txt";

const a = text;


将编译为

const a = "contents_of_foo.txt";

最佳答案

Webpack具有装载程序的概念,它负责装载东西。 :-)

这里有一个官方装载机here的列表。有一个raw-loader可以将原始文件作为字符串加载。一旦配置完毕,就可以按照显示的方式使用它(尽管不需要const):

import a from "foo.txt";


它们是上面链接中显示的配置:

// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.txt$/i,
use: 'raw-loader',
},
],
},
};


我不知道它会完全编译为您所显示的内容,尤其是因为如果您在多个地方使用 import ... "foo.txt",Webpack将避免在文件之间复制文本。但是它将为您处理,因此您不必在运行时显式读取文件。

关于typescript - 在编译时将文件导入为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59877006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com