typescript - 构建和分发 Typescript 项目

标签 typescript npm

我有一个 typescript 项目,当我开发它时,代码分布在许多文件中。

我想将该项目分发为单个 js 和 d.ts 文件 - 最好的方法是什么?

最佳答案

打包文件时,通常不需要将其组合成一个文件。使用包管理器(例如 NPM),您的文件将被捆绑到一个您可以保密或公开的包中,并且该包包含运行您的模块所需的所有文件。

特别是对于 TypeScript,您将打包 .js.d.ts 文件,这意味着您的包将适用于 TypeScript 和 JavaScript 使用者。您不会将 .ts 文件添加到包中。

如果您的目标是浏览器和 Node 环境,您可以使用 UMD 模块,它可以在这两种环境中工作。

实际示例 - TypeSpec。

请注意 - 我已将整个文件放在下面以确保上下文在那里,但重要的部分通常是我突出显示的一两行。

TypeScript 配置文件 - 重要的部分是“模块”类型和发出“声明”文件。

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "ES5",
    "module": "umd", // <--
    "strict": true,
    "experimentalDecorators": true,
    "noEmitOnError": false,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "sourceMap": true,
    "removeComments": false,
    "declaration": true, // <--
    "downlevelIteration": true,
    "noUnusedLocals": true,
    "noUnusedParameters": false
  }
}

Gulp 文件 - 这会将文件移动到 dist 文件夹中,包括 package.json 和自述文件,但最重要的是所有 JavaScript 和类型定义。

var gulp = require('gulp');

gulp.task('default', function () {
    gulp.src('./node_modules/requirejs/require.js')
        .pipe(gulp.dest('./lib'));

    // This bit moves type definitions
    gulp.src('./Scripts/TypeSpec/*.d.ts')
        .pipe(gulp.dest('./dist/src'));

    // And this bit moves the JavaScript
    gulp.src('./Scripts/TypeSpec/*.js')
        .pipe(gulp.dest('./dist/src'));

    gulp.src('../README.md')
        .pipe(gulp.dest('./dist'));

    gulp.src('./package.json')
        .pipe(gulp.dest('./dist'));
});

package.json 文件提示可以在“main”和“types”部分中找到主要源文件和类型信息的位置:

{
  "author": "Steve Fenton",
  "name": "typespec-bdd",
  "description": "BDD framework for TypeScript.",
  "keywords": [
    "typespec",
    "typescript",
    "bdd",
    "behaviour",
    "driven"
  ],
  "version": "0.7.1",
  "homepage": "https://github.com/Steve-Fenton/TypeSpec",
  "bugs": "https://github.com/Steve-Fenton/TypeSpec/issues",
  "license": "(Apache-2.0)",
  "files": [
    "src/"
  ],
  "repository": {
    "url": "https://github.com/Steve-Fenton/TypeSpec"
  },
  "main": "./src/TypeSpec.js", <-- main file
  "types": "./src/TypeSpec.d.ts", <-- type information starts here
  "dependencies": {},
  "devDependencies": {
    "gulp": "^3.9.1",
    "requirejs": "^2.3.5"
  },
  "optionalDependencies": {},
  "engines": {
    "node": "*"
  }
}

您现在有了一个“dist”文件夹,里面只有您需要打包的文件。您可以在不发布到 NPM 的情况下试用它。

npm pack 

关于typescript - 构建和分发 Typescript 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46520882/

相关文章:

javascript - 在链接库和工作区应用程序之间链接 react 版本

typescript - Typescript 类型 `in` 运算符的困惑

javascript - 表单验证空字段在 Angular 2+ 中显示为无效

javascript - 获取 Node 模块目录的路径

javascript - 是否可以在不执行 npm 安装的情况下只生成一个 package-lock.json 文件?

reactjs - Vite、NPM、React 组件库 无效的 hook 调用、外部问题?

angular - 'Employee' 仅指类型,但在此处用作值。ts(2693)

javascript - Serverless NodeJS跳过https请求

javascript - React HOC 上的 Typescript

node.js - Bcrypt 在 Linux 上安装失败