Skip to content

Commit

Permalink
build: optimize js bundle (#5300)
Browse files Browse the repository at this point in the history
- use dynamic import for @canonical/macaroon-bakery
- reduce JS bundle by 505.47 kB for installations without external auth
  • Loading branch information
petermakowski committed Jan 22, 2024
1 parent cb0de9c commit e3444af
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
23 changes: 12 additions & 11 deletions src/app/base/sagas/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type { Script } from "@/app/store/script/types";
import { ScriptResultNames } from "@/app/store/scriptresult/types";
import type { SimpleNode } from "@/app/store/types/node";
import { getCookie } from "@/app/utils";
import bakery from "@/bakery";

type CSRFToken = string;

Expand Down Expand Up @@ -102,17 +101,19 @@ export const api = {
},
externalLogin: (): Promise<XMLHttpRequest["response"]> => {
return new Promise((resolve, reject) => {
bakery.get(
BAKERY_LOGIN_API,
DEFAULT_HEADERS,
(_: unknown, response: XMLHttpRequest["response"]) => {
if (response.currentTarget.status !== 200) {
localStorage.clear();
reject(Error(response.currentTarget.responseText));
} else {
resolve({ response });
import("@/bakery").then(({ default: bakery }) =>
bakery.get(
BAKERY_LOGIN_API,
DEFAULT_HEADERS,
(_: unknown, response: XMLHttpRequest["response"]) => {
if (response.currentTarget.status !== 200) {
localStorage.clear();
reject(Error(response.currentTarget.responseText));
} else {
resolve({ response });
}
}
}
)
);
});
},
Expand Down
19 changes: 19 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ import react from "@vitejs/plugin-react-swc";
import * as path from "path";
import eslint from "vite-plugin-eslint";

const manualChunks = [
"@canonical/react-components",
"@canonical/maas-react-components",
"@canonical/macaroon-bakery",
"@/app/store/machine/slice",
];

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, "./");
Expand All @@ -20,6 +27,18 @@ export default defineConfig(({ mode }) => {
rollupOptions: {
output: {
sanitizeFileName: false,
// Creates an object with sanitized camel-cased module names as keys and original module names as values.
// e.g.: { "canonicalReactComponents": ["@canonical/react-components"] }.
manualChunks: manualChunks.reduce((chunks, module) => {
const sanitizedModule = module
.replace(/(^|[-\/])(.)/g, (_, _separator, letter) =>
letter.toUpperCase()
)
.replace(/[^a-zA-Z0-9]/g, "")
.replace(/^./, (firstChar) => firstChar.toLowerCase());
chunks[sanitizedModule] = [module];
return chunks;
}, {}),
},
},
sourcemap: true,
Expand Down

0 comments on commit e3444af

Please sign in to comment.