Skip to content

Commit 0f078f7

Browse files
committed
Add lib script 'loadnpm'
- Make 'node circular module' to 'non circular module' using browserify.
1 parent de9e889 commit 0f078f7

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
const delay = require('./delay');
2+
const npm = require('./npm');
3+
4+
module.exports = (moduleName = '', global = {}) => {
5+
const validModuleName = moduleName.replace(/\//g, "_");
6+
7+
const __scriptPath = Context.GetDir('GameContent') + 'Scripts';
8+
const __srcScriptPath = `${__scriptPath}/${validModuleName}.js`;
9+
const __desScriptPath = `${__scriptPath}/bundle_${validModuleName}.js`;
10+
11+
function IsNeedPrepare() {
12+
return JavascriptLibrary.FileExists(__desScriptPath);
13+
}
14+
15+
function Prepare() {
16+
return new Promise(resolve => {
17+
npm('browserify').then(() => npm(validModuleName)).then(() => {
18+
const script = `global['cached_${validModuleName}'] = require('${moduleName}');`;
19+
JavascriptLibrary.WriteStringToFile(Context, __srcScriptPath, script);
20+
resolve()
21+
});
22+
});
23+
}
24+
25+
function Process() {
26+
const script = `(() => {
27+
var browserify = require('browserify');
28+
var b = browserify();
29+
b.add('${__srcScriptPath}');
30+
31+
var fs = require('fs');
32+
var bundleFs = fs.createWriteStream('${__desScriptPath}');
33+
34+
b.bundle().pipe(bundleFs);
35+
})()`;
36+
37+
const __browsifyScriptPath = `${__scriptPath}/temp.js`;
38+
JavascriptLibrary.WriteStringToFile(Context, __browsifyScriptPath, script);
39+
40+
let p = JavascriptProcess.Create(
41+
'node',
42+
`${__browsifyScriptPath}`,
43+
true, false, false, 0, '', true
44+
)
45+
console.log('browserify', __srcScriptPath, __desScriptPath)
46+
function pipe() {
47+
let s = p.ReadFromPipe()
48+
// @NOTE:
49+
// console.log(s)
50+
}
51+
return new Promise(resolve => {
52+
while (p.IsRunning()) {
53+
delay(50).then(pipe);
54+
}
55+
56+
JavascriptLibrary.DeleteFile(__browsifyScriptPath);
57+
JavascriptLibrary.DeleteFile(__srcScriptPath);
58+
59+
resolve();
60+
})
61+
}
62+
63+
function PostInit() {
64+
require(__desScriptPath);
65+
66+
newModule = global[`cached_${validModuleName}`];
67+
delete global[`cached_${validModuleName}`];
68+
}
69+
70+
let newModule = {};
71+
72+
if (IsNeedPrepare() == false) {
73+
Prepare().then(Process).then(PostInit);
74+
} else {
75+
PostInit();
76+
}
77+
78+
return newModule;
79+
};

0 commit comments

Comments
 (0)