Home Web Front-end JS Tutorial How to build a webpack microserver?

How to build a webpack microserver?

Jun 26, 2017 pm 01:36 PM
web webpack good us

[Preface]: Because I recently used webpack’s externals when working on Baidu Map API, I discovered that I had only used webpack to do some things before. The "finishing work" after building the project - that is, packaging, without incorporating it into the "main process" of project development, is really "not making the best use of it". So here is my learning article today: Use webpack-dev-server to build a webpack server
Reference:
webpack-dev-server’s github address:
webpack1 official documentationhttp://webpack.github.io/docs/webpack-dev-server.html (It is recommended to read the document of 2)
webpack2 official document (It is recommended to read this)
Outline:
1. Review webpack Knowledge
2. Detailed explanation of the configuration properties of webpack-dev-server
3. Automatic refresh and module hot replacement of webpack-dev-server Mechanism
4. Three ways to configure the server under webpack
Review webpack Knowledge
After I simplified the directory structure, it looks like 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')
  }
}
Copy after login

My src/index .js:

require('./a.js')
require('./b.js')
console.log('我是index.js')
Copy after login
my src/a.js:
console.log('我是a.js')
Copy after login
My src/b.js:
console.log('我是b.js')
Copy after login
My dist /index.html:
/*其他部分省略*/<body>  <script src="./bundle.js?1.1.11"></script></body>
Copy after login
When we run the "webpack" command in the terminal, the directory becomes:

A picture to review the mechanism of webpack:

OK, let’s start building a server:
How to use it best An easy way to set up a server?
1. You need to install a module
in the terminal Enter the project directory, type npm install webpack-dev-server --save-dev and press Enter
2. Run a command in the terminal:
node_modules/.bin/webpack-dev-server(网上有的说直接输webpack-dev-server那是错的)
 
成功!输出的是这一段信息:

 

然后进入默认的localhost:8080页面:
服务器的根目录就是我们工程的目录
 
到这里,我们要做的第一步就成功啦!
 
进入dist后,我们发现报了这样一段错误:
what?没有找到bundle.js?
 
所以我们要在webpack.config.js里写一下配置:
module.exports = {/*这里省略entry和output,参照上面写的内容*/
  devServer: {
       contentBase: path.join(__dirname, "dist")
   }
}
Copy after login
保存,后打开页面看控制台,报错已经消失了!正确打印了被打包的文件内容:
 

详解webpack-dev-server的配置属性 

1.devServer.contentBase
contentBase是我们今天要讲的第一个webpack-dev-server的配置属性,那么,contentBase做了什么事情呢?——它指定了服务器资源的根目录如果不写入contentBase的值,那么contentBase默认是项目的目录
在上面例子中产生错误和后来解决错误的原因:
产生错误:因为bundle.js被"放在了"我们的项目根目录里,在dist/html里此时显然不能根据路径找到bundle.js
解决错误:通过配置contentBase: path.join(__dirname, "dist")将bundle.js"放在了"dist目录下,此时bundle.js和dist/index.html位于同一目录下,通过 src="./bundle.js?1.1.11"自然就找到bundle.js了
 
webpack打包和webpack-dev-server开启服务的区别——
webpack输出真实的文件,而webpack-dev-server输出的文件只存在于内存中,不输出真实的文件!(注意下面两张图的区别)
 
webpack:当我们在终端运行"webpack"后:

 

webpack-dev-server:当我们在终端运行"node_modules/.bin/webpack-dev-server后:
这也就是我在上面的阐述中将bundle.js?1.1.11"放在了"加上双引号的原因
 
2.devServer.port
port配置属性指定了开启服务的端口号:
devServer: {
   port:7000}
Copy after login
设置端口号为7000:
运行:node_modules/.bin/webpack-dev-server
这个时候就不是默认的8080的端口了,而是我们设置的7000
 
3.devServer.host
host设置的是服务器的主机号:
修改配置为:
devServer: {
   contentBase: path.join(__dirname, "dist"),
   port:7000,
   host:'0.0.0.0'}
Copy after login

 

此时localhost:7000和0.0.0.0:7000都能访问成功
 
4.devServer.historyApiFallback
在文档里面说的很清楚,这个配置属性是用来应对返回404页面时定向到特定页面用的(the index.html page will likely have to be served in place of any 404 responses)
在dist目录下新增一个HTML页面:
/*剩下的都是很常规的HTML内容,故省略*/<p>这里是404界面</p>
Copy after login
 
我们把webpack.config.js修改如下:
module.exports = {/*这里省略entry和output,参照上面写的内容*/devServer: {
contentBase: path.join(__dirname, "dist"),
historyApiFallback:{
   rewrites:[
      {from:/./,to:'/404.html'}
   ]
  }
 }
}
Copy after login
 
打开页面,输入一个不存在的路由地址:

 

 
5.devServer.overlay
这个配置属性用来在编译出错的时候,在浏览器页面上显示错误,默认是false,可设置为true
首先我们人为制造一个编译错误:在我们尚未配置babel loader的项目里使用ES6写法:
在src/index.js里写入“const a”
在shell里提示编译错误:
 
但在浏览器里没有提示:
所以我们把webpack.config.js修改为:
module.exports = {     /*这里省略entry和output,参照上面写的内容*/
   devServer: {
       contentBase: path.join(__dirname, "dist"),
       overlay: true
   }
}
Copy after login
 
再重新运行node_modules/.bin/webpack-dev-server,浏览器上把错误显示出来了

 

6.devServer.stats(字符串)
 
这个配置属性用来控制编译的时候shell上的输出内容,我们没有设置devServer.stats时候编译输出是这样子的:
(其中看起来有许多看似不重要的文件也被打印出来了)

 

stats: "errors-only"表示只打印错误:
我们把配置改成:
devServer: {
   contentBase: path.join(__dirname, "dist"),
   stats: "errors-only"}
Copy after login
 
因为只有错误才被打印,所以,大多数信息都略过了
除此之外还有"minimal","normal","verbose",这里不多加赘述
 
7.devServer.quiet
当这个配置属性和devServer.stats属于同一类型的配置属性
当它被设置为true的时候,控制台只输出第一次编译的信息,当你保存后再次编译的时候不会输出任何内容,包括错误和警告
来做个对比吧:
quiet:false(默认):
第一次编译:
第二次编译(当你保存的时候)

quiet:true

第一次编译同上
第二次编译什么都不输出
【吐槽】这样看的话感觉这个配置好像只有负面作用呢.....
 
8.devServer.compress
这是一个布尔型的值,当它被设置为true的时候对所有的服务器资源采用gzip压缩
采用gzip压缩的优点和缺点:
优点:对JS,CSS资源的压缩率很高,可以极大得提高文件传输的速率,从而提升web性能
缺点:服务端要对文件进行压缩,而客户端要进行解压,增加了两边的负载
 
9.devServer.hot和devServer.inline
在这之前,首先要说一下的是webpack-dev-server的自动刷新和模块热替换机制
 
webpack-dev-server的自动刷新和模块热替换机制
 
这两个机制是紧紧联系在一起的
 
从外部角度看——自动刷新
当我们对业务代码做了一些修改然后保存后(command+s),页面会自动刷新,我们所做的修改会直接同步到页面上而不需要我们刷新页面,或重新开启服务
(The webpack-dev-server supports multiple modes to automatically refresh the page)
 
从内部角度看——模块热替换
在热替换(HMR)机制里,不是重载整个页面,HMR程序会只加载被更新的那一部分模块,然后将其注入到运行中的APP中
(In Hot Module Replacement, the bundle is 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有两种模式可以实现自动刷新和模块热替换机制
1. Iframe mode(默认,无需配置)
页面被嵌入在一个iframe里面,并且在模块变化的时候重载页面
2.inline mode(需配置)添加到bundle.js中
当刷新页面的时候,一个小型的客户端被添加到webpack.config.js的入口文件中
例如在我们的例子中,在使用inline mode的热替换后,相当于入口文件从
entry:{
    app:path.join(__dirname,'src','index.js')
}
Copy after login
变成了:
entry:{
    app:[path.join(__dirname,'src','index.js'),             'webpack-dev-server/client?http://localhost:8080/'  ]
}
Copy after login
从一个入口变成了两个入口,并实现刷新
 
那怎么才能inline mode模式的刷新呢?
 
你需要做这些:
1在配置中写入devServer.hot:true和devServer.inline:true
2增加一个插件配置webpack.HotModuleReplacementPlugin()
 
例如:
var webpack = require('webpack')
module.exports = {   /*省略entry ,output等内容*/
   plugins:[new webpack.HotModuleReplacementPlugin()
    ],
   devServer: {
        inline:true,
        hot:true}
}
Copy after login
 
打开页面:
如果有上面两行输出则表明你已经配置成功
 
现在还有一个问题,那就是每次直接输入node_modules/.bin/webpack-dev-server来启动服务器对我们来说简直就是莫大的痛苦,那么怎么对这一过程进行简化呢?
答案:把这个运行脚本写到package.json里就行了!
 
这里我把我的package.json写成:
{   "name": "webpackTest2",   "dependencies": {},   "devDependencies": {},   "scripts": {       "start": "node_modules/.bin/webpack-dev-server" }
}
Copy after login
 
在终端运行npm start:
运行成功!
 
配置服务的三种方式:
 
1在webpack.config.js输出对象中的devServer属性中写配置(也就是我们上述所有例子的做法)
 
2写在package.json中,写在node 命令对应的脚本中,例如我们可以写成:
"scripts": {
"start": "node_modules/.bin/webpack-dev-server --port 8000 --inline true "
}
(但这显然并不是一个值得推荐的方式)
 
3使用纯node的API实现,下面是一个官方给的例子
var config = require("./webpack.config.js?1.1.11");
config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080/");var compiler = webpack(config);var server = new WebpackDevServer(compiler, {       /*我们写入配置的地方*/});
server.listen(8080);
Copy after login

The above is the detailed content of How to build a webpack microserver?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VUE3 Getting Started Tutorial: Packaging and Building with Webpack VUE3 Getting Started Tutorial: Packaging and Building with Webpack Jun 15, 2023 pm 06:17 PM

Vue is an excellent JavaScript framework that can help us quickly build interactive and efficient web applications. Vue3 is the latest version of Vue, which introduces many new features and functionality. Webpack is currently one of the most popular JavaScript module packagers and build tools, which can help us manage various resources in our projects. This article will introduce how to use Webpack to package and build Vue3 applications. 1. Install Webpack

Using Jetty7 for Web server processing in Java API development Using Jetty7 for Web server processing in Java API development Jun 18, 2023 am 10:42 AM

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

Real-time protection against face-blocking barrages on the web (based on machine learning) Real-time protection against face-blocking barrages on the web (based on machine learning) Jun 10, 2023 pm 01:03 PM

Face-blocking barrage means that a large number of barrages float by without blocking the person in the video, making it look like they are floating from behind the person. Machine learning has been popular for several years, but many people don’t know that these capabilities can also be run in browsers. This article introduces the practical optimization process in video barrages. At the end of the article, it lists some applicable scenarios for this solution, hoping to open it up. Some ideas. mediapipeDemo (https://google.github.io/mediapipe/) demonstrates the mainstream implementation principle of face-blocking barrage on-demand up upload. The server background calculation extracts the portrait area in the video screen, and converts it into svg storage while the client plays the video. Download svg from the server and combine it with barrage, portrait

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

Use Spring Boot and Webpack to build front-end projects and plug-in systems Use Spring Boot and Webpack to build front-end projects and plug-in systems Jun 22, 2023 am 09:13 AM

As the complexity of modern web applications continues to increase, building excellent front-end engineering and plug-in systems has become increasingly important. With the popularity of Spring Boot and Webpack, they have become a perfect combination for building front-end projects and plug-in systems. SpringBoot is a Java framework that creates Java applications with minimal configuration requirements. It provides many useful features, such as automatic configuration, so that developers can build and deploy web applications faster and easier. W

See all articles