Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 733
Jake Avatar asked Oct 19 '25 09:10

Jake


1 Answers

Install raw-loader and use it load txt files:

npm install raw-loader --save-dev

Add to rules:

rules: [
  {
    test: /\.txt$/,
    use: 'raw-loader'
  }
]
like image 98
m1ch4ls Avatar answered Oct 21 '25 22:10

m1ch4ls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!