You probably saw some warnings that say you’re using React in development mode, and want to know how to create a production build using React.
Why you get a warning of being in React development mode
Normally you import React JS in your javascript ECMA 6 code with the following statements in a .js file
1 2 |
import React from 'react'; import ReactDOM from 'react-dom'; |
When you use your taskrunner, being it Grunt, Webpack or something else, the development code of React JS is included in the build and you get a warning in the browser console.
Development mode does some checks that can be useful during… development, but not in production.
How to turn off development mode and create a production build
If you want to create a production build when using React JS and turn off development mode, one solution is to set the NODE_ENV environment variable to “production“.
This can be easily done with the taskrunner Grunt.
Grunt, as you may already know, lets you run different tasks to create your production bundle.
In this case, you have to define a task env and calling it before other tasks, as the code below, GruntFile.js, shows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
module.exports = function(grunt) { grunt.initConfig({ // set var node_env to build a production reactjs env: { prod: { NODE_ENV: 'production' } }, watch: { watch1: { files: [ 'js/**/*.js', 'js/**/*.jsx' ], tasks: ['browserify'] } }, browserify: { dist1: { options: { transform: [ ['babelify', {presets: ['es2015', 'react']}] ] }, src: ['js/bmv/app.jsx'], dest: 'WebContent/bmv/js/bundle.js', }, }, uglify: { my_target1: { files: { 'WebContent/bmv/js/bundle.min.js': ['WebContent/bmv/js/bundle.js'] } }, } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-env'); grunt.registerTask('default', ['watch']); grunt.registerTask('release', ['env', 'browserify', 'uglify']); }; |
Remember to load grunt-env plugin with the following code
1 |
grunt.loadNpmTasks('grunt-env'); |
after having installed it with
1 |
npm install --save grunt-env |
The default task is watch, the release task calls env followed by browserify and uglify.
You don’t need to call uglify to create a production build using React, but it can be useful to minimize and obfuscate the code.
The browserify task includes the presets es2015 react to create ES2015 compliant code and transform React .jsx files into normal javascript.