html-webpack-plugin not inject js file into index.html when using webpack-dev-server

徘徊边缘 提交于 2019-12-02 21:14:38

This issue is related specifically to the fact that the webpack-development-server does not have the ability to write files to your local file system and instead writes its files to MEMORY Only.

This is why you were able to properly generate files wth Html-Webpack-Plugin when you run the default webpack build command (NOT the WDS / Webpack-Development-Server) with:

webpack 

Alternately since you were using vue.js Webpack-simple project (https://github.com/vuejs-templates/webpack-simple/tree/master/template) you were also able to use the npm scripts that come with the Vue.js sample (located inside of your package.json) via:

npm run build

In either case the files ARE written to the directory as you would have thought they should be since Building with webpack CAN write the file system, where as no files were written when using Webpack-Development-Server (again this does not work because WDS writes to memory and not the local file system).

I stumbled onto this answer when working on the same problem thanks to your comment:

"If I run webpack or npm run build, the js file is injected successfully. Can html-webpack-plugin also inject js file into index.html when I'm in localhost?"

To sum up: Html-Webpack-Plugin WILL NOT write files to the local file system when it is used as a part of the Webpack-Development-Server (WDS) even though Html-Webpack-Plugin WILL write files (with an identical webpack configuration) when using the normal webpack build process (no WDS).

You can try config like this..

new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    })

and Index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>My App</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

You will need install npm i -D html-webpack-plugin vue-loader vue-html-loader

but I recommend you create a project from template, vue init webpack

This template use the html-webpack-plugin

I have same problem and below config work for me.

I used to have absolute path and when change it to relative, it work.

new HtmlWebpackPlugin({
        inject: true,
        template:'public/index.html', // relative to project root 
        filename:'index.html'         // relative to build folder
    })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!