Last active
July 28, 2021 01:25
-
-
Save ulises-castro/a86cd67fcbab0220db9660a2f8516c02 to your computer and use it in GitHub Desktop.
Reload forcing to react typescript project - Hot reloading breaks when encountering Typescript error (Create React App)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This scripts is a simple patch to force our react project to recompile after an typescript error was throwed and app had been frozen. | |
// More Details about the issue: https://github.com/facebook/create-react-app/issues/8667 | |
// The steps | |
// Save the script into your project's root folder | |
// yarn chokidar --dev | npm install chokidar --save-dev | |
// then run your app and in a another terminal run "node reload-force.js" | |
// NOTE: It needs be refactor in order to become more flexible, right now IT ONLY WORKS WITH App () | |
var fs = require("fs"); | |
var chokidar = require("chokidar"); | |
// Your root app component | |
var rootAppFile = "src/App.tsx"; | |
var watcher = chokidar.watch("src", { | |
ignored: rootAppFile, | |
persistent: true, | |
}); | |
function updateRootFileToForceReload() { | |
return new Promise(function (resolve) { | |
var appRootComponent = "App() "; | |
var oldVersionOfFile = null; | |
fs.readFile(rootAppFile, "utf-8", function (err, fileBody) { | |
if (err) { | |
throw err; | |
} else { | |
oldVersionOfFile = fileBody; | |
fileBody = fileBody.replace( | |
appRootComponent, | |
appRootComponent + "\r\n" | |
); | |
} | |
fs.writeFile(rootAppFile, fileBody, "utf-8", function (err) { | |
if (err) { | |
throw err; | |
} else { | |
// Removing the temp chapters added to file | |
setTimeout(function () { | |
fs.writeFile( | |
rootAppFile, | |
oldVersionOfFile, | |
"utf-8", | |
function (err) { | |
if (err) { | |
throw err; | |
} else { | |
resolve(); | |
} | |
} | |
); | |
}, 300); | |
} | |
}); | |
}); | |
}); | |
} | |
watcher | |
.on("change", function (filePath) { | |
updateRootFileToForceReload(); | |
console.log("File", filePath); | |
}) | |
.on("error", function (error) { | |
console.log("Error happend", error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment