f8687d2e82eebbd1fbf2a389f0b0bdc88b9b0951.svn-base
2.19 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict';
const path = require('path');
const destructuringTransform = require('@babel/plugin-transform-destructuring');
const restSpreadTransform = require('@babel/plugin-proposal-object-rest-spread');
const jsxTransform = require('@babel/plugin-transform-react-jsx');
const resolveFrom = require('resolve-from');
const callerPath = require('caller-path');
const babel = require('@babel/core');
const importJsx = (moduleId, options) => {
if (typeof moduleId !== 'string') {
throw new TypeError('Expected a string');
}
options = Object.assign({
pragma: 'h',
pragmaFrag: 'Fragment',
cache: true,
// Put on options object for easier testing.
supportsDestructuring: Number(process.versions.node.split('.')[0]) >= 6
}, options);
const modulePath = resolveFrom(path.dirname(callerPath()), moduleId);
if (!options.cache) {
delete require.cache[modulePath];
}
// If they used .jsx, and there's already a .jsx, then hook there
// Otherwise, hook node's default .js
const ext = path.extname(modulePath);
const hookExt = require.extensions[ext] ? ext : '.js';
const oldExtension = require.extensions[hookExt];
require.extensions[hookExt] = module => {
const oldCompile = module._compile;
module._compile = source => {
if (source.includes('React')) {
options.pragma = 'React.createElement';
options.pragmaFrag = 'React.Fragment';
}
const plugins = [
[restSpreadTransform, {useBuiltIns: true}],
options.supportsDestructuring ? null : destructuringTransform,
[jsxTransform, {pragma: options.pragma, pragmaFrag: options.pragmaFrag, useBuiltIns: true}]
].filter(Boolean);
const result = babel.transformSync(source, {
plugins,
filename: modulePath,
sourceMaps: 'inline',
babelrc: false,
configFile: false
});
module._compile = oldCompile;
module._compile(result.code, modulePath);
};
require.extensions[hookExt] = oldExtension;
oldExtension(module, modulePath);
};
const m = require(modulePath);
require.extensions[hookExt] = oldExtension;
if (!options.cache) {
delete require.cache[modulePath];
}
return m;
};
module.exports = importJsx;
module.exports.create = options => {
return moduleId => importJsx(moduleId, options);
};