Skip to content

Instantly share code, notes, and snippets.

@sle-c
Last active April 24, 2019 04:44
Show Gist options
  • Save sle-c/157f07bfcbdd3186bfc60def83478a9d to your computer and use it in GitHub Desktop.
Save sle-c/157f07bfcbdd3186bfc60def83478a9d to your computer and use it in GitHub Desktop.
Create react app with webpack 4

Webpack config

Init project

mkdir project-folder
cd project-folder
npm init

Install webpack

npm i -D webpack webpack-cli

Install Babel

npm i -D babel-core babel-loader babel-preset-react

.babelrc file

{ 
  "presets": [
    "react"
  ]
}

package.json scripts

"scripts": {
  "dev": "webpack --mode development",
  "build": "webpack --mode production"
}

watch mode

"scripts": {
  "dev": "webpack --mode development --watch",
  "build": "webpack --mode production --watch"
}

CSS and Sass

npm i -D css-loader style-loader node-sass sass-loader

Post CSS

npm i -D postcss-loader autoprefixer

webpack dev server

npm i -D webpack-dev-server

html-webpack plugin

npm i -D html-webpack-plugin

mini-css-extract plugin

npm i -D mini-css-extract-plugin

webpack.config

const path = require('path');
const autoprefixer = require('autoprefixer');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html"
});

const miniCssPlugin = new MiniCssExtractPlugin({
  // chunk version for cache refresh
  // filename: 'style.[contentHash].css',
  filename: 'style.css',
});

module.exports = {
  entry: { main: './src/index.js' },
  output: {
    path: path.resolve(__dirname, 'dist'),
    // hashing for cache refresh
    // filename: 'main.[chunkHash].js',
    filename: 'main.js',
    publicPath: '/'
  },
  devServer: {
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.scss$/,
        use:  [
          'style-loader', 
          MiniCssExtractPlugin.loader, 
          'css-loader', 
          'sass-loader'
        ]
      }
    ]
  },
  plugins: [ 
    htmlPlugin,
    miniCssPlugin
  ]
};

Webpack dev server scripts

webpack-dev-server --mode development --open

React

npm i react react-dom
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment