Reputation: 6695
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?
Upvotes: 11
Views: 19836
Reputation: 145
Webpack 5 Update:
I attempted rrd answer above and ran into an error trying to install uglifyjs-webpack-plugin
as I am using Webpack 5 which appears to not work past Webpack 4 and instead to use the terser-webpack-plugin
which comes with Webpack 5. Below is the modified webpack.config.js
to make this work with Webpack 5.
webpack.config.js
const path = require("path")
const TerserPlugin = require("terser-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"],
},
],
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
}
modified build scripts in package.json
"build": "npm run build:react && npm run build:bundle",
"build:react": "react-scripts build",
"build:bundle": "webpack --config webpack.config.js",
devDependencies in package.json
"devDependencies": {
"css-loader": "^6.7.1",
"glob": "^8.0.3",
"path": "^0.12.7",
"style-loader": "^3.3.1",
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2"
}
Upvotes: 1
Reputation: 5977
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",
Upvotes: 9
Reputation: 106
Try webpack to customise build, minimize and lot more features are available
Please fallow this link https://www.npmjs.com/package/webpack, docs: https://webpack.js.org/concepts/
Upvotes: 0