12. devServer

232 阅读2分钟

相关代码

开发环境下,我们往往需要启动一个 web 服务,方便我们模拟一个用户从浏览器中访问我们的 web 服务,读取我们的打包产物,以观测我们的代码在客户端的表现。Webpack 内置了这样的功能,我们只需要简单的配置就可以开启它。

一、基本使用

npm install webpack-dev-server -D
const { resolve } = require('path')

module.exports = {
    devServer: {
        static: resolve(__dirname, './dist'),
        compress: true,
        port: 3000,
    },
}
  • static: resolve(__dirname, './dist'):把 dist 目录当作 web 服务的根目录
  • compress: true:是否在服务器端进行代码压缩,开启 gzips 压缩功能,对应静态资源请求响应头里的 Content-Encoding: gzip
  • port: 3000:配置服务的端口号

webpack-dev-server 的最底层实现是源自于 node 的 http 模块。

二、添加响应头

在有些场景下,我们需要将一些头部信息,通过 http 传输给浏览器。通过 headers 可以配置任何我们想要的头部信息。

比如传一个 token 信息给浏览器:

module.exports = {
    devServer: {
        headers: {
            'X-Access-Token': 'abc123'
        }
    },
}

在浏览器中查看:

image.png

三、开启代理

使用 devServer 自带的 proxy 功能开启代理,可以让我们进行跨域请求。

webpack.config.js:

module.exports = {
    devServer: {
        proxy: {
            '/api': 'http://localhost:9000'     // 当请求 /api,会指向到新的服务器地址
        }
    },
}

server.js:

const http = require('http')

const app = http.createServer((req, res) => {
    if (req.url === '/api/hello') {
        res.end('hello node')
    }
})

app.listen(9000, 'localhost', () => {
    console.log('localhost: 9000')
})

入口文件 app.js:

fetch('/api/hello')
    .then(response => response.text())
    .then(result => {
        console.log('result:', result)
    })

四、https 与 http2

1. https

开启 https 服务:

module.exports = {
    devServer: {
        https: true
    },
}

image.png

2. http2

module.exports = {
    devServer: {
        http2: true
    },
}

五、historyApiFallback

如果我们的应用是个SPA(单页面应用),当路由到 /home 时(可以直接在地址栏里输入),会发现此时刷新页面后,控制台会报错。

image.png

因为浏览器把这个路由当作静态资源地址去请求,然而我们并没有打包出 /home 这样的资源,所以会 404。此时,我们可以通过配置来提供页面代替任何 404 的静态资源响应。

module.exports = {
    devServer: {
        historyApiFallback: true
    },
}

当然,在多数业务场景下,我们需要根据不同的访问路径定制替代的页面,这种情况下,我们可以使用 rewrites 这个配置项。如:

module.exports = {
    devServer: {
        historyApiFallback: {
            rewrites: [
                { from: /^\/$/, to: '/views/landing.html' },
                { from: /^\/subpage/, to: '/views/subpage.html' },
                { from: /./, to: '/views/404.html' },
            ],
        }
    },
}

六、开发服务器主机

如果在开发环境中起了一个 devserve 服务,并期望你的同事能访问到它,你只需要配置:

module.exports = {
    devServer: {
        host: '0.0.0.0'
    },
}

image.png

此时,如果你的同事跟你处在同一局域网下,就可以通过局域网 IP 来访问你的服务。