无需安装nodejs,无需nginx,双击.exe就行运行前端项目

4 阅读1分钟

package.json

  "name": "vue-app",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "pkg": "pkg . --targets node18-win-x64 --output vue-app.exe --compress Brotli"
  },
  "bin": "server.js",
  "pkg": {
    "assets": [],
    "ignore": [
      "**/node_modules/*/.git",
      "**/*.md",
      "**/*.log",
      "dist/**/*"
    ]
  },
  "dependencies": {
    "express": "^5.2.1"
  },
  "devDependencies": {
    "pkg": "^5.8.1"
  }
}

server.js

const path = require('path');
const { exec } = require('child_process');
const app = express();
const port = 8000;
const distPath = process.pkg 
  ? path.resolve(path.dirname(process.execPath)) // pkg打包后指向exe所在目录
  : path.resolve(__dirname); // 普通运行指向脚本目录

// 核心:托管静态文件(仅保留必要逻辑)
app.use(express.static(distPath));

app.use((req, res) => {
  res.sendFile(path.join(distPath, 'index.html'), (err) => {
    if (err) res.status(404).send('未找到index.html');
  });
});

// 启动服务 + 精简版自动打开浏览器(移除冗余变量/判断,保留核心兼容)
app.listen(port, () => {
  const url = `http://localhost:${port}`;
  console.log(`服务运行在: ${url}`);
  
  // 极简跨系统打开浏览器逻辑(减少冗余分支)
  const cmd = process.platform === 'win32' ? `start ${url}` 
    : process.platform === 'darwin' ? `open ${url}` : `xdg-open ${url}`;
  exec(cmd, (err) => err && console.log('手动访问:', url))
});

1. 执行npm i; npm run pkg;

2. 现在只是单独生成exe壳体,将这个.exe放入打包的dist中即可;如何报错在命令行中执行./vue-app.exe查看报错信息

3. 如何想把整个dist打到exe中,需要添加"assets": ["dist/**/*"]配置