瀏覽代碼

electron适配

main
郑州 3 年之前
父節點
當前提交
d4b0a56cee
共有 8 個檔案被更改,包括 163 行新增37 行删除
  1. +21
    -6
      .umirc.ts
  2. +16
    -0
      .vscode/launch.json
  3. +2
    -0
      .yarnrc
  4. +69
    -0
      electron/main.js
  5. +7
    -0
      package.json
  6. +20
    -10
      src/pages/login/index.tsx
  7. +15
    -13
      src/services/user.ts
  8. +13
    -8
      src/utils/request.ts

+ 21
- 6
.umirc.ts 查看文件

@@ -1,25 +1,40 @@
import { defineConfig } from 'umi'; import { defineConfig } from 'umi';


const isBuildingElectron = process.env.BUILD_TYPE === 'electron';

export default defineConfig({ export default defineConfig({
nodeModulesTransform: { nodeModulesTransform: {
type: 'none', type: 'none',
}, },
history: {
type: 'hash',
},
// routes: [ // routes: [
// { path: '/', component: '@/pages/index' }, // { path: '/', component: '@/pages/index' },
// ], // ],
fastRefresh: {}, fastRefresh: {},
publicPath: './',
theme: { theme: {
"primary-color": "#7850FF",
"app-header-height": "48px"
'primary-color': '#7850FF',
'app-header-height': '48px',
},
chainWebpack(config) {
if (isBuildingElectron) {
config.target('electron-renderer');
}
}, },
proxy: {
proxy: {
'/api': { '/api': {
target: 'http://139.198.180.242:9003', target: 'http://139.198.180.242:9003',
// target: 'http://www.lockingos.org:9003', // target: 'http://www.lockingos.org:9003',
//target: 'http://192.168.8.114:8082', //target: 'http://192.168.8.114:8082',
changeOrigin: true, changeOrigin: true,
secure: false, secure: false,
}
}

},
},
define: {
'global.URL_PREFIX': isBuildingElectron
? 'http://139.198.180.242:9003/'
: '',
},
}); });

+ 16
- 0
.vscode/launch.json 查看文件

@@ -0,0 +1,16 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Electron Main",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"program": "${workspaceFolder}/electron/main.js",
"skipFiles": ["<node_internals>/**"]
}
]
}

+ 2
- 0
.yarnrc 查看文件

@@ -0,0 +1,2 @@
electron_mirror https://npm.taobao.org/mirrors/electron/
registry https://registry.npm.taobao.org

+ 69
- 0
electron/main.js 查看文件

@@ -0,0 +1,69 @@
const { app, BrowserWindow, protocol } = require('electron');
const path = require('path');
const url = require('url');

function createWindow() {
//创建窗口
let mainWindow = new BrowserWindow({
height: 900,
webPreferences: {
// preload: path.join(__dirname, 'preload.js'),
webSecurity: false,
nodeIntegration: true,
},
backgroundColor: '#2e2c29',
darkTheme: true,
title: 'My App',
width: 1700,
frame: true,
minWidth: 1300,
minHeight: 900,
});
// 隐藏菜单栏
mainWindow.setMenuBarVisibility(false);
if (process.env.NODE_ENV === 'development') {
// 开发环境
// 加载页面并打开调试工具,根据 NODE_ENV
// umijs 在dev时会给出相应的url,直接加载即可
mainWindow.loadURL('http://localhost:8000/');
mainWindow.webContents.openDevTools();
} else {
//生产环境
// 加载html文件
// 这里的路径是umi输出的html路径,如果没有修改过,路径和下面是一样的
mainWindow.webContents.openDevTools();
// mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, '../dist/index.html'),
protocol: 'file:',
slashes: true,
}),
);
}
mainWindow.on('closed', () => {
mainWindow = null;
});
}

app.on('ready', () => {
createWindow();

app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// protocol.interceptFileProtocol('file', (req,cb) => {

// cb({
// url: req.url,
// })
// });
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});

+ 7
- 0
package.json 查看文件

@@ -2,7 +2,10 @@
"private": true, "private": true,
"scripts": { "scripts": {
"start": "umi dev", "start": "umi dev",
"electron": "electron ./electron/main.js",
"build": "umi build", "build": "umi build",
"build:electron": "cross-env BUILD_TYPE=electron umi build",
"pack": "electron-packager . --platform=win32 --out=release --arch=x64 --out ./electron_dist --overwrite",
"postinstall": "umi generate tmp", "postinstall": "umi generate tmp",
"prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'", "prettier": "prettier --write '**/*.{js,jsx,tsx,ts,less,md,json}'",
"test": "umi-test", "test": "umi-test",
@@ -19,6 +22,7 @@
"prettier --parser=typescript --write" "prettier --parser=typescript --write"
] ]
}, },
"homepage": "./",
"dependencies": { "dependencies": {
"@ant-design/icons": "^4.6.2", "@ant-design/icons": "^4.6.2",
"@ant-design/pro-layout": "^6.5.0", "@ant-design/pro-layout": "^6.5.0",
@@ -28,6 +32,8 @@
"antd": "^4.16.5", "antd": "^4.16.5",
"classnames": "^2.3.1", "classnames": "^2.3.1",
"dayjs": "^1.10.5", "dayjs": "^1.10.5",
"electron": "^13.1.4",
"electron-packager": "^15.2.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"umi": "^3.4.25" "umi": "^3.4.25"
}, },
@@ -37,6 +43,7 @@
"@types/react-dom": "^17.0.0", "@types/react-dom": "^17.0.0",
"@umijs/preset-dumi": "^1.1.20", "@umijs/preset-dumi": "^1.1.20",
"@umijs/test": "^3.4.25", "@umijs/test": "^3.4.25",
"cross-env": "^7.0.3",
"lint-staged": "^10.0.7", "lint-staged": "^10.0.7",
"prettier": "^2.2.0", "prettier": "^2.2.0",
"react": "17.x", "react": "17.x",


+ 20
- 10
src/pages/login/index.tsx 查看文件

@@ -18,8 +18,14 @@ export default function Login() {
// const { loading, signin } = useModel('useAuthModel'); // const { loading, signin } = useModel('useAuthModel');


const onLogin = useCallback(async () => { const onLogin = useCallback(async () => {
if(!account) { setErrText('账号/手机号不能为空'); return;}
if (!password) { setErrText('密码不能为空'); return; }
if (!account) {
setErrText('账号/手机号不能为空');
return;
}
if (!password) {
setErrText('密码不能为空');
return;
}
setLoading(true); setLoading(true);
const res = await login(account, password); const res = await login(account, password);
setLoading(false); setLoading(false);
@@ -29,8 +35,10 @@ export default function Login() {
}) })
.success(() => { .success(() => {
// history.push('/'); // history.push('/');
window.location.href = '/';
})
// window.location.href = '/';
history.replace('/');
window.location.reload();
});
// if(!isReqSuccess(res)) { // if(!isReqSuccess(res)) {
// setErrText(res.msg); // setErrText(res.msg);
// return; // return;
@@ -41,7 +49,7 @@ export default function Login() {


useEffect(() => { useEffect(() => {
setErrText(''); setErrText('');
}, [account, password])
}, [account, password]);


return ( return (
<div className={styles.login}> <div className={styles.login}>
@@ -56,7 +64,7 @@ export default function Login() {
disabled={loading} disabled={loading}
className={styles.mb24} className={styles.mb24}
value={account} value={account}
onChange={e => setAccount(e.target.value)}
onChange={(e) => setAccount(e.target.value)}
/> />
<Input <Input
size="large" size="large"
@@ -65,11 +73,13 @@ export default function Login() {
disabled={loading} disabled={loading}
className={styles.mb4} className={styles.mb4}
value={password} value={password}
onChange={e => setPassword(e.target.value)}
onChange={(e) => setPassword(e.target.value)}
/> />
<div className={styles.errText}>{errText}</div> <div className={styles.errText}>{errText}</div>
<Button loading={loading} type="primary" block onClick={onLogin} >登录</Button>
<Button loading={loading} type="primary" block onClick={onLogin}>
登录
</Button>
</div> </div>
</div> </div>
)
}
);
}

+ 15
- 13
src/services/user.ts 查看文件

@@ -1,4 +1,4 @@
import { history } from '@/.umi/core/history';
import { history } from 'umi';
import { fetchApi } from '@/utils/request'; import { fetchApi } from '@/utils/request';
import storage from '@/utils/storage'; import storage from '@/utils/storage';
import { errorReponse, firstCharToLowerCase, isReqSuccess } from '@/utils/tool'; import { errorReponse, firstCharToLowerCase, isReqSuccess } from '@/utils/tool';
@@ -6,21 +6,22 @@ import { propertyOf } from 'lodash';


export async function queryCurrent() { export async function queryCurrent() {
const accountId = storage.get('accountId'); const accountId = storage.get('accountId');
if(!accountId) {
if (!accountId) {
return errorReponse(''); return errorReponse('');
} }
const res = await fetchApi<API.ResponseData<DATA.User>>('user/queryUserByUserId', { id: accountId });

// const data = firstCharToLowerCase(Object.assign({}, propertyOf(res)('Data.UserExt', {}), res.data || {}));
// data.roleName = roleMap[data.permission] || '';
// data.backgroundRoleName = consoleRoleMap[data.backgroundPermission] || '';
// data.userState = stateMap[data.staffStatus] || '';
// data.isDeparture = data.staffStatus;
const res = await fetchApi<API.ResponseData<DATA.User>>(
'user/queryUserByUserId',
{ id: accountId },
);
return res; return res;
} }


export async function login(account: string, password: string) { export async function login(account: string, password: string) {
const res = await fetchApi('authentication/login', { UserName: account, Password: password }, { silent: true });
const res = await fetchApi(
'authentication/login',
{ UserName: account, Password: password },
{ silent: true },
);
if (!isReqSuccess(res)) { if (!isReqSuccess(res)) {
// dispatch(logout()); // dispatch(logout());
return res; return res;
@@ -37,7 +38,6 @@ export async function login(account: string, password: string) {
// return companyInfoRes; // return companyInfoRes;
// } // }



// const { data: { company: { SoftwareVersion } = {} } = {} } = companyInfoRes; // const { data: { company: { SoftwareVersion } = {} } = {} } = companyInfoRes;


// 角色判断 // 角色判断
@@ -62,5 +62,7 @@ export async function login(account: string, password: string) {


export function logout() { export function logout() {
storage.clear(); storage.clear();
window.location.href = '/login';
}
// window.location.href = '/login';
history.replace('/login');
window.location.reload();
}

+ 13
- 8
src/utils/request.ts 查看文件

@@ -3,16 +3,21 @@ import { request } from 'umi';
import { parseRequest } from './request.config'; import { parseRequest } from './request.config';
import { firstCharToLowerCase, handleRequest } from './tool'; import { firstCharToLowerCase, handleRequest } from './tool';



export async function fetchApi<T = any>(path: string, params = {}, options = { silent: false }) {
export async function fetchApi<T = any>(
path: string,
params = {},
options = { silent: false },
) {
const [method, fullpath] = parseRequest(path); const [method, fullpath] = parseRequest(path);
const { silent, ...restOptions } = options; const { silent, ...restOptions } = options;
const res = await request<API.ResponseData<T>>(fullpath, { method, [method === 'GET' ? 'params' : 'data']: params, ...restOptions });
if(!silent) {
handleRequest(res)
.error(() => {
const res = await request<API.ResponseData<T>>(
`${global.URL_PREFIX || ''}${fullpath}`,
{ method, [method === 'GET' ? 'params' : 'data']: params, ...restOptions },
);
if (!silent) {
handleRequest(res).error(() => {
message.error(res.message); message.error(res.message);
})
});
} }
return res; return res;
}
}

Loading…
取消
儲存