Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch over to Create React App on Existing Project?

I have an existing application that I am using "webpack-serve" as it was recommended to me by the developer(at that time he was not going to update webpack-dev-server anymore).

Anyways now it is deprecated and not being used, I got to back to webpack-dev-server but I am thinking if I should just go through the effort and try to use something like "Create React App" as I don't really know if I can use these old wepack.js files I made for webpack-serve and they also don't seem to work 100% as everytime I try to build a production build it gives me a dev build.

webpack.common.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const webpack = require('webpack');

module.exports = {
  entry: ["@babel/polyfill", "./src/index.js"],
  output: {
    // filename and path are required
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        // JSX and JS are all .js
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}  
          }
        ]
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(["dist"]),
    new HtmlWebpackPlugin({
      template: "./src/index.html"
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
   })
  ]
};

webpack.dev

const path = require("path");
const merge = require("webpack-merge");
const convert = require("koa-connect");
const proxy = require("http-proxy-middleware");
const historyApiFallback = require("koa2-connect-history-api-fallback");

const common = require("./webpack.common.js");

module.exports = merge(common, {
  // Provides process.env.NODE_ENV with value development.
  // Enables NamedChunksPlugin and NamedModulesPlugin.
  mode: "development",
  devtool: "inline-source-map",
  // configure `webpack-serve` options here
  serve: {
    // The path, or array of paths, from which static content will be served.
    // Default: process.cwd()
    // see https://github.com/webpack-contrib/webpack-serve#options
    content: path.resolve(__dirname, "dist"),
    add: (app, middleware, options) => {
      // SPA are usually served through index.html so when the user refresh from another
      // location say /about, the server will fail to GET anything from /about. We use
      // HTML5 History API to change the requested location to the index we specified
      app.use(historyApiFallback());
      app.use(
        convert(
          // Although we are using HTML History API to redirect any sub-directory requests to index.html,
          // the server is still requesting resources like JavaScript in relative paths,
          // for example http://localhost:8080/users/main.js, therefore we need proxy to
          // redirect all non-html sub-directory requests back to base path too
          proxy(
            // if pathname matches RegEx and is GET
            (pathname, req) => pathname.match("/.*/") && req.method === "GET",
            {
              // options.target, required
              target: "http://localhost:8080",
              pathRewrite: {
                "^/.*/": "/" // rewrite back to base path
              }
            }
          )
        )
      );
    }
  },
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        use: ["style-loader", "css-loader", "sass-loader"]
      }
    ]
  }
});

webpack.prod

const merge = require("webpack-merge");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const common = require("./webpack.common.js");

module.exports = merge(common, {
  // Provides process.env.NODE_ENV with value production.
  // Enables FlagDependencyUsagePlugin, FlagIncludedChunksPlugin,
  // ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin,
  // SideEffectsFlagPlugin and UglifyJsPlugin.
  mode: "production",
  devtool: "source-map",
  // see https://webpack.js.org/configuration/optimization/
  optimization: {
    // minimize default is true
    minimizer: [
      // Optimize/minimize CSS assets.
      // Solves extract-text-webpack-plugin CSS duplication problem
      // By default it uses cssnano but a custom CSS processor can be specified
      new OptimizeCSSAssetsPlugin({})
    ]
  },
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        // only use MiniCssExtractPlugin in production and without style-loader
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      }
    ]
  },
  plugins: [
    // Mini CSS Extract plugin extracts CSS into separate files.
    // It creates a CSS file per JS file which contains CSS.
    // It supports On-Demand-Loading of CSS and SourceMaps.
    // It requires webpack 4 to work.
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    }),
    new BundleAnalyzerPlugin()
  ]
});

Edit

If I where to go over to Create React App how would I handle this stuff?

I have a .babelrc with

  "presets": ["@babel/env", "@babel/react"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "@babel/plugin-transform-object-assign",
    "@babel/plugin-proposal-object-rest-spread",
    "transform-class-properties",
    "emotion"
  ]

I think react-app takes care of some of the stuff but not sure if all. I also have if you noticed in webpack.common I am pollying filling everything, would I just need "react-app-polyfill."?

How can I add another "dev mode"

  "scripts": {
    "dev": "cross-env NODE_ENV=dev webpack-serve --config webpack.dev.js --open",
    "prod": "cross-env NODE_ENV=prod  webpack -p --config webpack.prod.js",
    "qa": "cross-env NODE_ENV=QA webpack --config webpack.prod.js"
  },

I need to setup the Node_ENV for QA as I have a check to point to my api that changes in each enviroment.

like image 354
chobo2 Avatar asked May 23 '19 19:05

chobo2


3 Answers

it's a simple as below today:

npx create-react-app .
like image 153
armnov Avatar answered Nov 09 '22 04:11

armnov


I've had to do something like this a couple times. This has been my approach:

  1. create-react-app my-app-cra // clean slate
  2. npm i [list of dependencies] // minus any build, compile, transpile, etc. dependencies
  3. Copy over my src folder, preserving as much of the structure as possible
  4. npm start // and keep fingers crossed! Typically, a bit of manual work is involved

To preserve your git history:

  1. Copy your src to a folder outside your repo
  2. Clean your repo git rm -rf
  3. Perform the above steps (create react app, install deps, copy src back in)
  4. git add // If you preserve your folder structure, git will find the copied over files (and will notice a possible change in path) and handles gracefully, preserving history.
like image 23
Arash Motamedi Avatar answered Nov 09 '22 04:11

Arash Motamedi


Both create-react-app and webpack 4 are good options and very simple. In my opinion, create-react-app is the most practical.

In order to conserve your git history, I recomend:

  1. create a branch and go to it.
  2. install and save the dependencies and dev-dependencies of create-react-app. you will see them in your package.json file.
  3. do the configuration. use the create-react-app repo as an example.
  4. if it works fine, return to your master branch and merge this branch with the migration.
  5. Execute npm i in order to install the dependencies you added from your branch.
like image 26
Nico Diz Avatar answered Nov 09 '22 06:11

Nico Diz