1

I have a config.ts and I do

module.exports = { something: 123 }

when I import like import { something } from './config.ts' I got error of config.ts' is not a module, what's the issue? my typescript is configured rightly and it's working in other places.

1 Answer 1

3

If you're using import { something } from './config.ts', you're using JavaScript modules, but your code in config.ts is using CommonJS modules. Some bundlers and such may let you mix them, but it's best not to.

To make config.ts a JavaScript module compatible with that import declaration (which expects a named export called something), change it to:

export const something = 123;

Or, of course, to use config.ts via CommonJS, your code using it would be:

const { something } = require("./config.ts");

...but given the error you're getting, I think your project is set up to use JavaScript modules (import/export), which here in almost 2021 is probably best (now that we have dynamic import to handle the cases where static modules don't quite do the job).

3
  • (FWIW, I go into JavaScript modules, including dynamic import and a bit about the contrast with CommonJS, in Chapter 13 of my new[ish] book, JavaScript: The New Toys about the new features in ES2015-ES2020 [plus a bit]. Links in my profile if you're interested.) Commented Dec 1, 2020 at 8:48
  • I'm able to import package using import moment from 'moment', I don't have to use require as I use typescript I guess? or I should use another type of exports? Commented Dec 1, 2020 at 8:53
  • @NadielyJade - Right, you don't need to use require. You're using JavaScript modules. What you need to do is make config.ts a JavaScript module, as shown above. (No, there's no need to use a different type of module. You could, but IMHO there's no good reason to now that ESM [JavaScript module syntax] is so well supported in TypeScript and across various other tools.) Commented Dec 1, 2020 at 8:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.