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

如何配置tsconfig不编译templates文件夹并复制到dist目录?

实现方案

1. 配置tsconfig.json,仅编译指定文件并排除模板目录

修改你的tsconfig.json,通过include指定只编译入口文件,exclude排除模板文件夹,同时确保outDir指向输出目录:

{
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./dist",
    "module": "CommonJS", // 根据npx包需求调整模块规范
    "target": "ES6", // 适配目标环境的ES版本
    "strict": true // 可选,开启严格模式
  },
  "include": ["./src/index.ts"],
  "exclude": ["./src/templates/**/*"]
}

这样tsc命令只会编译src/index.ts并输出到dist目录,完全忽略src/templates下的所有文件。

2. 添加脚本自动复制模板文件夹到dist

TypeScript编译器不会处理非编译文件的复制,需要额外添加复制步骤,以下是两种常用方案:

方式一:使用copyfiles工具(简单快捷)

  • 安装开发依赖:
    npm install copyfiles --save-dev
    
  • 在package.json的scripts中添加构建命令:
    "scripts": {
      "build": "tsc && copyfiles -u 1 src/templates/**/* dist/"
    }
    
    其中-u 1表示移除路径中的src/层级,确保模板文件夹直接输出到dist/templates,而非dist/src/templates。

方式二:用Node.js脚本复制(无额外依赖,灵活可控)

  • 在项目根目录创建copy-templates.js文件:
    const fs = require('fs').promises;
    const path = require('path');
    
    async function copyTemplates() {
      const srcPath = path.join(__dirname, 'src', 'templates');
      const destPath = path.join(__dirname, 'dist', 'templates');
    
      try {
        await fs.cp(srcPath, destPath, { recursive: true });
        console.log('模板文件夹复制完成');
      } catch (err) {
        console.error('复制模板失败:', err);
        process.exit(1);
      }
    }
    
    copyTemplates();
    
  • 修改package.json的构建脚本:
    "scripts": {
      "build": "tsc && node copy-templates.js"
    }
    

3. 验证效果

运行npm run build后,检查dist目录:

  • 会生成编译后的index.js(若开启declaration选项,还会生成对应的.d.ts类型文件)
  • templates文件夹完整复制到dist下,内部文件保持原格式,未被编译

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:10:40