webpack4-04-配置devServer服务器,热更新、热替换

配置devServer服务器、热更新

在实际开发过程当中,咱们但愿每次修改文件都会帮咱们自动的刷新修改的页面或者部分被修改的内容,让开发更加高效,因此咱们就须要为咱们的项目提供一个简单的web服务器(webpack-dev-server),该服务器可以实现时从新加载(live reloading)、热替换的功能。css

安装html

npm i webpack-dev-server -D
复制代码

修改 webpack.config.jswebpack

...
const webpack = require('webpack')  // 新增

const resolve = (dir) =>  path.resolve(__dirname, dir)
module.exports = {
  mode: 'development',
  entry: {
    ...
  },
  output: {
    ...
  },
  devServer: {                  // 新增
    open: true,                 // +
    hot: true,                  // +
    port: 3002,                 // +
    publicPath: '/'             // +
    contentBase: './dist'       // +
  },                            // 新增
  module: {
    ...
  },
  plugins: [
    ...
    new webpack.NamedModulesPlugin(),           // +
    new webpack.HotModuleReplacementPlugin()    // +
  ]
} 
复制代码
  • 在配置中新增devServer选项
  1. open:服务器启动成功后,将自动打开浏览器
  2. hot:启用模块热替换功能(备注①)
  3. port:指定要监听的端口号
  4. publicPath:将用于肯定应该从哪里提供资源、此路径下的打包文件可在浏览器中访问,优先级高于contentBase
  5. contentBase:告诉服务器从哪里提供内容。
  6. .....更多参数请前往官网

备注①:在配置文件中开启hot时,须要配合HotModuleReplacementPlugin才能彻底启用HMR。 若是使用package.json内联--hot选项启动webpack或webpack-dev-server,则会自动添加此插件,所以您可能不须要将其添加到webpack.config.js。git

内联以下:github

{
    ...
    "scripts": {
        "serve": "npx webpack-dev-server --hot --config ./build/webpack.config.js"
    }
    ...
}
复制代码
  • 新增webpack内置插件
  1. NamedModulesPlugin:在热加载时直接返回更新文件名,而不是文件的id。
  2. HotModuleReplacementPlugin:热替换插件

修改 package.jsonweb

在scripts中添加serve选项,以下:npm

{
  "name": "lesson-04",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "serve": "npx webpack-dev-server --config ./build/webpack.config.js",
    "dev": "npx webpack --config ./build/webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.4.4",
    "@babel/polyfill": "^7.4.4",
    "@babel/preset-env": "^7.4.4",
    "autoprefixer": "^9.5.1",
    "babel-loader": "^8.0.5",
    "clean-webpack-plugin": "^2.0.1",
    "css-loader": "^2.1.1",
    "dart-sass": "^1.19.0",
    "file-loader": "^3.0.1",
    "html-webpack-plugin": "^3.2.0",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.0",
    "webpack-dev-server": "^3.3.1"
  }
}
复制代码

运行servejson

npm run serve
复制代码

便可自动打开浏览器,启动咱们的项目。。浏览器

项目地址

源码地址点击这GitHubsass

相关文章
相关标签/搜索