Front-end Modular tool-webpack

Source: Internet
Author: User
Tags node server

Webpack is a module management tool, like Grunt,gulp,fis and many other front-end tools, in order to make the growing number of JS code reasonable and orderly, the emergence of modular tools

1 - It supports both the COMMONJS and AMD specifications (even mixed forms);2 - It can be broken into a complete package, or it can be divided into multiple parts, asynchronously loaded at run time (can reduce the time of first load);  3 - dependencies are processed at compile time, which reduces the size of the run-time package, and4 -loaders allows the file to be preprocessed at compile time, which can help us do many things, such as pre-compiling the template, Base64 processing of images;5 -rich and extensible plug-ins can adapt to changing needs.

Here is the configuration of my webpack:

varWebpack = require ('Webpack');varCommonsplugin =NewWebpack.optimize.CommonsChunkPlugin ('Common.js'); Module.exports= {    //plug-in itemsplugins: [Commonsplugin],//Page Portal File configurationentry: {index:'./app/js/index.js'    },    //ingress file Output configurationoutput: {path:'Dist/js', FileName:'[Name].js'}, module: {//Loader ConfigurationLoaders: [{test:/\.css$/, Loader:'Style-loader!css-loader'}, {test:/\.jsx?$/, Loader:'Babel', exclude:/node_modules/,query: {presets: ['es2015','react']}}, {test:/\. (png|jpg) $/, loader:'url-loader?limit=8192'}        ]    },    //Other Solution ConfigurationsResolve: {root:'E:/react/app',//Absolute PathExtensions: ["','. js','CSS'], alias: {reactdom:'React-dom.js'        }    }};

The Webpack.config.js file is usually placed in the root of the project and is itself a standard COMMONJS specification module. There are several key parameters in the exported configuration object:

1.entry

Entry can be a string or an array or an object.

When entry is a string, it is used to define the entry file:

' ./js/main.js '

When entry is a group, it also contains the portal JS file, another parameter can be used to configure the Webpack provided by a static resource server, Webpack-dev-server. Webpack-dev-server monitors changes to each file in the project, builds in real time, and automatically refreshes the page:

entry: [      'webpack/hot/only-dev-server',      './ Js/app.js']

When entry is an object, we can build different files into different files and use them on demand, such as on my Hello page as long as \<script src= ' build/profile.js ' ></script> The introduction of Hello.js can:

entry: {      './js/hello.js',      './js/form.js ' }  

2.output

The output parameter is an object that defines the outputs of the built file. These include path and filename:

output: {      './build',      '  Bundle.js'}    

3.module

Regarding the loading of modules, we define them in module.loaders. This is done by matching the file names of the different suffixes with the regular expressions, and then defining different loaders for them.

module: {//Loader ConfigurationLoaders: [{test:/\.css$/, Loader:'Style-loader!css-loader'}, {test:/\.jsx?$/, Loader:'Babel', exclude:/node_modules/,query: {presets: ['es2015','react']}}, {test:/\. (png|jpg) $/, loader:'url-loader?limit=8192'}        ] }

4.resolve

Webpack when building a package, the file is searched by directory, and the extensions array in the Resolve property is used to configure which file suffixes the program can self-complement:

Resolve: {        'e:/react/app'// absolute path        extensions: [' '. js','css',        alias: {              'react-dom.js'}    }

5.plugin

Webpack provides a rich set of components to meet different needs, and of course we can implement a component on our own to meet our own needs.

plugins: [      new webpack.optimize.CommonsChunkPlugin ('common.js' ) );    ],

6.externals

This is necessary in practical development when we want to require some other class libraries or APIs in the project, and do not want the source code of these libraries to be built into the runtime files. At this point we can fix the problem by configuring the Externals parameter:

externals: {      "jquery""jquery " }

This allows us to safely use these APIs in our projects: var jquery = require ("jquery");

Webpack and gulp are not contradictory, even use together will get the maximum benefit. Using Webpack for assets compiling, packaging with Gulp seems to be to get them to do their own work and use their strengths.

React-hot-loader Loader:

Configure a React-hot loader, through which you can implement hot replacements for react components.

The ' Webpack/hot/only-dev-server ' is configured in the entry parameter, so we can use React-hot-loader as long as the--hot parameter is turned on when the Webpack development server is started.

" Scripts " : {      "start""webpack-dev-server--hot--progress--colors " ,       " Build " " webpack--progress--colors " }

Webpack-dev-server:web Server

A development server based on the node. JS Express Framework, which is a static resource Web server that can be developed directly using this development server for simple static pages or for front-end pages that rely solely on standalone services. In the development process, the development server listens for each file change, carries on the real-time packing, and can push the notification front page code to change, thus can realize the page automatic refresh.

React-hot-loader + Webpack-dev-server can implement functions similar to Gulp-connect: Build server, code modify real-time refresh

1. Download the installation of two plugins

NPM install-g webpack-dev-servernpm install-save-dev react-hot-loader

2. After that, the Webpack development server needs to turn on the HMR parameter hot, for convenience, we create a file named Server.js to start the Webpack development server:

varWebpack = require ('Webpack');varWebpackdevserver = require ('Webpack-dev-server');varConfig = require ('.. /webpack.config');Newwebpackdevserver (webpack (config), {publicPath:config.output.publicPath, hot:true, Noinfo:false, Historyapifallback:true}). Listen ( the,'127.0.0.1', function (err, result) {if(Err) {Console.log (err); } console.log ('Listening at localhost:3000');});

3. In order to heat load the react component, we need to include the corresponding code in the front page to receive the Webpack push code module, so that all relevant react components can be notified to re-render. Adding this code is simple:

entry: [  'webpack-dev-server/client?http://127.0.0.1:3000',    'webpack/hot/only-dev-server',  './scripts/ Entry'  ]

It is important to note that the client?127.0.0.1:3000 here need to match the address of the Webpack development server that was started in server.js.

4. Next, we need to get webpack to load the react component with React-hot-loader, as described in the previous section, which is done with the loader configuration:

loaders: [{    /\.js$/,    /node_modules/,    'react-hot!jsx-loader? Harmony'  },  ...]

After you have done these configurations, run server.js using node. JS:

Node Server.js

In this way, react's hot-load development environment is configured to complete, and any modifications that are saved will be immediately reflected on the page. Whether the modification of the style, or the modification of the interface rendering, or even the modification of the event binding handler function, can be effective immediately, it must be said to improve the development efficiency of the artifact.

Babel-loader Loader: Babel for parsing ES6

1. Download the Babel Loader

NPM Install--dave-dev Babel-loader

2. Use Babel in the loader:

' Babel-loader '},

Run the code, Webpack will be an error (parsing ES6 and JSX are unsuccessful), this is why?

Babel-loader parsing ES6, also need plug-in support, while parsing JSX also need plug-in support:

NPM Install--dave-dev babel-preset-es2015     --dave-dev babel-preset-react

Configuration

{     /\.jsx?$/,     'Babel',    /node_modules/,    query: {        presets: [            'es2015',            ' react '         ]    }},        

So that we can successfully parse ES6 and JSX.

Front-end Modular tool-webpack

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.