Why is node.js unable to locate other typescript React components

253 Views Asked by At

I'm rewriting some react server-side rendering files with typescript, and I just ran into a problem of finding my custom components.

Path structure:

node_modules/
src/
    page/Homepage.tsx
    component/Layout.tsx
    utility/
typings/

When node.js parses Homepage.tsx, it can locate all modules under node_modules like react and memobind, however, it fails to locate my component Layout. My IDE phpstorm has no problem identifying my component location but when I visit the page it gives:

 Error: Cannot find module '../component/Layout'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/base/node/src/page/Homepage.tsx:5:1)
    at Module._compile (module.js:571:32)
    at loader (/home/base/node/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/home/base/node/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at /home/base/node/socket.js:90:25
    at Layer.handle [as handle_request] (/home/base/node/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/base/node/node_modules/express/lib/router/route.js:131:13)

Homepage.tsx:

import * as React from "react";
import memobind from 'memobind'
import {Layout} from '../component/Layout'

class Homepage extends React.Component<{},{}>{

    render(){

        return <Layout><h4>Hello!!!</h4></Layout>
    }

}

module.exports = Homepage;

Layout.tsx:

import * as React from "react";

export class Layout extends React.Component<{},{}>{

    render(){

        return <div class="header">{this.props.children}</div>
    }

}

When I remove component Layout from the script everything works fine.

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "moduleResolution": "node",
    "baseUrl": "src",
    "removeComments": true,
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": false,
    "sourceMap": true,
    "jsx": "react",
    "experimentalDecorators": true,
    "noLib": false,
    "declaration": false
  },
  "exclude": [
    "node_modules"
  ]
}
1

There are 1 best solutions below

0
On

my guess is:

Layout.tsx is not compiling, because you the use of 'class' instead of 'className'.

hence ...there isn't a generated Layout.js, (or the related code in the bundled output) ...

then ...

at Function.Module._resolveFilename (module.js:470:15)

based on the fact that you said it doesn't work,... only when you try to use "layout.tsx". assuming you don't have 'visible' compile errors . assuming too many things....