You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Vue项目执行npm run build未生成index.html,如何解决?

解决Vue项目build后dist目录缺少index.html的问题

我看了你的配置和问题描述,核心原因是你的webpack配置里没有使用HtmlWebpackPlugin插件——这个插件的作用就是帮你把打包好的js文件自动注入到指定的HTML模板中,并将最终的index.html输出到dist目录里。

按照下面的步骤操作就能解决问题:

1. 安装兼容版本的HtmlWebpackPlugin

因为你的webpack版本是3.6.0,建议安装适配的旧版本(新版本可能不支持webpack3),执行命令:

npm install html-webpack-plugin@3.2.0 --save-dev

2. 修改webpack.config.js配置

第一步:引入HtmlWebpackPlugin

在文件顶部添加插件引入代码:

var HtmlWebpackPlugin = require('html-webpack-plugin');

第二步:调整output的publicPath

由于你要部署到AWS EC2的/var/www/html/目录,需要把publicPath改成根路径'/',否则部署后静态资源会找不到:

output: {
  path: path.resolve(__dirname, './dist'),
  publicPath: '/', // 原来的'/dist/'替换为根路径
  filename: 'build.js'
},

第三步:添加HtmlWebpackPlugin到plugins数组

在生产环境的plugins配置块中,新增插件实例:

new HtmlWebpackPlugin({
  filename: 'index.html', // 输出到dist的文件名
  template: 'index.html', // 项目根目录下的HTML模板文件(如果模板在public文件夹,就改成'public/index.html')
  inject: true, // 自动将打包后的js注入到HTML中
  minify: { // 生产环境下压缩HTML代码
    removeComments: true,
    collapseWhitespace: true,
    removeAttributeQuotes: true
  }
})

修改后的生产环境plugins部分完整代码如下:

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    }),
    // 新增的HtmlWebpackPlugin配置
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
      }
    })
  ])
}

3. 验证并重新构建

确保你的项目根目录存在基础HTML模板文件(示例结构如下):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Prototype</title>
</head>
<body>
  <div id="app"></div>
  <!-- webpack会自动注入build.js -->
</body>
</html>

最后重新执行构建命令:

npm run build

现在你的dist目录里应该会生成index.html了,把dist下的所有文件上传到AWS EC2的/var/www/html/目录,就能完成部署访问。

内容的提问来源于stack exchange,提问作者user10930017

火山引擎 最新活动