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).

Sign up to request clarification or add additional context in comments.

3 Comments

(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.)
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?
@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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.