简体   繁体   中英

How come I can't find a module in nodejs?

So I'm working off of https://github.com/mhart/react-server-example/blob/master/server.js to figure out server side rendering in React. It takes advantage of browserify.

The example is a flat folder structure cause it's just that, an example. So below here are some of my changes that are confusing me.

/server/controllers/bundles.jsx has this

browserify()
  .add('./app/scripts/checkout.jsx')
  .transform(literalify.configure({
    'react': 'window.React',
    'react-dom': 'window.ReactDOM',
  }))
  .bundle()
  .pipe(res)

At this point I gather that even though I'm nested in a folder, browserify is working off of root. Meanwhile inside checkout.jsx I have this:

require('./app/scripts/components/checkout/layout');

When I boot up my server, it can't find the file. I also tried doing ./components/checkout/layout since that's where it's sitting in relation to checkout.jsx .

No matter what I try, my server says it can't find the layout module.

Update I added console.log for __dirname and saw /app/scripts so it makes me think require('components/checkout/layout') should hit /app/scripts/components/checkout/layout but it's still not found. I should also note that the file does do module.exports = Layout and is being required just fine in another file while being used on the server.

You need to add the file extension ( .jsx ).

Basically, require in node has a bunch of rules it goes through, all outlined in the docs here .

In your case, the most relevant is this part:

require(X) from module at path Y
1. If X is a core module,
   a. return the core module
   b. STOP
2. If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"

LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text.  STOP
2. If X.js is a file, load X.js as JavaScript text.  STOP
3. If X.json is a file, parse X.json to a JavaScript Object.  STOP
4. If X.node is a file, load X.node as binary addon.  STOP

You're hitting #2, and then going to the LOAD_AS_FILE , and there's no case for jsx files by default there, so you need the extension to make it match #1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM