Compare commits

..

No commits in common. "master" and "v2.1.0" have entirely different histories.

18 changed files with 1242 additions and 1179 deletions

2
.eslintignore Normal file
View File

@ -0,0 +1,2 @@
node_modules
dist

39
.eslintrc.cjs Normal file
View File

@ -0,0 +1,39 @@
module.exports = {
root: true,
env: {
commonjs: true,
es6: true,
node: true
},
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module',
ecmaVersion: 2022
},
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:prettier/recommended'
],
rules: {
'prettier/prettier': 'warn',
'no-empty': ['warn', { allowEmptyCatch: true }],
'@typescript-eslint/ban-ts-comment': ['error', { 'ts-ignore': 'allow-with-description' }],
'@typescript-eslint/explicit-function-return-type': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-empty-function': ['error', { allow: ['arrowFunctions'] }],
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-var-requires': 'off'
},
overrides: [
{
files: ['*.js'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off'
}
}
]
}

2
.gitignore vendored
View File

@ -1,5 +1,5 @@
node_modules
dist
.DS_Store
.eslintcache
*.log*

View File

@ -1,57 +1,6 @@
### v3.1.0 (_2025-03-25_)
- fix(bytecodePlugin): optimize 'use strict' directive replacement ([#681](https://github.com/alex8088/electron-vite/issues/681))
- perf: build compatilibity target for Electron 35 ([#729](https://github.com/alex8088/electron-vite/pull/729))
- chore(deps): update all non-major dependencies
- chore(deps): update globals to v16
- chore(deps): update esbuild to v0.25
### v3.1.0-beta.0 (_2025-03-12_)
See [v3.1.0-beta.0 changelog](https://github.com/alex8088/electron-vite/blob/v3.1.0-beta.0/CHANGELOG.md)
### v3.0.0 (_2025-02-16_)
- feat: resolve conditions for preload
- perf: build compatilibity target for Electron 32
- perf: build compatilibity target for Electron 33 ([#651](https://github.com/alex8088/electron-vite/pull/651))
- perf: build compatilibity target for Electron 34
- chore: move to eslint flat config
- chore(deps): update all non-major dependencies
- chore(deps): update @rollup/plugin-node-resolve to v16
- chore(deps): update @rollup/plugin-typescript to v12
- chore(deps): update esbuild to v0.24
- chore(deps): update vite to v6
- chore(deps): update @type/node to v22
### v3.0.0-beta.0 (_2025-01-22_)
See [v3.0.0-beta.0 changelog](https://github.com/alex8088/electron-vite/blob/v3.0.0-beta.0/CHANGELOG.md)
### v2.3.0 (_2024-06-23_)
- feat: resolve import.meta.\[dirname|filename\] to support CommonJS format
- fix: don't handle module ID that begin with \0 ([#530](https://github.com/alex8088/electron-vite/pull/530))
- fix: not using the mode from the config file ([#539](https://github.com/alex8088/electron-vite/pull/539))
- fix: default mode should not overrite user config mode
- perf: build compatilibity target for Electron 31
- perf: improve cjs shim
- chore(deps): update all non-major dependencies
- chore(deps): update @typescript-eslint/\* to v7
- chore(deps): update esbuild to v0.21
### v2.2.0 (_2024-04-21_)
- feat: export mergeConfig from vite ([#471](https://github.com/alex8088/electron-vite/issues/471))
- fix(types): narrow down the return type of defineConfig
- perf: build compatilibity target for Electron 30
- refactor(config): defineConfig types
- chore: fix camelcase typo
- chore: use rollup-plugin-rm to clean dist
### v2.1.0 (_2024-03-03_)
- feat: easy way to fork processes and use workers
- feat: feat: easy way to fork processes and use workers
- fix: config via build.lib fails when default entry point not found ([#393](https://github.com/alex8088/electron-vite/issues/393))
- perf: build compatilibity target for Electron 29
- perf: allow integrating more complex render solutions ([#412](https://github.com/alex8088/electron-vite/pull/412))

View File

@ -1,42 +0,0 @@
// ts-check
import eslint from '@eslint/js'
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'
import globals from 'globals'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['**/node_modules', '**/dist', '**/bin'] },
eslint.configs.recommended,
tseslint.configs.recommended,
eslintPluginPrettierRecommended,
{
languageOptions: {
parser: tseslint.parser,
parserOptions: {
sourceType: 'module',
ecmaVersion: 2022
},
globals: {
...globals.es2021,
...globals.node
}
},
rules: {
'prettier/prettier': 'warn',
'@typescript-eslint/ban-ts-comment': ['error', { 'ts-ignore': 'allow-with-description' }],
'@typescript-eslint/explicit-function-return-type': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-empty-function': ['error', { allow: ['arrowFunctions'] }],
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-var-requires': 'off'
}
},
{
files: ['*.js', '*.mjs'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off'
}
}
)

View File

@ -1,6 +1,6 @@
{
"name": "electron-vite",
"version": "3.1.0",
"version": "2.1.0",
"description": "Electron build tooling based on Vite",
"type": "module",
"main": "dist/index.cjs",
@ -47,7 +47,7 @@
],
"scripts": {
"format": "prettier --write .",
"lint": "eslint --cache .",
"lint": "eslint --ext .ts src/**",
"typecheck": "tsc --noEmit",
"build": "pnpm run lint && rollup -c rollup.config.ts --configPlugin typescript"
},
@ -66,7 +66,7 @@
},
"peerDependencies": {
"@swc/core": "^1.0.0",
"vite": "^4.0.0 || ^5.0.0 || ^6.0.0"
"vite": "^4.0.0 || ^5.0.0"
},
"peerDependenciesMeta": {
"@swc/core": {
@ -74,33 +74,31 @@
}
},
"devDependencies": {
"@eslint/js": "^9.22.0",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-typescript": "^12.1.2",
"@swc/core": "^1.11.9",
"@types/node": "^22.13.10",
"eslint": "^9.22.0",
"eslint-config-prettier": "^10.1.1",
"eslint-plugin-prettier": "^5.2.3",
"globals": "^16.0.0",
"lint-staged": "^15.4.3",
"prettier": "^3.5.3",
"rollup": "^4.35.0",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-rm": "^1.0.2",
"simple-git-hooks": "^2.11.1",
"tslib": "^2.8.1",
"typescript": "^5.7.3",
"typescript-eslint": "^8.26.1",
"vite": "^6.2.1"
"@rollup/plugin-json": "^6.0.1",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-typescript": "^11.1.5",
"@swc/core": "^1.3.100",
"@types/node": "^18.19.3",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
"eslint": "^8.55.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.0.1",
"lint-staged": "^15.2.0",
"prettier": "^3.1.0",
"rollup": "^4.6.1",
"rollup-plugin-dts": "^6.1.0",
"simple-git-hooks": "^2.9.0",
"tslib": "^2.6.2",
"typescript": "^5.3.3",
"vite": "^5.0.6"
},
"dependencies": {
"@babel/core": "^7.26.10",
"@babel/plugin-transform-arrow-functions": "^7.25.9",
"@babel/core": "^7.23.5",
"@babel/plugin-transform-arrow-functions": "^7.23.3",
"cac": "^6.7.14",
"esbuild": "^0.25.1",
"magic-string": "^0.30.17",
"picocolors": "^1.1.1"
"esbuild": "^0.19.8",
"magic-string": "^0.30.5",
"picocolors": "^1.0.0"
}
}

2073
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,33 @@
import { createRequire } from 'node:module'
import { defineConfig } from 'rollup'
import fs from 'node:fs/promises'
import { type Plugin, defineConfig } from 'rollup'
import ts from '@rollup/plugin-typescript'
import resolve from '@rollup/plugin-node-resolve'
import json from '@rollup/plugin-json'
import dts from 'rollup-plugin-dts'
import rm from 'rollup-plugin-rm'
const require = createRequire(import.meta.url)
const pkg = require('./package.json')
const external = ['esbuild', ...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})]
function clean(when: 'buildStart' | 'buildEnd', target: string): Plugin {
const _clean = async (target): Promise<void> => {
await fs.rm(target, { recursive: true, force: true }).catch(() => {})
}
return {
name: 'clean',
buildStart: async (): Promise<void> => {
if (when !== 'buildStart') return
await _clean(target)
},
buildEnd: async (): Promise<void> => {
if (when !== 'buildEnd') return
await _clean(target)
}
}
}
export default defineConfig([
{
input: ['src/index.ts', 'src/cli.ts'],
@ -30,7 +47,7 @@ export default defineConfig([
],
external,
plugins: [
rm('dist', 'buildStart'),
clean('buildStart', 'dist'),
json(),
ts({ compilerOptions: { rootDir: 'src', declaration: true, declarationDir: 'dist/types' } }),
resolve()
@ -42,6 +59,6 @@ export default defineConfig([
{
input: 'dist/types/index.d.ts',
output: [{ file: pkg.types, format: 'es' }],
plugins: [dts(), rm('dist/types', 'buildEnd')]
plugins: [dts(), clean('buildEnd', 'dist/types')]
}
])

View File

@ -5,7 +5,7 @@ import { createRequire } from 'node:module'
import colors from 'picocolors'
import {
type UserConfig as ViteConfig,
type UserConfigExport as ViteConfigExport,
type UserConfigExport as UserViteConfigExport,
type ConfigEnv,
type Plugin,
type LogLevel,
@ -18,7 +18,7 @@ import { build } from 'esbuild'
import { electronMainVitePlugin, electronPreloadVitePlugin, electronRendererVitePlugin } from './plugins/electron'
import assetPlugin from './plugins/asset'
import workerPlugin from './plugins/worker'
import importMetaPlugin from './plugins/importMeta'
import importMetaUrlPlugin from './plugins/importMetaUrl'
import esmShimPlugin from './plugins/esm'
import modulePathPlugin from './plugins/modulePath'
import { isObject, isFilePathESM } from './utils'
@ -46,25 +46,25 @@ export interface UserConfig {
preload?: ViteConfig & { configFile?: string | false }
}
export interface ElectronViteConfig {
export interface UserConfigSchema {
/**
* Vite config options for electron main process
*
* https://vitejs.dev/config/
*/
main?: ViteConfigExport
main?: UserViteConfigExport
/**
* Vite config options for electron renderer process
*
* https://vitejs.dev/config/
*/
renderer?: ViteConfigExport
renderer?: UserViteConfigExport
/**
* Vite config options for electron preload files
*
* https://vitejs.dev/config/
*/
preload?: ViteConfigExport
preload?: UserViteConfigExport
}
export type InlineConfig = Omit<ViteConfig, 'base'> & {
@ -73,28 +73,16 @@ export type InlineConfig = Omit<ViteConfig, 'base'> & {
ignoreConfigWarning?: boolean
}
export type ElectronViteConfigFnObject = (env: ConfigEnv) => ElectronViteConfig
export type ElectronViteConfigFnPromise = (env: ConfigEnv) => Promise<ElectronViteConfig>
export type ElectronViteConfigFn = (env: ConfigEnv) => ElectronViteConfig | Promise<ElectronViteConfig>
export type ElectronViteConfigExport =
| ElectronViteConfig
| Promise<ElectronViteConfig>
| ElectronViteConfigFnObject
| ElectronViteConfigFnPromise
| ElectronViteConfigFn
export type UserConfigFn = (env: ConfigEnv) => UserConfigSchema | Promise<UserConfigSchema>
export type UserConfigExport = UserConfigSchema | Promise<UserConfigSchema> | UserConfigFn
/**
* Type helper to make it easier to use `electron.vite.config.*`
* accepts a direct {@link ElectronViteConfig} object, or a function that returns it.
* accepts a direct {@link UserConfig} object, or a function that returns it.
* The function receives a object that exposes two properties:
* `command` (either `'build'` or `'serve'`), and `mode`.
*/
export function defineConfig(config: ElectronViteConfig): ElectronViteConfig
export function defineConfig(config: Promise<ElectronViteConfig>): Promise<ElectronViteConfig>
export function defineConfig(config: ElectronViteConfigFnObject): ElectronViteConfigFnObject
export function defineConfig(config: ElectronViteConfigExport): ElectronViteConfigExport
export function defineConfig(config: ElectronViteConfigExport): ElectronViteConfigExport {
export function defineConfig(config: UserConfigExport): UserConfigExport {
return config
}
@ -112,6 +100,8 @@ export async function resolveConfig(
const config = inlineConfig
const mode = inlineConfig.mode || defaultMode
config.mode = mode
process.env.NODE_ENV = defaultMode
let userConfig: UserConfig | undefined
@ -140,8 +130,6 @@ export async function resolveConfig(
if (loadResult.config.main) {
const mainViteConfig: ViteConfig = mergeConfig(loadResult.config.main, deepClone(config))
mainViteConfig.mode = inlineConfig.mode || mainViteConfig.mode || defaultMode
if (outDir) {
resetOutDir(mainViteConfig, outDir, 'main')
}
@ -151,7 +139,7 @@ export async function resolveConfig(
assetPlugin(),
workerPlugin(),
modulePathPlugin(),
importMetaPlugin(),
importMetaUrlPlugin(),
esmShimPlugin()
])
@ -162,15 +150,13 @@ export async function resolveConfig(
if (loadResult.config.preload) {
const preloadViteConfig: ViteConfig = mergeConfig(loadResult.config.preload, deepClone(config))
preloadViteConfig.mode = inlineConfig.mode || preloadViteConfig.mode || defaultMode
if (outDir) {
resetOutDir(preloadViteConfig, outDir, 'preload')
}
mergePlugins(preloadViteConfig, [
...electronPreloadVitePlugin({ root }),
assetPlugin(),
importMetaPlugin(),
importMetaUrlPlugin(),
esmShimPlugin()
])
@ -181,8 +167,6 @@ export async function resolveConfig(
if (loadResult.config.renderer) {
const rendererViteConfig: ViteConfig = mergeConfig(loadResult.config.renderer, deepClone(config))
rendererViteConfig.mode = inlineConfig.mode || rendererViteConfig.mode || defaultMode
if (outDir) {
resetOutDir(rendererViteConfig, outDir, 'renderer')
}
@ -406,7 +390,7 @@ async function loadConfigFormBundledFile(
configFile: string,
bundledCode: string,
isESM: boolean
): Promise<ElectronViteConfigExport> {
): Promise<UserConfigExport> {
if (isESM) {
const fileNameTmp = path.resolve(configRoot, `${CONFIG_FILE_NAME}.${Date.now()}.mjs`)
fs.writeFileSync(fileNameTmp, bundledCode)
@ -417,7 +401,6 @@ async function loadConfigFormBundledFile(
} finally {
try {
fs.unlinkSync(fileNameTmp)
// eslint-disable-next-line no-empty
} catch {}
}
} else {

View File

@ -41,11 +41,6 @@ export function supportESM(): boolean {
return parseInt(majorVer) >= 28
}
export function getElectronMajorVersion(): number {
const majorVer = getElectronMajorVer()
return parseInt(majorVer)
}
export function getElectronPath(): string {
let electronExecPath = process.env.ELECTRON_EXEC_PATH || ''
if (!electronExecPath) {
@ -69,12 +64,6 @@ export function getElectronNodeTarget(): string {
const electronVer = getElectronMajorVer()
const nodeVer = {
'35': '22.14',
'34': '20.18',
'33': '20.18',
'32': '20.16',
'31': '20.14',
'30': '20.11',
'29': '20.9',
'28': '18.18',
'27': '18.17',
@ -89,7 +78,9 @@ export function getElectronNodeTarget(): string {
'18': '16.13',
'17': '16.13',
'16': '16.9',
'15': '16.5'
'15': '16.5',
'14': '14.17',
'13': '14.17'
}
if (electronVer && parseInt(electronVer) > 10) {
let target = nodeVer[electronVer]
@ -103,12 +94,6 @@ export function getElectronChromeTarget(): string {
const electronVer = getElectronMajorVer()
const chromeVer = {
'35': '134',
'34': '132',
'33': '130',
'32': '128',
'31': '126',
'30': '124',
'29': '122',
'28': '120',
'27': '118',
@ -123,7 +108,9 @@ export function getElectronChromeTarget(): string {
'18': '100',
'17': '98',
'16': '96',
'15': '94'
'15': '94',
'14': '93',
'13': '91'
}
if (electronVer && parseInt(electronVer) > 10) {
let target = chromeVer[electronVer]

View File

@ -1,4 +1,4 @@
export { type LogLevel, createLogger, mergeConfig, splitVendorChunkPlugin, splitVendorChunk } from 'vite'
export { type LogLevel, createLogger, splitVendorChunkPlugin, splitVendorChunk } from 'vite'
export * from './config'
export { createServer } from './server'
export { build } from './build'

View File

@ -87,12 +87,6 @@ export default function assetPlugin(): Plugin {
return wasmHelperCode
}
if (id.startsWith('\0')) {
// Rollup convention, this id should be handled by the
// plugin that marked it with \0
return
}
const assetResolved = resolveAsset(id)
if (!assetResolved) {
return
@ -115,7 +109,7 @@ export default function assetPlugin(): Plugin {
const hash = this.emitFile({
type: 'asset',
name: path.basename(file),
source: source as unknown as Uint8Array
source
})
referenceId = `__VITE_NODE_ASSET__${hash}__`
assetCache.set(file, referenceId)

View File

@ -310,7 +310,7 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
const chunkFileName = path.resolve(outDir, name)
if (bytecodeChunks.includes(name)) {
const bytecodeBuffer = await compileToBytecode(_code)
fs.writeFileSync(path.resolve(outDir, name + 'c'), bytecodeBuffer as unknown as Uint8Array)
fs.writeFileSync(path.resolve(outDir, name + 'c'), bytecodeBuffer)
if (chunk.isEntry) {
if (!removeBundleJS) {
keepBundle(chunkFileName)
@ -344,9 +344,7 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
}
}
const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName)
_code = hasBytecodeMoudle
? _code.replace(/("use strict";)|('use strict';)/, `${useStrict}\n${bytecodeLoaderBlock}`)
: _code
_code = hasBytecodeMoudle ? _code.replace(useStrict, `${useStrict}\n${bytecodeLoaderBlock}`) : _code
}
fs.writeFileSync(chunkFileName, _code)
}

View File

@ -198,12 +198,6 @@ export function electronPreloadVitePlugin(options?: ElectronPluginOptions): Plug
const format = pkg.type && pkg.type === 'module' && supportESM() ? 'es' : 'cjs'
const defaultConfig = {
ssr: {
resolve: {
conditions: ['module', 'browser', 'development|production'],
mainFields: ['browser', 'module', 'jsnext:main', 'jsnext']
}
},
build: {
outDir: path.resolve(root, 'out', 'preload'),
target: nodeTarget,
@ -278,8 +272,7 @@ export function electronPreloadVitePlugin(options?: ElectronPluginOptions): Plug
// enable ssr build
config.build.ssr = true
config.build.ssrEmitAssets = true
config.ssr = mergeConfig(defaultConfig.ssr, config.ssr || {})
config.ssr.noExternal = true
config.ssr = { ...config.ssr, ...{ noExternal: true } }
}
},
{

View File

@ -8,11 +8,9 @@ import MagicString from 'magic-string'
import type { SourceMapInput } from 'rollup'
import type { Plugin } from 'vite'
import { getElectronMajorVersion } from '../electron'
const CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/
const CJSShim_normal = `
const CJSShim = `
// -- CommonJS Shims --
import __cjs_url__ from 'node:url';
import __cjs_path__ from 'node:path';
@ -22,14 +20,6 @@ const __dirname = __cjs_path__.dirname(__filename);
const require = __cjs_mod__.createRequire(import.meta.url);
`
const CJSShim_node_20_11 = `
// -- CommonJS Shims --
import __cjs_mod__ from 'node:module';
const __filename = import.meta.filename;
const __dirname = import.meta.dirname;
const require = __cjs_mod__.createRequire(import.meta.url);
`
const ESMStaticImportRe =
/(?<=\s|^|;)import\s*([\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu
@ -47,9 +37,6 @@ function findStaticImports(code: string): StaticImport[] {
export default function esmShimPlugin(): Plugin {
let sourcemap: boolean | 'inline' | 'hidden' = false
const CJSShim = getElectronMajorVersion() >= 30 ? CJSShim_node_20_11 : CJSShim_normal
return {
name: 'vite:esm-shim',
apply: 'build',

View File

@ -1,20 +1,14 @@
import type { Plugin } from 'vite'
export default function importMetaPlugin(): Plugin {
export default function importMetaUrlPlugin(): Plugin {
return {
name: 'vite:import-meta',
name: 'vite:import-meta-url',
apply: 'build',
enforce: 'pre',
resolveImportMeta(property, { format }): string | null {
if (property === 'url' && format === 'cjs') {
return `require("url").pathToFileURL(__filename).href`
}
if (property === 'filename' && format === 'cjs') {
return `__filename`
}
if (property === 'dirname' && format === 'cjs') {
return `__dirname`
}
return null
}
}

View File

@ -2,7 +2,7 @@ import type { ChildProcess } from 'node:child_process'
import {
type UserConfig as ViteConfig,
type ViteDevServer,
createServer as viteCreateServer,
createServer as ViteCreateServer,
build as viteBuild,
createLogger,
mergeConfig
@ -80,7 +80,7 @@ export async function createServer(
if (rendererViteConfig) {
logger.info(colors.gray(`\n-----\n`))
server = await viteCreateServer(rendererViteConfig)
server = await ViteCreateServer(rendererViteConfig)
if (!server.httpServer) {
throw new Error('HTTP server not available')

View File

@ -29,10 +29,7 @@ export function parseRequest(id: string): Record<string, string> | null {
}
export function getHash(text: Buffer | string): string {
return createHash('sha256')
.update(text as unknown as Uint8Array)
.digest('hex')
.substring(0, 8)
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}
export function toRelativePath(filename: string, importer: string): string {