vue router mode模式在webpack 打包上线问题

vue-router mode模式有两种 hash和history。

1.hash —— 即地址栏 URL 中的 # 符号。
比如这个 URL:http://www.abc.com/#/hello,hash 的值为 #/hello。它的特点在于:hash 虽然出现在 URL 中,但不会被包括在 HTTP 请求中,对后端完全没有影响,因此改变 hash 不会重新加载页面。
2.history —— 利用了 HTML5 History Interface 中新增的 pushState() 和 replaceState() 方法。(需要特定浏览器支持)
这两个方法应用于浏览器的历史记录栈,在当前已有的 back、forward、go 的基础之上,它们提供了对历史记录进行修改的功能。只是当它们执行修改时,虽然改变了当前的 URL,但浏览器不会立即向后端发送请求。
hash 模式和 history 模式都属于浏览器自身的特性,Vue-Router 只是利用了这两个特性(通过调用浏览器提供的接口)来实现前端路由。

一般项目上vue-router mode模式默认为hash,也可以设置history。

 config文件夹下 index.js

问题

当mode 模式为history,使用vue-cli构建项目, 打包 npm run build ,dist文件夹下 有index.html和static文件夹。

build: {
    //打包时的index放置位置
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
   //公共资源路径
    assetsPublicPath: '/',

    productionSourceMap: true,
    devtool: '#source-map',
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

里面  assetsPublicPath: '/', /开头路径固定以根目录为起点。公共资源请求路径是从服务器根目录开始。

1.当项目文件放到根目录

正常情况,大家项目文件都会放在服务器的根目录,当项目文件(index.html static)放在根目录时。

如服务器网址 https://xxxxx.com 的根目录   https://xxxxx.com/index.html    

请求css文件路径       https://xxxxx.com/static/css/app.cca059254702f9ed953b7df749673cf4.css

2.项目文件放到根目录下的子文件夹

当项目文件(index.html static)放到根目录下的子文件夹时。

例如   项目文件夹名 myprojct     访问index文件路径为https://xxxxx.com/myprojct/index.html  且assetsPublicPath: '/'

则index.html文件夹所依赖的 css js img 的请求路径 依旧是从项目根目录  https://xxxxx.com/static/css/app.cca059254702f9ed953b7df749673cf4.css

导致资源无法访问。

解决途径:confing index.js     改为assetsPublicPath: './'      把绝对路径改为使用相对路径来访问依赖文件

history模式问题

通过history api,我们丢掉了丑陋的#,但是它也有个毛病:
不怕前进,不怕后退,就怕刷新,f5,(如果后端没有准备的话),因为刷新是实实在在地去请求服务器的,不玩虚的。

在hash模式下,前端路由修改的是#中的信息,而浏览器请求时是不带它玩的,所以没有问题.但是在history下,你可以自由的修改path,当刷新时,如果服务器中没有相应的响应或者资源,会分分钟刷出一个404来。

所以,如果你想在github.io上搭一个单页博客,就应该选择hash模式。比如这个博客

404错误

在History mode下,如果直接通过地址栏访问路径,那么会出现404错误,这是因为这是单页应用(废话)…其实是因为调用了history.pushState API 所以所有的跳转之类的操作都是通过router来实现的,解决这个问题很简单,只需要在后台配置如果URL匹配不到任何静态资源,就跳转到默认的index.html。具体配置如下:

//Apache

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>


//nginx
location / {
  try_files $uri $uri/ /index.html;
}

猜你喜欢

转载自www.cnblogs.com/zjx304/p/9859300.html