Skip to content

Commit dba6957

Browse files
committed
build: fix global object and document not defined error in SSR (#202)
1 parent aaa62de commit dba6957

File tree

2 files changed

+53
-3
lines changed

2 files changed

+53
-3
lines changed

scripts/ssr_vue_loader.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const importReg = /import (style\d+) from (".+")\n/g;
2+
const injectReg = /\nfunction injectStyles[^]+?\n}/;
3+
4+
function replaceImportWithRequire(source) {
5+
let result;
6+
let count = source.match(importReg).length;
7+
const fragments = [];
8+
const hasInjection = injectReg.test(source);
9+
10+
result = source.replace(importReg, (_match, name, request) => {
11+
fragments.push([
12+
`var ${name} = require(${request})\n`,
13+
`if (${name}.__inject__) ${name}.__inject__(context)\n`
14+
].join(''));
15+
16+
// replace import with require through append way if there has no injection
17+
return (!hasInjection && !(--count))
18+
? `
19+
function injectStyles (context) {
20+
${fragments.join('')}
21+
}`
22+
: '';
23+
});
24+
25+
// append require statements into inject function if there already has injection
26+
if (hasInjection) {
27+
result = result.replace(injectReg, (func) => {
28+
return func.replace(/}$/, `${fragments.join('')}}`);
29+
});
30+
}
31+
32+
// replace argument for normalizer function
33+
result = result.replace(/(normalizer\((?:[^,]+,){4})([^,]+)/, '$1\n injectStyles');
34+
35+
return result;
36+
}
37+
38+
module.exports = function(source) {
39+
let result = source;
40+
41+
// only enable if there has import statement
42+
if (importReg.test(source)) {
43+
result = replaceImportWithRequire(source);
44+
}
45+
46+
return result;
47+
};

scripts/webpack.config.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ module.exports = {
1010
output: {
1111
path: path.join(__dirname, '../dist'),
1212
filename: '[name].js',
13-
publicPath: '/',
1413
library: 'VueInfiniteLoading',
15-
libraryTarget: 'umd'
14+
libraryTarget: 'umd',
15+
globalObject: 'this'
1616
},
1717
resolve: {
1818
extensions: ['.js', '.vue'],
@@ -48,7 +48,10 @@ module.exports = {
4848
},
4949
{
5050
test: /\.vue$/,
51-
loader: 'vue-loader'
51+
use: [
52+
path.join(__dirname, './ssr_vue_loader'),
53+
'vue-loader'
54+
]
5255
},
5356
{
5457
test: /\.less$/,

0 commit comments

Comments
 (0)