-
Notifications
You must be signed in to change notification settings - Fork 0
/
runer.js
executable file
·81 lines (69 loc) · 1.87 KB
/
runer.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
/***
* loader 执行过程
* loader 转换规则
*/
const path = require('path');
const fs = require('fs');
const { runLoaders } = require('loader-runner');
const entryFile = path.resolve(__dirname, 'src', 'titleLoader.js');
const rules = [
{
test: /\.js$/,
// enforce: 'normal', // 默认
use: ['normal1-loader.js', 'normal2-loader.js']
},
{
test: /\.js$/,
enforce: 'post', // 后置
use: ['post1-loader.js', 'post2-loader.js']
},
{
test: /\.js$/,
enforce: 'pre', // 前置
use: ['pre1-loader.js', 'pre2-loader.js']
},
];
const request = `inline1-loader!inline2-loader!${entryFile}`;
const parts = request.replace(/^-?!+/, '').split('!');
const resource = parts.pop();
const resolveLoader = loader => path.resolve(__dirname, 'loaders', loader);
const inlineLoaders = parts;
const prelLoaders = [];
const normalLoaders = [];
const postLoaders = [];
rules.forEach(rule => {
if (rule.test.test(entryFile)) {
if (rule.enforce === 'pre') {
prelLoaders.push(...rule.use);
} else if (rule.enforce === 'post') {
postLoaders.push(...rule.use);
} else {
normalLoaders.push(...rule.use);
}
}
});
let loaders = [];
/**
* -! 不要普通 normal & 前置 pre
* ! 不要普通 normal
* !! 只要内敛 pre
*/
if (request.startsWith('!!')) {
loaders = inlineLoaders;
} else if (request.startsWith('-!')) {
loaders = [...postLoaders, ...inlineLoaders];
} else if (request.startsWith('!')) {
loaders = [...postLoaders, ...inlineLoaders, ...prelLoaders];
} else {
loaders = [...postLoaders, ...inlineLoaders, ...normalLoaders, ...prelLoaders];
}
loaders = loaders.map(loader => resolveLoader(loader));
runLoaders({
resource,
loaders,
context: { name: "loader" },
readResource: fs.readFile.bind(fs)
}, (err, result) => {
console.log(result.request)
console.log(result.resourceBuffer.toString('utf-8'));
})