forked from alibaba/ice
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebpack-plugin-import.js
More file actions
68 lines (58 loc) · 1.79 KB
/
webpack-plugin-import.js
File metadata and controls
68 lines (58 loc) · 1.79 KB
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
const fs = require('fs');
const path = require('path');
const webpackLoaderRequire = require.resolve('./webpack-loader-require');
const fileExistsCache = {};
function fileExists(id) {
if (fileExistsCache[id]) {
return fileExistsCache[id];
}
fileExistsCache[id] = fs.existsSync(id);
return fileExistsCache[id];
}
// 在 resolve 阶段, 修改上下文中的 loaders 属性, 让 next 包的 index.js 经过以下 loader 加工
// see https://webpack.js.org/plugins/normal-module-replacement-plugin/
module.exports = class WebpackPluginImport {
constructor(options) {
if (Array.isArray(options)) {
this.options = options;
} else if (typeof options === 'object') {
this.options = [options];
} else {
this.options = [];
}
}
// eslint-disable-next-line
needAdditionalStyle(result, opt) {
if (opt.libraryName instanceof RegExp) {
return opt.libraryName.test(result.rawRequest);
}
if (result.rawRequest.match(opt.libraryName)) {
return true;
}
return false;
}
apply(compiler) {
compiler.plugin('normal-module-factory', (nmf) => {
nmf.plugin('after-resolve', (result, callback) => {
if (!result) {
return callback();
}
// only enable for .js or .jsx
if (result.loaders && /\.jsx?$/i.test(result.resource)) {
this.options.forEach((opt) => {
if (this.needAdditionalStyle(result, opt)) {
const modPath = path.join(
path.dirname(result.resource),
opt.stylePath || 'style.js'
);
if (fileExists(modPath)) {
result.loaders.push(`${webpackLoaderRequire}?mod=${modPath}`);
}
}
});
}
return callback(null, result);
});
});
}
};