首页 > 解决方案 > Vue CLI - 将构建输出组合到单个 html 文件

问题描述

我有一个用 vue-cli 创建的 vue 项目。运行时的正常输出yarn build是一个 dist 文件夹,其中包含一个index.html和一个 js 和 css 子目录以及相应的 .js 和 .css 文件。

我希望构建输出是包含 js 和 css 的单个 html 文件。

我在项目的根目录中添加了一个vue.config.js文件,并将其设置为输出单个 js 文件,这一切正常。但我只想拥有一个带有 js 的 html 文件以及 html 文件中已有的任何 css。

module.exports = {
    css: {
        extract: false,
    },
    configureWebpack: {
      optimization: {
        splitChunks: false
      }
    }
  }

基本上我希望我的 html 文件是这样的:

<html lang=en>
    <head>
        ... meta tags
        <title>my title</title>
    </head>
    <body>
        <div id=app></div>
        <script>
           // contents of the output js file here
        </script>
    </body>
</html>

这可能吗?

使用 Vue 3.9.3

标签: javascripthtmlvue.jswebpack

解决方案


有人回答建议调查html-webpack-inline-source-plugin但删除了他们的答案。但这正是我完成这项工作所需要的。

该插件不是 Vue 或 Vue-CLI 特定的,但如果您执行以下操作,它就可以工作:

vue.config.js1)在应用程序的根目录中添加一个文件。

2)上面的链接插件实际上是另一个包的扩展。你需要两者。

npm install --save-dev html-webpack-plugin 
npm install --save-dev html-webpack-inline-source-plugin 

3)

// vue.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
module.exports = {
    css: {
        extract: false,
    },
    configureWebpack: {
      optimization: {
        splitChunks: false // makes there only be 1 js file - leftover from earlier attempts but doesn't hurt
      },
      plugins: [
        new HtmlWebpackPlugin({
          filename: 'output.html', // the output file name that will be created
          template: 'src/output-template.html', // this is important - a template file to use for insertion
          inlineSource: '.(js|css)$' // embed all javascript and css inline
        }),
        new HtmlWebpackInlineSourcePlugin()
      ]
    }
  }

4) 添加模板。这对于在 Vue 上下文中工作是必要的,因为没有它,默认情况下输出的 html 文件将没有必要的<div id="app"></div>内容,并且 Vue 不会挂载到任何东西。我基本上拿了正常的输出html文件并稍微修改了一下。

<!-- output-template.html -->
<!DOCTYPE html>
<html lang=en>
    <head>
        <meta charset=utf-8>
        <meta http-equiv=X-UA-Compatible content="IE=edge">
        <meta name=viewport content="width=device-width,initial-scale=1">        
        <title>example title</title>
    </head>
    <body><noscript><strong>We're sorry but my example doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript>
        <div id=app>

        </div>
        <!-- plugin will insert js here by default -->
    </body>
</html>

然后像正常一样构建,output.html文件将在/dist文件夹中


推荐阅读