Rollup: dealing with dependencies that are typescript files. Getting Error: Unexpected token

Rollup: dealing with dependencies that are typescript files. Getting Error: Unexpected token

这是重现此问题的 github repo

我有这个package.json:

{
  "name": "rollup-ts-deps",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Mike Hogan",
  "license": "ISC",
  "devDependencies": {
    "@rollup/plugin-typescript": "^8.2.0",
    "rollup": "^2.41.0",
    "typescript": "^4.2.3"
  },
  "dependencies": {
    "@http4t/core": "0.0.121"
  }
}

和这个rollup.config.js

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

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

and src/index.ts 包含这个:

import {post} from "@http4t/core/requests";

console.log(post)

当我 运行 npx rollup -c 我得到:

[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
node_modules/@http4t/core/requests.ts (5:30)
3: import {Authority, Uri, UriLike} from "./uri";
4: 
5: export function request(method: Method, uri: UriLike, body?: HttpBody, ...headers: Header[]): HttpRequest {

如何配置汇总来处理 Typescript 文件的依赖项?

This commit 演示了该问题的修复。

总而言之,我添加了以下 tsconfig.json 文件:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ES2020",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist/esm",
    "declaration": true,
    "moduleResolution": "node"
  },
  "include": [
    "./src",
    "node_modules/@http4t"
  ]
}

重要的一点是将 node_modules/@http4t 作为源目录包含在内。

frederikhorsthis issue 的评论是有说服力的贡献。

我花了几个小时试图解决这个问题,结果证明这是一个简单的插件顺序问题。

您需要使用@rollup/plugin-node-resolve从node_modules引入第三方模块。我已经在这样做了,但我首先使用的是 TypeScript 插件。调换订单为我解决了问题:

// rollup.config.js
import nodeResolve from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';

export default {
    // ...
    plugins: [
        nodeResolve(), // must come before the typescript plugin!
        typescript(),
    ]
};