从webpack迁移到vite

This commit is contained in:
lyswhut
2023-08-07 18:49:14 +08:00
parent 31e16a7ed7
commit 028bf5919d
166 changed files with 3071 additions and 11869 deletions
+18
View File
@@ -0,0 +1,18 @@
/* eslint-env node */
const { base, typescript } = require('../../.eslintrc.base.cjs')
module.exports = {
root: true,
...base,
overrides: [
{
...typescript,
parserOptions: {
project: './tsconfig.json',
},
},
],
ignorePatterns: [
'vendors',
],
}
+14 -17
View File
@@ -1,4 +1,4 @@
import { join, dirname } from 'path'
import path from 'node:path'
import { existsSync, mkdirSync, renameSync } from 'fs'
import { app, shell, screen, nativeTheme, dialog } from 'electron'
import { URL_SCHEME_RXP } from '@common/constants'
@@ -10,22 +10,19 @@ import { createAppEvent, createListEvent } from '@main/event'
import { isMac, log } from '@common/utils'
import createWorkers from './worker'
import { migrateDBData } from './utils/migrate'
import { openDirInExplorer } from '@common/utils/electron'
import { encodePath, openDirInExplorer } from '@common/utils/electron'
export const initGlobalData = () => {
global.isDev = process.env.NODE_ENV !== 'production'
const envParams = parseEnvParams()
global.envParams = {
cmdParams: envParams.cmdParams,
deeplink: envParams.deeplink,
}
if (global.isDev) {
// eslint-disable-next-line no-undef
global.staticPath = webpackStaticPath
} else {
global.staticPath = join(__dirname, '/static')
}
global.staticPath =
process.env.NODE_ENV !== 'production'
? __STATIC_PATH__
: path.join(encodePath(__dirname), '../static')
}
export const initSingleInstanceHandle = () => {
@@ -75,10 +72,10 @@ export const applyElectronEnvParams = () => {
export const setUserDataPath = () => {
// windows平台下如果应用目录下存在 portable 文件夹则将数据存在此文件下
if (process.platform == 'win32') {
const portablePath = join(dirname(app.getPath('exe')), '/portable')
const portablePath = path.join(path.dirname(app.getPath('exe')), '/portable')
if (existsSync(portablePath)) {
app.setPath('appData', portablePath)
const appDataPath = join(portablePath, '/userData')
const appDataPath = path.join(portablePath, '/userData')
if (!existsSync(appDataPath)) mkdirSync(appDataPath)
app.setPath('userData', appDataPath)
}
@@ -86,12 +83,12 @@ export const setUserDataPath = () => {
const userDataPath = app.getPath('userData')
global.lxOldDataPath = userDataPath
global.lxDataPath = join(userDataPath, 'LxDatas')
global.lxDataPath = path.join(userDataPath, 'LxDatas')
if (!existsSync(global.lxDataPath)) mkdirSync(global.lxDataPath)
}
export const registerDeeplink = (startApp: () => void) => {
if (global.isDev && process.platform === 'win32') {
if (process.env.NODE_ENV !== 'production' && process.platform === 'win32') {
// Set the path of electron.exe and your app.
// These two additional parameters are only available on windows.
// console.log(process.execPath, process.argv)
@@ -117,8 +114,8 @@ export const registerDeeplink = (startApp: () => void) => {
export const listenerAppEvent = (startApp: () => void) => {
app.on('web-contents-created', (event, contents) => {
contents.on('will-navigate', (event, navigationUrl) => {
if (global.isDev) {
console.log('navigation to url:', navigationUrl)
if (process.env.NODE_ENV !== 'production') {
console.log('navigation to url:', navigationUrl.length > 130 ? navigationUrl.substring(0, 130) + '...' : navigationUrl)
return
}
if (!navigationUrlWhiteList.some(url => url.test(navigationUrl))) {
@@ -240,13 +237,13 @@ export const initAppSetting = async() => {
if (!isInitialized) {
let dbFileExists = await global.lx.worker.dbService.init(global.lxDataPath)
if (dbFileExists === null) {
const backPath = join(global.lxDataPath, `lx.data.db.${Date.now()}.bak`)
const backPath = path.join(global.lxDataPath, `lx.data.db.${Date.now()}.bak`)
dialog.showMessageBoxSync({
type: 'warning',
message: 'Database verify failed',
detail: `数据库表结构校验失败,我们将把有问题的数据库备份到:${backPath}\n若此问题导致你的数据丢失,你可以尝试从备份文件找回它们。\n\nThe database table structure verification failed, we will back up the problematic database to: ${backPath}\nIf this problem causes your data to be lost, you can try to retrieve them from the backup file.`,
})
renameSync(join(global.lxDataPath, 'lx.data.db'), backPath)
renameSync(path.join(global.lxDataPath, 'lx.data.db'), backPath)
openDirInExplorer(backPath)
dbFileExists = await global.lx.worker.dbService.init(global.lxDataPath)
}
+1 -1
View File
@@ -26,5 +26,5 @@ app.on('ready', () => {
})
// Require `main` process to boot app
require('./index')
import('./index')
+1
View File
@@ -1,4 +1,5 @@
import { app } from 'electron'
import './utils/logInit'
import '@common/error'
import {
initGlobalData,
+2 -2
View File
@@ -1,8 +1,8 @@
import WebSocket from 'ws'
import { encryptMsg, decryptMsg } from './utils'
import * as modules from './modules'
// import { action as commonAction } from '@/store/modules/common'
// import { getStore } from '@/store'
// import { action as commonAction } from '@root/store/modules/common'
// import { getStore } from '@root/store'
import registerSyncListHandler from './syncList'
import log from '../log'
import { SYNC_CLOSE_CODE, SYNC_CODE } from '@common/constants'
+1 -1
View File
@@ -1,6 +1,6 @@
import handleAuth from './auth'
import { connect as socketConnect, disconnect as socketDisconnect, sendSyncStatus, sendSyncMessage } from './client'
// import { getSyncHost } from '@/utils/data'
// import { getSyncHost } from '@root/utils/data'
import { SYNC_CODE } from '@common/constants'
import log from '../log'
import { parseUrl } from './utils'
+3 -3
View File
@@ -1,6 +1,6 @@
import { Tray, Menu, nativeImage } from 'electron'
import { isWin } from '@common/utils'
import { join } from 'path'
import path from 'node:path'
import {
hideWindow as hideMainWindow,
isExistWindow as isExistMainWindow,
@@ -45,7 +45,7 @@ export const createTray = () => {
themeId = global.lx.appSetting['tray.themeId']
let theme = themeList.find(item => item.id === themeId) ?? themeList[0]
const iconPath = join(global.staticPath, 'images/tray', theme.fileName + '.png')
const iconPath = path.join(global.staticPath, 'images/tray', theme.fileName + '.png')
// 托盘
tray = new Tray(nativeImage.createFromPath(iconPath))
@@ -140,7 +140,7 @@ export const createMenu = () => {
export const setTrayImage = (themeId: number) => {
if (!tray) return
let theme = themeList.find(item => item.id === themeId) ?? themeList[0]
const iconPath = join(global.staticPath, 'images/tray', theme.fileName + '.png')
const iconPath = path.join(global.staticPath, 'images/tray', theme.fileName + '.png')
tray.setImage(nativeImage.createFromPath(iconPath))
}
-2
View File
@@ -1,2 +0,0 @@
exports.userApis = []
+2
View File
@@ -0,0 +1,2 @@
export const userApis: LX.UserApi.UserApiInfo[] = []
+8 -7
View File
@@ -1,7 +1,7 @@
import { mainSend } from '@common/mainIpc'
import { BrowserWindow } from 'electron'
import fs from 'fs'
import { join } from 'path'
import path from 'node:path'
import { openDevTools as handleOpenDevTools } from '@main/utils'
import { encodePath } from '@common/utils/electron'
@@ -27,15 +27,16 @@ const winEvent = () => {
export const createWindow = async(userApi: LX.UserApi.UserApiInfo) => {
await closeWindow()
dir ??= global.isDev ? webpackUserApiPath : join(encodePath(__dirname), 'userApi')
dir ??= process.env.NODE_ENV !== 'production' ? path.join(__USER_API_PATH__, 'renderer') : encodePath(__dirname)
if (!html) {
html = await fs.promises.readFile(join(dir, 'renderer/user-api.html'), 'utf8')
html = await fs.promises.readFile(path.join(dir, 'user-api.html'), 'utf8')
}
const preloadUrl = global.isDev
? `${join(encodePath(__dirname), '../dist/user-api-preload.js')}`
: `${join(encodePath(__dirname), 'user-api-preload.js')}`
// console.log(preloadUrl)
const preloadUrl = process.env.NODE_ENV !== 'production'
? `${path.join(encodePath(__dirname), '../dist/user-api-preload.js')}`
: `${path.join(encodePath(__dirname), '../preload/user-api-preload.js')}`
// console.log(preloadUrl, html)
/**
* Initial window options
+5 -5
View File
@@ -1,8 +1,8 @@
const { contextBridge, ipcRenderer } = require('electron')
const needle = require('needle')
const zlib = require('zlib')
const { createCipheriv, publicEncrypt, constants, randomBytes, createHash } = require('crypto')
const USER_API_RENDERER_EVENT_NAME = require('../rendererEvent/name')
import { contextBridge, ipcRenderer } from 'electron'
import needle from 'needle'
import zlib from 'zlib'
import { createCipheriv, publicEncrypt, constants, randomBytes, createHash } from 'crypto'
import USER_API_RENDERER_EVENT_NAME from '../rendererEvent/name'
for (const key of Object.keys(process.env)) {
if (/^(?:http_proxy|https_proxy|NO_PROXY)$/i.test(key)) delete process.env[key]
@@ -10,4 +10,5 @@ const names = {
for (const key of Object.keys(names)) {
names[key] = `userApi_${key}`
}
module.exports = names
export default names
@@ -104,7 +104,7 @@ export const loadApi = async(apiId: string) => {
// // const path = require('path')
// // // eslint-disable-next-line no-undef
// // userApi.script = require('fs').readFileSync(join(global.isDev ? __userApi : __dirname, 'renderer/test-api.js')).toString()
// // userApi.script = require('fs').readFileSync(join(process.env.NODE_ENV !== 'production' ? __userApi : __dirname, 'renderer/test-api.js')).toString()
// console.log('load api', userApi.name)
// mainSend(global.modules.userApiWindow, USER_API_RENDERER_EVENT_NAME.init, { userApi })
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { join } from 'path'
import path from 'node:path'
import { BrowserWindow } from 'electron'
import { debounce, isLinux, isWin } from '@common/utils'
import { initWindowSize } from './utils'
@@ -139,7 +139,7 @@ export const createWindow = () => {
},
})
const winURL = global.isDev ? 'http://localhost:9081/lyric.html' : `file://${join(encodePath(__dirname), 'lyric.html')}`
const winURL = process.env.NODE_ENV !== 'production' ? 'http://localhost:9081' : `file://${path.join(encodePath(__dirname), '../renderer-lyric/index.html')}`
void browserWindow.loadURL(winURL + `?dark=${shouldUseDarkColors}&theme=${encodeURIComponent(JSON.stringify(theme))}`)
winEvent()
+2 -2
View File
@@ -1,5 +1,5 @@
import { BrowserWindow, dialog } from 'electron'
import { join } from 'path'
import path from 'node:path'
import { createTaskBarButtons, getWindowSizeInfo } from './utils'
import { isLinux, isWin } from '@common/utils'
import { openDevTools as handleOpenDevTools } from '@main/utils'
@@ -96,7 +96,7 @@ export const createWindow = () => {
}
browserWindow = new BrowserWindow(options)
const winURL = global.isDev ? 'http://localhost:9080' : `file://${join(encodePath(__dirname), 'index.html')}`
const winURL = process.env.NODE_ENV !== 'production' ? 'http://localhost:9080' : `file://${path.join(encodePath(__dirname), '../renderer/index.html')}`
void browserWindow.loadURL(winURL + `?dt=${!!global.envParams.cmdParams.dt}&dark=${shouldUseDarkColors}&theme=${encodeURIComponent(JSON.stringify(theme))}`)
winEvent()
@@ -1,5 +1,5 @@
import { createInflate, constants as zlibConstants } from 'node:zlib'
// import path from 'path'
import path from 'node:path'
import { mainHandle } from '@common/mainIpc'
import { WIN_MAIN_RENDERER_EVENT_NAME } from '@common/ipcNames'
@@ -38,9 +38,9 @@ const decode = async(str: string): Promise<string> => {
const handleDecode = async(lrc: string, tlrc: string, rlrc: string) => {
if (!qrc_decode) {
// const nativeBindingPath = path.join(__dirname, '../build/Release/qrc_decode.node')
// const nativeBindingPath = isDev ? path.join(__dirname, '../build/Release/qrc_decode.node')
// const nativeBindingPath = process.env.NODE_ENV !== 'production' ? path.join(__dirname, '../build/Release/qrc_decode.node')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const addon = require('qrc_decode.node')
const addon = require(path.join(__QRC_DECODE_NODE_PATH__, 'qrc_decode.node'))
// console.log(addon)
qrc_decode = addon.qrc_decode
}
+2 -2
View File
@@ -1,5 +1,5 @@
// import fs from 'fs'
import { join } from 'path'
import path from 'node:path'
import { type WindowSize, windowSizeList } from '@common/config'
import { nativeImage } from 'electron'
@@ -8,7 +8,7 @@ export const getWindowSizeInfo = (windowSizeId: number | string): WindowSize =>
}
const getIconPath = (name: string): Electron.NativeImage => {
return nativeImage.createFromPath(join(global.staticPath, 'images/taskbar', name + '.png'))
return nativeImage.createFromPath(path.join(global.staticPath, 'images/taskbar', name + '.png'))
}
export const createTaskBarButtons = ({
+1 -1
View File
@@ -1,7 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
// "module": "esnext",
"resolveJsonModule": true,
"typeRoots": [
"./types"
],
+1 -1
View File
@@ -43,7 +43,7 @@ declare global {
// }
// }
var isDev: boolean
// var isDev: boolean
var envParams: LX.EnvParams
var staticPath: string
var lxDataPath: string
+3 -2
View File
@@ -9,6 +9,7 @@
// // }
// // }
declare const webpackStaticPath: string
declare const webpackUserApiPath: string
declare const __STATIC_PATH__: string
declare const __USER_API_PATH__: string
declare const __QRC_DECODE_NODE_PATH__: string
+4
View File
@@ -0,0 +1,4 @@
import log from 'electron-log'
log.transports.file.level = 'info'
log.initialize()
+5 -5
View File
@@ -1,8 +1,8 @@
import Store from 'electron-store'
import { dialog, shell } from 'electron'
import { join } from 'path'
import fs from 'fs'
import log from 'electron-log'
import path from 'node:path'
import fs from 'node:fs'
import { log } from '@common/utils'
type Stores = Record<string, Store>
@@ -27,8 +27,8 @@ export default (name: string, isIgnoredError = true, isShowErrorAlert = true): S
if (!isIgnoredError) throw error
const backPath = join(global.lxDataPath, name + '.json.bak')
fs.renameSync(join(global.lxDataPath, name + '.json'), backPath)
const backPath = path.join(global.lxDataPath, name + '.json.bak')
fs.renameSync(path.join(global.lxDataPath, name + '.json'), backPath)
if (isShowErrorAlert) {
dialog.showMessageBoxSync({
type: 'error',
+3 -3
View File
@@ -18,20 +18,20 @@ const initTables = (db: Database.Database) => {
// 打开、初始化数据库
export const init = (lxDataPath: string): boolean | null => {
const databasePath = path.join(lxDataPath, 'lx.data.db')
const nativeBinding = path.join(__dirname, '../node_modules/better-sqlite3/build/Release/better_sqlite3.node')
const nativeBinding = path.join(__dirname, '../../node_modules/better-sqlite3/build/Release/better_sqlite3.node')
let dbFileExists = true
try {
db = new Database(databasePath, {
fileMustExist: true,
nativeBinding,
verbose: global.isDev ? console.log : undefined,
verbose: process.env.NODE_ENV !== 'production' ? console.log : undefined,
})
} catch (error) {
console.log(error)
db = new Database(databasePath, {
nativeBinding,
verbose: global.isDev ? console.log : undefined,
verbose: process.env.NODE_ENV !== 'production' ? console.log : undefined,
})
initTables(db)
dbFileExists = false
+7 -7
View File
@@ -1,15 +1,15 @@
import { Worker } from 'worker_threads'
import { Worker } from 'node:worker_threads'
import * as Comlink from 'comlink'
import nodeEndpoint from 'comlink/dist/esm/node-adapter'
import path from 'node:path'
// import dbService from '../dbService/index'
export type DBSeriveTypes = Comlink.Remote<LX.WorkerDBSeriveListTypes>
export declare type DBSeriveTypes = Comlink.Remote<LX.WorkerDBSeriveListTypes>
export const createDBServiceWorker = () => {
const worker: Worker = new Worker(new URL(
/* webpackChunkName: 'dbService.worker' */
'../dbService',
import.meta.url,
))
// console.log(new URL('../dbService', import.meta.url))
// console.log(__dirname)
const worker: Worker = new Worker(path.join(__dirname, './dbService.worker'))
return Comlink.wrap<LX.WorkerDBSeriveListTypes>(nodeEndpoint(worker))
}
+3 -3
View File
@@ -1,9 +1,9 @@
import { parentPort } from 'worker_threads'
import worker from 'node:worker_threads'
import * as Comlink from 'comlink'
import nodeEndpoint from 'comlink/dist/esm/node-adapter'
export const exposeWorker = (obj: any) => {
if (parentPort == null) return
Comlink.expose(obj, nodeEndpoint(parentPort))
if (worker.parentPort == null) return
Comlink.expose(obj, nodeEndpoint(worker.parentPort))
}