webpack中path、publicPath的关系

2,574 阅读2分钟

前序

工欲善其事,必先利其器。

本地开发

本地开发需要起一个本地服务,”http:localhost:8080“访问的就是我们在本机上的8080端口开启的服务。这个服务机制是谁搞的呢?答案是:webpack-dev-server。并且为了保证热加载的速度够快,webpack-dev-server将webpack build出来的代码直接保存到内存中,便于读取与更改。

线上部署

既然webpack-dev-server使用的是内存中的build资源,那我们在磁盘中看到的webpack build出来的文件(默认是放在dist目录下的)是干嘛的呢?

答案是:用于部署到线上机器上的。一个构建机器负责build一份代码(放在磁盘上的path下),然后部署到线上服务上,客户端访问的资源就是在这个线上服务上的。

path

output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
},

webpack build之后代码存储在磁盘上的位置。本地开发时用不到这个path下的资源,线上部署的时候用这个build出来的资源去发布线上机器。

publicPath

在本地开发时webpack-dev-server访问的是内存中的build资源。而客户端的线上环境,才是由构建机器build出来的保存在path目录下,并部署到线上机器的资源。但是客户端咋知道我们的机器的地址呢?答案就是:publicPath。publicPath在本地环境指的是webpack-dev-server运行的内存代码的地址;在线上环境,publicPath就代表着客户端所访问的上线资源地址。

总之,publicPath就是客户端访问的资源的地址。

publicPath是相对路径时,资源路径是相对于index.html文件的;当publicPath  是绝对路径时,资源的被访问路径前缀直接就是这个绝对路径

 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

 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

实践

/* 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-dev-server上运行的代码是在内存中的outDist下
),而非webpack产物的其他静态资源是在
contentdist目录下。

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"),

项目里会多出一个
dist目录,里面是webpack的编译产物。