Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - Custom loader before HtmlWebpackPlugin causes "Unexpected token" error

I'm working on making a custom loader that's going to take the HTML template specified for HtmlWebpackPlugin, perform some alterations, and then pass it along.

To start, I made a loader that echos what it is given:

//loader.js

module.exports = function(fileContent){
  return fileContent
}

But this results in the following error:

Html Webpack Plugin:
  Error: Child compilation failed:
  Module parse failed: Unexpected token (1:0)
  File was processed with these loaders:
   * ./node_modules/html-webpack-plugin/lib/loader.js
   * ./loader.js

The HTML file is just for testing, it looks like this:

//index.html

<!DOCTYPE html>
<html>
  <body>
  </body>
</html>

I'm not sure why such an error would happen. I looked at the source code for the HtmlWebpackPlugin and tried logging what it receives to the console, but it's the exact same as what I return in loader.js.

I tried giving it a plain string to see what would happen, like this:

//loader.js

module.exports = function(fileContent){
  return "test"
}

But then it tells me:

HtmlWebpackPlugin
ReferenceError: test is not defined
 - loader.js:1 eval
//...and so on

Huh? So I guess it's trying to evaluate what I give it? I'm not sure what's going on. Any help is appreciated.

Here is the loader code for HtmlWebpackPlugin:

question from:https://stackoverflow.com/questions/65854251/custom-loader-before-htmlwebpackplugin-causes-unexpected-token-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figured out that in my case, a better approach would just be to load the template as a Javascript module from a file.

//webpack.config.js

new HtmlWebpackPlugin({
  template: "./src/customLoader.js",
  filename: name + ".html",
  chunks: [name],
})
//customLoader.js

module.exports = (htmlFile) => {
  //...do stuff
  return modifiedHtmlFile;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...