返回

TypeScript + Rollup 从 0 到 1 搭建工具库工程指南

前端

从 0 到 1 搭建 TypeScript + Rollup 工具库工程

在当今快速发展的软件开发世界中,构建和维护可重用的代码库至关重要。使用 TypeScript 和 Rollup,我们可以轻松创建模块化、可维护的工具库工程。本指南将引导你完成从头开始构建一个这样的工程的每一步。

创建文件夹结构

首先,让我们创建我们的工程文件夹结构:

├── package.json
├── src
│   ├── index.ts
├── dist
│   ├── index.js
│   ├── index.d.ts
└── tsconfig.json
  • package.json: 定义工程元数据,例如名称、版本和依赖项。
  • src/index.ts: 包含工具库的源代码。
  • dist/: 将编译后的 JavaScript 和 TypeScript 声明文件输出到此目录。
  • tsconfig.json: 配置 TypeScript 编译器选项。

安装依赖项

接下来,我们需要安装必要的依赖项:

npm install --save-dev rollup typescript

配置 Rollup

rollup.config.js 中,我们指定输入文件、输出配置和其他选项:

import typescript from "@rollup/plugin-typescript";

export default {
  input: "src/index.ts",
  output: {
    file: "dist/index.js",
    format: "cjs",
  },
  plugins: [
    typescript({
      tsconfig: "./tsconfig.json",
    }),
  ],
};

配置 TypeScript

tsconfig.json 中,我们配置 TypeScript 编译器选项:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "dist"
  }
}
  • target: 编译目标 JavaScript 版本。
  • module: 模块类型,指定为 CommonJS。
  • declaration: 生成 TypeScript 声明文件(*.d.ts)。
  • outDir: 指定编译输出目录。

构建工程

运行以下命令编译工程:

npx rollup -c

这将在 dist 目录中生成编译后的 JavaScript 和 TypeScript 声明文件。

使用工具库

在另一个项目中,我们可以通过 require 导入工具库:

const myLib = require("my-lib");

结论

通过遵循这些步骤,你已经成功地从头开始使用 Rollup 和 TypeScript 构建了一个工具库工程。这个工程提供了构建和维护可重用代码模块的强大基础。通过遵循本指南,你可以在自己的项目中实现更有效的代码重用和模块化。