【问题标题】:How can I import the text of a file into a variable in javascript during compilation using webpack?如何在使用 webpack 编译期间将文件文本导入 javascript 中的变量?
【发布时间】:2019-02-02 07:01:39
【问题描述】:

我有一个应用程序需要使用长字符串值,这些值最好存储在单独的文本文件中。

但是,我对如何执行以下操作感到有些困惑:

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

最终结果类似于:

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

如果我必须将原始文本重构为一个返回字符串的 javascript 文件,因为我不想放弃原始文本文件的语法突出显示,那将是不理想的。

更新:

使用 raw-loader 就像一个魅力,除了我使用的是 typescript 并且它在编译期间抛出错误。设置以下打字稿声明最终让它为我工作。

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

非常感谢!

【问题讨论】:

标签: javascript node.js webpack


【解决方案1】:

安装raw-loader并使用它加载txt文件:

npm install raw-loader --save-dev

添加到规则:

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

【讨论】:

    猜你喜欢
    • 2014-08-01
    • 2021-12-06
    • 2019-05-17
    • 2019-09-04
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 2021-05-20
    • 2019-08-08
    相关资源
    最近更新 更多