-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
129 lines (109 loc) · 2.45 KB
/
index.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import fs from 'fs'
import parser from '@babel/parser'
import traverse from '@babel/traverse'
import { transformFromAst } from '@babel/core'
import path from 'path'
import ejs from 'ejs'
import { jsonLoader } from './jsonLoader.js'
import { ChangeOutPath } from './ChangeOutPath.js'
import { SyncHook } from 'tapable'
let id = 0
const webpackConfig = {
module: {
rules: [
{
test: /\.json$/,
use: [jsonLoader]
}
]
},
plugins: [new ChangeOutPath()]
}
const hooks = {
emitFile: new SyncHook(['context'])
}
function createAsset(filePath) {
// 获取文件内容
let source = fs.readFileSync(filePath, {
encoding: 'utf-8'
})
// init loader
const loaders = webpackConfig.module.rules
const loaderContext = {
addDeps(dep) {
console.log('addDeps', dep)
}
}
loaders.forEach(({ test, use }) => {
if (test.test(filePath)) {
if (Array.isArray(use)) {
use.forEach((fn) => {
source = fn.call(loaderContext, source)
})
}
}
})
// 获取依赖关系
// AST 抽象语法树
const ast = parser.parse(source, {
sourceType: 'module'
})
const deps = []
traverse.default(ast, {
ImportDeclaration({ node }) {
deps.push(node.source.value)
}
})
const { code } = transformFromAst(ast, null, {
presets: ['env']
})
return {
filePath,
code,
deps,
mapping: {},
id: id++
}
}
function createGraph() {
const mainAsset = createAsset('./example/main.js')
const queue = [mainAsset]
for (const asset of queue) {
asset.deps.forEach((relativePath) => {
const child = createAsset(path.resolve('./example', relativePath))
asset.mapping[relativePath] = child.id
queue.push(child)
})
}
return queue
}
function initPlugins() {
const plugins = webpackConfig.plugins
plugins.forEach((plugin) => {
plugin.apply(hooks)
})
}
initPlugins()
const graph = createGraph()
function build(graph) {
const template = fs.readFileSync('./bundle.ejs', { encoding: 'utf-8' })
const data = graph.map((asset) => {
const { id, code, mapping } = asset
return {
id: id,
code: code,
mapping: mapping
}
})
const code = ejs.render(template, { data })
let outputPath = './dist/bundle.js'
const context = {
changeOutputPath(path) {
outputPath = path
}
}
// hooks 发出对应事件
hooks.emitFile.call(context)
fs.writeFileSync(outputPath, code)
}
build(graph)