自动编译和刷新浏览器
安装 webpack-dev-server 即可实现。webpack 不运行打包,它只是将结果存储在内存中。”—open” 可以自动打开浏览器。
yarn webpack-dev-server --open// webpack 5可以写成yarn webpack serve --open
Dev Server 静态资源访问
配置文件中指定额外资源路径。
// webpack.config.jsdevServer: {contentBase: ['./public']},
Dev Server 代理 API
Dev Server 支持配置代理,在服务端不支持 CORS 的时候,通过配置可以将 API 代理到开发服务器。
devServer: {contentBase: ['./public'],proxy: { // 代理配置属性'/api': { // 需要被代理的请求路径前缀// http://localhost:8080/api/users -> https://api.github.com/api/userstarget: 'https://api.github.com', // 代理目标// http://localhost:8080/api/users -> https://api.github.com/userspathRewrite: {'^/api': ''},//changeOrigin是false:请求头中host仍然是浏览器发送过来的host,在这里就是 localhost:8080;如果设置成true:发送请求头中host会设置成target// 不能使用 localhost:8080 作为请求 GitHub 的主机名,所以设置为 true , 这样请求时主机名就是 https://api.github.comchangeOrigin: true}},},
示例:
// ======================== fetch proxy api example ========================const ul = document.createElement('ul')document.body.append(ul)// 跨域请求,虽然 GitHub 支持 CORS,但是不是每个服务端都应该支持。// fetch('https://api.github.com/users')fetch('/api/users') // http://localhost:8080/api/users.then(res => res.json()).then(data => {data.forEach(item => {const li = document.createElement('li')li.textContent = item.loginul.append(li)})})
