【问题标题】:Vue + html-webpack-plugin not load index.html generatedVue + html-webpack-plugin 不加载 index.html 生成
【发布时间】:2024-04-30 01:10:03
【问题描述】:

我尝试使用 HtmlWebPackPlugin 来生成我的 index.html 所以...

  1. 我启动了一个新项目vue init webpack-simple#1.0 vue-html-webpack
  2. 安装npm i -D html-webpack-plugin
  3. index.html 重命名为entry-template.html
  4. 配置webpack.config.js ..

我添加..

  plugins: [
      new HtmlWebpackPlugin({
        template: 'entry-template.html',
        environment: process.env.NODE_ENV
      })
    ],

但是网页我启动应用程序npm run dev,返回404(我想是找不到index.html

我的entry-template.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>GitSkills</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

完整的source here

结果 -> https://vue-html-webpack-ogqlguavxx.now.sh/

问题

如何在 Vue 1.0 中使用 HtmlWebpackPlugin

【问题讨论】:

标签: webpack vue.js html-webpack-plugin vue-loader


【解决方案1】:

HtmlWebpackPlugin 使用全局配置的加载器来处理模板,如果没有不同的定义。在您的情况下,这会导致vue-html-loader 处理您的entry-template.html。可能这就是原因,您的模板 html 未正确处理。请查看docs for the HtmlWebpackPlugin 了解加载程序的处理方式。

在您的情况下直接指定加载程序是否有效?

plugins: [
  new HtmlWebpackPlugin({
    template: '!!html!entry-template.html',
    environment: process.env.NODE_ENV
  })
],

有关语法的详细信息,请参阅docs about loaders order 并覆盖它们。

更新:

vue-html-loader 是原始html-loader 的扩展,似乎不会导致这里出现问题。从您的 webpack 输出中,我看到您正在使用 publicPath 属性,该属性控制提供内容时要使用的基本路径。这不是磁盘上文件的路径,而是应该从其中提供内容的 url 中的路径。因此,当您访问 localhost:8080/dist 时,您的设置已经生效。省略 publicPath 属性使其从根路径服务。

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'build.js'
  },
  ...

另外,在使用路由器时,您应该在模板中添加一个路由器插座,以便您的模板内容(例如登录)可以包含在主模板中(我猜是app)。

<template>
  <div id="app">
    <h1>{{ msg }}</h1>
    <router-view></router-view>
  </div>
</template>

【讨论】:

  • 我有 HTML { test: /\.html$/, loader: 'vue-html' } 的加载器,我尝试将 HtmlWebpackPlugin 配置更改为 template: '!!html!entry-template.html', 但出现同样的错误
  • 你用npm安装了loader吗?您能否将运行 webpack 的控制台输出添加到您的问题中?
  • 你可以在这里看到项目..github.com/Ridermansb/vue-html-plugin-problem
【解决方案2】:

在阅读了这里的答案和大约两天的研究之后,在同一个问题上,事实证明这个问题与 webpack-development-server 没有将文件写入本地文件系统而是相反的事实有关将其文件写入仅限内存

应该在运行默认的 webpack 构建命令时能够使用 Html-Webpack-Plugin 正确生成文件(NOT WDS /Webpack-Development-Server) 与:

webpack 

请记住,您必须位于项目目录中。或者,对于那些使用 vue.js Webpack-simple 项目 (https://github.com/vuejs-templates/webpack-simple/tree/master/template) 的人,您可以通过以下方式使用 Vue.js 示例(位于 package.json 中)附带的 npm 脚本:

npm run build

如果一切顺利,您会注意到文件已写入目录,正如您认为应该的那样,但在使用 Webpack-Development-Server 时却没有(同样这不起作用,因为 WDS 写入内存并不是本地文件系统)。

您可以看到这个 * 问题在使用基本 Vue.js Webpack 项目时也遇到了问题: html-webpack-plugin not inject js file into index.html when using webpack-dev-server

由于用户提到,我在阅读上述问题时偶然发现了这个答案:

"如果我运行webpack或者npm run build,js文件注入成功。我在localhost时html-webpack-plugin也能注入js文件到index.html吗?"

【讨论】: