vue : history模式与项目部署的爬坑

需求:url不能有#符号,且不放在服务器虚拟主机的根目录。

假设放在虚拟主机的 medicine 文件夹下。

需要改两个文件,一个是 ./config/index.js (vue设置文件) ,另一个是 ./src/router.js (vue-router设置文件)。

 ./config/index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8084, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/medicine/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

红色的部分是改过的部分。

./src/router.js

// 系统组件
import Vue from 'vue'
import VueRouter from 'vue-router'
// import store from './store.js'

// 引入组件
import home from './components/pages/home_page' 
import mark from './components/pages/mark_page'

// vue-router 使用中间件
Vue.use(VueRouter)

const routes = [
    {
        path:'/',
        name:'home',
        component:home,
    },
    {
        path:'/mark',
        component:mark,
    },
]


// vue-router 实例化
export const router =  new VueRouter({
    routes, 
    base:'/medicine/',       // build时打开 dev不要
    mode:'history',
})

注意红色的部分。

注释里提过了,开发的时候把router.js红色的部分注释掉,部署的时候再把注释去掉。

这样,至少src文件夹里面的文件(vue,js,css/less/stylus/...,png/jpeg/...)是没有问题的,至于static文件夹的问题,则需要进一步测试。

原文地址:https://www.cnblogs.com/foxcharon/p/10337027.html