学习笔记13(webpack进阶1)

自动清理构建目录

// webpack.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');

module.exports = {
  mode: "production", // 如果不添加就会警告
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "[name].[chunkhash:8].js" // 出口文件
  },
  plugins: [
    new CleanWebpackPlugin()
  ]
}

postcss插件自动补全功能

// src/index.js
import './file.css'
// src/file.css
div{
    display: flex;
}

// webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css'
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                plugins: [
                  [
                    "postcss-preset-env",
                    {
                      browsers: 'last 2 versions',
                      // autoprefixer: false, // 默认true, false则不转换
                    },
                  ],
                ],
              },
            },
          },
        ],
      },
    ],
  },
};

px 转为 rem

  • lib-flexible 计算 html元素 fontSize , 宽 375px 下为 37.5(1rem = 37.5px)
  • px2rem-loader 将 css 文件中的 px 转换为 rem
    • remUnit, 1个 rem 对应的 px 数
    • 宽 750px 设计稿,1rem = 75px
  • hmtl中引入 lib-flexible 资源
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')

module.exports = {
  module: {
    rules: [
      {
        test: /.css$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'px2rem-loader',
            options: {
              remUnit: 75,
              remPrecision: 8
            }
          }
        ]
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, `src/index.html`)
    })
  ]
}

多页面打包

配置多个入口,多个htmlWebpackPlugins。使用 chunks 指定HTML使用的 chunk
不指定chunks问题:
在这里插入图片描述

const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const glob = require("glob");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

const entry = {};
const htmlWebpackPlugins = [];

glob.sync(path.join(__dirname, "./src/*/index.js")).forEach((url) => {
  const match = url.match(/src\/(.*)\/index\.js/);
  const pageName = match && match[1];

  entry[pageName] = path.join(__dirname, `src/${pageName}`);
  htmlWebpackPlugins.push(
    new HtmlWebpackPlugin({
      filename: `${pageName}.html`,
      template: path.join(__dirname, `src/${pageName}/index.html`),
      chunks: [pageName], // 使用的 chunks,默认 all
      inject: "head", // 注入位置
    })
  );
});

module.exports = {
  entry,
  output: {
    path: path.join(__dirname, "dist"),
    filename: "[name]_[chunkhash:8].js",
  },
  plugins: [new CleanWebpackPlugin(), ...htmlWebpackPlugins],
};

sourcemap

使用 sourceURL 解决 eval字符串代码不能调试的问题

调式 eval 函数和 Function 函数的动态代码,通过 sourceURL生成指定文件

// index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="foo">foo</button>
  <button id="foo2">foo2</button>
  <script>
    var script = `function foo() {
      alert('called foo');
    }
    //# sourceURL=my-foo.js`;

    var script2 = `function foo2() {
      alert('called foo2');
    }
    //# sourceURL=my-foo2.js`;

    eval(script);
    eval(script2)

    var button = document.getElementById("foo");
    button.addEventListener("click", foo, false);

    var button = document.getElementById("foo2");
    button.addEventListener("click", foo2, false);
  </script>
</body>

</html>
  • 效果图
    在这里插入图片描述
webapck之devtool
  • eval:eval 模式会把每个 module 封装到 eval 里包裹起来执行
(() => {
  eval("document.write('search')\n\n//# sourceURL=webpack://note12/./src/search/index.js?")
})();
  • source-map
    • 源码转换:压缩减少体积;合并文件,减少 http 请求;代码转化。不利于代码调试。
    • source map:信息文件,储存位置信息,可定位错误的源码位置。
    • 生成 map 映射文件
// xx.js
document.write("search");
//# sourceMappingURL=search_516cb46c.js.map

// xx.js.map
{
  "version": 3,
  "sources": [
    "webpack://note12/./src/search/index.js"
  ],
  "names": [
    "document",
    "write"
  ],
  "mappings": "AAAAA,SAASC,MAAM",
  "file": "search_516cb46c.js",
  "sourcesContent": [
    "document.write('search')"
  ],
  "sourceRoot": ""
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值