4

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!

Jake
  • 6,096
  • 1
  • 10
  • 13
  • 2
    Seems like you just need [raw-loader](https://github.com/webpack-contrib/raw-loader). – Kirk Larkin Aug 27 '18 at 17:42
  • See https://stackoverflow.com/questions/56175900/how-do-you-import-a-text-file-into-typescript/75313118#75313118 for a full answer – toddmo Feb 03 '23 at 16:25

1 Answers1

4

Install raw-loader and use it load txt files:

npm install raw-loader --save-dev

Add to rules:

rules: [
  {
    test: /\.txt$/,
    use: 'raw-loader'
  }
]
m1ch4ls
  • 3,317
  • 18
  • 31