Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import file as string at compile time

I'm using Typescript and Webpack. Is it possible to import a file as a string at compile-time, so I don't need the file at run-time?

I.e.

import text from "foo.txt";

const a = text;

would compile to

const a = "contents_of_foo.txt";
like image 932
Timmmm Avatar asked Oct 15 '25 16:10

Timmmm


1 Answers

Webpack has the concept of loaders, which are responsible for, well, loading things. :-)

There's a list of official loaders here. There's a raw-loader that can load raw files as strings. Once you configure it, you use it just as you showed (though there's no need for the const):

import a from "foo.txt";

Here's the configuration they show in the link above:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/i,
        use: 'raw-loader',
      },
    ],
  },
};

I don't know that it would compile to exactly what you've shown, not least because Webpack will avoid duplicating the text across files if you use import ... "foo.txt" in more than one place. But it'll be handled for you so you don't have to read the file explicitly at runtime.

like image 78
T.J. Crowder Avatar answered Oct 18 '25 12:10

T.J. Crowder