Skip to content

Commit

Permalink
feat: making the transpiled version of react-template optional (#243)
Browse files Browse the repository at this point in the history
Co-authored-by: Lukasz Gornicki <lpgornicki@gmail.com>
  • Loading branch information
Gmin2 and derberg authored Aug 12, 2024
1 parent 61568f2 commit 74759e6
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/renderer/template.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from "react";
import fs from "fs";

import { render } from "./renderer";
import { isJsFile } from "../utils";
Expand Down Expand Up @@ -47,10 +48,24 @@ function importComponent(filepath: string): Promise<TemplateFunction | undefined
try {
// we should import component only in NodeJS
if (require === undefined) resolve(undefined);
// remove from cache imported file
delete require.cache[require.resolve(filepath)];

const component = require(filepath);
let componentPath = filepath;

// Check if the file exists
if (!fs.existsSync(componentPath)) {
// If transpiled version doesn't exist, try the original version
const originalPath = componentPath.replace('__transpiled', 'template');
if (fs.existsSync(originalPath)) {
componentPath = originalPath;
} else {
throw new Error(`Neither transpiled nor original template file found: ${filepath}`);
}
}

// Remove from cache and require the file
delete require.cache[require.resolve(componentPath)];
const component = require(componentPath);

if (typeof component === "function") resolve(component);
if (typeof component.default === "function") resolve(component.default);
resolve(undefined);
Expand Down

0 comments on commit 74759e6

Please sign in to comment.