工欲善其事,必先利其器。javascript
本地开发须要起一个本地服务,”http:localhost:8080“访问的就是咱们在本机上的8080端口开启的服务。这个服务机制是谁搞的呢?答案是:webpack-dev-server。而且为了保证热加载的速度够快,webpack-dev-server将webpack build出来的代码直接保存到内存中,便于读取与更改。html
既然webpack-dev-server使用的是内存中的build资源,那咱们在磁盘中看到的webpack build出来的文件(默认是放在dist目录下的)是干吗的呢?java
答案是:用于部署到线上机器上的。一个构建机器负责build一份代码(放在磁盘上的path下),而后部署到线上服务上,客户端访问的资源就是在这个线上服务上的。webpack
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},复制代码
webpack build以后代码存储在磁盘上的位置。本地开发时用不到这个path下的资源,线上部署的时候用这个build出来的资源去发布线上机器。web
在本地开发时webpack-dev-server访问的是内存中的build资源。而客户端的线上环境,才是由构建机器build出来的保存在path目录下,并部署到线上机器的资源。可是客户端咋知道咱们的机器的地址呢?答案就是:publicPath。publicPath在本地环境指的是webpack-dev-server运行的内存代码的地址;在线上环境,publicPath就表明着客户端所访问的上线资源地址。json
总之,publicPath就是客户端访问的资源的地址。bash
当publicPath是相对路径时,资源路径是相对于index.html文件的;当publicPath
是绝对路径时,资源的被访问路径前缀直接就是这个绝对路径;app
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: 'http://localhost:8080/'
},复制代码
这里,publicPath是绝对路径,则页面中webpack build出来的a.js文件代码的路径就是http://localhost:8080/a.bundle.js =>
${域名}+${publicPath}+${文件名}.bundle.js
webpack-dev-server
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: 'outdist'
},复制代码
这里,publicPath是相对路径,则页面中webpack build出来的a.js文件代码的路径就是http://localhost:8080/
outdist
/a.bundle.js
=>
${publicPath}+${文件名}.bundle.js
ui
/* package.json */
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack-dev-server --open --mode development"
},复制代码
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: '[name].[hash].js',
path: path.resolve(__dirname, 'dist'),
publicPath: "outDist",
},
mode: 'development',
module: {
},
devtool: 'source-map',
devServer: {
contentBase: path.resolve(__dirname, "contentdist"),
port: 8080,
host: 'localhost',
overlay: true,
compress: true,
},
}复制代码
咱们运行yarn dev( "dev": "webpack-dev-server --open --mode development")
webpack output is served from /outDist
Content not from webpack is served from /Users/panzhiying/study/webpack4-init/contentdist
Hash: c042bc2a7a1f180291f8复制代码
因为咱们的html文档也是静态资源,因此此时页面的访问路径是:http://localhost:8080/outdist。
咱们运行yarn build("build": "webpack"),