javascript - 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
解决方案
有人回答建议调查html-webpack-inline-source-plugin但删除了他们的答案。但这正是我完成这项工作所需要的。
该插件不是 Vue 或 Vue-CLI 特定的,但如果您执行以下操作,它就可以工作:
vue.config.js
1)在应用程序的根目录中添加一个文件。
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
文件夹中
推荐阅读
- shiny - 以两行打印表格标题 R 闪亮
- python - discord.py on_guild_join 事件
- .net - WebView2 控件中的打印功能
- android - 在 github 中删除 repo 后,Android Studio 警告“...Repository not found.”,我如何指定从 Android Studio 中的另一个 repo 获取
- node.js - 用于虚拟下游设备的 Azure IoT Edge 模块标识转换
- reactjs - React Js 功能组件不返回任何内容
- r - 通过从分钟到小时分组来查找平均值
- c - 在 C 编程中使用 win32 api 获取所有本地用户及其对给定文件的权限的程序
- mysql - 如何在 MySQL Query 中有条件地连接表
- openapi - Swagger(OpenAPI) 2.0 是否支持元组类型?