Import Javascript files as a string?

Viewed 9457

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?

2 Answers

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'
    },
  ]
}
Related