Webpack notes (ii)--build react development environment

Source: Internet
Author: User
Tags npm scripts

A few days ago has been learning Webpack, finally more than before the time has a point of harvest, so in yesterday released a Webpack introductory note, today continue to use webpack practice practiced hand, built a react development environment, If you are unfamiliar with children's shoes, you can look at the notes released yesterday: Getting Started Webpack notes

First, initialize the project folder

In any directory, create a new folder as your project folder and name it as you wish. Then, using the command-line tool, switch to the folder, type npm init to initialize (the problem you've encountered has been a good return), and you can see that a file was generated after the initialization is complete package.json .

You then create a new two folder under the project folder: /dist and /src , which is used to place the source code for the /src development, /dist to place the "compiled" codes.

Then in the /src directory index.html , New, index.css and index.js file

Second, install Webpack tools

Using Webpack 4 from the command line requires the installation of two modules: Webpack and WEBPACK-CLI, all installed as a development environment dependency.

NPM install-d Webpack webpack-cli

  

After the installation, you can see that your file has changed package.json and that you have two more properties under the Devdependencies property.

Third, the configuration of the most basic webpack
  • 1. Install the most basic plug-in:

    NPM install-d html-webpack-plugin clean-webpack-plugin webpack-dev-server css-loader webpack-merge style-loader

      

  • 2. Create a new file under the project folder Webpack.base.conf.js , which represents the most basic configuration file, as follows:

    const path = require (' path ');  Const Htmlwebpackplugin = require (' Html-webpack-plugin ');  Const Cleanwebpackplugin = require (' Clean-webpack-plugin '); Module.exports = {entry: './src/index.js ', output: {filename: ' bundle.[                  Hash].js ', Path:path.join (__dirname, '/dist ')}, module: {rules: [{ Test:/\.css$/, use: [' Style-loader ', ' Css-loader '}]}, plugins : [New Htmlwebpackplugin ({Template: './src/index.html '}), new Cleanwebpackplugi N ([' Dist '])}; 

    Where /src/index.html is your website portal HTML file, /src/index.js is your portal JS file.

  • 3. Create a new file under the project folder that webpack.dev.conf.js represents the configuration under the development environment. The contents are as follows:

    Const MERGE = require (' Webpack-merge ');  Const BASECONFIG = require ('./webpack.base.conf.js ');  Module.exports = Merge (Baseconfig, {      mode: ' Development ',      devtool: ' Inline-source-map ',      devserver: {          Contentbase: './dist ',          port:3000      }  });

      

  • 4. Create a new file under the project folder that webpack.prod.conf.js represents the configuration of the production environment as follows:

    Const MERGE = require (' Webpack-merge ');  Const BASECONFIG = require ('./webpack.base.conf.js ');  Console.log (__dirname);  Module.exports = Merge (Baseconfig, {      mode: ' Production '  });

      

Iv. Configuring NPM Scripts

Three profiles are configured to meet code constructs in two different environments, making it easier to construct code that is more semantic- npm scripts friendly.

Add the new scripts content to the package.json file's scripts properties, remember to enclose it in double quotation marks, with the following properties:

package.json{    "Scripts": {        "start": "Webpack-dev-server--open--config webpack.dev.conf.js",        "Build" : "Webpack--config webpack.prod.conf.js"    }}

  

After the configuration is complete, you can try to modify /src/index.html , /src/index.js or /src/index.css run the NPM scripts command to see the effect.

For example, create a file with the following content:

Index.html

  

Index.css

body {    background-color:blue;} #root {    color:white;    Background-color:black;}

  

Index.js

Import './index.css '; Console.log (' success! ');

  

npm run startyou can then use the command to see the effect. Modify the CSS or JS file, after saving you can see the browser automatically refresh and show the changes you have just made.

To do this, a basic development environment has been built, and the next step is to configure different webpack for react specific environments.

Using react development, mainly ES6 (although all recent advanced browsers have already supported ES6, but still want to prepare for low-level IE) and react JSX syntax need to be converted. The following are configured for both syntaxes.

V. Configuration Babel

Babel is a good JavaScript compiler (this is from the Babel website), through the Babel of some plug-ins, you can convert JSX syntax, ES6 syntax to ES5 syntax, so that the lower-level browser can also run the code we write.

(1) Installing Babel presets

Install the Babel presets, babel-loader , babel-polyfill and babel-preset-react : using the following command

NPM install-d babel-preset-env babel-loader babel-polyfill babel-preset-react

  

(2) configuration. BABELRC

Create a new file under the root of the project folder .babelrc (cannot be created directly under Windows, you can enter the following in the file by naming the file for .babelrc. creation purposes):

{    "presets": ["env", "React"]}

  

(3) configurationwebpack.base.conf.js

module.rulesinsert a new object in the contents as follows:

{    test:/\.js$/, use    : ' Babel-loader ',    exclude:/node_modules/}

  

(4) InstallationreactAndreact-domModule
NPM Install--save react react-dom

  

(5) Start development

/srcCreate a new App.js file in, with the following content:

Import React from ' React '; class App extends React.component {    render () {        return <div>            

   export default App;

index.jsafter emptying, write the following in it:

Import React from ' React ', import reactdom from ' React-dom ', import App from './app '; Import './index.css '; Reactdom.render (<app/>, document.getElementById (' root '));

  

Use npm run start the command to open the page to see the effect written using react.

Open the browser to see the compiled code, find the app component of the map function this paragraph, you can find that the ES6 syntax has been converted to the ES5 syntax:

[' A ', ' B ', ' C '].map (function (name) {    return _react2.default.createelement (        ' li ',        null,        ' i\ ' m ' + name + '! '    );})

  

The arrow functions are written as function anonymous functions.

Vi. description

The above steps, I have run again, step by step according to can build a success, interested children shoes can run through. ^_^

In addition, if there are errors, please remind me, I will definitely correct it right away!

Webpack notes (ii)--build 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.