- Rename the file from
.js
to.ts
- Change
module.exports =
toexport =
- Change all
exports.foobar =
toexport const foobar =
- Update top-level
require
calls to staticimport
.- Note: You can use vscode to help you with that
- Put the caret inside
require
, press cmd-. -> "Convert require to import" - If you have multiple
require
: select all those lines, and choose "Convert all require to import"
- Fix remaining TS errors (see below)
- Update inline
require('foobar')
toawait import('foobar')
or(await import('foobar')).default
- Put the caret inside param list of a function
- Press cmd-. -> "Infer parameter types from usage"
If you have import foobar from 'foobar'
npm package imports, with TS error TS7016 like Could not find a declaration file for module 'foobar'
, you can try to install the type definitions as follows:
yarn add @types/foobar
After installation, you may need to do cmd-shift-p
: TypeScript: Restart TS server
.
If you have the same errors as above (TS7016) for local files, you can try to generate .d.ts
file from the input .js
file
yarn tsc --allowJs --declaration --emitDeclarationOnly path/to/file.js
Edge cases
"Convert require to import" won't work for cases like this:
const glob = require('util').promisify(require('glob'));