Vue build subfolder setup

User
run vue build in subfolder in server
Assistant
If you want to run a Vue build inside a subfolder on your server, follow these steps:

### 1. **Modify Vue Config for Subfolder Deployment**
Since Vue assumes the app is deployed at the root by default, you need to update `vue.config.js` to specify the subfolder:

module.exports = {
  publicPath: '/your-subfolder/'
};

Replace `/your-subfolder/` with the actual subfolder where you are deploying your Vue app.

### 2. **Build Vue App**
Run the build command inside your Vue project:

yarn build  # or npm run build

This generates a `dist` folder with the built files.

### 3. **Move Build Files to Server Subfolder**
Upload the `dist` contents to your server’s subfolder. If your server root is `/var/www/html`, and you want the app inside `/var/www/html/your-subfolder/`, run:

scp -r dist/* user@yourserver:/var/www/html/your-subfolder/

### 4. **Set Up Apache/Nginx Configuration**
Ensure your web server properly serves the Vue app.

#### Apache:
Create or edit your `.htaccess` in `/var/www/html/your-subfolder/`:

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

#### Nginx:
Modify your Nginx config (`/etc/nginx/sites-available/default` or equivalent):

server {
    listen 80;
    server_name yourdomain.com;

    location /your-subfolder/ {
        root /var/www/html;
        index index.html;
        try_files $uri /index.html;
    }
}

Then reload Nginx:

sudo systemctl reload nginx

### 5. **Clear Cache and Verify**
– If using Cloudflare or a caching system, purge the cache.
– Open `http://yourdomain.com/your-subfolder/` to check if the Vue app loads correctly.

Let me know if you need adjustments! πŸš€

User
import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig({
base: '/frontend/',
plugins: [
vue(),
vueJsx(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
server: {
host: 'localhost',
port: 5173,
strictPort: true,
origin: 'http://localhost:5173',
watch: {
ignored: ['**/node_modules/**', '**/vendor/**'],
usePolling: true,
},

},
})

Assistant
Your Vite configuration is already set up for serving the Vue app from a subfolder (`base: '/frontend/'`). To ensure it works properly on the server, follow these steps:

### **1. Build the Vue App**
Since you've set `base: '/frontend/'`, when you build the Vue project, assets will be correctly referenced with `/frontend/` as the prefix.

Run the build command:

yarn build  # or npm run build

This will generate a `dist` folder with the compiled Vue application.

### **2. Deploy the Build Files**
Upload the contents of the `dist` folder to your server inside the `/var/www/html/frontend/` directory (or the appropriate web directory).

Example SCP command:

scp -r dist/* user@yourserver:/var/www/html/frontend/

### **3. Configure Apache/Nginx for Serving Vue in a Subfolder**
Depending on your server, configure either Apache or Nginx:

#### **Apache Configuration (`.htaccess` inside `/var/www/html/frontend/`)**
Create or update `.htaccess` to handle Vue's history mode correctly:

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

If needed, modify your Apache `VirtualHost` configuration (`/etc/apache2/sites-available/000-default.conf` or similar):

<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /var/www/html

    <Directory /var/www/html/frontend>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Restart Apache:

sudo systemctl restart apache2

#### **Nginx Configuration (`/etc/nginx/sites-available/default`)**
Modify your Nginx configuration to ensure Vue routing works:

server {
    listen 80;
    server_name yourdomain.com;

    location /frontend/ {
        root /var/www/html;
        index index.html;
        try_files $uri /frontend/index.html;
    }
}

Restart Nginx:

sudo systemctl reload nginx

### **4. Verify and Clear Cache**
– If using Cloudflare or a caching service, purge the cache.
– Visit `http://yourdomain.com/frontend/` to confirm it loads correctly.

Let me know if you encounter any issues! πŸš€

User
still only layout showing without content
content showing yourdomain.com/page not yourdomain/frontend/page
Assistant
It looks like Vue Router is handling navigation as if the app is hosted at the root (`/`), while your actual deployment is in a subfolder (`/frontend/`). To fix this, follow these steps:

### **1. Ensure `base` is Set in Vue Router**
Modify your **Vue Router** configuration file (`src/router/index.js` or wherever you define routes):

import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/Home.vue';

const router = createRouter({
  history: createWebHistory('/frontend/'), // <-- Add your subfolder here
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: () => import('@/views/About.vue') },
  ],
});

export default router;

### **2. Update `vite.config.js`**
You already have `base: '/frontend/'`, which is correct:

export default defineConfig({
  base: '/frontend/', // Ensure this matches the subfolder
  plugins: [vue()],
});

### **3. Rebuild and Deploy**
Now rebuild your Vue app:

yarn build  # or npm run build

Then upload the `dist` contents to the server inside `/var/www/html/frontend/`:

scp -r dist/* user@yourserver:/var/www/html/frontend/

### **4. Update `.htaccess` (For Apache)**
If you use **Apache**, ensure the `.htaccess` file inside `/var/www/html/frontend/` correctly redirects requests:

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

Restart Apache:

sudo systemctl restart apache2

### **5. Update Nginx Configuration (If Using Nginx)**
If you're using **Nginx**, modify your site configuration (`/etc/nginx/sites-available/default`):

server {
    listen 80;
    server_name yourdomain.com;

    location /frontend/ {
        root /var/www/html;
        index index.html;
        try_files $uri /frontend/index.html;
    }
}

Then reload Nginx:

sudo systemctl reload nginx

### **6. Clear Cache and Test**
– If you're using **Cloudflare** or a caching plugin, clear the cache.
– Open `http://yourdomain.com/frontend/` and navigate to `/frontend/page`.

πŸš€ This should now correctly serve Vue inside `/frontend/`, ensuring internal links work properly. Let me know if you still face issues!

User
import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
NProgress.configure({ showSpinner: false, speed: 500, minimum: 0.2 });
import HomeView from '../views/HomeView.vue'
import Youtubeiew from '@/views/Youtubeiew.vue'
import NewsView from '@/views/NewsView.vue'
import LoginView from '@/views/LoginView.vue'
import RegisterView from '@/views/RegisterView.vue'
import DashboardView from '@/views/User/DashboardView.vue'
import ProfileView from '@/views/User/ProfileView.vue'
import SettingsView from '@/views/User/SettingsView.vue'
import ForgetPasswordView from '@/views/ForgetPasswordView.vue'

import { useAuthStore } from '@/stores/auth';
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/news',
name: 'news',
component: NewsView,
},
{
path: '/youtube',
name: 'youtube',
component: Youtubeiew,
},
{
path: '/login',
name: 'login',
component: LoginView,
},
{
path: '/register',
name: 'register',
component: RegisterView,
},
{
path: '/forget-password',
name: 'forget-password',
component: ForgetPasswordView,
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue'),
},
{
path: '/dashboard',
name: 'dashboard',
component: DashboardView,
meta: { requiresAuth: true },
},
{
path: '/profile',
name: 'profile',
component: ProfileView,
meta: { requiresAuth: true },
},
{
path: '/settings',
name: 'settings',
component: SettingsView,
meta: { requiresAuth: true },
},
],
})
router.beforeEach((to, from, next) => {
const authStore = useAuthStore();
NProgress.start();
if (to.meta.requiresAuth && !authStore.token) {
next('/login'); // Redirect if not logged in
} else {
next();
}
});
router.afterEach(() => {
NProgress.done();
});
export default router
use env base url

Assistant
To correctly use `import.meta.env.BASE_URL` for handling the subfolder deployment (`/frontend/`), ensure the following steps are properly set up:

### **1. Update `vite.config.js`**
You already have `base: '/frontend/'`, which ensures assets and routing use the correct base path.

export default defineConfig({
  base: '/frontend/', // Ensure it matches the subfolder
  plugins: [vue()],
});

### **2. Modify Vue Router to Use `import.meta.env.BASE_URL`**
In your **router configuration** (`router/index.js`), ensure that `createWebHistory()` uses `import.meta.env.BASE_URL`:

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // Uses the base path from Vite config
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/news',
      name: 'news',
      component: NewsView,
    },
    {
      path: '/youtube',
      name: 'youtube',
      component: Youtubeiew,
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
    },
    {
      path: '/forget-password',
      name: 'forget-password',
      component: ForgetPasswordView,
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: DashboardView,
      meta: { requiresAuth: true },
    },
    {
      path: '/profile',
      name: 'profile',
      component: ProfileView,
      meta: { requiresAuth: true },
    },
    {
      path: '/settings',
      name: 'settings',
      component: SettingsView,
      meta: { requiresAuth: true },
    },
  ],
});

### **3. Rebuild and Deploy the Application**
Once you have updated the configuration, **run the build command**:

yarn build  # or npm run build

Then upload the contents of the `dist` folder to the `/frontend/` subfolder on your server:

scp -r dist/* user@yourserver:/var/www/html/frontend/

### **4. Configure Apache/Nginx to Serve the App from `/frontend/`**
If you're using **Apache**, update `.htaccess` inside `/var/www/html/frontend/`:

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

For **Nginx**, update your site configuration (`/etc/nginx/sites-available/default`):

server {
    listen 80;
    server_name yourdomain.com;

    location /frontend/ {
        root /var/www/html;
        index index.html;
        try_files $uri /frontend/index.html;
    }
}

Restart your server:

sudo systemctl restart apache2  # For Apache
sudo systemctl reload nginx     # For Nginx

### **5. Test and Verify**
– Visit `http://yourdomain.com/frontend/`
– Navigate to different pages and ensure routes work properly.
– If using **Cloudflare** or a caching service, **clear the cache**.

πŸš€ Now, your Vue app should work correctly inside the `/frontend/` subfolder, and `import.meta.env.BASE_URL` will dynamically adjust URLs accordingly. Let me know if you need further refinements! 😊

Leave a Comment

Your email address will not be published. Required fields are marked *