0

Cannot read property 'json' of undefined

at Object. (C:\web\learnTypescript\dist\index.js:7:40)

dist/index.js:7

app_1.default.use(body_parser_1.default.json());

I created a simple project to learn TypeScript. I have my dependencies and their @types counterparts installed but I continue to get the above error when I try to start node node dist/index.js.

tsconfig.json

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "moduleResolution": "node",
        "module": "commonjs",
        "target": "es6",
        "outDir": "dist"
    },
    "include": [ "src/**/*" ],
    "exclude": [ "node_modules" ]
}

src/index.ts

import app from './app'
import bodyParser from 'body-parser'
/* more imports */

app.use(bodyParser.json());
/* more code follows */

dist/index.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const app_1 = require("./app");
const body_parser_1 = require("body-parser");
/* more requires */
app_1.default.use(body_parser_1.default.json());
/* more code follows */
2
  • What if you change this to import * as bodyParser from 'body-parser';? Commented Oct 31, 2017 at 11:06
  • That did it. Please add that as the answer and I'll give you credit. I some question around why I need to import that way, but I'll save that for your answer for documentation purposes. Thank you. Commented Oct 31, 2017 at 11:16

1 Answer 1

1

If you change your import to be;

import * as bodyParser from 'body-parser';

Then that should fix it.

* as syntax is known as a namespace import, and effectively creates 1 variable which contains everything within the file.

There are a few ways you can import from a file depending on the exports from the other file.

file1.ts

export default class Foo {
}

export class Bar {
}

const a = 'Hello';

export { a as A }

file2.ts

import A from 'file1'; // A is now the default export from file1
import * as File from 'file1'; // File is now a constant with Foo, Bar and A
import { Bar } from 'file1'; // Importing only Bar from file1

As James has also mentioned, you can also use the code; import { json } from 'body-parser';

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

1 Comment

Seems unnecessary, should tree shake and do import { json } from 'body-parser'

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.