@Phil's answer 如果你有一个不需要任何变量扩展的不变的web.config 文件,那就简单而完美。但是,如果您想生成一个 web.config 文件,其中包括例如带有 BASE_URL 的重写规则,则以下内容将起作用:
在vue.config.js:
"use strict";
// Do NOT use the HtmlWebpackPlugin name to avoid a collision with standard Vue usage of the html-webpack-plugin
// NOTE also this uses the vue-cli-service dependency path for html-webpack-plugin
// Beware if the require() path is incorrect, it may fail silently, thus ignoring vue.config.js (per (per https://github.com/vuejs/vue-cli/issues/5442)
const HtmlWebpackPlugin2 = require('@vue/cli-service/node_modules/html-webpack-plugin');
module.exports = {
devServer: {
disableHostCheck: true,
},
transpileDependencies: ['vuetify'],
publicPath: process.env.NODE_ENV === 'production' ? process.env.BASE_URL : '/',
configureWebpack: {
plugins: [
new HtmlWebpackPlugin2({ // generate web.config
title: 'web_config',
template: 'src/web.config',
filename: 'web.config',
inject: false
})
]
}
}
一个关键元素是声明const HtmlWebpackPlugin2 = require('@vue/cli-service/node_modules/html-webpack-plugin'); 使用名称不同于 HtmlWebpackPlugin,以避免与vue-cli-service 使用HtmlWebpackPlugin 发生冲突。然后,在configureWebpack: 元素中,将带有template 路径的“新”HtmlWebpackPlugin2 插件添加到web.config 模板。 inject: false 选项对于避免将 <head> 和 <script> 标记注入到您的 web.config XML 中也很重要。
如 OP 的问题中所述,要在 IIS 下运行,web.config 文件应包含一个重写规则,该规则将客户端路由路径重写到您的虚拟根目录(也描述为here)。这可以通过html-webpack-plugin的变量扩展语法<%= process.env.MY_VARIABLE_NAME %>来完成:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="SPA Routes" stopProcessing="true">
<!-- match everything by default -->
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<!-- unless its a file -->
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<!-- or a directory -->
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<!-- or is under the /api directory -->
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
<!-- list other routes or route prefixes here if you need to handle them server side -->
</conditions>
<!-- rewrite to application root -->
<action type="Rewrite" url="<%= process.env.BASE_URL %>" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
BASE_URL 变量本身定义在与vue.config.js 相同文件夹中的.env.production 文件中,如here 或here 所述。它是一个纯文本文件,仅包含:
BASE_URL="/my-vroot-name/"
使用上述内容,您的标准yarn build 命令将在您的src\web.config 模板中执行变量替换并将输出写入dist\web.config。
设置 IIS 虚拟应用程序时,请确保您的物理路径指向 dist 文件夹,或根据您的服务器环境的需要调整 BASE_URL 和 HtmlWebpackPlugin2 输出 filename 路径。