How to do it...

Here are the steps to add React to Webpack 4:

  1. Using the same code of the last recipe, create a .babelrc file and add some presets:
  {
"presets": [
"env",
"react"
]
}
File: .babelrc

  1. In our webpack.config.js file, where we have our babel-loader, we need to add the .jsx extension beside the .js extension to be able to apply babel-loader to our React components:
  const webpackConfig = {
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};

module.exports = webpackConfig;
File: webpack.config.js
  1. After we added the .jsx extension to our babel-loader, we need to create the src/components/App.jsx file:
  // Dependencies
import React from 'react';

// Components
import Home from './Home';

const App = props => (
<div>
<Home />
</div>
);

export default App;
File: src/components/App.jsx

  1. Creating the Home component:
  import React from 'react';

const Home = () => <h1>Home</h1>;

export default Home;
File: src/components/Home/index.jsx
  1. In our main index.js file, we need to include react, the render method from react-dom and our App component, and render the application:
  // Dependencies
import React from 'react';
import { render } from 'react-dom';

// Components
import App from './components/App';

render(<App />, document.querySelector('#root'));
File: src/index.jsx
  1. You may wonder where the #root div is since we have not created index.html yet. In this specific recipe, we are going to use the html-webpack-plugin plugin to process our HTML:
    npm install --save-dev html-webpack-plugin
  1. Open your webpack.config.js file. We need to add our html-webpack-plugin and create a plugins node in our config file:
  const HtmlWebPackPlugin = require('html-webpack-plugin');

const webpackConfig = {
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
},
plugins: [
new HtmlWebPackPlugin({
title: 'Codejobs',
template: './src/index.html',
filename: './index.html'
})
]
};

module.exports = webpackConfig;
File: webpack.config.js
  1. Create the index.html template at your src directory level:
  <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
File: src/index.html

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset