fix: 构建环境避开 esm2cjs

This commit is contained in:
草鞋没号 2021-05-16 20:14:05 +08:00
parent 099467de43
commit abd91f809a
3 changed files with 56 additions and 49 deletions

View File

@ -1,4 +1,3 @@
import fs from 'fs'
import path from 'path' import path from 'path'
import acorn from 'acorn' import acorn from 'acorn'
import { Plugin as RollupPlugin } from 'rollup' import { Plugin as RollupPlugin } from 'rollup'
@ -29,7 +28,7 @@ export function cjs2esm() {
} }
/** esm2cjs */ /** esm2cjs */
export function esm2cjs(needConvertModules: string[]): VitePlugin { export function esm2cjs(moduleList: string[]): VitePlugin {
const filter = { const filter = {
include: (id: string) => vue_js_ts_extensions.includes(path.parse(id).ext) include: (id: string) => vue_js_ts_extensions.includes(path.parse(id).ext)
} }
@ -47,9 +46,8 @@ export function esm2cjs(needConvertModules: string[]): VitePlugin {
let codeRet = code let codeRet = code
node.body.reverse().forEach((item) => { node.body.reverse().forEach((item) => {
console.log(item)
if (item.type !== 'ImportDeclaration') return if (item.type !== 'ImportDeclaration') return
if (!needConvertModules.includes(item.source.value)) return // 跳过不要转换的模块 if (!moduleList.includes(item.source.value)) return // 跳过不要转换的模块
const statr = codeRet.substring(0, item.start) const statr = codeRet.substring(0, item.start)
const end = codeRet.substring(item.end) const end = codeRet.substring(item.end)
@ -80,8 +78,6 @@ const { ${modules.join(', ')} } = ${deftModule}${end}`
} }
}) })
fs.writeFileSync(path.join(__dirname, '.tmp/') + `${parsed.name + parsed.ext}.js`, codeRet)
return codeRet return codeRet
} }
}, },

View File

@ -6,7 +6,6 @@ import { ipcRenderer } from 'electron'
import Store from 'electron-store' import Store from 'electron-store'
import './index.css' import './index.css'
console.log('fs', fs)
console.log('ipcRenderer:', ipcRenderer) console.log('ipcRenderer:', ipcRenderer)
console.log('electron-store', new Store({ name: 'electron-vue' })) console.log('electron-store', new Store({ name: 'electron-vue' }))

View File

@ -13,13 +13,21 @@ import {
const root = join(__dirname, 'src/render') const root = join(__dirname, 'src/render')
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig(env => {
const isserve = env.command === 'serve'
return {
plugins: [ plugins: [
vue(), vue(),
...(isserve ? [
/**
* !!! electron commonjs vite
*/
esm2cjs([ esm2cjs([
'electron', 'electron',
'electron-store', 'electron-store',
]), ]),
] : []),
], ],
root, root,
base: './', // index.html 中静态资源加载位置 base: './', // index.html 中静态资源加载位置
@ -35,7 +43,10 @@ export default defineConfig({
}, },
}, },
optimizeDeps: { optimizeDeps: {
exclude: ['electron'], exclude: [
'electron',
'electron-store', // optional
],
}, },
build: { build: {
outDir: join(__dirname, 'dist/render'), outDir: join(__dirname, 'dist/render'),
@ -58,4 +69,5 @@ export default defineConfig({
}, },
}, },
}, },
}
}) })