mirror of
https://github.com/alex8088/electron-vite.git
synced 2026-07-07 14:47:06 +08:00
Compare commits
4 Commits
28bb22b353
...
7587d2c674
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7587d2c674 | ||
|
|
0fb8918090 | ||
|
|
c7955aa6fd | ||
|
|
70e027d38a |
@ -3,48 +3,15 @@ import fs from 'node:fs/promises'
|
||||
import type { SourceMapInput } from 'rollup'
|
||||
import { type Plugin, normalizePath } from 'vite'
|
||||
import MagicString from 'magic-string'
|
||||
import { cleanUrl, parseRequest, getHash, toRelativePath } from '../utils'
|
||||
|
||||
interface AssetResolved {
|
||||
type: 'asset' | 'native' | 'wasm'
|
||||
file: string
|
||||
query: Record<string, string> | null
|
||||
}
|
||||
|
||||
function resolveAsset(id: string): AssetResolved | null {
|
||||
const file = cleanUrl(id)
|
||||
const query = parseRequest(id)
|
||||
|
||||
if (query && typeof query.asset === 'string') {
|
||||
return {
|
||||
type: 'asset',
|
||||
file,
|
||||
query
|
||||
}
|
||||
}
|
||||
|
||||
if (file.endsWith('.node')) {
|
||||
return {
|
||||
type: 'native',
|
||||
file,
|
||||
query
|
||||
}
|
||||
}
|
||||
|
||||
if (id.endsWith('.wasm?loader')) {
|
||||
return {
|
||||
type: 'wasm',
|
||||
file,
|
||||
query
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
import { cleanUrl, getHash, toRelativePath } from '../utils'
|
||||
|
||||
const nodeAssetRE = /__VITE_NODE_ASSET__([\w$]+)__/g
|
||||
const nodePublicAssetRE = /__VITE_NODE_PUBLIC_ASSET__([a-z\d]{8})__/g
|
||||
|
||||
const assetImportRE = /(?:[?|&]asset(?:&|$)|\.wasm\?loader$|\.node$)/
|
||||
const assetRE = /[?|&]asset(?:&|$)/
|
||||
const assetUnpackRE = /[?|&]asset&asarUnpack$/
|
||||
|
||||
const wasmHelperId = '\0__electron-vite-wasm-helper'
|
||||
|
||||
const wasmHelperCode = `
|
||||
@ -59,7 +26,6 @@ export default async function loadWasm(file, importObject = {}) {
|
||||
`
|
||||
|
||||
export default function assetPlugin(): Plugin {
|
||||
let sourcemap: boolean | 'inline' | 'hidden' = false
|
||||
let publicDir = ''
|
||||
let outDir = ''
|
||||
const publicAssetPathCache = new Map<string, string>()
|
||||
@ -73,7 +39,6 @@ export default function assetPlugin(): Plugin {
|
||||
assetCache.clear()
|
||||
},
|
||||
configResolved(config): void {
|
||||
sourcemap = config.build.sourcemap
|
||||
publicDir = normalizePath(config.publicDir)
|
||||
outDir = normalizePath(path.resolve(config.root, config.build.outDir))
|
||||
},
|
||||
@ -87,19 +52,12 @@ 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) {
|
||||
if (id.startsWith('\0') || !assetImportRE.test(id)) {
|
||||
return
|
||||
}
|
||||
|
||||
let referenceId: string
|
||||
const file = assetResolved.file
|
||||
const file = cleanUrl(id)
|
||||
if (publicDir && file.startsWith(publicDir)) {
|
||||
const hash = getHash(file)
|
||||
if (!publicAssetPathCache.get(hash)) {
|
||||
@ -122,8 +80,8 @@ export default function assetPlugin(): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
if (assetResolved.type === 'asset') {
|
||||
if (assetResolved.query && typeof assetResolved.query.asarUnpack === 'string') {
|
||||
if (assetRE.test(id)) {
|
||||
if (assetUnpackRE.test(id)) {
|
||||
return `
|
||||
import { join } from 'path'
|
||||
export default join(__dirname, ${referenceId}).replace('app.asar', 'app.asar.unpacked')`
|
||||
@ -134,46 +92,42 @@ export default function assetPlugin(): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
if (assetResolved.type === 'native') {
|
||||
if (id.endsWith('.node')) {
|
||||
return `export default require(${referenceId})`
|
||||
}
|
||||
|
||||
if (assetResolved.type === 'wasm') {
|
||||
if (id.endsWith('.wasm?loader')) {
|
||||
return `
|
||||
import loadWasm from ${JSON.stringify(wasmHelperId)}
|
||||
export default importObject => loadWasm(${referenceId}, importObject)`
|
||||
}
|
||||
},
|
||||
renderChunk(code, chunk): { code: string; map: SourceMapInput } | null {
|
||||
renderChunk(code, chunk, { sourcemap }): { code: string; map: SourceMapInput } | null {
|
||||
let match: RegExpExecArray | null
|
||||
let s: MagicString | undefined
|
||||
|
||||
nodeAssetRE.lastIndex = 0
|
||||
if (code.match(nodeAssetRE)) {
|
||||
while ((match = nodeAssetRE.exec(code))) {
|
||||
s ||= new MagicString(code)
|
||||
const [full, hash] = match
|
||||
const filename = this.getFileName(hash)
|
||||
const outputFilepath = toRelativePath(filename, chunk.fileName)
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
while ((match = nodeAssetRE.exec(code))) {
|
||||
s ||= new MagicString(code)
|
||||
const [full, hash] = match
|
||||
const filename = this.getFileName(hash)
|
||||
const outputFilepath = toRelativePath(filename, chunk.fileName)
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
|
||||
nodePublicAssetRE.lastIndex = 0
|
||||
if (code.match(nodePublicAssetRE)) {
|
||||
while ((match = nodePublicAssetRE.exec(code))) {
|
||||
s ||= new MagicString(code)
|
||||
const [full, hash] = match
|
||||
const filename = publicAssetPathCache.get(hash)!
|
||||
const outputFilepath = toRelativePath(filename, normalizePath(path.join(outDir, chunk.fileName)))
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
while ((match = nodePublicAssetRE.exec(code))) {
|
||||
s ||= new MagicString(code)
|
||||
const [full, hash] = match
|
||||
const filename = publicAssetPathCache.get(hash)!
|
||||
const outputFilepath = toRelativePath(filename, normalizePath(path.join(outDir, chunk.fileName)))
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
|
||||
if (s) {
|
||||
@ -181,9 +135,9 @@ export default function assetPlugin(): Plugin {
|
||||
code: s.toString(),
|
||||
map: sourcemap ? s.generateMap({ hires: 'boundary' }) : null
|
||||
}
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -140,6 +140,8 @@ const bytecodeModuleLoaderCode = [
|
||||
`};`
|
||||
]
|
||||
|
||||
const bytecodeChunkExtensionRE = /.(jsc|cjsc)$/
|
||||
|
||||
export interface BytecodeOptions {
|
||||
chunkAlias?: string | string[]
|
||||
transformArrowFunctions?: boolean
|
||||
@ -180,13 +182,10 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
|
||||
return re ? { code: re.code || '', map: re.map } : null
|
||||
}
|
||||
|
||||
let bytecodeChunkCount = 0
|
||||
|
||||
const useStrict = '"use strict";'
|
||||
const bytecodeModuleLoader = 'bytecode-loader.cjs'
|
||||
|
||||
let logger: Logger
|
||||
let sourcemap: boolean | 'inline' | 'hidden' = false
|
||||
let supported = false
|
||||
|
||||
return {
|
||||
@ -198,7 +197,6 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
|
||||
return
|
||||
}
|
||||
logger = config.logger
|
||||
sourcemap = config.build.sourcemap
|
||||
const useInRenderer = config.plugins.some(p => p.name === 'vite:electron-renderer-preset-config')
|
||||
if (useInRenderer) {
|
||||
config.logger.warn(colors.yellow('bytecodePlugin does not support renderer.'))
|
||||
@ -223,7 +221,7 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
|
||||
config.logger.warn(colors.yellow('Strings cannot be protected when minification is enabled.'))
|
||||
}
|
||||
},
|
||||
renderChunk(code, chunk): { code: string; map?: SourceMapInput } | null {
|
||||
renderChunk(code, chunk, { sourcemap }): { code: string; map?: SourceMapInput } | null {
|
||||
if (supported && isBytecodeChunk(chunk.name) && shouldTransformBytecodeChunk) {
|
||||
return _transform(code, !!sourcemap)
|
||||
}
|
||||
@ -250,6 +248,8 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
|
||||
return `require("${toRelativePath(bytecodeModuleLoader, normalizePath(chunkFileName))}");`
|
||||
}
|
||||
|
||||
let bytecodeChunkCount = 0
|
||||
|
||||
const bundles = Object.keys(output)
|
||||
|
||||
await Promise.all(
|
||||
@ -257,17 +257,20 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
|
||||
const chunk = output[name]
|
||||
if (chunk.type === 'chunk') {
|
||||
let _code = chunk.code
|
||||
if (bytecodeRE && _code.match(bytecodeRE)) {
|
||||
if (bytecodeRE) {
|
||||
let match: RegExpExecArray | null
|
||||
const s = new MagicString(_code)
|
||||
let s: MagicString | undefined
|
||||
while ((match = bytecodeRE.exec(_code))) {
|
||||
s ||= new MagicString(_code)
|
||||
const [prefix, chunkName] = match
|
||||
const len = prefix.length + chunkName.length
|
||||
s.overwrite(match.index, match.index + len, prefix + chunkName + 'c', {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
_code = s.toString()
|
||||
if (s) {
|
||||
_code = s.toString()
|
||||
}
|
||||
}
|
||||
if (bytecodeChunks.includes(name)) {
|
||||
const bytecodeBuffer = await compileToBytecode(_code)
|
||||
@ -330,8 +333,9 @@ export function bytecodePlugin(options: BytecodeOptions = {}): Plugin | null {
|
||||
})
|
||||
}
|
||||
},
|
||||
writeBundle(): void {
|
||||
writeBundle(_, output): void {
|
||||
if (supported) {
|
||||
const bytecodeChunkCount = Object.keys(output).filter(chunk => bytecodeChunkExtensionRE.test(chunk)).length
|
||||
logger.info(`${colors.green(`✓`)} ${bytecodeChunkCount} chunks compiled into bytecode.`)
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,19 +46,14 @@ 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',
|
||||
enforce: 'post',
|
||||
configResolved(config): void {
|
||||
sourcemap = config.build.sourcemap
|
||||
},
|
||||
renderChunk(code, _chunk, options): { code: string; map?: SourceMapInput } | null {
|
||||
if (options.format === 'es') {
|
||||
renderChunk(code, _chunk, { format, sourcemap }): { code: string; map?: SourceMapInput } | null {
|
||||
if (format === 'es') {
|
||||
if (code.includes(CJSShim) || !CJSyntaxRe.test(code)) {
|
||||
return null
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@ import path from 'node:path'
|
||||
import { type Plugin, type InlineConfig, build as viteBuild, mergeConfig } from 'vite'
|
||||
import type { SourceMapInput, RollupOutput, OutputOptions } from 'rollup'
|
||||
import MagicString from 'magic-string'
|
||||
import { cleanUrl, parseRequest, toRelativePath } from '../utils'
|
||||
import { cleanUrl, toRelativePath } from '../utils'
|
||||
|
||||
const modulePathRE = /__VITE_MODULE_PATH__([\w$]+)__/g
|
||||
|
||||
@ -10,25 +10,14 @@ const modulePathRE = /__VITE_MODULE_PATH__([\w$]+)__/g
|
||||
* Resolve `?modulePath` import and return the module bundle path.
|
||||
*/
|
||||
export default function modulePathPlugin(config: InlineConfig): Plugin {
|
||||
let sourcemap: boolean | 'inline' | 'hidden' = false
|
||||
return {
|
||||
name: 'vite:module-path',
|
||||
apply: 'build',
|
||||
enforce: 'pre',
|
||||
configResolved(config): void {
|
||||
sourcemap = config.build.sourcemap
|
||||
},
|
||||
resolveId(id, importer): string | void {
|
||||
const query = parseRequest(id)
|
||||
if (query && typeof query.modulePath === 'string') {
|
||||
return id + `&importer=${importer}`
|
||||
}
|
||||
},
|
||||
async load(id): Promise<string | void> {
|
||||
const query = parseRequest(id)
|
||||
if (query && typeof query.modulePath === 'string' && typeof query.importer === 'string') {
|
||||
const entry = path.resolve(path.dirname(query.importer), cleanUrl(id))
|
||||
const bundle = await bundleEntryFile(entry, config)
|
||||
if (id.endsWith('?modulePath')) {
|
||||
// id resolved by Vite resolve plugin
|
||||
const bundle = await bundleEntryFile(cleanUrl(id), config)
|
||||
const [outputChunk, ...outputChunks] = bundle.output
|
||||
const hash = this.emitFile({
|
||||
type: 'asset',
|
||||
@ -44,25 +33,27 @@ export default function modulePathPlugin(config: InlineConfig): Plugin {
|
||||
})
|
||||
const refId = `__VITE_MODULE_PATH__${hash}__`
|
||||
return `
|
||||
import { join } from 'path'
|
||||
export default join(__dirname, ${refId})`
|
||||
import { join } from 'path'
|
||||
export default join(__dirname, ${refId})`
|
||||
}
|
||||
},
|
||||
renderChunk(code, chunk): { code: string; map: SourceMapInput } | null {
|
||||
if (code.match(modulePathRE)) {
|
||||
let match: RegExpExecArray | null
|
||||
const s = new MagicString(code)
|
||||
renderChunk(code, chunk, { sourcemap }): { code: string; map: SourceMapInput } | null {
|
||||
let match: RegExpExecArray | null
|
||||
let s: MagicString | undefined
|
||||
|
||||
while ((match = modulePathRE.exec(code))) {
|
||||
const [full, hash] = match
|
||||
const filename = this.getFileName(hash)
|
||||
const outputFilepath = toRelativePath(filename, chunk.fileName)
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
modulePathRE.lastIndex = 0
|
||||
while ((match = modulePathRE.exec(code))) {
|
||||
s ||= new MagicString(code)
|
||||
const [full, hash] = match
|
||||
const filename = this.getFileName(hash)
|
||||
const outputFilepath = toRelativePath(filename, chunk.fileName)
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
|
||||
if (s) {
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: sourcemap ? s.generateMap({ hires: 'boundary' }) : null
|
||||
|
||||
@ -1,58 +1,58 @@
|
||||
import type { Plugin } from 'vite'
|
||||
import type { SourceMapInput } from 'rollup'
|
||||
import MagicString from 'magic-string'
|
||||
import { cleanUrl, parseRequest, toRelativePath } from '../utils'
|
||||
import { cleanUrl, toRelativePath } from '../utils'
|
||||
|
||||
const nodeWorkerAssetUrlRE = /__VITE_NODE_WORKER_ASSET__([\w$]+)__/g
|
||||
const nodeWorkerRE = /\?nodeWorker(?:&|$)/
|
||||
const nodeWorkerImporterRE = /(?:\?)nodeWorker&importer=([^&]+)(?:&|$)/
|
||||
|
||||
/**
|
||||
* Resolve `?nodeWorker` import and automatically generate `Worker` wrapper.
|
||||
*/
|
||||
export default function workerPlugin(): Plugin {
|
||||
let sourcemap: boolean | 'inline' | 'hidden' = false
|
||||
return {
|
||||
name: 'vite:node-worker',
|
||||
apply: 'build',
|
||||
enforce: 'pre',
|
||||
configResolved(config): void {
|
||||
sourcemap = config.build.sourcemap
|
||||
},
|
||||
resolveId(id, importer): string | void {
|
||||
const query = parseRequest(id)
|
||||
if (query && typeof query.nodeWorker === 'string') {
|
||||
if (id.endsWith('?nodeWorker')) {
|
||||
return id + `&importer=${importer}`
|
||||
}
|
||||
},
|
||||
load(id): string | void {
|
||||
const query = parseRequest(id)
|
||||
if (query && typeof query.nodeWorker === 'string' && typeof query.importer === 'string') {
|
||||
const cleanPath = cleanUrl(id)
|
||||
const hash = this.emitFile({
|
||||
type: 'chunk',
|
||||
id: cleanPath,
|
||||
importer: query.importer
|
||||
})
|
||||
const assetRefId = `__VITE_NODE_WORKER_ASSET__${hash}__`
|
||||
return `
|
||||
import { Worker } from 'node:worker_threads';
|
||||
export default function (options) { return new Worker(new URL(${assetRefId}, import.meta.url), options); }`
|
||||
if (nodeWorkerRE.test(id)) {
|
||||
const match = nodeWorkerImporterRE.exec(id)
|
||||
if (match) {
|
||||
const hash = this.emitFile({
|
||||
type: 'chunk',
|
||||
id: cleanUrl(id),
|
||||
importer: match[1]
|
||||
})
|
||||
const assetRefId = `__VITE_NODE_WORKER_ASSET__${hash}__`
|
||||
return `
|
||||
import { Worker } from 'node:worker_threads';
|
||||
export default function (options) { return new Worker(new URL(${assetRefId}, import.meta.url), options); }`
|
||||
}
|
||||
}
|
||||
},
|
||||
renderChunk(code, chunk): { code: string; map: SourceMapInput } | null {
|
||||
if (code.match(nodeWorkerAssetUrlRE)) {
|
||||
let match: RegExpExecArray | null
|
||||
const s = new MagicString(code)
|
||||
renderChunk(code, chunk, { sourcemap }): { code: string; map: SourceMapInput } | null {
|
||||
let match: RegExpExecArray | null
|
||||
let s: MagicString | undefined
|
||||
|
||||
while ((match = nodeWorkerAssetUrlRE.exec(code))) {
|
||||
const [full, hash] = match
|
||||
const filename = this.getFileName(hash)
|
||||
const outputFilepath = toRelativePath(filename, chunk.fileName)
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
nodeWorkerAssetUrlRE.lastIndex = 0
|
||||
while ((match = nodeWorkerAssetUrlRE.exec(code))) {
|
||||
s ||= new MagicString(code)
|
||||
const [full, hash] = match
|
||||
const filename = this.getFileName(hash)
|
||||
const outputFilepath = toRelativePath(filename, chunk.fileName)
|
||||
const replacement = JSON.stringify(outputFilepath)
|
||||
s.overwrite(match.index, match.index + full.length, replacement, {
|
||||
contentOnly: true
|
||||
})
|
||||
}
|
||||
|
||||
if (s) {
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: sourcemap ? s.generateMap({ hires: 'boundary' }) : null
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import { URL, URLSearchParams } from 'node:url'
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
@ -20,14 +19,6 @@ export const hashRE = /#.*$/s
|
||||
|
||||
export const cleanUrl = (url: string): string => url.replace(hashRE, '').replace(queryRE, '')
|
||||
|
||||
export function parseRequest(id: string): Record<string, string> | null {
|
||||
const { search } = new URL(id, 'file:')
|
||||
if (!search) {
|
||||
return null
|
||||
}
|
||||
return Object.fromEntries(new URLSearchParams(search))
|
||||
}
|
||||
|
||||
export function getHash(text: Buffer | string): string {
|
||||
return createHash('sha256')
|
||||
.update(text as unknown as Uint8Array)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user