Webpack Basic
2024年11月11日
一、认识
基础的 Webpack
项目,区分开发和生产环境,并通过 SWC
高效地编译 TypeScript
文件,提高开发效率和运行速度。
二、准备
2.1 初始化
mkdir webpack-basic
cd webpack-basic
2.2 安装依赖
1. 安装 Webpack
及必要依赖
pnpm add webpack webpack-cli webpack-merge webpack-dev-server html-webpack-plugin -D
2. 安装 SWC
和 TypeScript
: 安装 SWC
加载器和核心依赖, 安装 TypeScript
及类型支持
pnpm add @swc/cli @swc/core swc-loader typescript -D
2.3 项目结构
webpack-basic/
├── build/
│ ├── webpack.common.js # Webpack 公共配置
│ ├── webpack.dev.js # 开发环境配置
│ ├── webpack.prod.js # 生产环境配置
├── dist/ # 打包输出目录
├── public/
│ ├── index.html # HTML 模板文件
├── src/
│ ├── index.ts # TypeScript 入口文件
├── package.json # 项目信息
├── tsconfig.json # TypeScript 配置文件
三、配置
3.1 webpack.common.js
const Path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: Path.resolve(process.cwd(), "./src", "index.ts"),
output: {
clean: true,
filename: "[name].[contenthash].js",
path: Path.resolve(process.cwd(), "dist"),
},
module: {
rules: [
{
test: /\.ts$/,
use: ["swc-loader"],
exclude: /node_modules/,
include: Path.resolve(process.cwd(), "src"),
},
],
},
resolve: {
extensions: [".ts", ".js"],
},
plugins: [
new HtmlWebpackPlugin({
template: Path.resolve(process.cwd(), "public", "index.html"),
}),
],
};
3.2 webpack.dev.js
const Path = require("path");
const { merge } = require("webpack-merge");
const common = require("./webpack.config.common");
module.exports = merge(common, {
mode: "development",
devtool: "source-map",
devServer: {
port: 9000,
compress: true,
client: {
progress: true,
},
static: {
directory: Path.resolve(process.cwd(), "public"),
},
},
});
3.3 webpack.prod.js
const { merge } = require("webpack-merge");
const common = require("./webpack.config.common");
module.exports = merge(common, {
mode: "production",
devtool: "source-map",
});
3.4 package.json
{
"name": "dll",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack serve --config ./build/webpack.config.dev.js",
"build": "webpack --config ./build/webpack.config.prod.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@swc/cli": "^0.5.1",
"@swc/core": "^1.9.2",
"@types/lodash": "^4.17.13",
"html-webpack-plugin": "^5.6.3",
"swc-loader": "^0.2.6",
"typescript": "^5.6.3",
"webpack": "^5.96.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.1.0",
"webpack-merge": "^6.0.1"
},
"dependencies": {
"lodash": "^4.17.21"
}
}
3.5 tsconfig.json
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true
},
"exclude": ["node_modules", "dist"]
}