-
Notifications
You must be signed in to change notification settings - Fork 0
/
migration.js
1673 lines (1419 loc) · 51.7 KB
/
migration.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import prettier from 'prettier';
import HTMLtoJSX from 'htmltojsx';
import fs from 'fs';
import { exec } from 'child_process';
import ora from 'ora';
import chalk from 'chalk';
import { exit } from 'process';
import HTMLParser from 'node-html-parser';
import fse from 'fs-extra';
/**
* ===================== START UTILS =====================
*/
/**
* Consts
*/
const viteFolder = "./vite";
const processName = process.argv[2];
const assetsFolder = "/Assets";
const pagesFolder = "/Pages";
const layoutsFolder = "/Layouts";
const componentsFolder = "/Components";
const imgFolder = "/img";
const cssFolder = "/css";
const scssFolder = "/scss";
const jsFolder = "/js";
const fontsFolder = "/fonts";
// Conversion
const conversionFolder = "./jsx";
const conversionAssets = conversionFolder + assetsFolder;
const conversionPages = conversionFolder + pagesFolder;
const conversionLayouts = conversionFolder + layoutsFolder;
const conversionComponents = conversionFolder + componentsFolder;
const conversionImg = conversionAssets + imgFolder;
const conversionCss = conversionAssets + cssFolder;
const conversionScss = conversionAssets + scssFolder;
const conversionJs = conversionAssets + jsFolder;
const conversionFonts = conversionAssets + fontsFolder;
// Imports
const importBase = "..";
const importAssets = importBase + assetsFolder;
const importPages = "." + pagesFolder;
const importLayouts = "." + layoutsFolder;
const importComponents = importBase + componentsFolder;
const importImg = importAssets + imgFolder;
const scssImportImg = importBase + imgFolder;
const importCss = importAssets + cssFolder;
const importScss = importAssets + scssFolder;
const importJs = importAssets + jsFolder;
const importFonts = importAssets + fontsFolder;
/**
* Vars
*/
let componentDidMountMain = [];
let componentDidMountPage = [];
let functionName = "";
let HeaderContents, FooterContents, SidebarContents;
let dependencies = [];
let imports = [];
let logPrefix = "";
let imgFolderFound = false;
/**
* Find files in a directory recursively
*/
function findFiles(folder, extension)
{
let findFilesLoader = load("Finding " + extension + " files");
let files = [];
let filesFound = false;
if (fs.existsSync(folder))
{
files = fs.readdirSync(folder);
filesFound = true;
}
if (filesFound === false)
{
findFilesLoader.fail("Failed to find " + extension + " files");
return false;
}
else
{
findFilesLoader.succeed("Found " + extension + " files");
}
return files;
}
/**
* Find a single file in a directory recursively
*/
function findFile(file)
{
let fileFound = false;
let fileContents;
let fileLocation;
if (fs.existsSync(file))
{
fileFound = true;
fileContents = fs.readFileSync(file, "utf8");
fileLocation = file;
}
else
{
fileFound = false;
}
if (fileFound === false)
{
return false;
}
return fileLocation;
}
/**
* Show loading message
*/
function load(message)
{
return ora(`${chalk.cyanBright(message)}`).start();
}
/**
* Pretty log
*/
function log(message)
{
console.log(chalk.cyanBright("[MIGRATION] ") + message);
}
/**
* Exec shell command
*/
function execute(command, callback)
{
exec(command, function (error, stdout, stderr) { callback(stdout); });
};
// If path is assets, pages, layouts, components, images, css, scss or js
function isAssetsPath(path)
{
return path.includes(assetsDist);
}
function isPagesPath(path)
{
return path.includes(pagesDist);
}
function isLayoutsPath(path)
{
return path.includes(layoutsDist);
}
function isComponentsPath(path)
{
return path.includes(componentsDist);
}
function isImagePath(path)
{
return path === importImg;
}
/**
* Create function name
*/
function createFunction(fileName, name)
{
let createLoader = load("Creating " + name + " function");
if (name !== undefined && name !== null)
{
functionName = name;
}
else if (fileName !== undefined)
{
functionName = fileName.split("-").map((word, index) =>
{
return word.charAt(0).toUpperCase() + word.slice(1);
}).join("");
if (functionName === "404")
{
functionName = "NotFound";
}
else if (functionName === "500")
{
functionName = "InternalError";
}
else if (functionName === "403")
{
functionName = "Unauthorized";
}
}
else
{
functionName = "Unknown";
}
createLoader.succeed("Created " + functionName + " function");
return functionName;
}
/**
* Create function start
*/
function createFunctionStart(name, pageTitle)
{
let createFunctionStartLoader = load("Creating " + name + " function start");
let appendTitle = 0;
if (pageTitle !== undefined && pageTitle !== null)
{
appendTitle = 1;
}
if (processName === "function")
{
var JSXFunctionStart = "export default function " + name + "() {\n";
if (appendTitle === 1)
{
JSXFunctionStart += " document.title = \"" + pageTitle + "\";\n";
}
if (componentDidMountPage !== undefined && componentDidMountPage !== null)
{
if (componentDidMountPage.includes("undefined"))
{
componentDidMountPage = componentDidMountPage.replace("undefined", "");
}
JSXFunctionStart += componentDidMountPage.join("\n");
}
JSXFunctionStart += " return (\n";
}
else
{
var JSXFunctionStart = "import React from 'react';\n";
JSXFunctionStart += "export default class " + name + " extends React.Component {\n";
JSXFunctionStart += " constructor(props) {\n";
JSXFunctionStart += " super(props);\n";
JSXFunctionStart += " this.props = props;\n";
JSXFunctionStart += " }\n\n";
JSXFunctionStart += " componentDidMount() {\n";
if (appendTitle === 1 && !isComponent(name))
{
JSXFunctionStart += " document.title = \"" + pageTitle + "\";\n";
}
if (componentDidMountPage !== undefined && componentDidMountPage !== null && !isComponent(name))
{
JSXFunctionStart += componentDidMountPage.join("\n");
}
JSXFunctionStart += " }\n\n";
JSXFunctionStart += " render() {\n";
JSXFunctionStart += " return (\n";
}
createFunctionStartLoader.succeed("Created " + name + " function start");
return JSXFunctionStart;
}
/**
* Create function end
*/
function createFunctionEnd()
{
let createFunctionEndLoader = load("Creating " + functionName + " function end");
if (processName === "function")
{
var JSXFunctionEnd = " );\n";
JSXFunctionEnd += "}\n";
}
else
{
var JSXFunctionEnd = " );\n";
JSXFunctionEnd += "}\n";
JSXFunctionEnd += "}";
}
createFunctionEndLoader.succeed("Created " + functionName + " function end");
return JSXFunctionEnd;
}
/**
* Strip a path of its file name
*/
function stripPath(path)
{
const fileExtension = path.split(".").pop();
let pathWithoutExtension = path.replace("." + fileExtension, "");
const foldersToRemove = [
"css",
"style",
"stylesheet",
"asset",
"script",
"js",
"javascript",
"img",
"image",
"font",
]
for (let i = 0; i < foldersToRemove.length; i++)
{
const folderToRemove = foldersToRemove[i];
const doNotRemoveExtension = "." + folderToRemove;
const folderToRemoveUpperCase = folderToRemove.toUpperCase();
const folderToRemoveCamelCase = folderToRemove.replace(/-([a-z])/g, g => g[1].toUpperCase());
const folderToRemovePlural = folderToRemove + "s";
if (pathWithoutExtension.includes(folderToRemovePlural))
{
pathWithoutExtension = pathWithoutExtension.replace(folderToRemovePlural, "");
}
if (pathWithoutExtension.includes(foldersToRemove[i]))
{
pathWithoutExtension = pathWithoutExtension.replace(foldersToRemove[i], "");
}
if (pathWithoutExtension.includes(folderToRemoveUpperCase))
{
pathWithoutExtension = pathWithoutExtension.replace(folderToRemoveUpperCase, "");
}
if (pathWithoutExtension.includes(folderToRemoveCamelCase))
{
pathWithoutExtension = pathWithoutExtension.replace(folderToRemoveCamelCase, "");
}
// Remove "//" from pathWithoutExtension
pathWithoutExtension = pathWithoutExtension.replace("//", "/");
}
return pathWithoutExtension + "." + fileExtension;
}
function isComponent(html)
{
return html.includes("header") || html.includes("footer") || html.includes("sidebar");
}
/**
* Check if there are any .html files in the directory
*/
function htmlExists()
{
let checkHtml = load("Checking for HTML files");
const files = fs.readdirSync("./");
let filesExist = false;
for (let i = 0; i < files.length; i++)
{
const fileName = files[i];
const fileExtension = fileName.split(".").pop();
if (fileExtension === "html")
{
filesExist = true;
break;
}
}
if (!filesExist)
{
checkHtml.fail("No HTML files found");
exit
}
else
{
checkHtml.succeed("Found HTML files");
}
}
/**
* Create a folder
*/
function createFolder(folder)
{
let createFolderLoader = load("Creating " + folder + " folder");
fs.mkdirSync(folder);
createFolderLoader.succeed("Created " + folder + " folder");
}
/**
* Clear a single folder
*/
function clearFolder(folder)
{
if (fs.existsSync(folder))
{
let clearFolderLoader = load("Clearing " + folder + " folder");
fs.rmSync(folder, { recursive: true }, (err) =>
{
if (err)
{
clearFolderLoader.fail("Failed to clear " + folder + " folder");
throw err;
}
});
clearFolderLoader.succeed("Cleared " + folder + " folder");
}
}
/**
* Clear previous output
*/
function clearFolders()
{
// Clear and create conversion folder
clearFolder(conversionFolder);
createFolder(conversionFolder);
// Clear and create assets folder
clearFolder(conversionAssets);
createFolder(conversionAssets);
// Clear and create pages folder
clearFolder(conversionPages);
createFolder(conversionPages);
// Clear and create layouts folder
clearFolder(conversionLayouts);
createFolder(conversionLayouts);
// Clear and create Components folder
clearFolder(conversionComponents);
createFolder(conversionComponents);
// Clear and create scss folder
clearFolder(conversionScss);
createFolder(conversionScss);
// Clear and create js folder
clearFolder(conversionJs);
createFolder(conversionJs);
// Clear and create images folder
clearFolder(conversionImg);
createFolder(conversionImg);
// Clear and create css folder
clearFolder(conversionCss);
createFolder(conversionCss);
// Clear and create fonts folder
clearFolder(conversionFonts);
createFolder(conversionFonts);
// Clear vite folder
clearFolder(viteFolder);
}
/**
* Ensure that the user specified a process for the script. Either "function" or "class"
*/
function checkProcess()
{
if (!processName)
{
log('Usage: node migration.js <process?function,class>')
process.exit(1)
}
}
/**
* Handle page title
*/
function handlePageTitle(root)
{
// Extract page title
const titleTag = root.querySelector("title");
let pageTitle;
if (titleTag)
{
let pageTitleLoader = load(logPrefix + " - Extracting page title");
pageTitle = titleTag.innerHTML;
// Remove title tag
titleTag.remove();
pageTitleLoader.succeed(logPrefix + " - Extracted page title");
}
return pageTitle;
}
/**
* Handle Body
*/
function handleBody(body)
{
const bodyAttrs = body.rawAttrs;
const bodyAttrsArray = bodyAttrs.split(" ");
for (let i = 0; i < bodyAttrsArray.length; i++)
{
const attr = bodyAttrsArray[i];
if (attr.includes("class="))
{
const classes = attr.split("=")[1].replace(/"/g, "");
const classesArray = classes.split(" ");
for (let j = 0; j < classesArray.length; j++)
{
const className = classesArray[j];
if (className !== undefined && className !== null && className !== "")
{
const classToAdd = "document.body.classList.add(\"" + className + "\");\n";
if (!componentDidMountPage.includes(classToAdd))
{
componentDidMountPage.push(classToAdd);
}
else
{
componentDidMountPage.remove(classToAdd);
componentDidMountMain.push(classToAdd);
}
}
}
}
}
}
/**
* Handle Images
*/
function handleImages(root)
{
// Resolve unclosed img tags
let importImgLoader = load(logPrefix + " - Importing and converting img tag");
const imgTags = root.querySelectorAll("img");
imgTags.forEach(imgTag =>
{
const imgSrc = imgTag.getAttribute("src");
if (imgSrc !== null)
{
if (fs.existsSync(imgSrc))
{
// Create img folder if it doesn't exist
let imgDest;
if (imgSrc.startsWith("/"))
{
imgDest = imgSrc.substring(1);
}
if (imgSrc.includes("img/") || imgSrc.includes("images/"))
{
// Strip img/ or images/ from path
imgDest = stripPath(imgSrc);
}
// If image source contains folders, create them
const imgSrcFolders = imgDest.split("/");
if (imgSrcFolders.length > 1)
{
let folderPath = conversionImg;
for (let i = 0; i < imgSrcFolders.length - 1; i++)
{
folderPath += "/" + imgSrcFolders[i];
if (!fs.existsSync(folderPath))
{
fs.mkdirSync(folderPath);
}
}
}
// Remove potential "./" from path
if (imgDest.includes("./"))
{
imgDest = imgDest.replace("./", "/");
}
fs.copyFile(imgSrc, conversionImg + imgDest, (err) =>
{
if (err)
{
throw err;
}
});
let fileName = imgSrc.split("/").pop();
fileName = fileName.split(".").shift();
fileName = fileName.replace(/-([a-z])/g, g => g[1].toUpperCase());
// Replace remaining hyphens with underscores
fileName = fileName.replace(/-/g, "_");
// Replace remaining underscores with camel case
fileName = fileName.replace(/_([a-z])/g, g => g[1].toUpperCase());
fileName = fileName.charAt(0).toUpperCase() + fileName.slice(1);
fileName = fileName + "Img";
// If image is in a folder, add folder name to file name
if (imgSrcFolders.length > 1)
{
const folderName = imgSrcFolders[imgSrcFolders.length - 2];
const folderNameCamelCase = folderName.replace(/-([a-z])/g, g => g[1].toUpperCase());
fileName = folderNameCamelCase + fileName;
fileName = fileName.charAt(0).toUpperCase() + fileName.slice(1);
}
const fullImport = "import " + fileName + " from '" + importImg + imgDest + "';";
if (!imports.includes(fullImport))
{
imports.push(fullImport);
}
const jsxImgSrc = "{" + fileName + "}";
imgTag.setAttribute("src", jsxImgSrc);
const alt = imgTag.getAttribute("alt");
if (alt !== null && alt !== "" && alt !== undefined && alt !== "#")
{
imgTag.setAttribute("alt", alt);
}
else
{
imgTag.setAttribute("alt", fileName);
}
if (!imgTag.rawAttrs.endsWith("/"))
{
let unclosedImgLoader = load(logPrefix + " - Fixing unclosed img tag");
imgTag.rawAttrs += "/";
unclosedImgLoader.succeed(logPrefix + " - Fixed unclosed img tag");
}
}
}
});
importImgLoader.succeed(logPrefix + " - Imported and converted img tag");
}
/**
* Handle Inputs
*/
function handleInputs(root)
{
// Resolve unclosed input tags
const fixInputLoader = load(logPrefix + " - Fixing unclosed input tags");
const inputTags = root.querySelectorAll("input");
inputTags.forEach(inputTag =>
{
if (!inputTag.rawAttrs.endsWith("/"))
{
inputTag.rawAttrs += "/";
}
});
fixInputLoader.succeed(logPrefix + " - Fixed unclosed input tags");
}
/**
* Handle styles
*/
function handleStyles(root)
{
// Convert css link to import
const cssConvertLoader = load(logPrefix + " - Converting css link to import");
const cssLinkTags = root.querySelectorAll("link[rel='stylesheet']");
for (let i = 0; i < cssLinkTags.length; i++)
{
const cssLinkTag = cssLinkTags[i];
const link = cssLinkTag.getAttribute("href");
// Look for file in current directory
if (fs.existsSync(link))
{
const scssExtension = ".scss";
const cssFileNoExtension = link.split(".").shift();
const scssFileToFind = cssFileNoExtension.replace("css", "scss");
const scssFile = findFile(scssFileToFind + scssExtension);
if (scssFile !== false)
{
if (!dependencies.includes("sass"))
{
dependencies.push("sass");
}
const scssFileNoPathFound = scssFile.split("/").pop();
const scssFilePathFound = scssFile.replace(scssFileNoPathFound, "");
// Find all scss files in the same directory as the scss file found
const scssFiles = findFiles(scssFilePathFound, scssExtension);
fs.copyFile("./" + scssFile, conversionScss + "/" + scssFileNoPathFound, (err) =>
{
if (err)
{
throw err;
}
});
// Copy all scss files in the same directory as the scss file found
for (let i = 0; i < scssFiles.length; i++)
{
const scssFile = scssFiles[i];
const scssFileNoPath = scssFile.split("/").pop();
// Check if path is folder or file
if (scssFileNoPath.includes("."))
{
fs.copyFile("./" + scssFilePathFound + scssFile, conversionScss + "/" + scssFileNoPath, (err) =>
{
if (err)
{
throw err;
}
});
}
else
{
const newDestFolder = "./" + conversionScss + "/" + scssFileNoPath;
if (!fs.existsSync(newDestFolder))
{
fs.mkdirSync(newDestFolder);
}
// Copy all files in folder
const scssSubFiles = findFiles("./" + scssFilePathFound + scssFile, scssExtension);
for (let i = 0; i < scssSubFiles.length; i++)
{
const scssSubFile = scssSubFiles[i];
const scssSubFileNoPath = scssSubFile.split("/").pop();
fs.copyFileSync("./" + scssFilePathFound + scssFile + "/" + scssSubFileNoPath, newDestFolder + "/" + scssSubFileNoPath);
}
}
}
// // Fix paths in scss files
// for (let i = 0; i < scssFiles.length; i++)
// {
// const scssFile = scssFiles[i];
// const scssFileNoPath = scssFile.split("/").pop();
// const scssFileContent = fs.readFileSync("./" + scssFilePathFound + scssFile, "utf8");
// const urls = scssFileContent.match(/url\((.*?)\)/g);
// if (urls !== null)
// {
// for (let i = 0; i < urls.length; i++)
// {
// const url = urls[i];
// const urlPath = url.split("(").pop().split(")").shift();
// const urlFileName = urlPath.split("/").pop();
// // Check if url contains image
// if (url.includes(".png") || url.includes(".jpg") || url.includes(".jpeg") || url.includes(".gif"))
// {
// if (!isImagePath(url))
// {
// const newUrl = url.replace(url, "url('" + scssImportImg + "/" + urlFileName + ")");
// const newScssFileContent = scssFileContent.replace(url, newUrl);
// fs.writeFileSync(conversionScss + "/" + scssFileNoPath, newScssFileContent, "utf8");
// const imageFileName = urlPath.split("/").pop();
// let newPath = findFile(imageFileName);
// if (newPath !== false)
// {
// newPath = newPath.replace(imageFileName, "");
// fs.copyFile("./" + urlPath, conversionScss + "/" + newPath + imageFileName, (err) =>
// {
// if (err)
// {
// throw err;
// }
// });
// }
// }
// }
// }
// }
// }
// Remove the css link tag
cssLinkTag.remove();
// Add the scss import to the imports array
const scssImport = "import '" + importScss + "/" + scssFileNoPathFound + "';";
if (!imports.includes(scssImport))
{
imports.push(scssImport);
}
}
else
{
const cssFileNoPath = link.split("/").pop();
// Fix paths in css files
const cssFileContent = fs.readFileSync(link, "utf8");
const cssFileContentFixed = cssFileContent.replace(/url\((.*?)\)/g, "url(../img/$1)");
fs.writeFileSync(conversionCss + "/" + cssFileNoPath, cssFileContentFixed);
// Copy file to assets folder
const cssImport = "import '" + importCss + "/" + cssFileNoPath + "';";
imports.push(cssImport);
}
}
// Find images in css file
const cssFileContent = fs.readFileSync(link, "utf8");
const urls = cssFileContent.match(/url\((.*?)\)/g);
if (urls !== null)
{
for (let i = 0; i < urls.length; i++)
{
const url = urls[i];
const urlPath = url.split("(").pop().split(")").shift();
const urlFileName = urlPath.split("/").pop();
// Check if url contains image
if (url.includes(".png") || url.includes(".jpg") || url.includes(".jpeg") || url.includes(".gif"))
{
if (!isImagePath(url))
{
const newUrl = url.replace(url, "url('" + scssImportImg + "/" + urlFileName + ")");
const newCssFileContent = cssFileContent.replace(url, newUrl);
fs.writeFileSync(conversionCss + "/" + urlFileName, newCssFileContent, "utf8");
}
}
}
}
// Remove link tag
cssLinkTag.remove();
}
cssConvertLoader.succeed(logPrefix + " - Converted css link to import");
}
/**
* Handle Javascript
*/
function handleJavascript(root)
{
// Convert js link to import
const jsConvertLoader = load(logPrefix + " - Converting js link to import");
const jsLinkTags = root.querySelectorAll("script[src]");
for (let i = 0; i < jsLinkTags.length; i++)
{
const jsLinkTag = jsLinkTags[i];
const link = jsLinkTag.getAttribute("src");
if (!link.includes("wow"))
{
// Look for file in current directory
if (fs.existsSync(link))
{
const possibleLibraries = [
"jquery",
"bootstrap",
"popper",
"fontawesome",
"slick",
"aos",
"fancybox",
"jqueryui",
"tiny-slider",
"glightbox",
]
let importFile = true;
for (let i = 0; i < possibleLibraries.length; i++)
{
let library = possibleLibraries[i];
if (link.includes(library))
{
importFile = false;
switch (library)
{
case "jquery":
imports.push("import $ from 'jquery';");
dependencies.push("jquery");
break;
case "bootstrap":
imports.push("import 'bootstrap';");
dependencies.push("bootstrap");
break;
case "popper":
imports.push("import 'popper.js';");
dependencies.push("popper.js");
break;
case "fontawesome":
imports.push("import '@fortawesome/fontawesome-free';");
dependencies.push("@fortawesome/fontawesome-free");
break;
case "slick":
imports.push("import 'slick-carousel';");
dependencies.push("slick-carousel");
break;
case "aos":
imports.push("import AOS from 'aos';");
dependencies.push("aos");
if (!componentDidMountPage.includes("AOS.init();"))
{
componentDidMountPage.push("AOS.init();");
}
else
{
componentDidMountMain.push("AOS.init();");
componentDidMountPage.remove("AOS.init();");
}
break;
case "fancybox":
imports.push("import '@fancyapps/fancybox';");
dependencies.push("@fancyapps/fancybox");
break;
case "jqueryui":
imports.push("import 'jquery-ui';");
dependencies.push("jquery-ui");
break;
case "tiny-slider":
imports.push("import { tns } from '../../node_modules/tiny-slider/src/tiny-slider';");
dependencies.push("tiny-slider");
break;
case "glightbox":
imports.push("import GLightbox from 'glightbox';");
dependencies.push("glightbox");
if (!componentDidMountPage.includes("GLightbox"))
{
componentDidMountPage.push("new GLightbox({selector: '.glightbox'});");
}
else
{
componentDidMountMain.push("new GLightbox({selector: '.glightbox'});");
componentDidMountPage.remove("new GLightbox({selector: '.glightbox'});");
}
break;
default:
break;
}
if (library === "bootstrap")
{
if (!dependencies.includes("@popperjs/core"))
{
dependencies.push("@popperjs/core");
}
}
}
}
if (importFile)
{
let finalLink = link;
if (link.includes(".min"))
{
const jsFileNoExtension = link.split(".").shift();
const jsFileToFind = jsFileNoExtension.replace(".min", "");
const jsFile = findFile(jsFileToFind + ".js");
if (jsFile !== false)
{
finalLink = jsFile;
}
}
let jsFileContents = fs.readFileSync(finalLink, "utf8");
// Check if there is WOW.js in the file
if (jsFileContents.includes("new WOW().init();"))
{
// Strip out the WOW.js code
jsFileContents = jsFileContents.replace(/new WOW\(\)\.init\(\);/g, "");
}
componentDidMountPage.push(jsFileContents);
}
}
else if (link.includes("https://"))
{
imports.push("import '" + link + "';\n");
}
}
// Remove link tag
jsLinkTag.remove();