-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkkbpack.js
108 lines (98 loc) · 2.91 KB
/
kkbpack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#! /usr/bin/env node
const path = require('path')
const fs = require('fs')
const defaultConfig = {
entry: "./src/index.js",
output: {
filename: 'bundle.js'
}
}
const config = {
...defaultConfig,
...require(path.resolve('./kkbpack.config.js'))
}
// console.log(config)
class KkbPack {
constructor(config) {
this.config = config
// 入 口
this.entry = config.entry
// 工作路径
this.root = process.cwd()
// 依赖关系
this.modules = {}
}
// 创建模块
createModule(modulePath, name) {
// modulePath是绝对路径,获取文件
// name是相对路径,作为key
// let fileContent = fs.readFileSync(modulePath, 'utf-8')
let fileContent = this.getCode(modulePath);
// console.log('fileContent: ', fileContent);
// ./src/index.js 文件的父目录,其实就是src
// 解析soruce源码
const { code, deps } = this.parse(fileContent, path.dirname(name))
console.log('code, deps: ', code, deps);
// this.modules[name] = code
// console.log('name: ', name);
this.modules[name] = `function(module,exports,__kkbpack_require__){ eval(\`${code}\`)}`
// 递归获取依赖
deps.forEach(dep => {
this.createModule(path.join(this.root, dep), './' + dep)
})
}
getCode (modulePath) {
let content = fs.readFileSync(modulePath, 'utf-8')
// this.config.module.rules.forEach(r => {
// if(r.test.test(modulePath)) {
// const loader = require(r.use[0])
// content = loader(content)
// }
// })
return content
}
parse(code, parent) {
// console.log('code: ', code);
let deps = []
// 识别 require('xx')
var r = /require\((.*)\)/g;
code = code.replace(r, function (match, arg) {
// console.log('arg: ', arg);
// console.log(1,match, arg.replace(/'|"/g,''))
const retPath = path.join(parent, arg.replace(/'|"/g, ''))
deps.push(retPath)
return `__kkbpack_require__("./${retPath}")`
})
return {
code,
deps
}
}
generateModuleStr() {
// 生成model字符串
let fnTemp = ""
Object.keys(this.modules).forEach(name => {
fnTemp += `"${name}":${this.modules[name]},`
})
console.log('fnTemp: ', fnTemp);
return fnTemp
}
generateFile() {
// console.log(this.modules, this.entry)
// console.log(123,this.root)
let template = fs.readFileSync(path.resolve(__dirname, './template.js'), 'utf-8')
template = template.replace('__entry__', this.entry)
.replace('__content__', this.generateModuleStr())
fs.writeFileSync('./dist/' + this.config.output.filename, template)
}
start() {
// 创建模块依赖关系
console.log('开始啦1')
const entryPath = path.resolve(this.root, this.entry)
this.createModule(entryPath, this.entry)
this.generateFile()
}
}
const kkb = new KkbPack(config)
kkb.start()
console.log(' \n')