1

I have a module in TypeScript that look as follows:

import { CallerId, CallScreening, CustomTagRef, MediaRef, OutboundSettings, ServiceCommon } 
from '../src/shared/domain/dto';
import { ServiceCommonEntity } from '../src/shared/domain/entity';
import { CallerIdMode, ResourceRefType } from '../src/shared/domain/enum';

export const CONTACT_PAYLOAD = 'payload';

export const ACCOUNT_PAYLOAD = 'a_payload';

export function getFakeAccountPayload() {
  return fake_payload;
}

In the same project I have a js file in which I want to use functions from my .ts file.

How can I import my ts module to my js file?

3
  • 1
    Any reason you're not using a .ts file for importing a .ts file? Commented Oct 23, 2019 at 8:22
  • I'm using the Dredd framework, it doesn't support typescript yet Commented Oct 23, 2019 at 8:26
  • 1
    Possible duplicate of Import Typescript file in Javascript Commented Oct 23, 2019 at 8:29

1 Answer 1

0

Sometimes we face such situation in our projects. I am pretty sure that you are migrating some part of your code to typescript and somewhere in your project you need typescript in javascript file and creating javascript file for same ts file is not way to solve the problem, but If you really want to use typescript(.ts) in javascript(.js) files, so here is the one possible solution, I am assuming that your are suing webpack bundler, so you use ts-loader and babel-loader in your webpack. here are rule for your webpack configuration(Note: you must have airbnb preset, ts-loader, and all plugins installed)

{
rules: [
  {
    test: /\.tsx?$/,
    use: 'ts-loader',
    exclude: /node_modules/,
  },
  {
    test: /\.jsx?/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['airbnb'],
        plugins: ['@babel/plugin-transform-modules-commonjs', '@babel/transform-async-to-generator', 'source-map-support', 'babel-plugin-root-import'],
        ignore: ['node_modules/is_js'],
      },
    },
    exclude: /node_modules\/(?query-string|strict-uri-encode)/,
  }
]
}

In case of running spec, if you are using jest you might also need .babelrc configuration for tests

{
  "presets": [
    "airbnb",
    "@babel/preset-typescript"
  ],
  "env": {
    "development": {
      "sourceMaps": true,
      "plugins": ["source-map-support"]
    }
  },
  "plugins": ["@babel/plugin-transform-modules-commonjs", "@babel/plugin-proposal-class-properties", "@babel/transform-async-to-generator", "babel-plugin-root-import"],
  "ignore": ["node_modules/is_js"]
}

We also have one article which might be helpful. Use .ts File .js file

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.