Vue CLI - 将构建输出合并到单个 html 文件中

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


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


我vue.config.js在项目的根目录中添加了一个文件,并将其设置为输出单个 js 文件,并且工作正常。但我只想有一个 html 文件,其中包含 js 和 html 文件中已有的任何 css。


module.exports = {

    css: {

        extract: false,

    },

    configureWebpack: {

      optimization: {

        splitChunks: false

      }

    }

  }

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


<html>

    <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


RISEBY
浏览 228回答 1
1回答

浮云间

有人回答建议查看html-webpack-inline-source-plugin但删除了他们的答案。但这正是我完成这项工作所需要的。该插件不是 Vue 或 Vue-CLI 特定的,但如果您执行以下操作,它就可以工作:1)vue.config.js在应用程序的根目录中添加一个文件。2)上面链接的插件实际上是另一个包的扩展。你需要两者。npm install --save-dev html-webpack-plugin&nbsp;npm install --save-dev html-webpack-inline-source-plugin&nbsp;3)// vue.config.jsconst HtmlWebpackPlugin = require('html-webpack-plugin')const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');module.exports = {&nbsp; &nbsp; css: {&nbsp; &nbsp; &nbsp; &nbsp; extract: false,&nbsp; &nbsp; },&nbsp; &nbsp; configureWebpack: {&nbsp; &nbsp; &nbsp; optimization: {&nbsp; &nbsp; &nbsp; &nbsp; splitChunks: false // makes there only be 1 js file - leftover from earlier attempts but doesn't hurt&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; plugins: [&nbsp; &nbsp; &nbsp; &nbsp; new HtmlWebpackPlugin({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filename: 'output.html', // the output file name that will be created&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; template: 'src/output-template.html', // this is important - a template file to use for insertion&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inlineSource: '.(js|css)$' // embed all javascript and css inline&nbsp; &nbsp; &nbsp; &nbsp; }),&nbsp; &nbsp; &nbsp; &nbsp; new HtmlWebpackInlineSourcePlugin()&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }&nbsp; }4) 添加模板。这对于在 Vue 上下文中工作是必要的,因为没有它,默认情况下输出 html 文件将没有必要的,<div id="app"></div>并且 Vue 将不会挂载到任何东西。我基本上拿了正常输出的html文件,稍微修改了一下。<!-- output-template.html --><!DOCTYPE html><html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <meta charset=utf-8>&nbsp; &nbsp; &nbsp; &nbsp; <meta http-equiv=X-UA-Compatible content="IE=edge">&nbsp; &nbsp; &nbsp; &nbsp; <meta name=viewport content="width=device-width,initial-scale=1">&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <title>example title</title>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body><noscript><strong>We're sorry but my example doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript>&nbsp; &nbsp; &nbsp; &nbsp; <div id=app>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <!-- plugin will insert js here by default -->&nbsp; &nbsp; </body></html>然后像正常一样构建,output.html文件将在/dist文件夹中
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript