webpack-dev-server原理及要点笔记

webpack-dev-server启动了一个使用express的Http服务器,这个服务器与客户端采用websocket通讯协议当原始文件发生改变,webpack-dev-server会实时编译css

这里注意两点:html

1.webpack-dev-server伺服的是资源文件,不会对index.html的修改作出反应vue

2.webpack-dev-server生成的文件在内存中,所以不会呈现于目录中生成路径由content-base指定,不会输出到output目录中。react

3.默认状况下: webpack-dev-server会在content-base路径下寻找index.html做为首页webpack

4.webpack-dev-server不是一个插件,而是一个web服务器,因此不要想固然地将其引入web

content-base 用于设定生成的文件所在目录express

eg:sass

const path = require('path');
const HtmlWebpackPlugin= require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin')
var ManifestPlugin = require('webpack-manifest-plugin');
const webpack= require('webpack');

module.exports = {
  entry: {
    main: './src/main.js'
  },
  devServer: {
      historyApiFallback: true,
      noInfo: true,
      contentBase: './dist'    
  },
  module: {
      rules: [
      {
          test: /\.css$/,
          use: ['style-loader', 'css-loader']
      },{
         test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
              name: '[name].[ext]?[hash]'
        }
    },{
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
              loaders: {
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
              }
        }
      }
      ]
  },
  devtool: 'inline-source-map',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
    },
};

这里设定在dist文件夹下生成文件,可以看到dist文件夹下未生成文件(index.html是本人手动建立的),而index.html的引入路径应为<script src="./main.js"></script>服务器

必须注意的是: 若是配置了output的publicPath这个字段的值的话,index.html的路径也得作出相应修改,由于webpack-dev-server伺服的文件时相对于publicPath这个路径的websocket

那么,若是:

output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/a/'
}

那么,index.html的路径为: <script src="./a/main.js">

 

内联模式(inline mode)和iframe模式

webpack-dev-server默认采用内联模式,iframe模式与内联模式最大的区别是它的原理是在网页中嵌入一个iframe

咱们能够将devServer的inline设为false切换为iframe模式

devServer: {
     historyApiFallback: true,
    noInfo: true,
    contentBase: './dist',
    inline: false
 }

能够发现:

能够发现咱们的网页被嵌入iframe中。

 

模块热替换

webpack-dev-server有两种方式开启热替换

1.经过在devServer内将hot设为true并初始化webpack.HotModuleReplacementPlugin

2.命令行加入--hot(若是webpack或者webpack-dev-server开启时追加了--hot, 上述插件能自动初始化,这样就无需加入配置文件中)

而后在入口文件中加入热替换处理代码:

if (module.hot) {
  //当chunk1.js发生改变时热替换 module.hot.accept(
'./chunk1.js', function() { console.log('chunk1更新啦'); }) }

默认状况下,因为style-loader的帮助,css的模板热替换很简单,当发生改变时,style-loader会在后台使用module.hot.accept来修补style,同理,有许多loader有相似功能,例如vue-loader、react-hot-loader...

js文件发生改变会触发刷新而不是热替换,所以得加上处理语句,详情可查看: 

https://doc.webpack-china.org/guides/hot-module-replacement

相关文章
相关标签/搜索