使用webpack打包发布,网页不能正常访问,先看下路由配置
export default new Router({ mode: 'history', base: '/putian/', routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld }, { path: '/ClusterManage', name: 'ClusterManage', component: ClusterManage }, { path: '/MonitorWarn', name: 'MonitorWarn', component: MonitorWarn } ] })
其中mode为history模式后,vue访问将不需要"#"。去掉mode一行,采用默认路由访问路径时如下:
http://localhost:8000/putian#/ClusterManage
使用history模式后,访问路径如下:
http://localhost:8000/putian/ClusterManage
开发环境可以正常访问,打包使用部署直接404,我这边使用的nginx,来部署,首先需要更改webpack的发布路径,我这边是在config/index.js,如下:
build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', /** * 发布路径 */ assetsPublicPath: '/putian/', /** * 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 }
注意:index.js中assetsPublicPath: '/putian/',这个参数和Router路由中 base: '/putian/',保持一致。
有的同学可能环境架构跟我的不一致可以通过更改,webpack.cong.js代码如下:
module.exports = { context: path.resolve(__dirname, '../'), entry: { app: './src/main.js' }, output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src'), } },
其中output中publicPath参数更改这个就可以了。
到此还没完,访问还是有问题,访问时找不到ClusterManage相关文件
http://localhost:8000/putian/ClusterManage
会出现404错误,该如何处理,这是需要配置nginx,利用try_files特性,对404重新定位,配置如下
location /putian {
alias C:\Users\lhq\IDEAProject\accurate-portrait-vue\dist;
#root html;
index index.html index.htm;
try_files $uri $uri/ /putian/index.html;
}
访问上面地址,这里的$uri就是putian/ClusterManage,通过转换地址为去访问