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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With