Skip to content

Commit

Permalink
feat: initial move to vite
Browse files Browse the repository at this point in the history
  • Loading branch information
itschip committed Nov 6, 2023
1 parent c33c8cb commit c03d49f
Show file tree
Hide file tree
Showing 18 changed files with 2,296 additions and 555 deletions.
1 change: 0 additions & 1 deletion .github/workflows/tagged-releases.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


- name: Bump manifest version
run: node .github/actions/bump-manifest-version.js
env:
Expand Down
13 changes: 13 additions & 0 deletions apps/phone/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
12 changes: 8 additions & 4 deletions apps/phone/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
"dependencies": {
"@babel/runtime": "^7.17.2",
"@emotion/css": "^11.10.5",
"@emotion/react": "^11.10.5",
"@emotion/styled": "^11.10.5",
"@emotion/react": "^11.7.0",
"@emotion/styled": "^11.6.0",
"@mui/icons-material": "^5.11.0",
"@mui/lab": "^5.0.0-alpha.131",
"@mui/material": "^5.13.2",
Expand All @@ -31,17 +31,18 @@
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-i18next": "^11.14.3",
"react-virtuoso": "^4.3.8",
"react-infinite-scroll-component": "^6.1.0",
"react-router-dom": "^5.3.0",
"react-scripts": "^5.0.0",
"react-uuid": "^1.0.3",
"react-virtuoso": "^4.3.8",
"recoil": "^0.7.7",
"tailwind-merge": "^1.10.0",
"uuid": "^8.3.2",
"xss": "^1.0.13"
},
"devDependencies": {
"@originjs/vite-plugin-federation": "^1.3.2",
"@sentry/integrations": "^6.15.0",
"@sentry/react": "^5.29.2",
"@sentry/tracing": "^5.29.2",
Expand All @@ -57,6 +58,7 @@
"@types/react": "^18.2.6",
"@types/react-dom": "^16.9.8",
"@types/react-router-dom": "^5.3.2",
"@vitejs/plugin-react": "^4.1.1",
"@welldone-software/why-did-you-render": "^6.2.3",
"autoprefixer": "^10.4.14",
"babel-loader": "^8.2.3",
Expand All @@ -74,13 +76,15 @@
"tailwindcss": "^3.2.7",
"ts-loader": "^9.4.2",
"typescript": "^4.9.5",
"vite": "^4.5.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.7.4"
},
"scripts": {
"i18n:missing": "node --experimental-json-modules i18n.missingKeys.js",
"dev": "cross-env IS_BROWSER_DEV=1 webpack serve --config config/webpack.dev.js --mode development",
"dev:old": "cross-env IS_BROWSER_DEV=1 webpack serve --config config/webpack.dev.js --mode development",
"dev": "cross-env IS_BROWSER_DEV=1 vite",
"build": "webpack --config config/webpack.production.js --mode production --progress --color",
"dev:game": "cross-env REACT_APP_IN_GAME=1 BROWSER=none webpack --config config/webpack.dev.js --mode development --watch --progress"
},
Expand Down
72 changes: 39 additions & 33 deletions apps/phone/src/apps/contacts/components/modals/SendMoney.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useTranslation } from 'react-i18next';
import { Box, Typography } from '@mui/material';
import { Button } from '@ui/components/Button';
import { TabContext, TabPanel } from '@mui/lab';
import { useTranslation } from 'react-i18next';
import { useContactsAPI } from '../../hooks/useContactsAPI';

interface SendMoneyModalProps {
Expand All @@ -13,41 +12,48 @@ interface SendMoneyModalProps {
openContact: string;
}

export const SendMoneyModal: React.FC<SendMoneyModalProps> = ({ open, closeModal, openContact }) => {
const { payContact } = useContactsAPI();
const [t] = useTranslation();
export const SendMoneyModal: React.FC<SendMoneyModalProps> = ({
open,
closeModal,
openContact,
}) => {
const { payContact } = useContactsAPI();
const [t] = useTranslation();

const [amount, setAmount] = useState(500);
const [amount, setAmount] = useState(500);

const handleAmountChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.currentTarget.value;
setAmount(parseInt(inputVal));
};
const handleAmountChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.currentTarget.value;
setAmount(parseInt(inputVal));
};

const sendContactMoney = () => {
if (amount && amount > 0)
{
closeModal();
payContact({ number: openContact, amount: amount });
}
};
const sendContactMoney = () => {
if (amount && amount > 0) {
closeModal();
payContact({ number: openContact, amount: amount });
}
};

return (
<Modal visible={open} handleClose={closeModal}>
<TabContext value='1'>
<TabPanel value="1">
<Typography>{t('CONTACTS.SENDMONEY')}</Typography>
return (
<Modal visible={open} handleClose={closeModal}>
<TabContext value="1">
<TabPanel value="1">
<Typography>{t('CONTACTS.SENDMONEY')}</Typography>

<Box mt={2} mb={2}>
<Box display="flex" flexDirection="column" alignItems="flex-start" gap={2}>
<TextField placeholder={t('CONTACTS.AMOUNT')} value={amount} onChange={handleAmountChange} />
<Button onClick={sendContactMoney} variant="outlined" color="primary" >
{t('GENERIC.SEND')}
</Button>
</Box>
</Box>
</TabPanel>
</TabContext>
</Modal>
);
<Box mt={2} mb={2}>
<Box display="flex" flexDirection="column" alignItems="flex-start" gap={2}>
<TextField
placeholder={t('CONTACTS.AMOUNT')}
value={amount}
onChange={handleAmountChange}
/>
<Button onClick={sendContactMoney} variant="outlined" color="primary">
{t('GENERIC.SEND')}
</Button>
</Box>
</Box>
</TabPanel>
</TabContext>
</Modal>
);
};
29 changes: 19 additions & 10 deletions apps/phone/src/common/hooks/useExternalApps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ import { createExternalAppProvider } from '@os/apps/utils/createExternalAppProvi
import { useRecoilState, useRecoilValue } from 'recoil';
import { phoneState } from '@os/phone/hooks/state';

import {
__federation_method_getRemote,
__federation_method_setRemote,
__federation_method_unwrapDefault,
// @ts-ignore - This is Vite federation magic
} from '__federation__';

const useExternalAppsAction = () => {
const loadScript = async (url: string) => {
await new Promise((resolve, reject) => {
Expand All @@ -26,27 +33,29 @@ const useExternalAppsAction = () => {
};
});
};

const generateAppConfig = async (appName: string): Promise<IApp> => {
try {
const IN_GAME = process.env.NODE_ENV === 'production' || process.env.REACT_APP_IN_GAME;
const IN_GAME = import.meta.env.PROD || import.meta.env.REACT_APP_IN_GAME;
const url = IN_GAME
? `https://cfx-nui-${appName}/web/dist/remoteEntry.js`
: 'http://localhost:3002/remoteEntry.js';
: 'http://localhost:4173/assets/remoteEntry.js';
const scope = appName;
const module = './config';

await loadScript(url);

await __webpack_init_sharing__('default');
const container = window[scope];
console.log('Loaded external app', appName);

await container.init(__webpack_share_scopes__.default);
const factory = await window[scope].get(module);
const Module = factory();
__federation_method_setRemote(scope, {
url: () => Promise.resolve(url),
format: 'esm',
from: 'vite',
});

const appConfig = Module.default();
const mWrapper = await __federation_method_getRemote(scope, './config');
const m = await __federation_method_unwrapDefault(mWrapper);

const appConfig = m();
const config = appConfig;
config.Component = (props: object) => React.createElement(config.app, props);

Expand Down
2 changes: 1 addition & 1 deletion apps/phone/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const missingKeyHandler = (
key: string,
fallbackValue: string,
) => {
if (process.env.NODE_ENV !== 'development') return;
if (!import.meta.env.DEV) return;
console.error(
`!! TRANSLATION KEY NOT FOUND FOR LANGAUGE "${lng}", KEY "${key}". RENDERED ${fallbackValue} INSTEAD"" !!`,
);
Expand Down
3 changes: 1 addition & 2 deletions apps/phone/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import updateLocale from 'dayjs/plugin/updateLocale';
import { Theme as MaterialUITheme } from '@mui/material';
import { RewriteFrames } from '@sentry/integrations';
import attachWindowDebug from './os/debug/AttachWindowDebug';
import { NuiProvider } from 'fivem-nui-react-lib';
import { RecoilRootManager } from './lib/RecoilRootManager';
Expand All @@ -26,7 +25,7 @@ declare module '@emotion/react' {
}

// window.mockNuiEvent is restricted to development env only
if (process.env.NODE_ENV === 'development') {
if (import.meta.env.DEV) {
attachWindowDebug();
}

Expand Down
2 changes: 1 addition & 1 deletion apps/phone/src/os/apps/config/apps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export const APPS: IAppConfig[] = [
];

// Example app only in dev
if (process.env.NODE_ENV === 'development') {
if (import.meta.env.DEV) {
APPS.push({
id: 'EXAMPLE',
nameLocale: 'APPS_EXAMPLE',
Expand Down
7 changes: 3 additions & 4 deletions apps/phone/src/os/apps/hooks/useApps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { useSettingsValue } from '../../../apps/settings/hooks/useSettings';
import { IconSetObject } from '@typings/settings';
import { useRecoilValue } from 'recoil';
import { phoneState } from '@os/phone/hooks/state';
import { extname } from 'path';
import { usePhone } from '@os/phone/hooks';

export const useApps = () => {
Expand All @@ -21,16 +20,16 @@ export const useApps = () => {
const apps: IApp[] = useMemo(() => {
return APPS.map((app) => {
const SvgIcon = React.lazy<SvgIconComponent>(() =>
import(`${__dirname}/../icons/${curIconSet.name}/svg/${app.id}`).catch(
import(`../icons/${curIconSet.name}/svg/${app.id}`).catch(
() => 'Was not able to find a dynamic import for icon from this icon set',
),
);
const AppIcon = React.lazy<SvgIconComponent>(() =>
import(`${__dirname}/../icons/${curIconSet.name}/app/${app.id}`).catch(
import(`../icons/${curIconSet.name}/app/${app.id}`).catch(
() => 'Was not able to find a dynamic import for icon from this icon set',
),
);

const NotificationIcon = createLazyAppIcon(SvgIcon);
const Icon = createLazyAppIcon(AppIcon);

Expand Down
2 changes: 1 addition & 1 deletion apps/phone/src/os/debug/InjectDebugData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export interface DebugEvent<P = any> {
* ])
**/
const InjectDebugData = <P>(events: DebugEvent<P>[], timer = 3000) => {
if (process.env.NODE_ENV === 'development' && !process.env.REACT_APP_IN_GAME) {
if (import.meta.env.DEV && !import.meta.env.REACT_APP_IN_GAME) {
for (const event of events) {
console.log('EVENT', event);
setTimeout(() => {
Expand Down
6 changes: 1 addition & 5 deletions apps/phone/src/os/debug/LogDebugEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,7 @@ function LogDebugEvent(event: DebugEvent) {
const logLevel = event.level || 1;
const name = event.action || 'Undefined action';

if (
process.env.NODE_ENV === 'development' &&
config.debug.printDebugLogs &&
logLevel >= config.debug.logLevel
) {
if (import.meta.env.DEV && config.debug.printDebugLogs && logLevel >= config.debug.logLevel) {
console.group(`${name} | Level: ${logLevel}`);
console.dir(event.data);
console.groupEnd();
Expand Down
3 changes: 1 addition & 2 deletions apps/phone/src/utils/misc.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// Quickly determine whether we are in browser
import { ServerPromiseResp } from '@typings/common';

export const isEnvBrowser = (): boolean =>
process.env.NODE_ENV === 'development' && !(window as any).invokeNative;
export const isEnvBrowser = (): boolean => import.meta.env.DEV && !(window as any).invokeNative;

export const getResourceName = () =>
(window as any).GetParentResourceName ? (window as any)?.GetParentResourceName() : 'npwd';
Expand Down
1 change: 1 addition & 0 deletions apps/phone/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
2 changes: 1 addition & 1 deletion apps/phone/src/wdyr.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// <reference types="@welldone-software/why-did-you-render" />
import React from 'react';

if (process.env.NODE_ENV === 'development') {
if (import.meta.env.DEV) {
const whyDidYouRender = require('@welldone-software/why-did-you-render');
whyDidYouRender(React, {
trackAllPureComponents: true,
Expand Down
33 changes: 33 additions & 0 deletions apps/phone/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

import federation from '@originjs/vite-plugin-federation';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
federation({
remotes: { dummyRemote: 'dummyRemote.js' },
shared: ['react', 'react-dom', '@emotion/react', 'react-router-dom'],
}),
],
server: {
port: 3000,
},
resolve: {
alias: {
'@os': path.resolve(__dirname, './src/os/'),
'@ui': path.resolve(__dirname, './src/ui/'),
'@common': path.resolve(__dirname, './src/common/'),
'@utils': path.resolve(__dirname, './src/utils/'),
'@apps': path.resolve(__dirname, './src/apps/'),
'@typings': path.resolve(__dirname, '../../typings/'),
'@shared': path.resolve(__dirname, '../../shared'),
},
},
define: {
'process.env': {},
},
});
2 changes: 1 addition & 1 deletion config.default.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
},
"defaultContacts": [],
"disabledApps": [],
"apps": [],
"apps": ["mockapp"],
"voiceMessage": {
"enabled": false,
"authorizationHeader": "Authorization",
Expand Down
2 changes: 1 addition & 1 deletion config.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
},
"defaultContacts": [],
"disabledApps": [],
"apps": ["pefcl"],
"apps": ["mockapp"],
"voiceMessage": {
"enabled": false,
"authorizationHeader": "PE-Secret",
Expand Down
Loading

0 comments on commit c03d49f

Please sign in to comment.