一、问题

将vue使用打包后

npm run build

将dist文件的内容,放入nginx的html中,并在nginx.conf中,设置端口

启动nginx,打开发现网页内容为空白

二、解决问题

1.配置vue-route

const router = createRouter({
  history: createWebHistory('/'),
});

2.配置vite.config.js或vue.config.js

在vite.config.js中加入以下代码

export default defineConfig(({ mode }) => {
  const isProduction = mode === 'production'
  return {
    // ...
     base: isProduction ? '/' : '/'
  }
})

如果配置了vite.config.js就不用配置vue.config.js,在vue.config.js加入以下代码

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
};

3.配置nginx

在conf目录下,配置nginx.conf

    server {
        listen       8080;
        server_name  localhost;

        location / {
            root   html;
            index  index.html;
            # 需要指向下面的 @router 否则会出现 Vue 的路由在 Nginx 中刷新出现 40 
			try_files  $uri $uri/ @router; 
        }
		
        # 对应上面的 @router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
        # 因此需要 rewrite 到 index.html 中,然后交给路由在处理请求资源
		location @router {
		rewrite ^.&$ /index.html last;
		}
    }

关闭nginx

 taskkill /F /IM nginx.exe

再次启动就会成功!!! 

 

更多推荐