Search code examples
typescriptsvelterollupjs

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


I have a custom dependency which is a .ts file. It contains enums, interfaces and consts, I'm importing like so:

import type { inteface1, interface2} from "common";

This works completely fine and the compiler doesn't give me any errors.

If I try to do an import from the same dependency like so:

import { paths } from "common";

I get an error saying:

[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript) node_modules/common/types.ts (1:7)

Both of these imports are from the same file but for some reason trying to import a const or enum doesn't work and importing an interface works. The only difference seems to be that when importing interface, there's the type keyword.

rollup.config.js

typescript({
        sourceMap: !production,
        rootDir: "./src",
        exclude: ['node_modules/**']
    }),

tsconfig.json

{
    "extends": "@tsconfig/svelte/tsconfig.json",
  
    "include": ["src/**/*"],
    "exclude": ["node_modules/*", "__sapper__/*", "public/*"],
  }

I'm running with the command

rollup -c -w

versions:

"@rollup/plugin-typescript": "^9.0.0",

The file I'm importing (types.ts):

export interface interface1{
    field1: string
    field2: string
}
export interface interface2{
    status: "OK" | "NOK",
    field3: string;
}


export const paths = {
    path1: "/path1"
}

Here's the package.json from the dependency

{
  "name": "common",
  "version": "1.0.0",
  "description": "",
  "main": "types.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^18.8.3"
  }
}

Solution

  • Long story short, I was doing something incorrectly. After all kinds of testing, here's what finally worked for me:

    I added a index.ts file in the root of the project which explicitly exports my needed dependencies like so:

    export {interface1} from "./types";
    

    Added a tsconfig.json

    {
        "compilerOptions": {
          "strict": true,
            "module": "ES6",
          "target": "ES6",
          "lib": ["ES2020", "DOM", "DOM.Iterable"],
          "declaration": true,
          "outDir": "./dist/lib/es6",
          "moduleResolution": "node"
        },
        "include": ["src/**/*"]
      }
    

    Now when I run npx tsc command in the root, It'll create a /dist/lib/es6 folders which contains the compiled javascript.

    In the dependency project I modified the package.json to refer to the compiled javascript:

      "main": "./dist/lib/es6/index.js",
      "types": "./dist/lib/es6/index.d.ts",
    

    I still get a warning saying this, but so far no errors.

    (!) `this` has been rewritten to `undefined`