-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
103 lines (92 loc) · 2.59 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
const commandLineArgs = require("command-line-args");
const {
NodeJsInputFileSystem,
CachedInputFileSystem,
ResolverFactory
} = require("enhanced-resolve");
const pkgDir = require("pkg-dir");
const path = require("path");
const fs = require("fs");
const chalk = require("chalk");
const root = pkgDir.sync();
const getJestConfig = function(cliConfigParameter) {
const defaultFileNames = [
cliConfigParameter,
"jest.config.json",
"jest.config.js"
];
for (let file of defaultFileNames) {
if (!file || !fs.existsSync(file)) {
continue;
}
const filePath = path.join(root, file);
const configFile = require(filePath);
if (configFile) {
return configFile;
}
}
return {};
};
const cliOptions = commandLineArgs(
{ name: "config", type: String },
{ partial: true }
);
const packagejson = require(path.join(root, "package.json"));
const jestConfig = getJestConfig(cliOptions.config);
let options =
(jestConfig && jestConfig["jestWebpackResolver"]) ||
(packagejson && packagejson["jestWebpackResolver"]);
const log = function(message, status = "log") {
if (options.silent) return;
if (status === "log") {
console.log(chalk.bgBlue.bold("Webpack Resolver"), message);
} else {
console.log(
chalk.bgRed.bold("Webpack Resolver Error: ") + chalk.bgRed(message)
);
}
};
if (!(options && options.webpackConfig)) {
options = {
webpackConfig: "./webpack.config.js"
};
log(`couldn't find any configuration. Tries to resolve ./webpack.config.js`);
} else {
log(`using: ${options.webpackConfig}`);
}
if (!fs.existsSync(path.join(pkgDir.sync(), options["webpackConfig"]))) {
log("Not able to find any valid webpack configuration", "error");
return;
}
const webpackConfig = require(path.join(
pkgDir.sync(),
options["webpackConfig"]
));
const getWebpackResolveRules = function(webpackConfig) {
if (Array.isArray(webpackConfig)) {
var obj = {};
webpackConfig.forEach(item =>
Object.assign(obj, getWebpackResolveRules(item))
);
return obj;
}
if (typeof webpackConfig === "function") {
const config = webpackConfig();
return config ? getWebpackResolveRules(config) : {};
} else {
return webpackConfig.resolve || {};
}
};
const resolveRules = getWebpackResolveRules(webpackConfig);
const resolver = ResolverFactory.createResolver(
Object.assign(
{
fileSystem: new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000),
useSyncFileSystemCalls: true
},
resolveRules
)
);
module.exports = function(value, options) {
return resolver.resolveSync({}, options.basedir, value);
};