# 简单实现一个webpack

# 1.写一个打包案例

# 1.文件

src/base/b.js

module.exports = "b"
1

src/a.js

let b = require("./base/b.js")
module.exports = "a" + b
1
2

src/index.js

let str = require("./a.js")
console.log(str)
1
2

# 2.配置

webpack.config.js

let path = require("path")
module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
}
1
2
3
4
5
6
7
8
9

# 2.自己的 webpack

mypack/bin/mypack.js

#! /usr/bin/env node

console.log("start")
1
2
3

mypack/package.json

{
  "name": "mypack",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "bin": {
    "mypack": "./bin/mypack.js"
  }
}
1
2
3
4
5
6
7
8
9

# 2.将自己写的包链接到案例上

自己的包目录下

npm link
1

案例的目录下

npm link mypack
1

# 3.运行

案例的目录下

npx mypack
1

打印出:start

现在可以在 mypack.js 中写自己的逻辑实现打包功能

案例完整代码 (opens new window)

包完整代码 (opens new window)