1

not sure if its a problem in node-cron or in the way that tsc translate the code.

The thing is, when you try to export a ts file using node-cron, TSC converts:

import express = require('express');
import cron from 'node-cron'

const app = express();

cron.schedule('* * * * *', () => {
  console.log('Running a task every minute');
});

app.listen(3123);

Into this:

"use strict";
exports.__esModule = true;
var express = require("express");
var node_cron_1 = require("node-cron");
var app = express();
node_cron_1["default"].schedule('* * * * *', function () {
    console.log('Running a task every minute');
});
app.listen(3123);

Throwing the next error when you try to execute the code:

/home/xxx/cronjobs/index.js:7 node_cron_1["default"].schedule('* * * * *', function () { ^ TypeError: Cannot read property 'schedule' of undefined at Object. (/home/xxx/cronjobs/index.js:7:24)

If you delete ["default"], its works perfect. Any ideas why is this happening?

PD: ts-node execute it without problems.

Neoligero
  • 37
  • 1
  • 4
  • When you write `import cron from 'node-cron'`, you are importing the default export of `node-cron`. _Either_ set TypeScript's `"esModuleInterop": true` and change `import express = require('express');` to `import express from 'express';` for consistency _or_ change `import cron from 'node-cron';` to `import cron = require('node-cron');` – Aluan Haddad Aug 10 '20 at 21:52

0 Answers0