ericclemmons/grunt-react

How require component with .jsx extension?

kulakowka opened this issue · 5 comments

I had a problem.

When I try require a component without extension:

var Item = require('./Item');

In the console throws out an error:

Error: Cannot find module './Item' from '/Users/kulakowka/Documents/node.js/geekhub/assets/jsx'

But if I try to require a component with extension:

var Item = require('./Item.jsx');

It works!

Task configuration looks like this:

grunt.config.set('browserify', {
    options:      {
      transform:  [ require('grunt-react').browserify ]
    },
    dev:          {
      src:        'assets/jsx/app.jsx',
      dest:       '.tmp/public/js/app.js'
    }
  });
  grunt.loadNpmTasks('grunt-browserify');

I tried to add the extension option:

grunt.config.set('browserify', {
    options:      {
      transform:  [ require('grunt-react').browserify ],
      extension: 'jsx'
    },
    dev:          {
      src:        'assets/jsx/app.jsx',
      dest:       '.tmp/public/js/app.js'
    }
  });
  grunt.loadNpmTasks('grunt-browserify');

But it did not help.

I would use .jsx extension for files with components. But I am sure that indicate the file extension in the require () is not required. Maybe it's a bug?

Hi,

I am having the same issue, did you manage to fix it?

Thanks.

Unfortunately not. I use the extension .js

My best guess is that files are resolved the same way Node does it. Which means require('./Item') tries to find 'Item', 'Item.js', 'Item.json', and 'Item.node'.

More info here: http://nodejs.org/api/modules.html#modules_all_together

Any way of fixing this? I have the same issue.

Hmm, this is odd, seeing how I have a test for this:

grunt-react/Gruntfile.js

Lines 26 to 35 in eb333da

// Used for testing the transformer
browserify: {
options: {
transform: [ require('./main').browserify ]
},
module: {
src: 'test/fixtures/browserify/module.jsx',
dest: 'tmp/browserify/module.js'
}
},

There was just a patch, but I dunno if it helps your case.

The fact is, as @mauvm linked, require doesn't know to look for .jsx, so you'll need to use that: require('./Item.jsx')

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

Personally, I used to use jsx extensions, but once I switched to Babel, since everything is transpiled, I called it all .js and moved on :)