美文网首页
webpack4 - 6.webpack-dev-server

webpack4 - 6.webpack-dev-server

作者: yuanzicheng | 来源:发表于2018-09-21 15:00 被阅读51次

    webpack-dev-server用于开发调试,它提供了web服务、热更新、接口代理等支持。

    我们在上一篇的基础上添加webpack-dev-server功能

    首先在项目中安装webpack-dev-server

    npm i --save-dev webpack-dev-server
    

    package.json内容如下

    {
      "name": "webpack-demo",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack"
      },
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "css-loader": "^1.0.0",
        "file-loader": "^2.0.0",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "mini-css-extract-plugin": "^0.4.3",
        "style-loader": "^0.23.0",
        "url-loader": "^1.1.1",
        "webpack": "^4.19.1",
        "webpack-cli": "^3.1.0",
        "webpack-dev-server": "^3.1.8"
      }
    }
    
    

    webpack.config.js中添加devServer选项,制定web服务器的文件目录和入口

    const path = require('path');
    const MiniCssExtractPlugin = require("mini-css-extract-plugin")
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
        mode: 'development',
        entry: {
            index: './src/js/index.js'
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'js/[name].[hash:8].js'
        },
        module: {
            ...
        },
        plugins: [
            ...
        ],
        devServer: {
            contentBase: path.resolve(__dirname, "../dist/"),
            index:'./page/index.html'
        }
    };
    

    由于webpack-dev-server没有全局安装,所以在package.json的“scripts”中添加webpack-dev-server

    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "build": "webpack",
      "dev": "webpack-dev-server --inline --progress --compress --hot --open --config webpack.config.js --host 127.0.0.1 --port 8888"
    },
    

    最后,执行npm run dev,webpack编译打包完成后,会自动打开浏览器访问devServer中指定的页面(因为使用了--open选项)。

    webpack-dev-server更多用法及常用选项可以使用webpack-dev-server --help命令查看。

    相关文章

      网友评论

          本文标题:webpack4 - 6.webpack-dev-server

          本文链接:https://www.haomeiwen.com/subject/ddtqnftx.html