Jake
Jake

Reputation: 6206

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!

Upvotes: 4

Views: 2648

Answers (1)

m1ch4ls
m1ch4ls

Reputation: 3435

Install raw-loader and use it load txt files:

npm install raw-loader --save-dev

Add to rules:

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

Upvotes: 4

Related Questions