Skip to content

Commit

Permalink
Merge pull request #817 from ral-facilities/apply-changes-from-OG-vite
Browse files Browse the repository at this point in the history
Apply changes from OG Vite migration
  • Loading branch information
joelvdavies authored Sep 6, 2024
2 parents 4d39928 + dd44efe commit 17acaef
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 67 deletions.
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ For more details about the project's architecture, development guidelines and in

This project uses [Vite](https://vitejs.dev/).

## Code structure

The project is structured as a monorepo. This means that the actual code packages are located under `inventory-management-system`

### Available Scripts

In the project directory, you can run:
Expand Down
50 changes: 22 additions & 28 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,33 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Website created using Vite"
/>
<link rel="apple-touch-icon" href="/logo192.png" />
<!--

<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Website created using Vite" />
<link rel="apple-touch-icon" href="/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="/manifest.json" />
<title>Inventory Management System</title>
</head>
<body>
<script
crossorigin
src="https://unpkg.com/react@18/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"
></script>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="inventory-management-system"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
<link rel="manifest" href="/manifest.json" />
<title>Inventory Management System</title>
</head>

<body>
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="inventory-management-system"></div>
<script type="module" src="/src/main.tsx"></script>
</body>

</html>
47 changes: 17 additions & 30 deletions src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import axios from 'axios';
import * as log from 'loglevel';
import { SetupWorker } from 'msw/browser';
import log from 'loglevel';
import React from 'react';
import ReactDOMClient from 'react-dom/client';
import singleSpaReact from 'single-spa-react';
Expand Down Expand Up @@ -167,11 +166,19 @@ export const fetchSettings =
});
};

const settings = fetchSettings();
setSettings(settings);

async function prepare() {
if (import.meta.env.DEV || import.meta.env.VITE_APP_INCLUDE_MSW === 'true') {
// When in dev, only use MSW if the api url is given, otherwise load MSW as it must have been explicitly requested
const settingsResult = await settings;
if (
import.meta.env.VITE_APP_INCLUDE_MSW === 'true' ||
settingsResult?.apiUrl === ''
) {
// Need to use require instead of import as import breaks when loaded in SG
const { worker } = await import('./mocks/browser');
return (worker as SetupWorker).start({
return worker.start({
onUnhandledRequest(request, print) {
// Ignore unhandled requests to non-localhost things (normally means you're contacting a real server)
if (request.url.includes('localhost')) {
Expand All @@ -181,42 +188,22 @@ async function prepare() {
print.warning();
},
});
}
return Promise.resolve();
} else return Promise.resolve();
}

const settings = fetchSettings();

setSettings(settings);

/* Renders only if we're not being loaded by SG */
const conditionalSciGatewayRender = () => {
if (!document.getElementById('scigateway')) {
render();
}
};

if (import.meta.env.DEV) {
// When in dev, only use MSW if the api url or otherwise if MSW is explicitly requested
settings
.then((settings) => {
if (
(settings && settings.apiUrl !== '') ||
import.meta.env.VITE_APP_INCLUDE_MSW === 'false'
)
conditionalSciGatewayRender();
else prepare().then(() => conditionalSciGatewayRender());
})
.catch((error) => log.error(`Got error: ${error.message}`));
if (import.meta.env.DEV || import.meta.env.VITE_APP_INCLUDE_MSW === 'true') {
prepare().then(() => conditionalSciGatewayRender());

log.setDefaultLevel(log.levels.DEBUG);
} else {
// When in production, only use MSW if explicitly requested
if (import.meta.env.VITE_APP_INCLUDE_MSW === 'true') {
prepare().then(() => conditionalSciGatewayRender());
log.setDefaultLevel(log.levels.DEBUG);
} else {
conditionalSciGatewayRender();
log.setDefaultLevel(log.levels.ERROR);
}
conditionalSciGatewayRender();

log.setDefaultLevel(log.levels.ERROR);
}
15 changes: 10 additions & 5 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function jsonHMR(): PluginOption {
if (file.endsWith('.json')) {
console.log('reloading json file...');

server.hot.send({
server.ws.send({
type: 'full-reload',
path: '*',
});
Expand All @@ -38,10 +38,11 @@ function jsonHMR(): PluginOption {

// Obtain default coverage config from vitest when not building for production
// (to avoid importing vitest during build as its a dev dependency)
let coverageConfigDefaultsExclude: string[] = [];
let vitestCoverageConfigDefaultsExclude: string[] = [];
if (process.env.NODE_ENV !== 'production') {
await import('vitest/config').then((vitestConfig) => {
coverageConfigDefaultsExclude = vitestConfig.coverageConfigDefaults.exclude;
vitestCoverageConfigDefaultsExclude =
vitestConfig.coverageConfigDefaults.exclude;
});
}

Expand Down Expand Up @@ -90,7 +91,11 @@ export default defineConfig(({ mode }) => {
// Config for deployment in SciGateway
config.build = {
lib: {
// https://github.com/vitejs/vite/issues/7130
// We use `umd` here as `es` causes some import statements to leak into the main.js, breaking the build
// removing this entirely uses a default of both, which for build results in `umd` taking precedence but when
// using --watch, `es` appears to replace it intermittently. Hopefully this can be fixed in the future and we
// can use `es` instead.
formats: ['umd'],
entry: 'src/main.tsx',
name: 'inventory-management-system',
},
Expand Down Expand Up @@ -147,7 +152,7 @@ export default defineConfig(({ mode }) => {
['lcov', { outputFile: 'lcov.info', silent: true }],
],
exclude: [
...coverageConfigDefaultsExclude,
...vitestCoverageConfigDefaultsExclude,
'public/*',
'server/*',
// Leave handlers to show up unused code
Expand Down

0 comments on commit 17acaef

Please sign in to comment.