-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
95 lines (82 loc) · 2.16 KB
/
index.js
File metadata and controls
95 lines (82 loc) · 2.16 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
83
84
85
86
87
88
89
90
91
92
93
94
95
var through = require('through2');
var React = require.main.require('react')
var ReactDOMServer = require.main.require('react-dom/server');
var webpack = require('webpack');
var MemoryFS = require('memory-fs');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
function getWebpackConfig(filePath) {
const extractSass = new ExtractTextPlugin({
filename: "styles.css",
});
return {
entry: [
filePath
],
output: {
path: '/',
filename: "index.js",
libraryTarget: "umd",
library: "Bundle",
publicPath: '/'
},
resolve: {
extensions: [".js", ".jsx"]
},
module: {
rules: [{
test: /\.scss$/,
use: extractSass.extract({
use: [
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
})
},
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2016', 'react']
}
}
]
},
target: "node",
plugins: [
extractSass
]
}
}
function gulpRenderStaticPage(opts = {}) {
return through.obj(function(file, enc, cb) {
if (file.isNull()) {
// return empty file
return cb(null, file);
}
const fs = new MemoryFS();
const compiler = webpack(getWebpackConfig(file.path));
compiler.outputFileSystem = fs;
compiler.run((err, stats) => {
const js = fs.readFileSync('/index.js', "utf8");
const mod = new module.constructor;
mod._compile(js, './page.js');
let component = mod.exports.default;
let styles = fs.readFileSync('/styles.css', "utf8");
let html = "<!DOCTYPE html>"
+ ReactDOMServer.renderToStaticMarkup(React.createElement(component), {}, null);
html = html.replace(/\{\{\{ +REACT_STATIC_STYLES +\}\}\}/, styles);
if (file.isBuffer()) {
file.contents = Buffer.from(html, 'utf8');
}
if (file.isStream()) {
var stream = through();
stream.write(html);
file.contents = stream;
}
cb(null, file);
});
});
}
module.exports = gulpRenderStaticPage;