how to inject css bundle in head and js bundle in body using webpack html plugin

亡梦爱人 提交于 2019-12-02 06:08:00

问题


I am absolutely new to Webpack and I work with scss and vue on a little project. What I try is to compile all my .scss files to css and bundle them up in a bundle.css that is automatically injected into the head (I already set up the sass and css loaders to archieve the bundling to css). But I also want my vue app.js bundle at the end of the body, also injected by the htmlWebpackPlugin (already done). Using a single HtmlWebpackPlugin to put everything in my index.html would leave me with either the style in the body or the javascript in the head.

My first guess would be, that I have to define 2 Plugin-Instances like

var jsInjectorPlugin = new HtmlWebpackPlugin({
  filename: 'index.html',
  template: 'index.html',
  inject: 'body'
});
var cssInjectorPlugin = new HtmlWebpackPlugin({
  filename: 'index.html',
  template: 'index.html',
  inject: 'head'
})

But how do I tell webpack, to use the first plugin for css and the other one for js? Since I have no test like in loaders, I do not know how to do this

So the point of this question is, can someone explain me how I can achieve that my css-bundle gets injected into the head and my js-bundle gets injected in the body? (code snippets of how to do this in the webpack-config are appreciated)


回答1:


You need HtmlWebpackInjector

  • It works with HtmlWebpackPlugin and by just adding _head in the name of chunk, it automaticlly injects the chunk in the head.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInjector = require('html-webpack-injector');

module.exports = {
  entry: {
    index: "./index.ts",
    // add "_head" in the bundle name to inject in head.
    // use sass and css loaders to compile sass to js bundle.
    bundle_head: "./index.scss" 
  },
  output: {
    path: "./dist",
    filename: "[name].bundle.js"
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./index.html",
      filename: "./dist/index.html",
      chunks: ["index", "bundle_head"]
    }),
    new HtmlWebpackInjector()
  ]
}

This automatically injects index chunk to the body and bundle_head to the head of the html document. Final html looks like:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Archit's App</title>
    <script type="text/javascript" src="bundle_head.bundle.js"></script> <--injected in head
  </head>
  </head>
  <body>
    <script src="index_bundle.js"></script> <--injected in body
  </body>
</html>


来源:https://stackoverflow.com/questions/46202546/how-to-inject-css-bundle-in-head-and-js-bundle-in-body-using-webpack-html-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!