美文网首页
《webpack学习》- 入门使用DevServer

《webpack学习》- 入门使用DevServer

作者: 张中华 | 来源:发表于2021-08-22 22:58 被阅读0次

    在实际开发中,除了打包我们可能还需要一下功能:

    • 提供HTTP服务而不是使用本地文件预览
    • 监听文件变化并自动刷新网页,做好实时预览
    • 支持Source Map, 方便调试

    webpack原生支持2,3点内容,再结合官方提供的开发工具DevServer也可以很方便的实现第一点。

    DevServer

    npm install webpack-dev-server --save-dev

    pacakge.js

    {
      "name": "webpack-test",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "dev": "webpack serve"
      },
      "author": "zzh",
      "license": "ISC",
      "devDependencies": {
        "@webpack-cli/serve": "^1.5.2",
        "css-loader": "^6.2.0",
        "extract-text-webpack-plugin": "^3.0.2",
        "mini-css-extract-plugin": "^2.2.0",
        "style-loader": "^3.2.1",
        "webpack-cli": "^4.8.0",
        "webpack-dev-server": "^4.0.0"
      },
      "dependencies": {
        "webpack": "^5.50.0"
      }
    }
    

    wepack.config.js

    const path =  require('path');
    
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    
    module.exports = {
        mode:'development',
        entry: './main.js',
        output: {
            filename: 'bundle.js',
            path: path.resolve(__dirname, './dist'),
            publicPath:'./'
        },
        plugins: [new MiniCssExtractPlugin()],
        module: { 
            rules: [
                {
                  test: /\.css$/i,
                  use: [MiniCssExtractPlugin.loader, "css-loader"],
                },
              ],
         }, 
    
         devServer: {
           static: {
            directory: path.join(__dirname, './'),
           },
         },
    };
    

    运行npm run dev即可.
    注意这里的wepack里面的devServer配置,修改了服务的打开地址,默认是./public文件夹。

    参考地址

    https://blog.csdn.net/weixin_40599109/article/details/109582365

    https://blog.csdn.net/weixin_48383757/article/details/109824003

    相关文章

      网友评论

          本文标题:《webpack学习》- 入门使用DevServer

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