Skip to content

Latest commit

 

History

History
139 lines (104 loc) · 2.65 KB

ReactFundamentals.MD

File metadata and controls

139 lines (104 loc) · 2.65 KB

React Fundamentals

Create empty direcory and yarn init hitting enter until prompt ends then add react

yarn add react react-dom

Create src/index.js

In index.js import React and ReactDOM from react and react-dom respectively. (Expose react global and react dom global)

Create a component and reactDOM.render it to document.getElementById('app')

import React from 'react'
import ReactDOM from 'react-dom'

const App = () => <div>hello</div>

ReactDOM.render(<App />, document.getElementById('app'))

Configure babel

Install babel-loader and @babel/core for transpiling JS files

Install @babel/preset-react for the purpose of transforming JSX to react

<div> // React.createElement('div')

Also install @babel/preset-env which will let us use the latest JS

yarn add --dev babel-loader @babel/core @babel/preset-react @babel/preset-env

Create the .babelrc and add

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

Configure webpack

Add webpack for bundling our assets

yarn add --dev webpack webpack-dev-server webpack-cli

Create a file called webpack.config.js and populate it after docs

HTML file

Add src/index.html with a div with id="app" something like:

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="utf-8">
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
yarn add html-webpack-plugin --dev

and add it to module.exports in webpack config:

const HtmlWebpackPlugin = require('html-webpack-plugin')
...
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
yarn webpack-dev-server --open

What about styling?

yarn add --dev css-loader style-loader

These will handle importing css files into react component files. However, check out css-modules for locally scoping CSS.

Make a .gitignore

node_modules, dist

React .gitignore

Sample webpack config

(February 2020)

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
  ]
}