1

Context

  • I would like to convert my existing codebase to Typescript. It is not possible to do this in a single go, so I'm trying to change 1 single file to use Typescript and them import it from my existing JS.
  • If it helps with debugging, this is the repo I am working on, and these are the changes beyond master that are described below.

Prior Work

  • I use babel-node to run my program, so I added @babel/preset-typescript to the config, and then played around with tsconfig.json until I got it to work.
// babel.config.js
module.exports = {
    plugins: [
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-transform-runtime',
        ["module-resolver", {
            "alias": {
                "extensions": [".tsx",".ts"],
            }
        }]
    ],
    presets: [
        '@babel/preset-env',
        '@babel/preset-react',
        ['@babel/preset-typescript', { allExtensions: true }],
    ],
    compact: false,
    sourceType: 'unambiguous',
};
  • I tried using // @ts-check to confirm that the type-checker was active, but quickly realized that I want proper type-hints.
  • So then I started adding those to one file, and VS Code gave me warnings saying Type annotations can only be used in TypeScript files. I could suppress the warnings using the suggestions from here, but that does not solve the underlying problem.
  • And so I changed the file extension from ".js" to ".ts". This gave me useful signals about code correctness, but now I am unable to import that file, even if I try to tell babel-node that this is a valid extension.
// Things I have tried inside ./demo/src/index.js

import { ProcessWrapper, StreamIntender } from './process';

> Cannot find module '/Users/kaustubh/Github/glados/demo/src/process' imported from /Users/kaustubh/Github/glados/demo/src/index.js

import { ProcessWrapper, StreamIntender } from './process.ts';

> TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/kaustubh/Github/glados/demo/src/process.ts
  • Is there a way to fix this? I don't see any reason why babel can't allow this in theory, if it is capable of parsing Typescript.
  • Alternatively, is there another way to accomplish what I'm trying to do?
Kaustubh Karkare
  • 1,083
  • 9
  • 25
  • 1
    It's always wrong to use the `.ts` extension in a module specifier and it's actually an error in typescript to do so. Either provide no extension, letting it be resolved by the loader, or use the extension to which the file would have been transpiled, i.e. `.js`. You also need to configure be Babel to handle typescript via a plugin. – Aluan Haddad Dec 25 '21 at 03:59
  • I updated the question to show that using a module-resolver does not seem to work for me, either. – Kaustubh Karkare Dec 25 '21 at 04:40

0 Answers0