简体   繁体   中英

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.

Update:

Using raw-loader worked like a charm except I was using typescript and it was throwing errors during compilation. 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:

npm install raw-loader --save-dev

Add to rules:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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