0

I have the typescript file file1.ts

export function Hello(str: string) {
    console.log(str);
}

I have file index.js

{
   require('./some.js'); 
}

and script in package.json

"run": "node index.js"

How can I run the function from ts file in index.js

Nikita
  • 1,019
  • 2
  • 15
  • 39

2 Answers2

2

If you want to import a ts or es file inside a js file to execute it using node, you need to be able to transpile the imported files to javascript on fly. You can use babel-register plugin to achieve this.

You will have to include babel-register in the index.js like this

require('babel-register')({
    plugins: [/* List of plugins */],
    cache: process.env.NODE_ENV !== 'development'
});

If you use babel.rc, you dont need to include the plugins here. You can use @babel/preset-typescript plugin to transpile ts to js.

Edit:

You can import any exported values from a ts file, just like you would import from any other file.

var Hello = require('file1.js')
AvcS
  • 2,263
  • 11
  • 18
  • your answer also gives me another idea, that ok for me now: add ts-node to packages `yarn add ts-node`, update `packages.json` with `"run": "ts-node index.js"`, import function in this way `const hello = require('./tsgen/codeGenerator').Hello; hello('test');`. It is working - minimum work. ` – Nikita Oct 18 '19 at 12:58
0

Dynamic imports let the script load other scripts as needed:

<script type="module">
  import('hello.mjs').then(module => {
  module.hello('world');
});
</script>

Refer to this

Include a JavaScript file in another JavaScript file

sibabrat swain
  • 1,277
  • 8
  • 20
  • I don't think that's the question - the OP is asking how to run a TypeScript file within a JavaScript file; that's more than just `import` because the TS needs to be compiled first – Kousha Oct 18 '19 at 08:18