美文网首页
Vue项目打包部署Tomcat

Vue项目打包部署Tomcat

作者: 欢乐的乐 | 来源:发表于2020-03-07 13:29 被阅读0次

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 中的 publicPathVueRouter 创建实例中一定要添加 base ,并且设置一样的路径。不然会导致路由混乱,无法正确打开指定页面。

这里统一都是 /hello/ ,前后都有斜杠。

Vue-cil3 打包命令

到这里项目中的配置就完成了,打包项目。

npm run build

打包完,会看到项目文件夹中多了一个目录 dist

进去可以看到有三个东西:

  • static
  • favicon.ico
  • index.html

直接双击 index.html 打开浏览器,页面是空白了,啥都没有。如果想根据路由打开指定页面,就需要部署到服务器了。

Tomcat 部署

  1. 找到Tomcat的安装目录,进入webapps文件夹。
  2. 创建一个 hello 文件夹。
  3. 把刚才 dist 文件夹里面的东西拷贝过来。
  4. 创建一个 WEB-INF 文件夹,并进入。
  5. 创建 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>
  1. 启动Tomcat服务
  2. 输入 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

相关文章

网友评论

      本文标题:Vue项目打包部署Tomcat

      本文链接:https://www.haomeiwen.com/subject/oxaqdhtx.html