rollup打包TypeScript的SDK项目

Rollup

简介

Rollup 是一个模块打包工具, 可以将我们按照 ESM (ES2015 Module) 规范编写的源码构建输出如下格式:

  • IIFE: 自执行函数, 可通过 <script> 标签加载
  • AMD: 通过 RequireJS 加载
  • CommonJS: Node 默认的模块规范, 可通过 Webpack 加载
  • UMD: 兼容 IIFE, AMD, CJS 三种模块规范
  • ESM: ES2015 Module 规范, 可用 WebpackRollup 加载

优点:

支持动态导入。

支持tree shaking。仅加载模块里用得到的函数以减小文件大小。

Scope Hoisting。 rollup可以将所有小文件生成到一个大文件中,所有代码都在同一个函数作用域里:, 不会像 Webpack 那样用很多函数来包装模块。

没有其他冗余代码, 执行很快。除了必要的 cjsumd 头外,bundle 代码基本和源码差不多,也没有奇怪的 __webpack_require__Object.defineProperty 之类的东西,

缺点:

不支持热更新功能;对于commonjs模块,需要额外的插件将其转化为es2015供rollup 处理;无法进行公共代码拆分。

输入:

options.input  单/多文件入口点

输出:

rollup支持生成 iife、cjs、amd 、esm、umd格式的文件; 单/多js文件输出

文件资源处理: 

rollup 通过插件来编译处理各类静态资源:

  • rollup-plugin-typescript2
  • rollup-plugin-babel
  • rollup-plugin-uglify
  • rollup-plugin-commonjs
  • rollup-plugin-postcss
  • rollup-plugin-img
  • rollup-plugin-json

基本使用参考

 https://www.cnblogs.com/tugenhua0707/p/8179686.html

适用场景:

由纯js开发的第三方库; 需要生成单一的umd文件的场景

案例:

纯js/ts编写的第三方库:

React、Vue

UI组件库 evergreen

使用 babel 将 js/ts 编译成  esm 和 cjs 格式的模块文件, 使用 rollup 将库打包成  umd 格式的 evergreen.min.js 和 evergreen.js ,  打包出来的代码比较干净。

使用rollup打包TypeScript的SDK项目

项目目录:

 

 

初始化项目

npm init -y

安装 项目依赖

npm install --save-dev  @babel/core @babel/plugin-external-helpers @babel/preset-env @babel/preset-typescript cross-env rollup rollup-plugin-babel  @babel/plugin-transform-runtime @rollup/plugin-commonjs @rollup/plugin-json @rollup/plugin-node-resolve @types/jest @types/node babel-preset-latest jest rollup-plugin-replace rollup-plugin-terser rollup-plugin-uglify ts-jest ts-node

package.json 的内容如下

复制代码
{
  "name": "xcplayer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest",
    "dev": "cross-env NODE_ENV=development rollup -c -w",
    "build": "cross-env NODE_ENV=production rollup -c",
    "build-dev": "cross-env NODE_ENV=development rollup -c",
    "unit": "jest --coverage"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^4.5.4"
  },
  "devDependencies": {
    "@babel/core": "^7.16.7",
    "@babel/plugin-external-helpers": "^7.16.7",
    "@babel/plugin-transform-runtime": "^7.16.8",
    "@babel/preset-env": "^7.16.8",
    "@babel/preset-typescript": "^7.16.7",
    "@rollup/plugin-commonjs": "^21.0.1",
    "@rollup/plugin-json": "^4.1.0",
    "@rollup/plugin-node-resolve": "^13.1.3",
    "@types/jest": "^27.4.0",
    "@types/node": "^17.0.8",
    "babel-preset-latest": "^6.24.1",
    "cross-env": "^7.0.3",
    "jest": "^27.4.7",
    "rollup": "^2.63.0",
    "rollup-plugin-babel": "^4.4.0",
    "rollup-plugin-replace": "^2.2.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-uglify": "^6.0.4",
    "ts-jest": "^27.1.2",
    "ts-node": "^10.4.0"
  }
}
复制代码

创建 rollup.config.js 可根据具体需求修改

复制代码
import commonjs from "@rollup/plugin-commonjs"
import json from "@rollup/plugin-json"
import { nodeResolve } from "@rollup/plugin-node-resolve" // 告诉rollup去哪里找依赖库
import babel from "rollup-plugin-babel"
import replace from "rollup-plugin-replace"
import { terser } from "rollup-plugin-terser" // 压缩
const pkg = require("./package.json")
// Version
const pkgVersion =
  process.env.NODE_ENV === "production" ? pkg.version : `${pkg.version}_beta`

// Name of package
const pkgName = pkg.name

// banner
const banner =
  "/*!\n" +
  ` * xrtc.js v${pkgVersion}\n` +
  ` * (c) 2020-${new Date().getFullYear()} \n` +
  " * Released under the MIT License in iflytek.\n" +
  " */\n"

const isProduction = process.env.NODE_ENV === "production"

const destFolder = isProduction ? "dist" : "demo/lib"

const output = isProduction
  ? [
      {
        file: `./${destFolder}/${pkgName}-${pkgVersion}.js`,
        format: "umd", // 模块输出格式:es、cjs、amd、umd、iife、system
        name: "XRTC", // 指定打包后模块的输出结果接收变量
        globals: {
          crypto: "crypto",
        },
        banner: banner,
      },
      {
        file: `./${destFolder}/${pkgName}-${pkgVersion}.esm.js`,
        format: "esm", // 模块输出格式:es、cjs、amd、umd、iife、system
        name: "XRTC", // 指定打包后模块的输出结果接收变量
        globals: {
          crypto: "crypto",
        },
        banner: banner,
      },
    ]
  : [
      {
        file: `./${destFolder}/${pkgName}.js`,
        format: "esm", // 模块输出格式:es、cjs、amd、umd、iife、system
        name: "XRTC", // 指定打包后模块的输出结果接收变量
        globals: {
          crypto: "crypto",
        },
        banner: banner,
      },
    ]

const extensions = ["*", ".js", ".ts"]

const configuration = {
  input: "./src/index.ts",
  output,
  plugins: [
    json({
      namedExports: false,
    }),
    nodeResolve({
      extensions,
    }),
    babel({
      exclude: "node_modules/**", // 排除node_modules 下的文件
      runtimeHelpers: true,
      extensions,
    }),
    commonjs({
      sourceMap: true,
    }),
    replace({
      ENV: JSON.stringify(process.env.NODE_ENV),
      __VERSION__: JSON.stringify(pkgVersion),
    }),
  ],
}

if (isProduction) {
  const { terser } = require("rollup-plugin-terser")
  const output = configuration.output.map((output) => {
    const buildOutput = Object.assign({}, output)
    buildOutput.file = buildOutput.file.replace(/\.js$/, ".min.js")
    buildOutput.plugins = [
      terser({
        module: true,
        compress: {
          ecma: 2015,
          pure_getters: true,
        },
      }),
    ]
    return buildOutput
  })
  configuration.output = [...configuration.output, ...output]
}

export default configuration
复制代码

添加.babelrc文件 

{
  "presets": ["@babel/preset-env", "@babel/preset-typescript"],
  "plugins": [
    [
      "@babel/plugin-transform-runtime"
    ]
  ]
}

添加jest.config.js 文件(前端自动化测试 - Jest基础配置篇) npx jest --init

复制代码
/*
 * For a detailed explanation regarding each configuration property and type check, visit:
 * https://jestjs.io/docs/configuration
 */

export default {
  // All imported modules in your tests should be mocked automatically
  // automock: false,

  // Stop running tests after `n` failures
  // bail: 0,

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "C:\\Users\\ythu9\\AppData\\Local\\Temp\\jest",

  // Automatically clear mock calls, instances and results before every test
  clearMocks: true,

  // Indicates whether the coverage information should be collected while executing the test
  // collectCoverage: false,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  // collectCoverageFrom: undefined,

  // The directory where Jest should output its coverage files
  coverageDirectory: "coverage",

  // An array of regexp pattern strings used to skip coverage collection
  // coveragePathIgnorePatterns: [
  //   "\\\\node_modules\\\\"
  // ],

  // Indicates which provider should be used to instrument code for coverage
  // coverageProvider: "babel",

  // A list of reporter names that Jest uses when writing coverage reports
  // coverageReporters: [
  //   "json",
  //   "text",
  //   "lcov",
  //   "clover"
  // ],

  // An object that configures minimum threshold enforcement for coverage results
  // coverageThreshold: undefined,

  // A path to a custom dependency extractor
  // dependencyExtractor: undefined,

  // Make calling deprecated APIs throw helpful error messages
  // errorOnDeprecated: false,

  // Force coverage collection from ignored files using an array of glob patterns
  // forceCoverageMatch: [],

  // A path to a module which exports an async function that is triggered once before all test suites
  // globalSetup: undefined,

  // A path to a module which exports an async function that is triggered once after all test suites
  // globalTeardown: undefined,

  // A set of global variables that need to be available in all test environments
  // globals: {},

  // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
  // maxWorkers: "50%",

  // An array of directory names to be searched recursively up from the requiring module's location
  // moduleDirectories: [
  //   "node_modules"
  // ],

  // An array of file extensions your modules use
  // moduleFileExtensions: [
  //   "js",
  //   "jsx",
  //   "ts",
  //   "tsx",
  //   "json",
  //   "node"
  // ],

  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  // moduleNameMapper: {},

  // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
  // modulePathIgnorePatterns: [],

  // Activates notifications for test results
  // notify: false,

  // An enum that specifies notification mode. Requires { notify: true }
  // notifyMode: "failure-change",

  // A preset that is used as a base for Jest's configuration
  // preset: undefined,

  // Run tests from one or more projects
  // projects: undefined,

  // Use this configuration option to add custom reporters to Jest
  // reporters: undefined,

  // Automatically reset mock state before every test
  // resetMocks: false,

  // Reset the module registry before running each individual test
  // resetModules: false,

  // A path to a custom resolver
  // resolver: undefined,

  // Automatically restore mock state and implementation before every test
  // restoreMocks: false,

  // The root directory that Jest should scan for tests and modules within
  // rootDir: undefined,

  // A list of paths to directories that Jest should use to search for files in
  // roots: [
  //   "<rootDir>"
  // ],

  // Allows you to use a custom runner instead of Jest's default test runner
  // runner: "jest-runner",

  // The paths to modules that run some code to configure or set up the testing environment before each test
  // setupFiles: [],

  // A list of paths to modules that run some code to configure or set up the testing framework before each test
  // setupFilesAfterEnv: [],

  // The number of seconds after which a test is considered as slow and reported as such in the results.
  // slowTestThreshold: 5,

  // A list of paths to snapshot serializer modules Jest should use for snapshot testing
  // snapshotSerializers: [],

  // The test environment that will be used for testing
  testEnvironment: "jsdom",

  // Options that will be passed to the testEnvironment
  // testEnvironmentOptions: {},

  // Adds a location field to test results
  // testLocationInResults: false,

  // The glob patterns Jest uses to detect test files
  // testMatch: [
  //   "**/__tests__/**/*.[jt]s?(x)",
  //   "**/?(*.)+(spec|test).[tj]s?(x)"
  // ],

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  // testPathIgnorePatterns: [
  //   "\\\\node_modules\\\\"
  // ],

  // The regexp pattern or array of patterns that Jest uses to detect test files
  // testRegex: [],

  // This option allows the use of a custom results processor
  // testResultsProcessor: undefined,

  // This option allows use of a custom test runner
  // testRunner: "jest-circus/runner",

  // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
  // testURL: "http://localhost",

  // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
  // timers: "real",

  // A map from regular expressions to paths to transformers
  // transform: undefined,

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  // transformIgnorePatterns: [
  //   "\\\\node_modules\\\\",
  //   "\\.pnp\\.[^\\\\]+$"
  // ],

  // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
  // unmockedModulePathPatterns: undefined,

  // Indicates whether each individual test should be reported during the run
  // verbose: undefined,

  // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
  // watchPathIgnorePatterns: [],

  // Whether to use watchman for file crawling
  // watchman: true,
};
复制代码

 

posted @   webHYT  阅读(1341)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示