背景
默認(rèn)模式<domain>#/<path>
- 優(yōu)點(diǎn)是直接可以用,無需做額外配置
- 缺點(diǎn)是跟常規(guī)的URL方式不一致,造型古怪,想要在URL上加參數(shù)的時(shí)候容易出錯(cuò)
history模式<domain>/<path>
- 優(yōu)點(diǎn)是符合URL標(biāo)準(zhǔn)格式
- 缺點(diǎn)是需要做額外的配置
解法 -- 以 test.linkaka.cn 為例
部署在根域名下 test.linkaka.cn/<path>
-
<project path>/src/router.jsexport default new Router({ // 命名:組件名大駝峰、path/name小駝峰 mode: 'history', base, routes: [ // routes ] }) -
nginx.conf配置server { listen 80; server_name test.linkaka.cn; root /home/static/test.linkaka.cn; index index.html index.htm; location ^~/ { access_log off; try_files $uri $uri / /index.html; } }
部署在子路由下 test.linkaka.cn/demo/<path>
-
以下路由親測有效
有子路由: test.linkaka.cn/demo 有效 test.linkaka.cn/demo/news 有效 test.linkaka.cn/demo/news/someid 有效 -
<project path>/src/router.jsconst getRoute = (name, path = `/${name}`) => ({ name, path, component: resolve => require([`@/views/${name}.vue`], resolve) }) const routes = [ getRoute('home', '/'), getRoute('news', '/news/:id') ] // 通用做法,不需要關(guān)心到底是部署在那個(gè)子路由下面 const base = routes.reduce((pre, {name}) => { const reg = RegExp(`/${name}.*`) return pre.replace(reg, '') }, location.pathname) export default new Router({ // 命名:組件名大駝峰、path/name小駝峰 mode: 'history', // 通用做法 // base: base, // 更優(yōu)的做法 base: env.baseRoute, routes: routes.concat([ { path: '*', redirect: '/' } ]) }) -
webpack config
-
<project path>/config/dev.env.js'use strict' module.exports = { NODE_ENV: '"development"', baseRoute: '"/"', } -
<project path>/config/test.env.js'use strict' const merge = require('webpack-merge') const devEnv = require('./dev.env') module.exports = merge(devEnv, { NODE_ENV: '"testing"', baseRoute: '"/icity.jd.com"' }) -
<project path>/config/prod.env.js'use strict' module.exports = { NODE_ENV: '"production"', baseRoute: '"/"', domain: { icity: '"http://101.124.15.81:9080/icity/front"' } } -
<project path>/build/webpack.prod.conf.js// ... const env = process.env.NODE_ENV === 'testing' ? require('../config/test.env') : require('../config/prod.env') const webpackConfig = merge(baseWebpackConfig, { //... output: { publicPath: JSON.parse(env.baseRoute), // ... }, })
-
-
nginx.conf配置server { listen 80; server_name test.linkaka.cn; root /home/static/test.linkaka.cn; index index.html index.htm; location /icity.jd.com { access_log off; # try_files $uri $uri/ /index.html; if ( !-e $request_filename) { rewrite ^/(.*) /icity.jd.com/index.html last; break; } } }
運(yùn)行命令
- "start": "npm run dev",
- "build:test": "NODE_ENV=testing node build/build.js",
- "build": "NODE_ENV=production node build/build.js"
總結(jié)
不吹不黑,所有功能親測有效。 在這個(gè)過程中也發(fā)現(xiàn)了
config/*.env.js的作用。 以前都是自己新定義一個(gè)變量,感覺作者的這個(gè)環(huán)境配置的有些凌亂,通過這次的vue-router的實(shí)踐,發(fā)現(xiàn)作者的這種做法還是很有優(yōu)勢的。