1
1
import * as vscode from "vscode" ;
2
2
3
3
import { basename , join } from "path" ;
4
- import { rm } from "fs/promises" ;
4
+ import { rm , unlink , writeFile } from "fs/promises" ;
5
5
import * as esbuild from "esbuild" ;
6
6
7
7
import { render } from "@react-email/render" ;
@@ -29,27 +29,37 @@ export async function renderOpenEmailFile(
29
29
return { valid : false } ;
30
30
}
31
31
32
+
32
33
const currentlyOpenTabFilePath = activeEditor . document . fileName ; // actually a path not the name of the file
33
- const emailsDirectory = join ( currentlyOpenTabFilePath , ".. " ) ;
34
+ const currentlyOpenTabFilename = basename ( currentlyOpenTabFilePath , ".tsx " ) ;
34
35
36
+ const emailsDirectory = join ( currentlyOpenTabFilePath , ".." ) ;
35
37
const previewDirectory = join ( emailsDirectory , extensionPreviewFolder ) ;
38
+
39
+ // this is necessary so that we can still build things in a stable way
40
+ // and have a up-to date version of the email preview on the extension
41
+ const currentlyOpenTabFilesPathWithCurrentContents = join ( emailsDirectory , `${ currentlyOpenTabFilename } .vscpreview.tsx` ) ;
42
+ const currentContents = activeEditor . document . getText ( ) ;
43
+ await writeFile ( currentlyOpenTabFilesPathWithCurrentContents , currentContents ) ;
44
+
45
+ const builtFileWithCurrentContents = join ( previewDirectory , `${ currentlyOpenTabFilename } .js` ) ;
46
+
36
47
try {
37
48
await esbuild . build ( {
38
49
bundle : true ,
39
- entryPoints : [ currentlyOpenTabFilePath ] ,
50
+ entryPoints : [ currentlyOpenTabFilesPathWithCurrentContents ] ,
40
51
platform : "node" ,
41
52
write : true ,
42
- outdir : previewDirectory ,
53
+ outfile : builtFileWithCurrentContents ,
43
54
} ) ;
44
55
45
- const filename = basename ( currentlyOpenTabFilePath , ".tsx" ) ;
46
- const templatePath = `${ previewDirectory } /${ filename } .js` ;
56
+ await unlink ( currentlyOpenTabFilesPathWithCurrentContents ) ; // unlink the temporary file after building it
47
57
48
- delete require . cache [ templatePath ] ;
58
+ delete require . cache [ builtFileWithCurrentContents ] ;
49
59
// we need to use require since it has a way to programatically invalidate its cache
50
- const email = require ( templatePath ) ;
60
+ const email = require ( builtFileWithCurrentContents ) ;
51
61
52
- if ( typeof email . default === "undefined" ) {
62
+ if ( typeof email . default === "undefined" ) { // this means there is no "export default ..." in the file
53
63
return { valid : false } ;
54
64
}
55
65
@@ -63,7 +73,7 @@ export async function renderOpenEmailFile(
63
73
await rm ( previewDirectory , { recursive : true } ) ;
64
74
65
75
return {
66
- filename,
76
+ filename : currentlyOpenTabFilename ,
67
77
html : emailAsHTML ,
68
78
text : emailAsText ,
69
79
valid : true ,
0 commit comments