自动编译和刷新浏览器

安装 webpack-dev-server 即可实现。webpack 不运行打包,它只是将结果存储在内存中。”—open” 可以自动打开浏览器。

  1. yarn webpack-dev-server --open
  2. // webpack 5可以写成
  3. yarn webpack serve --open

Dev Server 静态资源访问

配置文件中指定额外资源路径。

  1. // webpack.config.js
  2. devServer: {
  3. contentBase: ['./public']
  4. },

Dev Server 代理 API

Dev Server 支持配置代理,在服务端不支持 CORS 的时候,通过配置可以将 API 代理到开发服务器。

  1. devServer: {
  2. contentBase: ['./public'],
  3. proxy: { // 代理配置属性
  4. '/api': { // 需要被代理的请求路径前缀
  5. // http://localhost:8080/api/users -> https://api.github.com/api/users
  6. target: 'https://api.github.com', // 代理目标
  7. // http://localhost:8080/api/users -> https://api.github.com/users
  8. pathRewrite: {
  9. '^/api': ''
  10. },
  11. //changeOrigin是false:请求头中host仍然是浏览器发送过来的host,在这里就是 localhost:8080;如果设置成true:发送请求头中host会设置成target
  12. // 不能使用 localhost:8080 作为请求 GitHub 的主机名,所以设置为 true , 这样请求时主机名就是 https://api.github.com
  13. changeOrigin: true
  14. }
  15. },
  16. },

示例:

  1. // ======================== fetch proxy api example ========================
  2. const ul = document.createElement('ul')
  3. document.body.append(ul)
  4. // 跨域请求,虽然 GitHub 支持 CORS,但是不是每个服务端都应该支持。
  5. // fetch('https://api.github.com/users')
  6. fetch('/api/users') // http://localhost:8080/api/users
  7. .then(res => res.json())
  8. .then(data => {
  9. data.forEach(item => {
  10. const li = document.createElement('li')
  11. li.textContent = item.login
  12. ul.append(li)
  13. })
  14. })