I want to be able to simply do an import file from 'file.js
and then have file be a string of the contents within file.js. I've toyed around with raw-loader but it doesn't give me the same contents (instead it loads it in a different format). Any suggestions?
it doesn't give me the same contents (instead it loads it in a different format)
That seems to mean that there are other loaders from your config applied to the file. You can enforce that only the loader in the import statement is used by prefixing it with a !
:
import file from '!raw-loader!file.js'
From the docs:
It's possible to overwrite any loaders in the configuration by prefixing the entire rule with
!
.
In Webpack 5 it's possible to handle it without raw-loader.
It's enough to add a rule with type: asset/source
(see the docs). Note that in this case, if you use babel loader or other JS loaders, the code will still be processed by them if not overridden manually.
A simplified code example:
module: {
rules: [
{
test: /(?<!boilerplate)\.js$/, // a negative look-behind regex to exclude your file
exclude: /node_modules/, // also can be handled here, adding a folder with file(s) to be excluded
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /boilerplate\.js$/,
type: 'asset/source'
},
]
}
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