Mike Hogan
Mike Hogan

Reputation: 10583

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

Here is a github repo that reproduces this problem.

I have this 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"
  }
}

and this 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 contains this:

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

console.log(post)

When I run npx rollup -c I get:

[!] 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 {

How do I configure rollup to deal with dependencies that are Typescript files?

Upvotes: 6

Views: 8810

Answers (2)

Trevor Burnham
Trevor Burnham

Reputation: 77416

I spent hours trying to find a fix for this, and it turned out to be a simple plugin order issue. 😔

You need to use @rollup/plugin-node-resolve to bring in third-party modules from node_modules. I was already doing that, but I was using the TypeScript plugin first. Swapping the order resolved the issue for me:

// 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(),
    ]
};

Upvotes: 0

Mike Hogan
Mike Hogan

Reputation: 10583

This commit demonstrates a fix for the issue.

In summary, I added the following tsconfig.json file:

{
  "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"
  ]
}

The important piece is to include node_modules/@http4t as a source directory.

frederikhors comments on this issue was the telling contribution.

Upvotes: 5

Related Questions