score:45
after observing number of viewers to this question i decided to conclude an answer from vikramaditya and sandeep.
to build the production code the first thing you have to create is production configuration with optimization packages like,
new webpack.optimize.commonschunkplugin('common.js'),
new webpack.optimize.dedupeplugin(),
new webpack.optimize.uglifyjsplugin(),
new webpack.optimize.aggressivemergingplugin()
then in the package.json file you can configure the build procedure with this production configuration
"scripts": {
"build": "node_env=production webpack --config ./webpack.production.config.js"
},
now you have to run the following command to initiate the build
npm run build
as per my production build configuration webpack will build the source to ./dist
directory.
now your ui code will be available in ./dist/
directory. configure your server to serve these files as static assets. done!
score:0
latest answer including webpack 5
for webpack (version not remember)
node_env=production webpack --config ./webpack.production.config.js
for webpack <4
plugins: [
new webpack.defineplugin({
'process.env':{
'node_env': json.stringify('production')
//for development -> json.stringify('development')
}
})
]
for webpack >=4 (including webpack 5) - specify mode
module.exports = {
mode: 'production', //for development -> development
devtool: 'inline-source-map',
...
};
quote from webpack's official website
since webpack v4, specifying mode automatically configures defineplugin for you
score:3
if you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isprod
to activate certain features only in certain situations and only have a single webpack.config.js file.
const isprod = (process.env.node_env === 'production');
if (isprod) {
plugins.push(new aotplugin({
"mainpath": "main.ts",
"hostreplacementpaths": {
"environments/index.ts": "environments/index.prod.ts"
},
"exclude": [],
"tsconfigpath": "src/tsconfig.app.json"
}));
plugins.push(new uglifyjsplugin({
"mangle": {
"screw_ie8": true
},
"compress": {
"screw_ie8": true,
"warnings": false
},
"sourcemap": false
}));
}
by the way: the dedupeplugin plugin was removed from webpack. you should remove it from your configuration.
update:
in addition to my previous answer:
if you want to hide your code for release, try enclosejs.com. it allows you to:
- make a release version of your application without sources
- create a self-extracting archive or installer
- make a closed source gui application
- put your assets inside the executable
you can install it with npm install -g enclose
score:5
in addition to gilson pj answer:
new webpack.optimize.commonschunkplugin('common.js'),
new webpack.optimize.dedupeplugin(),
new webpack.optimize.uglifyjsplugin(),
new webpack.optimize.aggressivemergingplugin()
with
"scripts": {
"build": "node_env=production webpack -p --config ./webpack.production.config.js"
},
cause that the it tries to uglify your code twice. see https://webpack.github.io/docs/cli.html#production-shortcut-p for more information.
you can fix this by removing the uglifyjsplugin from plugins-array or add the occurrenceorderplugin and remove the "-p"-flag. so one possible solution would be
new webpack.optimize.commonschunkplugin('common.js'),
new webpack.optimize.dedupeplugin(),
new webpack.optimize.uglifyjsplugin(),
new webpack.optimize.occurrenceorderplugin(),
new webpack.optimize.aggressivemergingplugin()
and
"scripts": {
"build": "node_env=production webpack --config ./webpack.production.config.js"
},
score:6
this will help you.
plugins: [
new webpack.defineplugin({
'process.env': {
// this has effect on the react lib size
'node_env': json.stringify('production'),
}
}),
new extracttextplugin("bundle.css", {allchunks: false}),
new webpack.optimize.aggressivemergingplugin(),
new webpack.optimize.occurrenceorderplugin(),
new webpack.optimize.dedupeplugin(),
new webpack.optimize.uglifyjsplugin({
mangle: true,
compress: {
warnings: false, // suppress uglification warnings
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true
},
output: {
comments: false,
},
exclude: [/\.min\.js$/gi] // skip pre-minified libs
}),
new webpack.ignoreplugin(/^\.\/locale$/, [/moment$/]), //https://stackoverflow.com/questions/25384360/how-to-prevent-moment-js-from-loading-locales-with-webpack
new compressionplugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minratio: 0
})
],
score:9
you can use argv npm module (install it by running npm install argv --save) for getting params in your webpack.config.js file and as for production you use -p flag "build": "webpack -p", you can add condition in webpack.config.js file like below
plugins: [
new webpack.defineplugin({
'process.env':{
'node_env': argv.p ? json.stringify('production') : json.stringify('development')
}
})
]
and thats it.
score:26
just learning this myself. i will answer the second question:
- how to use these files? currently i am using webpack-dev-server to run the application.
instead of using webpack-dev-server, you can just run an "express". use npm install "express" and create a server.js in the project's root dir, something like this:
var path = require("path");
var express = require("express");
var dist_dir = path.join(__dirname, "build");
var port = 3000;
var app = express();
//serving the files on the dist folder
app.use(express.static(dist_dir));
//send index.html when the user access the web
app.get("*", function (req, res) {
res.sendfile(path.join(dist_dir, "index.html"));
});
app.listen(port);
then, in the package.json, add a script:
"start": "node server.js"
finally, run the app: npm run start
to start the server
a detailed example can be seen at: https://alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/ (the example code is not compatible with the latest packages, but it will work with small tweaks)
score:42
use these plugins to optimize your production build:
new webpack.optimize.commonschunkplugin('common'),
new webpack.optimize.dedupeplugin(),
new webpack.optimize.uglifyjsplugin(),
new webpack.optimize.aggressivemergingplugin()
i recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. add this as well in the above listed plugins list to further optimize your production code.
new compressionplugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minratio: 0.8
})
server side dynamic gzip compression is not recommended for serving static client-side files because of heavy cpu usage.
score:74
you can add the plugins as suggested by @vikramaditya. then to generate the production build. you have to run the the command
node_env=production webpack --config ./webpack.production.config.js
if using babel
, you will also need to prefix babel_env=node
to the above command.
Source: stackoverflow.com
Related Query
- Webpack how to build production code and how to use it
- Why does production build of React app (with Webpack and Babel) use wrong development env with HMR, which causes errors?
- How to reduce react app build time and understanding behaviour of webpack when bundling
- Webpack config for Code splitting not working for production build
- using webpack code splitting, how to load chunks and HTML layout?
- How to use Jest with React and Webpack
- How to use images from sharp module in React and Webpack project
- How to split app and vendor code with Webpack
- How can I build a React app with Webpack and import an assets folder?
- How can I use useEffect in React to run some code only when the component first mounts, and some other code whenever an event occurs (repeatedly)?
- How to determine the order of css in my create react app build with webpack and customize-cra?
- how to use webpack and web3 in react?
- How to use foundation css with webpack and react?
- How to use extract and code splitting in Laravel Mix for React
- How to use webpack to build two separate bundles for different websites
- how to use different IP address for development and production with react and axios
- How use both webpack "file-loader" and "@svgr/webpack" (or svg-inline-loader)
- How to use ReactJs and Symfony without webpack config
- How to split and export the mysql code into other file and can be use anywhere in Reactjs
- I am learning react and my code is working fine but how can i declare currDate single time to use it globally to use in useState
- How to include my Index.html in webpack Production build
- How to make html code as a variable and use it?
- How to use different manifest files for development and production Excel JS React?
- how to use webpack on a website project and app
- What is npm run build command and how webpack is used in creating bundle file
- How to use Google maps api with webpack and typescript
- How to use code splitting with webpack in react app with components exported as export * from '...'
- how to replace this code snippet to not use attrs? react and emotion/styled
- How to use async await with webpack and typescript in react?
- How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?
More Query from same tag
- TypeError: Cannot read property 'value' of undefined - REACTJS
- How to post data through API (ExpressJS) (ReactJS)?
- Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at App.js:18:1 in console
- Responsive Navigation Not Working (React)
- How to add rowStyle for alternative rows in "material-table"?
- Why do my error messages not update when a field is filled out? (React)
- getting information from url
- Passing down an array of Objects as props for a React Component
- HandlingChange input REACTJS + TypeScript bug
- Graphcomment plugin - implementation with Gatsby
- Accesing object using props in ReactJs
- React useState: preserve state between instances of an element factory
- How to use nested groups of radio buttons with Antd?
- How to upload a file to MySQL database using Nodejs backend and display the photo
- Storybook throwing errors
- Box-shadow transition not working on scroll
- Verify firebase id token Issue
- Using redux-form I'm losing focus after typing the first character
- Trying to get Button to copy URL and render snackbar using React Hooks
- Frosted glass effect over dyanmic video
- How peristent is router state in react?
- Deploy a package to different projects
- PayPal .Net transfers from a customer to another customer
- Typescript - pass new key in object as generic
- Insights into React Render LifeCycle
- TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. when trying to append react element
- ReactJS: button (span) visual should re-render and change when clicked, but doesnt (using setState)
- react-select select multiple items in the drop-down list
- From static pagination to dynamic
- Each child should have a unique key prop even they're set - REACT