如何使用 Rollup 将本地打字稿文件捆绑到主捆绑包中

Kar*_*lor 4 javascript rollup npm typescript

我正在尝试创建一个可以在浏览器中使用的 npm 模块。

我正在使用打字稿和汇总。

我的tsconfig.json是:

{
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "lib",
    "strict": true,
    "rootDir": "src"
  }
}
Run Code Online (Sandbox Code Playgroud)

我的rollup.config.js是:

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

export default {
  input: "src/index.ts",
  output: {
    dir: "lib",
    format: "iife",
  },
  plugins: [typescript()],
};
Run Code Online (Sandbox Code Playgroud)

里面src/index.ts我有以下内容:

// src/index.ts
import log from './log'

const myFn = () => {
 ...myFn code
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,在捆绑包中,我得到以下内容:

// lib/index.js bundle
var log_1 = require("./log");
Run Code Online (Sandbox Code Playgroud)

当我实际上想将log文件捆绑在 main 中时lib/index.js

我如何使用 Typescript 和 rollup 来做到这一点?

注意:我尝试添加outFilets docs),但这不受“@rollup/plugin-typescript”支持。

我是否必须自己编译 tsc,然后编译汇总包?

小智 6

Rollup 需要 TypeScript 编译器生成 ES 模块,以便正确捆绑您的代码。您需要将模块格式更改为“ESNext”而不是“CommonJS” tsconfig.json,或者更改@rollup/plugin-typescriptRollup 配置中的配置:

typescript({ module: "ESNext" })
Run Code Online (Sandbox Code Playgroud)

截至rollup/plugins#788开始,如果配置不正确,您将收到警告。

@rollup/plugin-typescript:Rollup 要求 TypeScript 生成 ES 模块。不幸的是,您的配置指定了“esnext”以外的“模块”。除非您知道自己在做什么,否则请将目标 tsconfig.json 文件或插件选项中的“module”更改为“esnext”。