Webpack REACT+ES6

Source: Internet
Author: User
Tags node server

Webpack is a recent comparison of fire construction tools, with the same relatively fire Reacjs and ES6 (ES2015) must be now a lot of trend programmer pursuit. Not much nonsense, here's how to set up our build tool from 0.

Installation

If you install Webpack globally, or if you are prompted without Webpack Commond, you can try to install it by using Super Administrator.

$ npm Install webpack-g$ sudo npm install webpack-g

Or install them in the project.

$ NPM Install Webpack--save-dev

Configuration

Create a Directory

Index.js File Contents:

document.write (' Hello Webpack ');

Generate Package.json file,-y to generate default content

$ NPM init$ NPM init-y

Create a Webpack.config.js file

var webpack = require (' Webpack '); module.exports = {        entry: './app/index.js ',//inlet output    : {//output        path: ' Bundle ',         publicpath: '/static/',        filename: ' Bundle.js '    },    module: {         loaders: [//Loader            {test: /\.css$/, loader: ' Style-loader!css-loader '},            {test:/\.js$/, Loader: ' Babel-loader '},            {test:/\. ( png|jpg) $/, loader: ' url-loader?limit=8192 '}        ]    }}

Note that the output has a path property and a Publicpath property, the difference being that path is a local path, and Publicpath is the path when you enable the server (Webpack-dev-server/react-hot-loader).

In Webpack so the resources need to be loaded through the loader, with multiple loaders! Separated, where the suffix of the-loader can be omitted.

Each declared loader in the Webpack.config file needs to be installed, or the operation will error:

$ npm Install Style-loader Css-loader--save-dev

Given that there will be more than n loader in a project, these loader are typically written to the Devdependencies attribute of the Package.json file, and then all at once through the NPM install command.

Here choose Babel Loader to load our JS file, use it to install at least Babel-core and Babel-loader. If you want to use Babel to parse ES6 and React, you also need to install the babel-preset-es2015 and Babel-preset-react, this later.

Run

After the above configuration is completed, we will start Webpack

$ webpack

After executing the command, there is a bundle folder under the project with the output Bundle.js file.

Introduction of compiled Bundle.js in index.html

<script src= ". /bundle/bundle.js "></script>

Run the index.html file

This completes the basic configuration and runs the first demo, looking at the other more useful commands

$ webpack--config xxx.js//Use another config file $ webpack--watch/Auto-Monitor Package $ webpack-p//Compression obfuscation script $ webpack-d//Generate map Map file

Getting started the second and third commands are more commonly used, and--watch allows us to execute $ webpack without having to change the code every time. -P compresses the packaged files, making the volume much smaller and usually publishes the compressed file to the line.

In Webpack, all resources are introduced in a modular way. It supports both COMMONJS and AMD's syntax. Next we introduce CSS files. Also don't forget to install Style-loader and Css-loader.

STYLE.CSS Content

body {    color:red;}

Index.js Content

Require ('./style.css ');d ocument.write (' Hello Webpack ');

Results

Support ES6

As mentioned above, to support ES6, you also need to install babel-preset-2015.

$ NPM Install babel-preset-es2015

After installation, modify the Webpack.config file as follows:

{    test:/\.js$/,    loader: ' Babel-loader ',     query: {        presets: [' es2015 ']    }}

Here we create the App.js file in the app directory:

Let A = ' ES6 is working! '; Export default A;

Modify Index.js

Import './style.css '; Import text from './app.js '; alert (text);d ocument.write (' Hello Webpack ');

Results

Support Reactjs

First install react and babel-preset-react

$ npm Install react React-dom babel-preset-react--save-dev

Modify Webpack.config to add a react item to the preset property.

{    test:/\.js$/,    loader: ' Babel-loader ',     query: {        presets: [' es2015 ', ' React ']    }}

Modify App.js Content

Import React, {Component} from ' React '; class App extends Component {  render () {    return (      

Modify Index.js Content

Import './style.css '; import React from ' React ', import reactdom from ' React-dom ', import Title from './app.js '; Reactdom.render (<title/>, document.body);

Results

So that we can use ES6 and react in static projects, let's see if the browser is automatically refreshed via the local server.

If you do not use react in your project, you can automate the refresh by Webpack-dev-server. If you use react, you can use a tailor-made react-hot-loader.

Let's talk about the two in turn.

Webpack-dev-server

Installation

NPM Install Webpack-dev-server--save-dev

Change the index.html file

<script src= "Static/bundle.js" ></script>

The path at this point is the one set in Publickpath in the Webpack.config file.

Run

Webpack-dev-serverwebpack-dev-server--port 3000

The service starts port 8080 by default and can be changed by using the--port command. So we can access our page in localhost:3000/index.html.

Hot Refresh

Webpack hot flushes are divided into IFRAME mode and inline mode

The IFRAME mode operation is much simpler and requires no configuration changes, only access to localhost:3000/webpack-dev-server/index.html.

Now when we change the JS file, the browser will automatically refresh.

Inline mode is interesting to refer to the documentation.

React-hot-loader

Installation

NPM Install React-hot-loader--save-dev

Change the Webpack.config file and introduce plugins.

Entry: [' webpack-dev-server/client?http://localhost:2000 ', ' webpack/hot/only-dev-server ', './js/index.js '], Plugins: [New Webpack. Hotmodulereplacementplugin ()],module: {loaders: [{test:/\.js$/, loaders: [' Babel ', ' React-hot '],}]}

Create a Server.js file

var webpack = require (' Webpack '),    webpackdevserver = require (' Webpack-dev-server '),    config = require ('./  Webpack.config '); new Webpackdevserver (Webpack (config), {publicPath:config.output.publicPath, hot:true,  Historyapifallback:true}). Listen (n, ' localhost ', function (err, result) {if (err) {return console.log (err); } console.log (' Listening at Http://localhost:3000/');});

Start with a command

Node Server.js

Can also be written in Package.json

"Scripts": {"Start": "Node Server.js"}

Run

NPM start

This allows the react project to achieve a hot refresh, but in the actual use of the process will encounter a variety of pits. A complete official demo is introduced here, the pro-test is available, and the documentation is very concise and straightforward.

Https://github.com/gaearon/react-hot-boilerplate

Webpack REACT+ES6

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.