简体   繁体   English

使用Webpack进行编译时,如何在javascript中将文件的文本导入到变量中?

[英]How can I import the text of a file into a variable in javascript during compilation using webpack?

I have an application that requires the use of long string values that are ideally stored in a separate text file. 我有一个需要使用长字符串值的应用程序,该值理想情况下存储在单独的文本文件中。

However, I'm kind of stumped as to how I can perform something like the following: 但是,我对如何执行以下操作感到很困惑:

import fileText from './path/to/filename.txt'

and have the end result being something like: 最终结果是:

var fileText = 'Long text string that was derived during compilation'

It wouldn't be ideal if I have to reconstruct the original text into a javascript file that returns the string as I'd like to not abandon the syntax highlighting of the original text file. 如果我必须将原始文本重构到一个返回字符串的javascript文件中,这是不理想的,因为我不想放弃原始文本文件的语法高亮显示。

Update: 更新:

Using raw-loader worked like a charm except I was using typescript and it was throwing errors during compilation. 使用raw-loader就像一个魅力一样,除了我正在使用打字稿,而且它在编译期间会引发错误。 Setting up the following typescript declaration ended up getting it working for me. 设置以下打字稿声明最终使它对我有用。

declare module "*.txt" {
    const content :string;
    export = content;
}

Much appreciated! 非常感激!

Install raw-loader and use it load txt files: 安装raw-loader并使用它加载txt文件:

npm install raw-loader --save-dev

Add to rules: 添加到规则:

rules: [
  {
    test: /\.txt$/,
    use: 'raw-loader'
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM