webpack open a local server with hot update

  • The first local service webpack
  • webpack Some local services operating instructions and application-related

 A first local service webpack

// workspace 
    src // folder 
        index.js // entry file 
        index.css // test pattern file 
        index.html // structure file 
    package.json // packaged system configuration information 
    webpack.config.js // packaged configuration

Need to download the plugin loader and installation of:

1 npm install webpack --save-dev
2 npm install webpack-cli --save-dev
3 npm install style-loader --save-dev
4 npm install css-loader --save-dev
5 npm install html-webpack-plugin --save-dev
6 npm install clean-webpack-plugin --save-dev
7 npm install webpack-dev-server -g
8 npm install webpack-dev-server -save-dev

We must pay attention to install webpack-dev-server globally, and then installed in the local workspace. Then the test code is very simple, just to generate a default configuration html, body css to set the background color, and then introduced into the inlet index.js file css file. Then use the following package this configuration, if the contents of my previous blog webpacd have to know you will find this is the most simple configuration:

 1 var path = require('path');
 2 var {CleanWebpackPlugin} = require('clean-webpack-plugin');
 3 var HtmlWebpackPlugin = require('html-webpack-plugin');
 4 module.exports = {
 5     entry:{
 6         index:'./src/index.js'
 7     },
 8     output:{
 9         path:path.resolve(__dirname,'dist'),
10         filename:'[name][hash:5].bundle.js'
11     },
12     module:{
13         rules:[
14             {
15                 test:/\.css$/,
16                 use:[
17                     {loader:'style-loader'},
18                     {loader:'css-loader'}
19                 ]
20             }
21         ]
22     },
23     plugins:[
24         new CleanWebpackPlugin(),
25         new HtmlWebpackPlugin({
26             template:'./src/index.html'
27         })
28     ],
29     mode:'development'
30 }

Execution: webpack test whether the configuration is successful, the next instruction in the case of a successful configuration.

Execution: webpack-dev-server. Play successful execution webpack began to monitor the implementation of the code file scope, the console has been in the hands flashing. Then find instructions execute just to find local port link generated in the description, the following are my test shots generated port link (the link pasted directly into a browser link bar):

You will find the link to the page that you just edited packaged html page, this time back to modify the style editor (modified body background color), modified after a good save, this time the page will automatically refresh, and then test js code, in edit js a console.log ( 'hello') print instruction, (eDIT) can be seen in the automatic control of the browser print hello. The above operation is the function of local services, in many companies the front in order to improve the efficiency of development work will use the dual-screen at the same time, a coding a display effect from time to time, you can use webpack-dev-server to achieve.

Since it is a service, of course, the data requested operation, then you use the following ajax request:

npm install jquery --save-dev

Then, remove the config file package file clean-webpack-plugin Note, since the dist folder need to cache a json file server for testing a data request (data of an arbitrary file json):

//        new CleanWebpackPlugin(),

And then start the service again with a link to the new generation of open pages (open the browser console):

webpack-dev-server

Then edit index.js in the editor, to write a jQuery ajax JSON data request to request the local server:

Import './index.css' ;
 // var $ = the require ( 'jQuery'); 
Import from $ 'jQuery' ; 
$ .ajax ({ 
    URL: 'HTTP: // localhost: 8081 / dist / the data.json' , // Note that this path is generated by the link packed folder path + file name + JSON 
    Success: function (Data) { 
        the console.log (Data); 
    }, 
    error: function () { 
        the console.log ( 'error' ) ; 
    } 
})

When you save the edited index.js it you'll find that the request can happen to a local server via ajax.

 Two, webpack Some local services operating instructions and application-related

Because the program uses the default port of reasons, problems may arise port conflict if the port conflict, then you can re-configure the port config.js file:

1 module.exports = {
2     devServer:{
3         port:'9091'
4     }
5 }

Add this configuration to a configuration file, you can open on the specified port services, but one thing to note is that if modify the configuration file services are open state, it does not automatically refresh, you need to manually close the current monitor, and then start to take effect. (CTRL + C hotkey shut down service)

Because webpack local service monitor project code does not monitor environmental config.js packaged configuration file, so you need to re-start the service. Following the above configuration, you can also add a configuration property to specify the server address, server default interval is on the service in the console position, due to the work of this interval is the interval, in addition to containing the generated code below dist folder, and the code src folder, and configuration files, in order to better distinguish between server and development environment can add the following configuration:

1      devServer: {
 2          port: '9091' ,
 3          contentBase: 'dist'
 4      },
View Code

If you change the server space, then the ajax request would certainly need to change, and before the path dist need to remove this layer to find data.json.

url:'http://localhost:9091/data.json',

This step is not found to have an operation very convenient, is the need to manually copy the link to your browser or manually enter the link, webpack how convenient it would be so? The following instructions help you solve:

Server-dev---open WebPACK // turn on the local server is automatically in your default browser opens the page

Because after opening service, each time the trigger to update the page in the print control strip out the relevant information required in debugging the debug view the console, then go all-white tips will make you hurt, you only need to do this time:

webpack-dev-server --open --color

Add --color subsequent instruction command message console will have different colors to distinguish different information.

 Third, the hot update: hot module replace

Introduced in front of open local service and automatically refresh the page, pay attention to "refresh automatically", that is, in the front-end development should be very sensitive to this sentence, because it means that the page will refresh all data requests once again, this kind of thing in addition to the request after the first page should not appear in the front-end services, think about every time you save the source code files will be triggered once all network requests, compile, execute, estimated workday there half the time waiting for pages to refresh in the, in our test code because the source code is not very small amount of body perception, if you think about it in the actual development requests a page to have much. The severity of the problem to say more, and look at how to achieve the next webpack partial refresh to solve performance problems:

Open css to modify the code to achieve the partial refresh by built-ins webpack module :( add the following configuration in config configuration file)

. 1  var Webpack the require = ( 'WebPACK'); // introduced WebPACK module 
2  ...
 . 3 module.exports = {
 . 4      plugins: [
 . 5          ...
 . 6          new new Webpack.HotModuleReplacementPlugin () // introduced into the partial refresh plug 
7      ],
 . 8      devserver: {
 . 9          ...
 10          hot: to true // open hot update 
11      }
 12 }

After adding the above configuration, in the open service updates css code, you can realize hot update (partial refresh) instead of refreshing the entire page. However, this configuration does not solve the partial refresh js code, js hot update requires the following configuration:

js hot update only, only you need to add this code (note: add js code file) in js in front of the base configuration:

// determines whether to open the hot update, if the opening of the heat js file update operation performed 
IF (module.hot) { 
    module.hot.accept (); 
}

Js identify whether hot update, to see if the print result to the browser console will be cleared when updating, if every update emptied on the note is a page refresh, update the print result if it is added in the original print results Below opens hot update.

Finally, the code provides configuration files and js code:

 1 var path = require('path');
 2 var {CleanWebpackPlugin} = require('clean-webpack-plugin');
 3 var HtmlWebpackPlugin = require('html-webpack-plugin');
 4 var Webpack = require('webpack');
 5 module.exports = {
 6     entry:{
 7         index:'./src/index.js'
 8     },
 9     output:{
10         path:path.resolve(__dirname,'dist'),
11         filename:'[name][hash:5].bundle.js'
12     },
13     module:{
14         rules:[
15             {
16                 test:/\.css$/,
17                 use:[
18                     {loader:'style-loader'},
19                     {loader:'css-loader'}
20                 ]
21             }
22         ]
23     },
24     plugins:[
25         // new CleanWebpackPlugin(),
26         new HtmlWebpackPlugin({
27             template:'./src/index.html'
28         }),
29         new Webpack.HotModuleReplacementPlugin()
30     ],
31     devServer:{
32         port:'9091',
33         contentBase:'dist',
34         hot:true
35     },
36     mode:'development'
37 }
config configuration file code
. 1 Import './index.css' ;
 2  // var $ = the require (' jQuery '); 
. 3 Import from $' jQuery ' ;
 . 4  $ .ajax ({
 . 5      URL:' HTTP: // localhost: 9091 / Data .json ', // note that the path is generated by the link packed folder path + file name + JSON 
. 6      Success: function (Data) {
 . 7          the console.log (Data);
 . 8      },
 . 9      error: function () {
 10          the console.log ( 'error' );
 . 11      }
 12 is  })
 13 is the console.log ( 'hot date?' );
 14  
15 // determines whether to open the hot update, if the opening of the heat js file update operation performed 
16  IF (module.hot) {
 . 17      module.hot.accept ();
 18 is }
Test js code (the last full)

 

Guess you like

Origin www.cnblogs.com/ZheOneAndOnly/p/11117860.html