forked from m-turek/hexo-renderer-babel-webpack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (73 loc) · 2.06 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
var _ = require('lodash');
var webpack = require('webpack');
var extend = require('util')._extend;
var os = require('os');
var path = require('path');
var MemoryFS = require('memory-fs');
var fs = new MemoryFS();
var TMP_PATH = os.tmpdir();
var renderer = function(data, options, callback) {
var userConfig = extend(
hexo.theme.config.webpack || {},
hexo.config.webpack || {}
);
var baseDir = hexo.base_dir;
//
// Convert config of the entry to object.
//
var entry = (function(entry) {
if (_.isString(entry)) entry = [entry];
if (_.isArray(entry)) {
entry = entry.map(function(x){ return path.join(baseDir, x); });
return _.zipObject(entry.map(function(x){
return path.basename(x, path.extname(x));
}), entry);
}
return _.mapValues(entry, function(x){ return path.join(baseDir, x); });
})(userConfig.entry);
//
// If this file is not a webpack entry simply return the file.
//
if (!_.includes(entry, data.path)) {
return callback(null, data.text);
}
//
// Copy config then extend it with some defaults.
//
var config = extend({}, userConfig);
config = extend(config, {
entry: entry,
module: {
rules: [
{
test: /\.jsx$/,
loader: "babel-loader", // Do not use "use" here
options: {
// ...
}
}
]
},
output: {
entry: data.path,
path: TMP_PATH,
filename: path.basename(data.path)
}
});
//
// Setup compiler to use in-memory file system then run it.
//
var compiler = webpack(config);
compiler.outputFileSystem = fs;
compiler.run(function(err, stats) {
var output = compiler.options.output;
var outputPath = path.join(output.path, output.filename);
if (stats.toJson().errors.length > 0) {
hexo.log.log(stats.toString());
return callback(stats.toJson().errors, 'Webpack Error.');
}
contents = fs.readFileSync(outputPath).toString();
return callback(null, contents);
});
};
hexo.extend.renderer.register('js', 'js', renderer);