aarkerio
aarkerio

Reputation: 2354

Webpack 4 as JSX files

Is there a way to load JSX files on Webpack 4?

I tried:

module.exports = {
    resolve: {
        extensions: [".jsx", ".js"]
    }
}                              

But apparently my src/index.jsx file is loaded but not processed.

Upvotes: 3

Views: 1763

Answers (2)

Yilmaz
Yilmaz

Reputation: 49321

you need to install

 npm i @babel/preset-react --save

add this to .babelrc file inside presets array. We use loaders inside module property of the webpack.config object because loaders are effective on one type of files whereas plugins are effective on the entire bundle.

.babelrc

{
  "presets": [
    ["@babel/preset-env", { "targets": { "esmodules": true } }],
    "@babel/preset-react"
  ],

all webpack projects needs @babel/preset-env. you might install that as well. }

Upvotes: 1

SNyamathi
SNyamathi

Reputation: 776

What you have here is half of it. resolve.extensions lets you

require('./my-module.jsx')

without having to type in the .jsx portion. ie

require('./my-module')

However, as you noted - the source is not processed in any way so if you have syntax that needs to be transpiled such as jsx, you'll need to take care of that.

Webpack by default won't do this for you, you'll need to use babel-loader with a preset or plugin that will transform the syntax. There's a lot of tutorials how to do that but it would look something like this:

module: {
    rules: [{
        exclude: /node_modules/, // don't transpile node_modules
        test: /\.jsx$/,          // do transpile any files ending in .jsx
        use: {
            loader: 'babel-loader',
            options: {
                plugins: ['@babel/plugin-transform-react-jsx']
            }
        }
    }]
}

Upvotes: 5

Related Questions