Plugins: Typescript plugin 4.0.0 Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)

Created on 28 Mar 2020  ยท  55Comments  ยท  Source: rollup/plugins

  • Rollup Plugin Name: typescript
  • Rollup Plugin Version: 4.0.0
  • Rollup Version: 2.2.0
  • Operating System (or Browser): macOsx
  • Node Version: 10.16.3

How Do We Reproduce?

import tsPlugin from '@rollup/plugin-typescript';
import pkg from './package.json';

export default {
    input: 'src/index.tsx',
    output: [
        {
            file: pkg.main,
            format: 'cjs',
            sourcemap: true,
        },
        {
            file: pkg.module,
            format: 'es',
            sourcemap: true,
        },
    ],
    plugins: [
        tsPlugin(),
    ],
};

Expected Behavior

src/index.tsx โ†’ dist/index.js, dist/index.es.js... created dist/index.js, dist/index.es.js in 1.1s

Actual Behavior

[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript) src/index.tsx (1:25) 1: export function hasan(num: number): number { ^

I hope I'm doing something wrong because it is so bad to cant use ts plugin.
Ts plugin version 3.0.0 works perfect by the way.

๐Ÿ”Œ plugin-typescript

Most helpful comment

@talentlessguy I resolved this problem by removing outDir, declarationDir, declaration from tsconfig.json. If you need them when you invoke tsc, specify them using command line arguments.

All 55 comments

Thanks for opening an issue. Citing the issue template:

Issues without minimal reproductions will be closed! Please provide one by:

  1. Using the REPL.it plugin reproduction template at https://repl.it/@rollup/rollup-plugin-repro
  2. Provide a minimal repository link (Read https://git.io/fNzHA for instructions).
    These may take more time to triage than the other options.
  3. Using the REPL at https://rollupjs.org/repl/

Please add a reproduction and we'll be happy to triage further.

I have the same error and made a small project to reproduce the error (see this project)

I switched back to @rollup/plugin-typescript version 3.1.1. In this version I don't have the problems. I use tsc to make the declarations.

Thanks for the reproduction @JohanSchobben

Quick fix for now is to manually set your rootDir compiler option to "src".

@sssylvan I' getting this error:

Error: @rollup/plugin-typescript: 'dir' must be used when 'outDir' is specified.

@talentlessguy I resolved this problem by removing outDir, declarationDir, declaration from tsconfig.json. If you need them when you invoke tsc, specify them using command line arguments.

@talentlessguy I resolved this problem by removing outDir, declarationDir, declaration from tsconfig.json. If you need them when you invoke tsc, specify them using command line arguments.

I have a case when I need to generate typings, so it won't work probably

I have a case when I need to generate typings, so it won't work probably

I run tsc separately to generate typings. i.e. in my package.json

{
   ...
   "scripts": {
        "build": "tsc --outDir dist/lib --declarationDir dist/types --declaration true && rollup -c",
        "prepare": "npm run build"
    }
}

I came here after finding exactly the same problem. Just confirming this is still an issue in version 4.1.1 of the plugin, on both mac os and Windows 10. I too use tsc to generate my bindings, but they shouldn't conflict like this. Have reverted back to rollup-plugin-typescript2 for now, which works just fine.

I fixed this by deleting /dist folder before running rollup.

[EDIT] Even better, seems like if I remove just .tsbuildinfo before running rollup this error never happen.

I thought I had the same issue - maybe it is related.

I have a monorepo like this:

/projects/A/src/A.ts
/projects/A/rollup.config.js

/projects/B/src/B.ts

/projects/shared/src/somemod.ts
// somemod.ts
export const theAnswer: number = 42;
// A.ts
import {theAnswer} from "../../shared/src/somemod";
console.log(theAnswer);

When I run the build in /projects/A/, the build failes with the described error. Once I added ../shared/**/*.ts to my include list, it worked.

Have the same problem, repo at https://github.com/Jack-Works/async-call/tree/rollup (rollup branch)

I encountered this issue and switched to the unofficial rollup-plugin-typescript2 which seems to work.

I switched back to @rollup/plugin-typescript version 3.1.1.

Downgrade to 3.1 doesn't work for me

Quick fix for now is to manually set your rootDir compiler option to "src".

Doesn't work for me either

Oh strange, rollup-plugin-typescript2 doesn't work either

Oh sorry, my fault. I put my ts plugin in the output config, therefore, it's not working

We had a problem where --preserveSymlinks solved it... hard to understand why though.

Adding the "rootDir": "src" node to my tsconfig solved the problem for me, just as @sssylvan suggested. That was the only change I needed.

I had to downgrade to version 3.1 as well, nothing else worked for me.

I use ver 5.0.0. None of the given solutions worked for me except this https://github.com/rollup/plugins/issues/287#issuecomment-611368317 and this https://github.com/rollup/plugins/issues/287#issuecomment-611621543.

I removed declaration from tsconfig and added manually generated it after building with rollup.

    "build": "rollup -c && tsc -d --emitDeclarationOnly --declarationDir build/types",

Hey folks. This is a call for contribution and help in resolving this TypeScript plugin issue. We're working with limited resources and the folks who can help have limited time. If you can help by triaging and submitting a Pull Request, we'd be happy to review it.

hey @shellscape , I haven't contributed to any OSS projects yet. but I am willing to give this a try.

I've gone through this thread and reproduced the bug in a sample project. can you help me to get started? where I can get started and what I can look into to fix the issue.

@rashvaz thank you ๐Ÿ™Œ The best place to get started is probably with the source here: https://github.com/rollup/plugins/tree/master/packages/typescript. I typically take a reproduction and try to make a failing test from it. Then I try to fix the test. Sometimes it's necessary to debug the source of the plugin in node_modules within a reproduction repo for especially hard cases.

@NotWoods this one seems to be persistent (and we just ran into this at work haha). Any chance you have bandwidth for it in the coming weeks?

I was trying to fix this few days earlier and was able to create failing test, which works well with tsc by fails with plugin. By I do struggle to attach debugger with pnpm with ava to dive deeper into typescript generating output file paths. If I will not fix I may add some info (failing test, function that seem to be not working). Will check more on weekend.

I'll be taking another look at this next month, been busy with work over the summer. I think the solution lies in finding a better way to determine the output paths, as ts.getOutputFileNames is sometimes inaccurate.

The root of problem is in this line in ts repo
return configFile.options.rootDir || getDirectoryPath(Debug.checkDefined(configFile.options.configFilePath));

While running cli tsc seem to be working without rootDir option being provided. Without rootDir being set to tsconfig.json path and paths to generated files generated by ts. getOutputFileNames
look like that:
path-to-repo/lib/src/main.js
instead of:
path-to-repo/lib/main.js.

I don't think any changes should be made to computing file output paths. Maybe there should be a validation of incoming options, if the file specified as rollup input lies not in the top directory and compilerOptions.rootDir option is not provided.
Also webpack's ts-loader uses the same api if this function exists in typescript

This error output might be also a bit confusing and changed so it would be clear that dir option rollup specific

Hey guys, any idea when the fix will be ready?
Apart from @talentlessguy error, I'm also getting this:

[!] (plugin typescript) Error: @rollup/plugin-typescript: 'dir' must be used when 'declarationDir' is specified.

Thanks in advance

@didix16 As stated in the error, you need to use dir instead of file.

Hi @NotWoods, I'm not using any 'file' directive at any point.

@didix16 Please show your rollup config.

Here is my rollup config:

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import camelCase from 'lodash.camelcase';
import typescript from '@rollup/plugin-typescript';
import json from '@rollup/plugin-json';
import license from 'rollup-plugin-license';

const pkg = require('./package.json');

const libraryName = 'ecs';

export default {

    input: `src/${libraryName}.ts`,
    output: [
        {
            file: pkg.main,
            name: camelCase(libraryName),
            format: 'umd',
            sourcemap: true
        },
        {
            file: pkg.module,
            format: 'es',
            sourcemap:true
        }
    ],
    external: [
        'uuid'
    ],
    watch: {
        include: 'src/**'
    },
    plugins: [
        // Allow json resolution
        json(),
        // Compile TypeScript files
        typescript(),
        // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
        commonjs(),
        // Allow node_modules resolution, so you can use 'external' to control
        // which external modules to include in the bundle
        // https://github.com/rollup/plugins/tree/master/packages/node-resolve#usage
        resolve(),
        sourceMaps(),
        license({
            banner: `...`
          })
    ]
}

And here is my tsconfig.json:

{
    "compilerOptions": {

        "rootDir": "src",
        "moduleResolution": "node",
        "target": "es5",
        "module":"es2015",
        "lib": ["es2015", "es2016", "es2017", "dom"],
        "strict": false,
        "sourceMap": true,
        "declaration": true,
        "allowSyntheticDefaultImports": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declarationDir": "dist/types",
        "outDir": "dist/lib",
        "skipLibCheck": false,
        "typeRoots": [
            "dist/types",
            "node_modules/@types"
        ]
    },
    "include": [
      "src"
    ]
  }

It is very strange that the official plugin cannot be fixed for a long time. In fact, it is not doing the work it should be doing. It is virtually impossible to use rollup to build an application written in vue.

I've only ever had this issue once and it was due to a permission error. I recommend checking your permissions are all ok.

@wellrus that's not a constructive comment and it doesn't add anything to triaging the issue at hand. I recommend that you read https://liberamanifesto.com, and consider your view of open source.

You might also consider being a part of the solution and contributing a fix. Rollup and its plugins are community supported.

Please refrain from additional replies that are not constructive or helpful to the original issue.

Replies that do not help to triage or resolve the issue with the plugin in this repo will be removed. Suggesting alternatives does not assist with the triage of the original issue reported.

I'm using a shared folder as common source for several typescript projects (monorepo style). I've had the same error message: [!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)

After debugging the source I've found that the load(id) function filters out my ../shared/src/foo.ts file from transpilation.

This is because getPluginOptions creates a default file filter for files in the current folder (cwd) only.

As a solution I configure the plugin with a suiting include configuration:

  plugins: [
    typescript({
      include: ['../**/src/**/*.ts'],
    }),
  ],

In tsconfig.json I also had to add the shared sources in the include section:

  "include": [
    "src/**/*",
    "../shared/src/**/*"
  ]

I hope this description can help to others having similar problem.

I also see as a possible improvement to respect the paths in tsconfig's include (instead using the default ['*.ts+(|x)', '**/*.ts+(|x)']).

This description could be maybe added to the README.md?

@ribizli very helpful, thank you for sharing. would you be willing to submit a PR to add that to the README for the plugin?

I just want to say that the above solution did not work in my case. Updating the include option for the plugin doesn't seem to fix the issue in my repos, nor does it fix the issue in the reproduction repo from https://github.com/rollup/plugins/issues/287#issuecomment-605909100.

I have the same error and made a small project to reproduce the error (see this project)

Some leads for you:

Setting rootDir": "./src", in tsconfig
And changing to dir in rollup.config.js
output: {
dir: "dist",
solves it and creates both output and declaration.
removing outDir and setting declaration:false in tsconfig also solves it without removing the single out file from rollup.

@dstaley my solution is not for the original issue, but for this https://github.com/rollup/plugins/issues/287#issuecomment-626517864 from @htho

@shellscape I might include my solution into README.md, but I need to find a time for it.

I'm also considering a PR for taking the include and exclude values from tsconfig.json if they are not explicitly specified for the plugin. So one can avoid the double configuration.

Just confirming this issue, and the fact that it occurs only on successive builds (i.e. the first one is always successful). Removing the output dir effectively fixes the issue.

Just confirming this issue, and the fact that it occurs only on successive builds (i.e. the first one is always successful). Removing the output dir effectively fixes the issue.

Maybe same solution as mine https://github.com/rollup/plugins/issues/287#issuecomment-619256253. Probably there are more than 1 problem that throws this error

using "rollup-plugin-typescript2": "^0.26.0" with "typescript": "^4.0.5" works just fine. looks like there is some incompatibility with packages

I'm using a shared folder as common source for several typescript projects (monorepo style). I've had the same error message: [!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)

After debugging the source I've found that the load(id) function filters out my ../shared/src/foo.ts file from transpilation.

This is because getPluginOptions creates a default file filter for files in the current folder (cwd) only.

As a solution I configure the plugin with a suiting include configuration:

  plugins: [
    typescript({
      include: ['../**/src/**/*.ts'],
    }),
  ],

In tsconfig.json I also had to add the shared sources in the include section:

  "include": [
    "src/**/*",
    "../shared/src/**/*"
  ]

I hope this description can help to others having similar problem.

I also see as a possible improvement to respect the paths in tsconfig's include (instead using the default ['*.ts+(|x)', '**/*.ts+(|x)']).

This description could be maybe added to the README.md?

Thanks @ribizli you were on the right track for me to fix this.

For anyone else wanting a solution, just update your include to use RegExp and it should include .ts files outside of the cwd such as in monorepo. below is an example:

/packages
  /core
      /src
           ...your ts files
           index.ts
       rollup.config.js
  /shared <-- @example/shared
      ...other ts files

index.ts
import shared from '@example/shared'

export const hello = () => { ..... }


rollup.config.js
import typescript from '@rollup/plugin-typescript';
... your rollup config
plugins: [
                typescript({
                    include: [
                        "src/**/*.ts",
                        new RegExp("shared\\/(.)+\\/(.+\.ts)")
                    ]
                }),
            ],
...

None of all the solutions worked for me. What saved my life : increasing typescript.tsserver.maxTsServerMemory in my settings.json (work on VSCode)

Adding "rootDir": "src" and
"include": [ "**/*.ts" ],

To tsconfig.json fixed this issue for me.

@ivankoleda when I run tsc manually I don't see rootDirOfOptions getting called in my project. More importantly perhaps, I also don't see it calling getOutputFileNames, which seems to be the misbehaving function as @NotWoods mentioned. I do see tsc calling getSourceFilePathInNewDirWorker (via getSourceFilePathInNewDir) where newDirPath is the project root, currentDirectory is the project root, and commonSourceDirectory is src

I tried changing:

const emittedFileNames = ts.getOutputFileNames(parsedOptions, id, !ts.sys.useCaseSensitiveFileNames);
const codeFile = emittedFileNames.find(isCodeOutputFile);

To:

const codeFile = ts.getSourceFilePathInNewDir(id, formatHost, parsedOptions.outDir);

But got:

host.getCommonSourceDirectory is not a function

Perhaps you know if there are different types of hosts @NotWoods or how to get the appropriate host? I'm not sure I have a lot more time to spend on this at the moment, but hopefully this info helps move the investigation along a bit.

That seems like the right direction, thanks for the info! I'll investigate the host a bit more.

Ah, sadly that's a private TypeScript API so we can't use it in the plugin.

I've filed a bug over in the TypeScript repo for the getOutputFileNames issue: https://github.com/microsoft/TypeScript/issues/41780. It's scheduled for 4.2.1, so probably won't be looked at until March

I also wrote a test in https://github.com/rollup/plugins/pull/682

Woohoo! It looks like this bug is getting fixed already! https://github.com/microsoft/TypeScript/pull/41811

The fix has been merged in TypeScript and should be released with TypeScript 4.2.0. We can leave this open until then to track and make sure that we can enable the failing test when 4.2.0 is released

Was this page helpful?
0 / 5 - 0 ratings