search
HomeWeb Front-endJS TutorialHow to build a webpack microserver?
How to build a webpack microserver?Jun 26, 2017 pm 01:36 PM
webwebpackgoodus

[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')
  }
}

My src/index .js:

require('./a.js')
require('./b.js')
console.log('我是index.js')
my src/a.js:
console.log('我是a.js')
My src/b.js:
console.log('我是b.js')
My dist /index.html:
/*其他部分省略*/  <script></script>
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")
   }
}
保存,后打开页面看控制台,报错已经消失了!正确打印了被打包的文件内容:
 

详解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}
设置端口号为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'}

 

此时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>
 
我们把webpack.config.js修改如下:
module.exports = {/*这里省略entry和output,参照上面写的内容*/devServer: {
contentBase: path.join(__dirname, "dist"),
historyApiFallback:{
   rewrites:[
      {from:/./,to:'/404.html'}
   ]
  }
 }
}
 
打开页面,输入一个不存在的路由地址:

 

 
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
   }
}
 
再重新运行node_modules/.bin/webpack-dev-server,浏览器上把错误显示出来了

 

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

 

stats: "errors-only"表示只打印错误:
我们把配置改成:
devServer: {
   contentBase: path.join(__dirname, "dist"),
   stats: "errors-only"}
 
因为只有错误才被打印,所以,大多数信息都略过了
除此之外还有"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')
}
变成了:
entry:{
    app:[path.join(__dirname,'src','index.js'),             'webpack-dev-server/client?http://localhost:8080/'  ]
}
从一个入口变成了两个入口,并实现刷新
 
那怎么才能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}
}
 
打开页面:
如果有上面两行输出则表明你已经配置成功
 
现在还有一个问题,那就是每次直接输入node_modules/.bin/webpack-dev-server来启动服务器对我们来说简直就是莫大的痛苦,那么怎么对这一过程进行简化呢?
答案:把这个运行脚本写到package.json里就行了!
 
这里我把我的package.json写成:
{   "name": "webpackTest2",   "dependencies": {},   "devDependencies": {},   "scripts": {       "start": "node_modules/.bin/webpack-dev-server" }
}
 
在终端运行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);

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
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
VUE3入门教程:使用Webpack进行打包和构建VUE3入门教程:使用Webpack进行打包和构建Jun 15, 2023 pm 06:17 PM

Vue是一款优秀的JavaScript框架,它可以帮助我们快速构建交互性强、高效性好的Web应用程序。Vue3是Vue的最新版本,它引入了很多新的特性和功能。Webpack是目前最流行的JavaScript模块打包器和构建工具之一,它可以帮助我们管理项目中的各种资源。本文就为大家介绍如何使用Webpack打包和构建Vue3应用程序。1.安装Webpack

vite和webpack的区别是什么vite和webpack的区别是什么Jan 11, 2023 pm 02:55 PM

区别:1、webpack服务器启动速度比vite慢;由于vite启动的时候不需要打包,也就无需分析模块依赖、编译,所以启动速度非常快。2、vite热更新比webpack快;vite在HRM方面,当某个模块内容改变时,让浏览器去重新请求该模块即可。3、vite用esbuild预构建依赖,而webpack基于node。4、vite的生态不及webpack,加载器、插件不够丰富。

如何使用PHP和webpack进行模块化开发如何使用PHP和webpack进行模块化开发May 11, 2023 pm 03:52 PM

随着Web开发技术的不断发展,前后端分离、模块化开发已经成为了一个广泛的趋势。PHP作为一种常用的后端语言,在进行模块化开发时,我们需要借助一些工具来实现模块的管理和打包,其中webpack是一个非常好用的模块化打包工具。本文将介绍如何使用PHP和webpack进行模块化开发。一、什么是模块化开发模块化开发是指将程序分解成不同的独立模块,每个模块都有自己的作

vue webpack可打包哪些文件vue webpack可打包哪些文件Dec 20, 2022 pm 07:44 PM

在vue中,webpack可以将js、css、图片、json等文件打包为合适的格式,以供浏览器使用;在webpack中js、css、图片、json等文件类型都可以被当做模块来使用。webpack中各种模块资源可打包合并成一个或多个包,并且在打包的过程中,可以对资源进行处理,如压缩图片、将scss转成css、将ES6语法转成ES5等可以被html识别的文件类型。

Webpack是什么?详解它是如何工作的?Webpack是什么?详解它是如何工作的?Oct 13, 2022 pm 07:36 PM

Webpack是一款模块打包工具。它为不同的依赖创建模块,将其整体打包成可管理的输出文件。这一点对于单页面应用(如今Web应用的事实标准)来说特别有用。

webpack怎么将es6转成es5的模块webpack怎么将es6转成es5的模块Oct 18, 2022 pm 03:48 PM

配置方法:1、用导入的方法把ES6代码放到打包的js代码文件中;2、利用npm工具安装babel-loader工具,语法“npm install -D babel-loader @babel/core @babel/preset-env”;3、创建babel工具的配置文件“.babelrc”并设定转码规则;4、在webpack.config.js文件中配置打包规则即可。

web前端打包工具有哪些web前端打包工具有哪些Aug 23, 2022 pm 05:31 PM

web前端打包工具有:1、Webpack,是一个模块化管理工具和打包工具可以将不同模块的文件打包整合在一起,并且保证它们之间的引用正确,执行有序;2、Grunt,一个前端打包构建工具;3、Gulp,用代码方式来写打包脚本;4、Rollup,ES6模块化打包工具;5、Parcel,一款速度极快、零配置的web应用程序打包器;6、equireJS,是一个JS文件和模块加载器。

web是前端还是后端web是前端还是后端Aug 24, 2022 pm 04:10 PM

web有前端,也有后端。web前端也被称为“客户端”,是关于用户可以看到和体验的网站的视觉方面,即用户所看到的一切Web浏览器展示的内容,涉及用户可以看到,触摸和体验的一切。web后端也称为“服务器端”,是用户在浏览器中无法查看和交互的所有内容,web后端负责存储和组织数据,并确保web前端的所有内容都能正常工作。web后端与前端通信,发送和接收信息以显示为网页。

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.