I am trying to import a typescript file (src/index.ts
) in a javascript file(tests/steps/utils.js
)
But when I use const index_1 = require("../../src/index");
in my javascript file, it gives an error: Cannot find module '../../src/index'
But the file is right there. Is there any other way to import a typescript file into a javascript file?
I am trying to import a typescript file (src/index.ts
) in a javascript file(tests/steps/utils.js
)
But when I use const index_1 = require("../../src/index");
in my javascript file, it gives an error: Cannot find module '../../src/index'
But the file is right there. Is there any other way to import a typescript file into a javascript file?
Share Improve this question asked Sep 22, 2022 at 8:44 Salman ArefinSalman Arefin 3731 gold badge3 silver badges12 bronze badges 5 |4 Answers
Reset to default 6You can't. You need to compile the typescript files into js first. However, you can import the built typescript file i.e. js file from its build directory.
Updated May 2023: Just found this library: ts-import, it seems can import TS into JS project already.
You can't import a ts into js file.
If you really need the module in .ts file, try to import from dist folder, where the ts compiler output path, or refactor into javascript.
Full disclaimer: I'm the author of the proposed solution below
You can use import-single-ts
which is a drop-in replacement for the JS
-native import(..)
but it also works for TypeScript
by compiling it on-the-fly.
So instead of doing await import('./some.js')
you just do await importSingleTs('./some.ts')
. No config or extra compilation step necessary.
It's super tiny & very fast since it uses esbuild
and not tsc
or babel
which the other solutions offer.
Full example:
import { importSingleTs } from 'import-single-ts';
// or for cjs: const { importSingleTs } = require('import-single-ts');
// ...
await importSingleTs('./some.ts'); // place where you need it
Looks like you need babel and webpack. These tools allow js
and ts
to be used together in both development and build.
.babelrc
file (pay attention to @babel/preset-typescript
):
{
"presets": [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-transform-runtime"
]
}
and add something like this to webpack.config.js
(pay attention to ts
in rules/babel-loader
):
module: {
rules: [
{
test: /\.(js|ts|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
}
require()
is looking for .js file, not .ts. You should transpile typescript code to javascript if you really need to do this import. – Edmunds Folkmanis Commented Sep 22, 2022 at 9:02