Build Webpack + React development environment

Source: Internet
Author: User
Tags postcss

Say at the beginning

Last month, intermittent research on the configuration of Webpack, but a lot of online articles are basically just the configuration of the development environment, ignoring the production environment configuration. A general study of the road, and then to write an essay so that you can have a place in the future to do a reference.

Body Start

I just pretended that everyone was in the case of node.

1, enter the project directory, run ' NPM init ' follow the steps to complete the final build ' Package.json ' file, all use NPM to do the dependency management of the project, the root directory will have a file that describes the basic information of the project and some third-party dependencies (plugins). Detailed instructions for use can be found in the [official website document], but in English.  2, we know we will use Webpack as the build tool, then we need to install the appropriate plug-in, run ' npm install webpack webpack-dev-server--save-dev ' to install two plugins. We also know that we will be using React, and we need to install the corresponding plug-in, run ' npm i React react-dom--save ' to install two plugins. Where ' I ' is the abbreviated form of ' install '. After the installation is complete, see ' Package.json ' to see more ' devdependencies ' and ' dependencies ' two items, root directory also has a ' node_modules ' folder.  3, '--save ' and '--save-dev ' are distinguished by ' npm i ' using '--save ' and '--save-dev ', respectively, to record dependencies (plugins) into ' Package.json ' and ' Devdependencies ' below. ' Dependencies ' is recorded in the project at runtime must rely on plug-ins, common such as ' react ' jquery ', and so on, even if the project is packaged, on-line, these are also needed, otherwise the program will not be executed normally. ' Devdependencies ' records the plug-ins that the project uses in the development process, for example, we need to use ' webpack ' package in the development process, but once the project is packaged and released, the ' Webpack ' is useless and can be xiemoshalv. Extension, our project has ' Package.json ', other projects we use such as ' webpack ' also have ' Package.json ', see './node_modules/webpack/package.json ', which also has ' Devdependencies ' and ' dependencies '. When we use ' npm i webpack ', the ' dependencies ' in './node_modules/webpack/package.json ' will be installed by NPM, and ' devdependencies ' does not need to be installed.  4, Webpack. Config.js in order to improve the efficiency of learning, webpack the most basic usage, it is no longer a demonstration (recommend a very good [introductory article], as well as [more information]) Here we put the project "Webpack.config.js" This configuration file in detail to explain, The process will also take care of 0 of the basic students. Webpack.config.js is an ordinary JS file, in line with the CommonJS specification. Finally output an object, i.e. ' Module.exports = {...} ' This is a relatively basic, but need to create a new './app/index.js ' as a portal file, which is currently the only entry in the project. However, Webpack supports multiple portal files, which can be consulted. Output is a ' bundle.js ', JS and CSS are in the inside, but only in the development environment to use, when the release of code, it must not be only such a file, the next will be discussed.   ModuleFor different types of files, use different ' loader ', of course, before using to install, such as ' NPM I style-loader css-loader--save-dev '. In this project code, we use the file format: JS/JSX code, css/less code, picture, font file. Less is the CSS syntax sugar, can be more efficient and low redundancy of writing CSS, unfamiliar friends can go [official website] to see, very simple. When loading css/less, the use of ' postcss ', mainly using the ' autoprefixer ' function, to help automatically add css3 browser prefix, very useful. When compiling ES6 and JSX syntax, a household name of ' Babel ' is used, plus a '. BABELRC ' configuration file. PluginsUse an HTML template (' NPM i html-webpack-plugin--save-dev ') so that the output file name (such as './bundle.js ') can be automatically injected into the HTML without our own handwriting. If you write your handwriting, you need to change two places. Use hot load and auto-open Browser plugin DevserverConfiguration of the Webpack-dev-server NPM StartIn Package.json, enter the following code to encapsulate this string of commands as ' npm start ' so you can run the project code.
"Scripts": {"start": "Node_env=dev webpack-dev-server--progress--colors"}
The code ' Node_env=dev ' represents the current development environment, where ' dev ' can be obtained by ' Process.env.NODE_ENV ' in the JS code and do some other processing. 5, define the environment global variable The following definition, can make the code through ' __dev__ ' get current is not development mode.
New= = ' Dev ') | | ' false ')})


Open './app/util/localstore.js ' to see ' if (__dev__) {console.error (' Localstorage.getitem error, ' ', ' ex.message '} ', That is, only the development environment to prompt the error, after the release will not be prompted. (because the published command uses ' Node_env=production ') 6, the production environment configuration webpack.production.config.js development environment, can not consider the system performance, more consideration is how to increase the development efficiency. When you publish a system, you need to consider the performance of the post-release system, including loading speed, caching, and so on. The following is a different place for publishing with configuration code and development. Publish to './build ' folder: ' Path: __dirname + '/build ', ' VendorPackage third-party dependencies separately. The code in the Node_modules folder will be packaged as vendor.js to package our own business code as app.js. This helps in caching because third-party dependencies do not change frequently during project maintenance, and business code changes frequently. MD5 suffixAdd a MD5 suffix to each packaged file, such as '/js/[name '. [Chunkhash:8].js "', can make the file strong cache. Sub-cataloguePackage the different types of files, placed in different directories, the sample files will be placed in the ' img/' directory CopyrightAutomatically add content to your packaged code Sub-module' New Webpack.optimize.OccurenceOrderPlugin (), ' Compress CodeUse Uglify to compress the code, where ' Warnings:false ' is stripped of the code warning separating CSS and JS filesIn the development environment, CSS code is placed in the entire package of the Bundle.js file, in the publishing environment of course can not be confused with, using ' New Extracttextplugin ('/css/[name].[ Chunkhash:8].css '), ' separate the CSS code. 7. NPM Run build opens ' Package.json ' to view the following code. ' NPM start ' and ' npm run build ' are run code and packaged items, respectively. In addition, ' Start ' and ' test ' can be used without ' run '.
"Scripts": {"start": "Node_env=dev webpack-dev-server--progress--colors","Build": Rm-rf./build & amp;& node_env=production webpack--config./webpack.production.config.js--progress--colors "},


The two commands have the following main differences:
-The former uses webpack.config.js as the configuration file by default, and the latter forces the use of Webpack.production.config.js as the profile-the former ' Node_env=dev ' and the ' node_env= Production ', identify different environments. And this ' dev ' ' production ' can be obtained in code through ' Process.env.NODE_ENV '. minimizing compression ReactThe following configuration can tell React is currently a production environment, please minimize the compression JS, that is, the development environment of some hints, warnings, judgments are all removed, DC after the release of the code available.
New Webpack. Defineplugin ({' process.env ': {' node_env ': Json.stringify (Process.env.NODE_ENV)}}),

Next, the configuration of the development generation environment and the configuration of the production environment are affixed

Webpack.config.js

varPath = require (' path ')varWebpack = require (' Webpack '))varHtmlwebpackplugin = require (' Html-webpack-plugin '));varOpenbrowserplugin = require (' Open-browser-webpack-plugin ')); Module.exports={entry:path.resolve (__dirname,' App/index.js '), output: {filename:"Bundle.js"}, Resolve: {extensions: [', '. js ', '. Jsx ']}, module: {loaders: [{test:/\. (JS|JSX) $/, exclude:/node_modules/, Loader: ' Babel '}, {test:/\.less$/, exclude:/node_modules/, Loader: ' Style!css!postcss!less '}, {test:/\.css$/, exclude:/node_modules/, Loader: ' Style!css!postcss '}, {test:/\. (png|gif|jpg|jpeg|bmp) $/i, loader: ' url-loader?limit=5000 '},//Limit size 5kb{test:/\. (PNG|WOFF|WOFF2|SVG|TTF|EOT) ($|\?) /I, loader: ' url-loader?limit=5000 '}//Limit size less than 5k]}, POSTCSS: [Require (' Autoprefixer ')//Call the Autoprefixer plug-in, such as Display:flex], plugins: [//HTML Template Plugin        Newhtmlwebpackplugin ({Template: __dirname+ '/app/index.html '        }),        //Hot Load        NewWebpack. Hotmodulereplacementplugin (),//Open Browser        Newopenbrowserplugin ({URL:' http://localhost:8080 '        }),        //can use __dev__ in business JS code to determine whether the development environment (Dev mode can prompt errors, test reports, etc., production mode is not prompted)        NewWebpack. Defineplugin ({__dev__: Json.stringify (json.parse (Process.env.NODE_ENV= = ' Dev ') | | ' False '), })], Devserver: {proxy: {//all HTTP requests beginning with '/api ' will be proxied to localhost:3000, with mock data provided by KOA.           //KOA code in the./mock directory, start command for NPM run mock'/api ': {target:' http://localhost:3000 ', Secure:false}}, Colors:true,//Terminal comfort for colorHistoryapifallback:true,//does not jump, in the development of a single page application is very useful, it relies on the HTML5 history API, if set to true, all jumps will point to index.htmlInlinetrue,//Real-time RefreshHottrue,//using the hot load plug-in Hotmodulereplacementplugin    }}

Webpack.production.config.js

varpkg = require ('./package.json '))varPath = require (' path ')varWebpack = require (' Webpack '));varHtmlwebpackplugin = require (' Html-webpack-plugin '));varExtracttextplugin = require (' Extract-text-webpack-plugin ')); Module.exports={entry: {app:path.resolve (__dirname,' App/index.js '),    //Package third-party dependencies (in node_modules) separatelyVendor:Object.keys (pkg.dependencies)}, Output: {path: __dirname+ "/build", FileName:[/js/[name]. [Chunkhash:8].js]}, resolve:{extensions:[', '. js ', '. Jsx ']}, module: {loaders: [{test:/\. (JS|JSX) $/, exclude:/node_modules/, Loader: ' Babel '}, {test:/\.less$/, exclude:/node_modules/, Loader:ExtractTextPlugin.extract (' style ', ' css!postcss!less ')}, {test:/\.css$/, exclude:/node_modules/, Loader:ExtractTextPlugin.extract (' style ', ' css!postcss ')}, {test:/\. (png|gif|jpg|jpeg|bmp) $/i, loader: ' url-loader?limit=5000&name=img/[name]. [Chunkhash:8]. [ext] '}, {test:/\. (PNG|WOFF|WOFF2|SVG|TTF|EOT) ($|\?) /I, loader: ' url-loader?limit=5000&name=fonts/[name]. [Chunkhash:8]. [ext] '}]}, POSTCSS: [Require (' Autoprefixer ')], plugins: [//Webpack built -in Banner-plugin    NewWebpack. Bannerplugin ("Copyright by [email protected]"),    //HTML Template Plugin    Newhtmlwebpackplugin ({Template: __dirname+ '/app/index.html '    }),    //defined as a production environment, compressed to a minimum when compiling React    NewWebpack. Defineplugin ({' Process.env ':{        ' Node_env ': Json.stringify (Process.env.NODE_ENV)}),//assigning IDs to components, through which the plug-in Webpack can analyze and prioritize the most used modules and assign them the smallest IDs    NewWebpack.optimize.OccurenceOrderPlugin (),NewWebpack.optimize.UglifyJsPlugin ({compress: {//supresses warnings, usually from module minificationWarningsfalse        }    }),    //separating CSS and JS files    NewExtracttextplugin ('/css/[name].[ Chunkhash:8].css '),    //provide common code    NewWebpack.optimize.CommonsChunkPlugin ({name:' Vendor ', FileName:'/js/[name]. [Chunkhash:8].js '    }),    //can use __dev__ in business JS code to determine whether it is the dev mode (dev mode can prompt for errors, test reports, etc., production mode is not prompted)    NewWebpack. Defineplugin ({__dev__: Json.stringify (json.parse (Process.env.NODE_ENV= = ' Dev ') | | ' False '))    })  ]}

Build Webpack + React development environment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.