Browse Source

electron适配

main
郑州 3 years ago
parent
commit
d4b0a56cee
8 changed files with 163 additions and 37 deletions
  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 View File

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

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

export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
history: {
type: 'hash',
},
// routes: [
// { path: '/', component: '@/pages/index' },
// ],
fastRefresh: {},
publicPath: './',
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': {
target: 'http://139.198.180.242:9003',
// target: 'http://www.lockingos.org:9003',
//target: 'http://192.168.8.114:8082',
changeOrigin: true,
secure: false,
}
}

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

+ 16
- 0
.vscode/launch.json View File

@@ -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 View File

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

+ 69
- 0
electron/main.js View File

@@ -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 View File

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


+ 20
- 10
src/pages/login/index.tsx View File

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

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

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

return (
<div className={styles.login}>
@@ -56,7 +64,7 @@ export default function Login() {
disabled={loading}
className={styles.mb24}
value={account}
onChange={e => setAccount(e.target.value)}
onChange={(e) => setAccount(e.target.value)}
/>
<Input
size="large"
@@ -65,11 +73,13 @@ export default function Login() {
disabled={loading}
className={styles.mb4}
value={password}
onChange={e => setPassword(e.target.value)}
onChange={(e) => setPassword(e.target.value)}
/>
<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>
)
}
);
}

+ 15
- 13
src/services/user.ts View File

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

export async function queryCurrent() {
const accountId = storage.get('accountId');
if(!accountId) {
if (!accountId) {
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;
}

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)) {
// dispatch(logout());
return res;
@@ -37,7 +38,6 @@ export async function login(account: string, password: string) {
// return companyInfoRes;
// }


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

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

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

+ 13
- 8
src/utils/request.ts View File

@@ -3,16 +3,21 @@ import { request } from 'umi';
import { parseRequest } from './request.config';
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 { 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);
})
});
}
return res;
}
}

Loading…
Cancel
Save