【问题解决】在使用vite时如何在保持原目录结构前提下执行vite
写项目时遇到的了问题:vite默认将所有模块合并到主进程入口文件中,导致一些ts模块无法通过路径找到,而简单的使用external又会导致这些ts模块无法转换为js。
解决方法:
// vite.config.ts
vite: {
build: {
output:{
preserveModules: true // 将此项置为true
}
}
}
我使用的electron-vite-vue框架,如果遇到同样的问题的话可以参考我的配置文件
// vite.config.ts
import { defineConfig } from 'vite';
import fs from 'node:fs';
import path from 'node:path';
import vue from '@vitejs/plugin-vue';
import electron from 'vite-plugin-electron/simple';
import pkg from './package.json';
export default defineConfig(({ command }) => {
fs.rmSync('dist-main', { recursive: true, force: true })
const isServe = command === 'serve'
const isBuild = command === 'build'
const sourcemap = isServe || !!process.env.VSCODE_DEBUG
return {
plugins: [
vue(),
electron({
main: {
// Shortcut of `build.lib.entry`
entry: 'main/main/index.ts',
onstart({ startup }) {
if (process.env.VSCODE_DEBUG) {
console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')
} else {
startup()
}
},
vite: {
build: {
sourcemap,
minify: isBuild,
outDir: 'dist-main',
rollupOptions: {
// Some third-party Node.js libraries may not be built correctly by Vite, especially `C/C++` addons,
// we can use `external` to exclude them to ensure they work correctly.
// Others need to put them in `dependencies` to ensure they are collected into `app.asar` after the app is built.
// Of course, this is not absolute, just this way is relatively simple. :)
output:{
preserveModules: true // 这里是解决的关键
},
external: [
...Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
path.resolve(__dirname, 'main/common/**')
]
},
},
},
},
preload: {
// Shortcut of `build.rollupOptions.input`.
// Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`.
input: 'main/preload/index.ts',
vite: {
build: {
sourcemap: sourcemap ? 'inline' : undefined, // #332
minify: isBuild,
outDir: 'dist-main/preload',
rollupOptions: {
external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),
},
},
},
},
// Ployfill the Electron and Node.js API for Renderer process.
// If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process.
// See 👉 https://github.com/electron-vite/vite-plugin-electron-renderer
renderer: {},
}),
],
server: process.env.VSCODE_DEBUG && (() => {
const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)
return {
host: url.hostname,
port: +url.port,
}
})(),
clearScreen: false,
}
})
参考文档:https://www.rollupjs.com/configuration-options/
本文作者:Texley
本文链接:https://www.cnblogs.com/texley/p/18141600
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)