Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack can't find module if file named jsx

Webpack doesn't know to resolve .jsx files implicitly. You can specify a file extension in your app (import App from './containers/App.jsx';). Your current loader test says to use the babel loader when you explicitly import a file with the jsx extension.

or, you can include .jsx in the extensions that webpack should resolve without explicit declaration:

module.exports = {
  entry: './index.jsx',
  output: {
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['es2015', 'react']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
  }
};

For Webpack 2, leave off the empty extension.

resolve: {
  extensions: ['.js', '.jsx']
}

In the interest of readability and copy-paste coding. Here is the webpack 4 answer from mr rogers comment in this thread.

module: {
  rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      resolve: {
        extensions: [".js", ".jsx"]
      },
      use: {
        loader: "babel-loader"
      }
    },
  ]
}

Adding to the above answer,

The resolve property is where you have to add all the file types you are using in your application.

Suppose you want to use .jsx or .es6 files; you can happily include them here and webpack will resolve them:

resolve: {
  extensions: ["", ".js", ".jsx", ".es6"]
}

If you add the extensions in the resolve property, you can remove them from the import statement:

import Hello from './hello'; // Extensions removed
import World from './world';

Other scenarios like if you want coffee script to be detected you should configure your test property as well like:

// webpack.config.js
module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'       
  },
  module: {
    loaders: [
      { test: /\.coffee$/, loader: 'coffee-loader' },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
  resolve: {
    // you can now require('file') instead of require('file.coffee')
    extensions: ['', '.js', '.json', '.coffee'] 
  }
};

As mentioned in the comments on the answer from @max, for webpack 4, I found that I needed to put this in one of the rules that were listed under module, like so:

{
  module: {
    rules: [ 
      {
        test: /\.jsx?$/, 
        resolve: {
          extensions: [".js", ".jsx"]
        },
        include: ...
      }
    ]
  }
}

Verify, that bundle.js is being generated without errors (check the Task Runner Log).

I was getting 'can't find module if file named jsx' due to the syntax error in html in component render function.