Vue应用部署至网站子目录:如何修改Webpack构建路径
Hey there, let's get this sorted out for you! Since you mentioned it's a simple Vue app, I'm assuming you're using either Vue CLI or Vite (the two most common build setups for Vue these days). Let's break down exactly what you need to adjust depending on your tooling:
If you're using Vue CLI
Set the correct
publicPathinvue.config.js
If you don't have avue.config.jsfile in your project root, create one first. Then add thepublicPathproperty pointing to your subdirectory—make sure to include leading and trailing slashes for consistency:module.exports = { publicPath: '/subdirectory/' }This tells Webpack (under the hood of Vue CLI) to prefix all asset paths with your subdirectory instead of the root
/.Adjust Vue Router (if you're using it)
If your app uses Vue Router, you need to set thebaseoption when initializing the router to match your subdirectory:import Vue from 'vue' import VueRouter from 'vue-router' import routes from './routes' Vue.use(VueRouter) const router = new VueRouter({ base: '/subdirectory/', // Match your publicPath here mode: 'history', routes }) export default routerDeploy correctly
After runningnpm run build, take all the files from the generateddistfolder and upload them directly into your server'ssubdirectoryfolder (not nested inside another folder withinsubdirectory).
If you're using Vite
Vite uses base instead of publicPath, so the steps are slightly different:
Set the
baseproperty invite.config.js
Add or modify thebaseoption to point to your subdirectory:import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], base: '/subdirectory/' })Update Vue Router configuration
For Vue 3 + Vue Router 4, set thehistorybase to match your subdirectory:import { createRouter, createWebHistory } from 'vue-router' import routes from './routes' const router = createRouter({ history: createWebHistory('/subdirectory/'), // Match your Vite base here routes }) export default routerDeploy the
distfolder contents
Just like with Vue CLI, upload everything from thedistfolder directly into your server'ssubdirectory.
Common Pitfalls to Check
- Don't forget trailing slashes: Omitting the trailing slash (e.g.,
'/subdirectory'instead of'/subdirectory/') can cause unexpected path issues with assets. - Relative vs absolute asset paths: If you're referencing static assets in your components (like images), use relative paths (e.g.,
../assets/image.png) or place them in thepublicfolder and reference them with the subdirectory prefix (e.g.,'/subdirectory/image.png'). - Test locally first: To avoid deployment surprises, test your build locally with a server that simulates the subdirectory. For example, using
serve:
Then visitserve -s dist -l 3000 --prefix subdirectoryhttp://localhost:3000/subdirectoryto verify everything loads correctly.
内容的提问来源于stack exchange,提问作者Korgrue

