最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

webpack - Import Javascript files as a string? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked May 17, 2017 at 16:05 y_arly_arl 3511 gold badge3 silver badges15 bronze badges 4
  • Raw loader is the way to go. Maybe you are using Babel as well and it's applied before raw loader does its thing? Can you sure your code and configuration? – Felix Kling Commented May 17, 2017 at 16:08
  • 1 @FelixKling thanks for the reply. How would I go about checking/changing things if that is the case? edit: figured it out, just needed to change raw-loader to !raw-loader – y_arl Commented May 17, 2017 at 17:03
  • Applying the loader with import file from '!raw-loader!file.js' might do the trick. webpack.js.org/concepts/loaders/#via-require – Felix Kling Commented May 17, 2017 at 17:05
  • exactly, thank you!! – y_arl Commented May 17, 2017 at 17:05
Add a comment  | 

2 Answers 2

Reset to default 21

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'
    },
  ]
}
发布评论

评论列表(0)

  1. 暂无评论