Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Javascript files as a string?

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?

like image 908
y_arl Avatar asked Dec 07 '22 18:12

y_arl


2 Answers

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 !.

like image 85
Felix Kling Avatar answered Dec 10 '22 11:12

Felix Kling


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'
    },
  ]
}
like image 29
Roman Karagodin Avatar answered Dec 10 '22 12:12

Roman Karagodin