Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add middleware redirection in vite #2686

Merged
merged 3 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

###################################################################
# Vite local development without running a server. #
# set VITE_LOCA_DEV to true #
# set VITE_LOCAL_DEV to true #
# set VITE_HTTP_PROXY_TARGET to the rediction for the API calls. #
###################################################################
# VITE_LOCAL_DEV=true
Expand Down
228 changes: 131 additions & 97 deletions vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,108 +1,142 @@
import { fileURLToPath, URL } from 'node:url';
import { defineConfig, loadEnv, UserConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
import i18n from 'laravel-vue-i18n/vite';
import { fileURLToPath, URL } from "node:url";
import { defineConfig, loadEnv, PluginOption, UserConfig } from "vite";
import laravel from "laravel-vite-plugin";
import vue from "@vitejs/plugin-vue";
import i18n from "laravel-vue-i18n/vite";

const laravelPlugin = laravel({
input: [
'resources/sass/app.scss',
'resources/js/app.ts',
],
refresh: true,
})
input: ["resources/sass/app.scss", "resources/js/app.ts"],
refresh: true,
});

const baseConfig = {
base: './',
plugins: [
vue(
{
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
i18n(),
],
server: {
watch: {
ignored: [
"**/.*/**",
"**/app/**",
"**/database/**",
"**/node_modules/**",
"**/public/**",
"**/storage/**",
"**/tests/**",
"**/vendor/**",
"**/presets/**",
],
},
},
resolve: {
alias: {
// @ts-ignore-next-line
'@': fileURLToPath(new URL('./resources/js/', import.meta.url)),
vue: 'vue/dist/vue.esm-bundler.js',
},
},
build: {
rollupOptions: {
output:{
manualChunks(id) {
if (id.includes('node_modules')) {
return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
}
}
}
const localDevelopMiddleware: PluginOption = {
name: "develop-rewrite-middleware",
configureServer(server) {
const viteIndexPath = "/vite/index.html";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess if it's local we don't need subpath handling.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes.
in this specific case when you do npm run dev it is poping an server and redirecting you to http://localhost:5173/vite/index.html which we use to load the app.ts


server.middlewares.use((req, res, next) => {
if (!req.url) {
next();
return;
}

const requestUrl : string = req.url;
const doNotTouch = ["/@", "/api", "/resources", "/node_modules"];
if (doNotTouch.some((page) => requestUrl.startsWith(page))) {
next();
return;
}

console.log(req.url);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want the debug code?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better safe on that one, it will only be visible if using local dev without the composer part.

const startsWithPages = ["/gallery", "/frame", "/map", "/search"];
// Check if req.url starts with pages
if (startsWithPages.some((page) => requestUrl.startsWith(page))) {
req.url = viteIndexPath;
}

const pages = [
"/",
"/diagnostics",
"/permissions",
"/jobs",
"/maintenance",
"/profile",
"/settings",
"/sharing",
"/statistics",
"/users",
];
// Check if requestUrl is in pages
if (pages.includes(requestUrl)) {
req.url = viteIndexPath;
}

next();
});
},
css: {
preprocessorOptions: {
scss: {
api: 'modern'
},
}
}
} as UserConfig;
}

const baseConfig = {
base: "./",
plugins: [
vue({ template: { transformAssetUrls: { base: null, includeAbsolute: false } } }),
i18n(),
],
server: {
watch: {
ignored: [
"**/.*/**",
"**/app/**",
"**/database/**",
"**/node_modules/**",
"**/public/**",
"**/storage/**",
"**/tests/**",
"**/vendor/**",
"**/presets/**",
],
},
},
resolve: {
alias: {
// @ts-ignore-next-line
"@": fileURLToPath(new URL("./resources/js/", import.meta.url)),
vue: "vue/dist/vue.esm-bundler.js",
},
},
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes("node_modules")) {
return id.toString().split("node_modules/")[1].split("/")[0].toString();
}
},
},
},
},
css: {
preprocessorOptions: {
scss: {
api: "modern",
},
},
},
} as UserConfig;

/** @type {import('vite').UserConfig} */
export default defineConfig(
({ command, mode, isSsrBuild, isPreview }) => {
const config = baseConfig;
const env = loadEnv(mode, process.cwd(), '')

if (config.server === undefined) {
throw new Error('server config is missing');
}
if (config.plugins === undefined) {
throw new Error('plugins list is missing');
}
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
const config = baseConfig;
const env = loadEnv(mode, process.cwd(), "");

if (command === 'serve') {
if (config.server === undefined) {
throw new Error("server config is missing");
}
if (config.plugins === undefined) {
throw new Error("plugins list is missing");
}

console.log("LOCAL VITE MODE detected")
if (env.VITE_HTTP_PROXY_TARGET !== undefined) {
console.log("api calls will be forwarded to:")
console.log(env.VITE_HTTP_PROXY_TARGET);
}
if (command === "serve") {
console.log("LOCAL VITE MODE detected");
if (env.VITE_HTTP_PROXY_TARGET !== undefined) {
console.log("api calls will be forwarded to:");
console.log(env.VITE_HTTP_PROXY_TARGET);
}

if (env.VITE_LOCAL_DEV === 'true') {
if (env.VITE_HTTP_PROXY_TARGET === undefined) {
throw new Error('VITE_HTTP_PROXY_TARGET is missing');
}
config.server.open = 'vite/index.html';
config.server.proxy = {
'/api/': env.VITE_HTTP_PROXY_TARGET,
}
return config;
}
}
if (env.VITE_LOCAL_DEV === "true") {
if (env.VITE_HTTP_PROXY_TARGET === undefined) {
throw new Error("VITE_HTTP_PROXY_TARGET is missing");
}
config.server.open = "vite/index.html";
config.server.proxy = {
"/api/": env.VITE_HTTP_PROXY_TARGET,
};
config.plugins.push(localDevelopMiddleware);
ildyria marked this conversation as resolved.
Show resolved Hide resolved
return config;
}
}

// command === 'build'
config.plugins.push(laravelPlugin);
return config;
});
// command === 'build'
config.plugins.push(laravelPlugin);
return config;
});