Build a Webpack Micro server

Source: Internet
Author: User

[Preface]: Because recently in vue2.0 time used to Webpack externals, only then found that I used to do some of the project after the completion of the "finishing work"-that is, packaging, and did not include it in the project development of the "main process", really "things are not used." So I have this article of study today: use Webpack-dev-server to build a webpack server References: Webpack-dev-server's github address: Https://github.com/webpack/webpack-dev-server Webpack1 Official document http://webpack.github.io/docs/webpack-dev-server.html (recommended for 2 documents) Webpack2 Official Document https://webpack.js.org/configuration/dev-server/#devserver (read this) Outline:1. Review the knowledge of Webpack 2. Webpack-dev-server Configuration Properties 3.webpack-dev-server automatic refresh and module hot swap mechanism 4.webpack configuring the server in three ways Review the knowledge of WebpackI have simplified the directory structure after this: my webpack.config.js:
var webpack = require (' webpack ') var path =require (' path ') Module.exports = {entry:{   app:path.join (__dirname, ' src ', ' Index.js ')},output:{   filename: ' bundle.js ',   path:path.join (__dirname, ' Dist ')}  }

My src/index.js:

Require ('./a.js ') require ('./b.js ') console.log (' I am index.js ')
My src/a.js:
Console.log (' I am a.js ')
My src/b.js:
Console.log (' I am b.js ')
My dist/index.html:
/* Other parts omit */<body>  <script src= "./bundle.js" ></script></body>
When we run the "webpack" command at the terminal, the directory becomes:

A picture review the mechanism of Webpack:

OK, below, let's start building a server: How to build a server in the simplest way? 1. You need a module to installEnter the project directory in the terminal and tap npm install Webpack-dev-server--save-dev Enter 2. Run a command at the terminal:Node_modules/.bin/webpack-dev-server (online some say directly to lose webpack-dev-server that is wrong) success! The output is this section of information:

Then go to the default localhost:8080 page: The root directory of the server is our project directory here, we have to do the first step to success! After entering the Dist, we found that a mistake had been reported: what did not find bundle.js? So we're going to write the configuration in Webpack.config.js:
Module.exports = {/* omit entry and output here, refer to what is written above */  devserver: {       contentBase:path.join (__dirname, "dist")   }}
Save, then open the page to see the console, the error has disappeared! The contents of the packaged file are printed correctly:

Detailed Configuration properties for Webpack-dev-server

1.devserver.contentbaseContentbase is the first Webpack-dev-server configuration property We're going to talk about today, so what did Contentbase do? --it specifies the root directory of the server resource, and if the value of Contentbase is not written, then Contentbase is the project directory by default. In the example above, the cause of the error and the subsequent resolution of the error: An error occurred: because Bundle.js was "Put it in."Our project root directory, in dist/html <script src= "./bundle.js" ></script> at this time obviously cannot find bundle.js to resolve the error according to the path: by configuring Contentbase: Path.join (__dirname, "Dist") will Bundle.js "Put it in."Dist directory, Bundle.js and dist/index.html are located in the same directory, through the src= "./bundle.js" naturally found bundle.js. the difference between Webpack packaging and webpack-dev-server opening services--Webpack output real files, and webpack-dev-server output files only exist in memory, do not output real files! (Note the difference between the two charts below) Webpack: When we Run "Webpack" in the terminal:

Webpack-dev-server: When we Run "node_modules/.bin/webpack-dev-server" in the terminal: That's why I put Bundle.js "in" with double quotes in the above description 2.devserver.portThe Port configuration property specifies the port number on which the service is opened:
Devserver: {   port:7000}
Set the port number to 7000: run: Node_modules/.bin/webpack-dev-server This time is not the default 8080 port, but we set the 7000 3.devserver.hostHost is set to the server's hostname: Modify the configuration to:
Devserver: {   contentBase:path.join (__dirname, "Dist"),   port:7000,   host: ' 0.0.0.0 '}

At this point localhost:7000 and 0.0.0.0:7000 both have access to success 4.devserver.historyapifallbackIt's very clear in the document, This configuration property is used to target a specific page when returning 404 pages(The index.html page would likely has the to being served in place of any 404 responses) add an HTML page in the Dist directory:
/* The rest is very regular HTML content, so omit */<p> here is the 404 interface </p>
We modified the webpack.config.js as follows:
Module.exports = {/* Here omit entry and output, referring to what is written above */devserver: {contentBase:path.join (__dirname, "dist"), historyapifallback:{   rewrites:[      {from:/./,to: '/404.html '}   ]  }}}
Open the page and enter a non-existent routing address:

5.devserver.overlayThis configuration property is used to display errors on the browser page when compiling an error, the default is False, and can be set to true first we artificially create a compile error: Use ES6 notation in a project where we have not configured Babel loader: write in Src/index.js Const A "prompts a compiler error in the shell: but there is no hint in the browser: so we changed the webpack.config.js to:
Module.exports = {     /* omit entry and output here, refer to what is written above */   devserver: {       contentBase:path.join (__dirname, "dist") ,       overlay:true   }}
Re-run Node_modules/.bin/webpack-dev-server, the browser shows the error

6.devserver.stats (String)This configuration property is used to control the output of the shell when compiling, we do not set the devserver.stats when the compiler output is like this: (which seems to have a lot of seemingly unimportant files are also printed)

stats: "errors-only" means printing errors only:We changed the configuration to:
Devserver: {   contentBase:path.join (__dirname, "Dist"),   stats: "Errors-only"}
Because only the error is printed, so, most of the information is skipped in addition to "minimal", "normal", "verbose", here do not repeat 7.devserver.quietWhen this configuration property and Devserver.stats belong to the same type of configuration property when it is set to true, the console outputs only the information that was compiled for the first time, do not output any content, including errors and warnings, when you compile again after savingLet's make a comparison: Quiet:false (default):First compilation: Second compilation (When you Save)

Quiet:true

First compilation Ibid. second compilation nothing output "Spit Groove" like this look like this configuration seems to have only a negative effect .... 8.devserver.compressThis is a Boolean value when it is set to True when you use gzip compression for all server resources with the advantages and disadvantages of gzip compression: Advantages: The compression rate of JS,CSS resources is very high, can greatly improve the rate of file transfer, To improve Web performance disadvantage: The server to compress the file, and the client to decompress, increase the load on both sides 9.devserver.hot and Devserver.inlineBefore that, the first thing to say is the Webpack-dev-server automatic refresh and module hot swap mechanism Webpack-dev-server automatic refresh and module hot-swap mechanismThese two mechanisms are tightly linked. from an external point of view-Auto RefreshWhen we make some changes to the business code and then save (command+s), the page refreshes automatically, and the changes we make are synced directly to the page without needing us to refresh the page or reopen the service (the Webpack-dev-server supports Multiple modes to automatically refresh the page) from the internal point of view-module hot swapIn the heat substitution (HMR) mechanism, instead of overloading the entire page, the HMR program loads only the part of the module that was updated, and then injects it into the running app (in hot Module replacement, the bundle was notified that a Change happened. Rather than a full page reload, a hot Module replacement runtime could then load the updated modules and inject them into A running app.) Webpack-dev-server has two modes for automatic refresh and module hot-swap mechanism1. Iframe mode (default, no configuration required)The page is embedded in an IFRAME and reloads the page 2.inline when the module changes Mode (required configuration) added to Bundle.js when the page is refreshed, a small client is added to the Webpack.config.js portal file, for example, in our example, after a hot replacement using the inline mode, the import file is equivalent to the
entry:{    app:path.join (__dirname, ' src ', ' index.js ')}
has become:
entry:{    app:[path.join (__dirname, ' src ', ' index.js '),             ' webpack-dev-server/client?http://localhost:8080/'          ]}
Changed from one entry to two entrances and refreshed How can I refresh the inline mode? You need to do this: 1 write devServer.hot:true and devServer.inline:true2 in the configuration add a plug-in configuration Webpack.hotmodulereplacementplugin () For example:
var webpack = require (' webpack ') Module.exports = {/   * omit entry, OUTPUT, etc. */   plugins:[        new Webpack. Hotmodulereplacementplugin ()    ],   devserver: {        inline:true,        hot:true    }}
Open the page: if there are two lines above the output indicates that you have been configured successfully there is also a problem, that is, every time the direct input node_modules/.bin/webpack-dev-server to start the server is a great pain for us, So how to simplify this process? Answer: Write this running script in Package.json! Here I write my package.json:
{   "name": "WebpackTest2",   "dependencies": {}, "   devdependencies": {},   "scripts": {       "Start" : "Node_modules/.bin/webpack-dev-server"     }}
Run NPM start on Terminal: Run successfully! three ways to configure services:1 Write configuration in the Devserver attribute in the Webpack.config.js output object (that is, the practice of all our examples above) 2 is written in Package.json, written in the script corresponding to the node command, for example we can write: "Scripts": {" Start ":" Node_modules/.bin/webpack-dev-server--port 8000--inline True "} (but this is obviously not a recommended way) 3 uses the Pure node API implementation, Here is an example of an official given
var config = require ("./webpack.config.js"); Config.entry.app.unshift ("Webpack-dev-server/client?http://localhost : 8080/"), var compiler = Webpack (config), var server = new Webpackdevserver (compiler, {/       * We write to config place */}); Server.listen (8080);

Build a Webpack Micro server

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.