Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create-react-app - How to bundle JS files

Tags:

reactjs

I created a React app using create-react-app. If I run npm run build, create-react-app generates 3 different JS files inside the build/static/js folder.

But for the purpose of this specific app, I need to bundle all those 3 JS files in a single file.

Is it something, which I can achieve with create-react-app? If not what would be the best way to bundle those 3 JS files to a single file?

like image 245
user1941537 Avatar asked Oct 31 '19 09:10

user1941537


People also ask

What does create React app use for bundling?

Bundling. Most React apps will have their files “bundled” using tools like Webpack, Rollup or Browserify. Bundling is the process of following imported files and merging them into a single file: a “bundle”. This bundle can then be included on a webpage to load an entire app at once.

Where is bundle JS in React?

bundle. js file inside the dist folder. Next, specify a module object inside the config to select the file extension that babel should transpile.


1 Answers

You can build your own webpack.config.js at the root of your project, something like this:

const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const glob = require('glob');

module.exports = {
  entry: {
    "bundle.js": glob.sync("build/static/?(js|css)/main.*.?(js|css)").map(f => path.resolve(__dirname, f)),
  },
  output: {
    filename: "build/static/js/bundle.min.js",
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  plugins: [new UglifyJsPlugin()],
}

Then you can adapt the script to build in the package.json:

"build": "npm run build:react && npm run build:bundle",
"build:bundle": "webpack --config webpack.config.js",
like image 159
rrd Avatar answered Sep 20 '22 00:09

rrd