Vue 項目的配置
在打包之前,先確定項目中
vue-router
的路由模式,文中的例子是基于history
模式進行的配置打包和部署。
vue.config.js
vue.config.js 下的配置:
// vue.config.js
module.exports = {
devServer: {
port: 8080
},
publicPath: '/hello/',
assetsDir: 'static'
}
publicPath
:部署應用包時的基本 URL。
默認情況下,Vue CLI 會假設你的應用是被部署在一個域名的根路徑上,例如 https://www.my-app.com/。如果應用被部署在一個子路徑上,你就需要用這個選項指定這個子路徑。例如,如果你的應用被部署在 https://www.my-app.com/my-app/,則設置 publicPath 為 /my-app/。
assetsDir
:放置生成的靜態資源 (js、css、img、fonts) 的 (相對于 outputDir 的) 目錄。
router.js
new VueRouter({
base: '/hello/',
mode: 'history',
routes
})
如果調整了 vue.config.js
中的 publicPath
, VueRouter
創建實例中一定要添加 base
,并且設置一樣的路徑。不然會導致路由混亂,無法正確打開指定頁面。
這里統一都是 /hello/
,前后都有斜杠。
Vue-cil3 打包命令
到這里項目中的配置就完成了,打包項目。
npm run build
打包完,會看到項目文件夾中多了一個目錄 dist
。
進去可以看到有三個東西:
- static
- favicon.ico
- index.html
直接雙擊 index.html
打開瀏覽器,頁面是空白了,啥都沒有。如果想根據路由打開指定頁面,就需要部署到服務器了。
Tomcat 部署
- 找到Tomcat的安裝目錄,進入webapps文件夾。
- 創建一個
hello
文件夾。 - 把剛才
dist
文件夾里面的東西拷貝過來。 - 創建一個
WEB-INF
文件夾,并進入。 - 創建
web.xml
文件,拷貝以下的內容。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<display-name>hello</display-name>
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
</web-app>
- 啟動Tomcat服務
- 輸入
http://localhost:8080/hello
,就能訪問你的根目錄啦!!
因為 web.xml
配置了404的時候是訪問 index.html
頁面,那我就嘗試一下輸入錯誤的地址。http://localhost:8080/hello/asdfghjj
,雖然沒有顯示404的頁面,但是頁面是空白也不太友好,希望可以顯示一個指定的頁面。
一開始在 web.xml
中折騰了半天,最后看到這篇文章,成功解決了我的問題。
Vue-router History模式下,空白頁面,如何配置tomcat服務器
處理404狀態
回到前端項目,調整router.js。
const router = new VueRouter({
mode: 'history',
base: '/hello',
routes: [
// 404頁面
{ path: '*', component: ErrorPage},
{ ... }
]
})
添加一個 ErrorPage
組件,由前端路由來處理錯誤頁面。
重新打包和部署,就可以了!??ヽ(°▽°)ノ?
如果想部署Nginx,可以看看這篇文章。Vue 項目打包部署Nginx