Electron应用Git仓库需保存目录及自动生成文件恢复方案问询
Great question! When you create an Electron app using Node.js CLI tools (like create-electron-app, electron-forge init, or vite-plugin-electron), you’ll end up with loads of auto-generated files that don’t need to live in your Git repository. Here’s the standard approach to manage this, plus what does need to be tracked, and how to restore the missing stuff easily.
1. The Standard Practice: Use a .gitignore File
The first thing you should do is set up a .gitignore file to tell Git which files/directories to ignore. For Electron projects, this typically includes:
node_modules/: All installed dependencies (these can be re-installed from your lock file)dist/orout/: Compiled/bundled app files (generated when you build your app)*.log: Debug logs (likenpm-debug.log,electron-debug.log)Electron.app/(macOS) orelectron.exe(Windows): Auto-generated executable artifacts.cache/or.forge/: Temporary build caches from tools like Electron Forgenode_modules/.cache/: Internal npm/Yarn caches
You can create this file manually, or use a pre-built Electron .gitignore template—just make sure it’s tailored to your build tool (Forge, Vite, Webpack, etc.).
2. What Must Be Stored in Git?
These are the files that define your project and can’t be recreated automatically (or shouldn’t be, to avoid inconsistencies):
package.json: Your project’s metadata, dependency list, and script commandspackage-lock.json(npm) oryarn.lock(Yarn): Locks dependency versions to ensure everyone gets the exact same packages.gitignore: Obviously, you need this to keep Git ignoring the right stuff!src/: Your actual application code (main process, renderer process files, components, etc.)- Configuration files for your build tooling: e.g.,
forge.config.js,vite.config.js,webpack.config.js public/orassets/: Static resources you added (like custom icons, images, or HTML templates)README.mdor documentation: Important info for anyone working on the project
3. Restoring Auto-Generated Files Easily
If you’ve cloned the repo (or lost the auto-generated files), you can bring them back in two simple steps:
- Install dependencies: Run
npm install(oryarn installif you use Yarn) to rebuild thenode_modulesdirectory from yourpackage.jsonand lock file. - Regenerate build artifacts/caches: If you need to recreate temporary build files (like those in
.forge/), just run your build tool’s setup command—for example,npm run prepare(many Electron tools run this automatically after install) orelectron-forge importif you’re using Forge. For bundled app files, runnpm run buildto generate thedist/orout/directory again.
The key here is that all the auto-generated stuff is either derived from your tracked configuration files or can be pulled from npm/Yarn registries—so as long as you keep the core project files in Git, restoring everything is straightforward.
内容的提问来源于stack exchange,提问作者Damien Cappelle




