webpack(9)_使用webpack-dev-server

版权声明:本博客主要记录学习笔记和遇到的一些问题解决方案,转载请注明出处! https://blog.csdn.net/u010982507/article/details/82056221

webpack-dev-server

webpack-dev-server插件能够为本地提供一个node.js服务,来运行当前的html文件。
1、live reloading
2、路径重定向
3、https
4、浏览器中显示编译错误
5、接口代理
6、模块热更新

webpack-dev-server的使用

  • 安装
    npm install webpack-dev-server --save-dev
  • 在package..json中配置
"scripts": {
  "dev":"webpack-dev-server --open"
}
// 配置好之后就可以在控制台,使用`npm run dev`来开启服务。
  • 在webpack.config.js中配置端口
devServer: {
    port: '8888',
}

devServer中设置路径重定向

  • 如果在页面中请求一个url,需要配置一些公共请求时,则需要在proxy代理中,配置相关属性。
// 在index页面请求微博一个数据接口
import axios from 'axios';
axios.get('/comments/show', {
    params: {
        id: '4193586758833502',
        page: 1
    }
}).then((data) => {
    console.log(data.data)
})
  • 在webpack.config.js中配置重写规则
devServer: {
      port: '8888',
      //inline:false // inline为false的iFrame模式,会将打包过程显示在页面上,不会在控制台输出
      proxy: {
          '/': {
              target: 'https://m.weibo.cn', // 以/api开头的请求就指向target
              changeOrigin: true, // 改变请求源 localhost:改成微博https://m.weibo.cn
              logLevel: 'debug', // 可在控制台查看接口代理的信息,[HPM] GET /api/comments/show?id=4193586758833502&page=1 -> https://m.weibo.cn
              pathRewrite: { // 请求路径的重写规则
                  '^/comments': '/api/comments'
              },
              headers: { // 设置头信息
                  'Cookie':''
              }
          }
      },
      historyApiFallback: { // 对history中路径进行规则制定
          rewrites: [
              /*  {
               from: '/pages/a', // 在浏览器中输入http://localhost:8888/pages/a会定位到http://localhost:8888/pages/a.html
               to: '/pages/a.html'
               }*/
              {
                  from: /^\/([a-zA-Z0-9]+\/?)([a-zA-Z0-9]+)/,// 配置正则
                  to: function (context) {
                      return '/' + context.match[1] + context.match[2] + '.html'; // 返回当前匹配的html
                  }
              }
          ]
      }
  }

devServer中设置模块热更新

  • 配置devServer
devServer: {
      hot:true
}
  • 配置plugins
new webpack.HotModuleReplacementPlugin(), // 模块热更新插件
new webpack.NamedModulesPlugin() // 能看到模块打包的路径

  • 若要改变样式,需要使用css-loader和style-loader处理css。

SourceMap调试

1、js的SourceMap
- 设置devtool

devtool: 'cheap-module-source-map', 
//eval,source-map 在控制台显示文件名和行号,并且点击文件会看到js代码
  • 设置uglifyjs-webpack-plugin
var UglifyJSPlugin = require("uglifyjs-webpack-plugin");
....
plugins: [
    new CleanWebpackPlugin(['dist']),
    new UglifyJSPlugin({
        sourceMap: true // 开启sourceMap,不开启的话查看js代码就是压缩后的代码,开启后看到的是未压缩的源代码
    })
]

2、css的SourceMap
需要在style-loader、css-loader、postcss-loader中设置SourceMap

options: {
    //singleton: true, // 一个文件的时候是定位不到行号的,所以要去掉
    sourceMap:true, // 设置sourceMap,true
    insertAt: 'top'
}

猜你喜欢

转载自blog.csdn.net/u010982507/article/details/82056221