1

I'm using node-config in TypeScript.
I have the code like below:
config/default.ts:

import {deferConfig} from 'config/defer';
export default {
  service: {
    url: 'http://localhost',
    errorUrl: deferConfig(function() {
      console.info('config before defer:', this);
      return `${this['service']['url']}/error.html`;
    }),
  },
};

src/demo.ts:

import config from 'config';
console.info('resulting config: ', config)

It works fine when I run my code with ts-node.

$ npx ts-node ./src/demo.ts
config before defer: { service: { url: 'http://localhost', errorUrl: [Getter] } }
resulting config:  Config {
  service: { url: 'http://localhost', errorUrl: 'http://localhost/error.html' }
}

However, if I run the code compiled with tsc, I get

$ NODE_CONFIG_DIR=./build/config ./build/src/demo.js
config before defer: {
  default: { service: { url: 'http://localhost', errorUrl: [Getter] } }
}
.../build/config/default.js:9
            return `${this['service']['url']}/error.html`;
                                     ^
TypeError: Cannot read property 'url' of undefined

The value of this has an extra level of default.
Why the behavior is inconsistent for the ts and the js code? If I change export default to export =, it works for both ts and js code.
However, the document of node-config asks me to use export default.
Should I use export = instead?

someone
  • 100
  • 2
  • 8
  • where did you print `this` from? – tromgy Sep 23 '21 at 12:55
  • @tromgy I printed `this` inside the defer function. I've updated the question. I hope it's clearer. :) – someone Sep 24 '21 at 01:53
  • The discrepancy between tsc and ts-node might be due to the "experimental" support for ESM modules in ts-node: https://github.com/TypeStrong/ts-node/issues/1007. But also anonymous default export is considered a bad practice: https://github.com/import-js/eslint-plugin-import/blob/v2.24.2/docs/rules/no-anonymous-default-export.md So you can also try something like `const my_config = { /* the object you want to export */ }; export default my_config;` Still, I find it very strange that you get an actual object _named_ "default" as your `this`. – tromgy Sep 24 '21 at 10:29
  • @tromgy Using named default export doesn't seem to change the result. But thank you for pointing out the best practice. – someone Sep 24 '21 at 19:00

0 Answers0