文章目录
 
  
 
 
 
一、默认入口和默认出口
 
 
webpack-demo
|- package.json
|- package-lock.json
|- webpack.config.js 
|- /dist
  |- index.html
|- /src
  |- index.js
 
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>起步</title>
  </head>
  <body>
  
  
   <script src="main.js"></script>
  </body>
</html>
 
 
import _ from "lodash";
function component() {
  const element = document.createElement("div");
  
  element.innerHTML = _.join(["Hello", "webpack"], " ");
  return element;
}
document.body.appendChild(component());
 
 
npm config get registry
npm config set registry https://registry.npmmirror.com
npm i package --save-dev 
npm i package --save 
 
 
 npm init -y 
 npm i webpack webpack-cli -D
 npm i lodash -S
 
 
 
const path = require("path");
module.exports = {
  entry: "./src/index.js", 
  output: { 
    filename: "main.js",
    
    path: path.resolve(__dirname, "dist"),
  },
};
 
二、资源配置
 
 
.red {
    color: red;
    font-size: 20px;
}
import _ from "lodash";
import "./style.css";
function component() {
  const element = document.createElement("div");
  
  element.innerHTML = _.join(["Hello", "webpack"], " ");
  element.classList.add("red");
  return element;
}
document.body.appendChild(component());
 
 
const path = require("path");
module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
      	
        test: /\.css$/,
        
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};
 
 
.red {
    color: red;
    font-size: 20px;
    height: 300px;
    background: url('./logo.png'); 
}
{
  test: /\.(png|svg|jpg|jpeg|gif)$/i, 
  type: 'asset/resource', 
},
 
 
三、输出文件
 
3.1 多文件入口
 
 
export default function print(msg = "Hello World") {
  console.log(msg);
}
<!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8" />
     <title>起步</title>
     
     <script src="./print.js"></script>
   </head>
   <body>
    <script src="./index.js"></script>
   </body>
 </html>
import _ from "lodash";
import "./style.css";
import print from "./print";
function component() {
  const element = document.createElement("div");
  
  element.innerHTML = _.join(["Hello", "webpack"], " ");
  element.classList.add("red");
  const btn = document.createElement("button");
  btn.innerHTML = "click me";
  btn.onclick = print;
  element.appendChild(btn);
  return element;
}
document.body.appendChild(component());
const path = require("path");
module.exports = {
  
  entry: {
    index: "./src/index.js",
    print: "./src/print.js",
  },
  output: {
    filename: "[name].js", 
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i, 
        type: "asset/resource", 
      },
    ],
  },
};
 
 
3.2 HtmlWebpackPlugin插件
 
 
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
  entry: { 
    index: "./src/index.js",
    print: "./src/print.js", 
  },
  output: {
  	
    filename: "[name].[contenthash].js",
    path: path.resolve(__dirname, "dist"),
    
    clean: true, 
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i, 
        type: "asset/resource", 
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "Webpack Test",
    }),
  ],
};
 
四、环境
 
4.1 环境变量
 
 
"build": "webpack --env goal=local --env production --progress --color"
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
  
  console.log("env, argv", env, argv);
  return {
  	
    mode: "development", 
    
    devtool: "inline-source-map", 
    entry: {
      index: "./src/index.js",
      print: "./src/print.js",
    },
    output: {
      filename: "[name].[contenthash].js",
      path: path.resolve(__dirname, "dist"),
      clean: true,
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i, 
          type: "asset/resource", 
        },
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "Webpack Test",
      }),
    ],
  };
};
export default function print(msg = "Hello World") {
  
  
  console.log("process", process.env.NODE_ENV);
}
 
4.2 热更新
 
 
"start-dev": "webpack-dev-server --open --env production=false",
"start": "webpack serve --open --env production=false",
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
  console.log("env, argv", env, argv);
  return {
    mode: "development", 
    
    devtool: "inline-source-map", 
    entry: {
      print: "./src/print.js",
      index: "./src/index.js",
    },
    output: {
      filename: "[name].[contenthash].js",
      path: path.resolve(__dirname, "dist"),
      clean: true,
      publicPath: "/", 
    },
    optimization: {
      
      runtimeChunk: "single", 
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "Webpack Test",
      }),
    ],
    
    devServer: {
      static: "./dist", 
      hot: true, 
      open: true, 
      port: 3000, 
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i, 
          type: "asset/resource", 
        },
      ],
    },
  };
};
 
五、代码分离
 
5.1 公共模块
 
 
import _ from "lodash";
export default function print(msg = "Hello World") {
  console.log("process", process.env.NODE_ENV, 1111);
  console.log(_.join([1, 2, 3]));
}
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
  console.log("env, argv", env, argv);
  return {
    mode: "development", 
    
    devtool: "inline-source-map", 
    entry: {
      print: "./src/print.js",
      index: "./src/index.js",
    },
    output: {
      filename: "[name].[contenthash].js",
      path: path.resolve(__dirname, "dist"),
      clean: true,
      publicPath: "/", 
    },
    optimization: {
      runtimeChunk: "single",
      
      
      splitChunks: {
        chunks: "all",
      },
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "Webpack Test",
      }),
    ],
    
    devServer: {
      static: "./dist", 
      hot: true, 
      open: true, 
      port: 3000, 
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i, 
          type: "asset/resource", 
        },
      ],
    },
  };
};
 
5.2 懒加载
 
 
index.js
import _ from "lodash";
import "./style.css";
function component() {
  const element = document.createElement("div");
  
  element.innerHTML = _.join(["Hello", "webpack"], " ");
  element.classList.add("red");
  const btn = document.createElement("button");
  btn.innerHTML = "click me";
  btn.onclick = (e) =>
  
    import( "./print").then((module) =>
      module.default()
    );
  element.appendChild(btn);
  return element;
}
document.body.appendChild(component());
 
5.3 预获取/预加载模块
 
预获取,空闲时进行;加载将来需要的资源
import( './path/to/LoginModal.js');
预加载,父 chunk 加载时以并行方式开始加载;加载当前路由下可能需要的资源
import( './path/to/LoginModal.js');
 
六、缓存
 
 
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
  console.log("env, argv", env, argv);
  return {
    mode: "development", 
    
    devtool: "inline-source-map", 
    entry: {
      index: "./src/index.js",
    },
    output: {
      filename: "[name].[contenthash].js",
      path: path.resolve(__dirname, "dist"),
      clean: true,
      publicPath: "/", 
    },
    optimization: {
      
      
      moduleIds: "deterministic",
      runtimeChunk: "single",
      
      
      splitChunks: {
        chunks: "all",
        cacheGroups: {
          vendor: {
            
            test: /[\\/]node_modules[\\/]/,
            name: "vendors",
            chunks: "all",
          },
        },
      },
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "Webpack Test",
      }),
    ],
    
    devServer: {
      static: "./dist", 
      hot: true, 
      open: true, 
      port: 3000, 
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i, 
          type: "asset/resource", 
        },
      ],
    },
  };
};
 
七、Tree Shaking
 
 
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
  console.log("env, argv", env, argv);
  return {
    mode: "development", 
    
    devtool: "inline-source-map", 
    entry: {
      index: "./src/index.js",
    },
    output: {
      filename: "[name].[contenthash].js",
      path: path.resolve(__dirname, "dist"),
      clean: true,
      publicPath: "/", 
    },
    optimization: {
      
      
      moduleIds: "deterministic",
      runtimeChunk: "single",
      
      
      splitChunks: {
        chunks: "all",
        cacheGroups: {
          vendor: {
            
            test: /[\\/]node_modules[\\/]/,
            name: "vendors",
            chunks: "all",
          },
        },
      },
      
      
      usedExports: true, 
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "Webpack Test",
      }),
    ],
    
    devServer: {
      static: "./dist", 
      hot: true, 
      open: true, 
      port: 3000, 
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i, 
          type: "asset/resource", 
        },
      ],
    },
  };
};
 
八、公共路径
 
 
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ASSET_PATH = process.env.ASSET_PATH || "/"; 
console.log("ASSET_PATH", process.env.ASSET_PATH, ASSET_PATH);
module.exports = (env, argv) => {
  console.log("env, argv", env, argv);
  return {
    mode: "development", 
    
    devtool: "inline-source-map", 
    entry: {
      index: "./src/index.js",
    },
    output: {
      filename: "[name].[contenthash].js",
      path: path.resolve(__dirname, "dist"),
      clean: true,
      publicPath: "/", 
    },
    optimization: {
      
      
      moduleIds: "deterministic",
      runtimeChunk: "single",
      
      
      splitChunks: {
        chunks: "all",
        cacheGroups: {
          vendor: {
            
            test: /[\\/]node_modules[\\/]/,
            name: "vendors",
            chunks: "all",
          },
        },
      },
      
      
      usedExports: true, 
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "Webpack Test",
      }),
      
      
      new webpack.DefinePlugin({
        "process.env.ASSET_PATH": JSON.stringify("ASSET_PATH"),
      }),
    ],
    
    devServer: {
      static: "./dist", 
      hot: true, 
      open: true, 
      port: 3000, 
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i, 
          type: "asset/resource", 
        },
      ],
    },
  };
};