skip to Main Content

I’ve built reactJS projects before, but this time I just need to be able to run a command from the command line so I thought I’d use node for the task. However I’m stuck on importing functions from other files.

I have got this in my main.ts:

import testFunction from './testFunction.js'

async function main() {
    console.log('Node Start Project')
    console.log(testFunction('bobby'))
}

(async () => {
    await main()
})();

And in my package.json:

{
  "name": "testnode",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "main": "node main.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^5.0.4"
  },
  "dependencies": {
    "clarifai-nodejs-grpc": "^8.0.0",
    "dotenv": "^16.0.3",
    "sjcl": "^1.0.8"
  }
}

and in my tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "lib": ["es2015"]
}

I want to be able to use Typescript. The testFunction file contains as follows:


    export default function testFunction(name: string): string {
        return 'Hello ' + name
    }

But the error I keep getting is:

(node:12492) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/bridgeman/Projects/testnode/main.ts:3
import testFunction from './testFunction.js'

Things I have tried:

  • Adding "type":"module" to my package.json file
  • Renaming main.ts to main.mjs
  • Renaming testfunction.ts to testfunction.mjs
  • Using require instead of import: const testFunction = require('./testfunction.ts') (This works, but I can’t use typescript in my function then, I get the error SyntaxError: Unexpected token ':' in the function params)

Please help, I just want to import the function and get on with my project.

2

Answers


  1. First: npm install ts-node -D.

    Then: replace "main": "node main.ts" with "main": "ts-node main.ts" in package.json.

    Login or Signup to reply.
  2. You need to run tsc and change the file Node runs to dist/main.js. This is because the ourDir is configured in your TypeScript config. Node can’t run TypeScript without it being compiled.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search