You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含TypeScript装饰器的NodeJS后端打包为Windows可执行文件

问题:将带TypeScript装饰器的Node.js/Express应用打包为单可执行文件

背景

需要把基于Express、使用TypeScript装饰器(通过GraphQL Modules实现)的Node.js应用打包成单个可执行文件(.exe),以简化给客户端的交付流程。

已尝试的方案

方案1:esbuild + pkg

  • 结果:失败,核心原因是不支持装饰器;移除装饰器后可成功生成单个.exe文件。

方案2:Vite

  • 结果:接近目标,但仍存在问题
  • 使用的vite.config.ts配置:
import { defineConfig } from 'vite';
import { VitePluginNode } from 'vite-plugin-node';
import tsconfigPaths from 'vite-tsconfig-paths';
import graphqlLoader from 'vite-plugin-graphql-loader';

import { builtinModules } from 'node:module';

export default defineConfig({
  server: {
    port: 3210,
    open: '/graphql'
  },
  resolve: {
    preserveSymlinks: true
  },
  plugins: [
    tsconfigPaths(),
    graphqlLoader(),
    ...VitePluginNode({
      adapter: 'express',
      appPath: './index.ts',
      exportName: 'viteNodeApp',
      initAppOnBoot: true,
      tsCompiler: 'swc',
      swcOptions: {
        minify: true,
        jsc: {
          target: 'esnext',
          parser: {
            syntax: 'typescript',
            decorators: true
          },
          transform: {
            legacyDecorator: true,
            decoratorMetadata: true
          }
        }
      }
    })
  ],
  build: {
    minify: true,
    target: 'node',
    ssr: './index.ts',
    outDir: 'dist',
    rollupOptions: {
      output: {
        inlineDynamicImports: true
      },
      preserveSymlinks: true,
      external: [...builtinModules, ...builtinModules.map((m) => `node:${m}`)]
    }
  },
  ssr: {
    external: [...builtinModules, ...builtinModules.map((m) => `node:${m}`)],
    noExternal: process.env.NODE_ENV === "production" ? [/.*/] : undefined
  }
});
  • 生成结果:单个index.mjs文件,但文件中仍保留对Node核心模块的导入(例如:import require$$0$a, { Readable } from 'stream';)
  • 后续尝试用pkg打包的命令:
pkg -C GZip -t latest-win -o bin/test.exe dist/index.mjs
  • 出现的错误:

Warning Failed to make bytecode latest-x64 for file C:\snapshot\test\src\services\test\dist\index.mjs

需求

当前的实现思路可能存在问题,希望得到更简便的打包方案指导。

内容的提问来源于stack exchange,提问作者JoJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:02:16