ts-node seems can not require json file

Created on 30 Oct 2017  路  8Comments  路  Source: TypeStrong/ts-node

one of my config module like this

export interface ConfigSetting {
// some code 
}
export const config : ConfigSetting  = require('./config.json')

tsc compiles well.

when i use ts-node, it has some error like

let db = new Sequelize(config.database)
                             ^
TypeError: Cannot read property 'database' of undefined

Most helpful comment

I fixed my demo by adding "resolveJsonModule": true, to tsconfig.json, see: https://github.com/freewind-demos/ts-node-import-json-file-issue-demo/commit/0f9e472a462425d4324b1f911f6781de7dd20cb7

PS: resolveJsonModule is supported by typescript 2.9+ only, so old versions still have such issue

All 8 comments

A type error is an actual JavaScript error at runtime. It's nothing to do with ts-node. Just because you tell the compiler something is true, doesn't mean it actually is at runtime. That error is because config is undefined during runtime. If you'd like more help, you'll need to share a reproduction.

@blakeembrey i just create a test repo to reproduct what i say.

https://github.com/notedit/test-ts-node

i am new to ts, maybe i made a silly mistake.

ts-node  server.ts   will have an error,  

tsc  &&  node server.js  works fine 

@blakeembrey can you have a look?

This is (unfortunately) expected. You've named your .ts and .json file the same, .json has higher precedence than .ts. .js has higher precedence than .json.

@blakeembrey Please see my demo of this issue: https://github.com/freewind-demos/ts-node-import-json-file-issue-demo, I don't name .ts and .json file the same name, but there is the same error

I fixed my demo by adding "resolveJsonModule": true, to tsconfig.json, see: https://github.com/freewind-demos/ts-node-import-json-file-issue-demo/commit/0f9e472a462425d4324b1f911f6781de7dd20cb7

PS: resolveJsonModule is supported by typescript 2.9+ only, so old versions still have such issue

@freewind thanks it worked for me

Was this page helpful?
0 / 5 - 0 ratings