I'm trying to convert an existing JavaScript codebase to TypeScript one file at a time. Hitting a problem with the imports.
Converting:
// JavaScript
const AWS = require("aws-sdk");
to:
// TypeScript
import AWS = require("aws-sdk");
works as the AWS SDK is installed in node_modules. When I try to import one of my own modules, converting:
// This works, but is it "correct"? Path here is relative to compiled .js file
const C = require('../utils/constants');
to:
import C = require('../utils/constants');
it fails with Cannot find module '../utils/constants'.ts(2307).
For context, here are the paths of the concerned files (all paths relative to project root):
- Module file I am trying to use:
utils/constants.js - Original
.jsfile:utils/sesUtil.js - Equivalent
.tsfile:src/utils/sesUtil.ts(this is the one we're discussing here) - Compiled
.jsfile:dist/sesUtil.js
Leads me to some questions:
- What is the correct way to import my own (CommonJS) JavaScript modules?
- Should the path be relative to where the
.tsfile exists (src/utils/ses.ts) or relative to where the compiled.jsfile will go (dist/ses.js)?
Here's my tsconfig.json file:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
}
},
"include": [
"src/**/*"
]
}
require. Useimport * as C from ''orimport C from ''. Also, make sure to setrootDirandoutDirlike "mirroring". YouroutDirstructure will be mirroring yourrootDirstructure.