Skip to content

Instantly share code, notes, and snippets.

@tordans
Created October 11, 2023 08:01
Show Gist options
  • Save tordans/314d7671c622aac0c3852bbb18976ee9 to your computer and use it in GitHub Desktop.
Save tordans/314d7671c622aac0c3852bbb18976ee9 to your computer and use it in GitHub Desktop.
Quick helper script to add `use client` to all ts/tsx files in all folders except when it was added already. (Thanks to Github Copilot for creating this.)
// 0. Stash everything in git to have a clean slate
// 1. Update `folderPath`
// 2. Run with `node add-use-client-to-all-files.cjs` from the root of your project
const fs = require('fs')
const path = require('path')
const folderPath = './src/app' // Replace with the path to your folder
function updateFilesInFolder(folderPath) {
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error(err)
return
}
files.forEach((file) => {
const filePath = path.join(folderPath, file)
// Check if the file is a directory
if (fs.statSync(filePath).isDirectory()) {
// Recursively call the function for subdirectories
updateFilesInFolder(filePath)
} else if (path.extname(filePath) === '.ts' || path.extname(filePath) === '.tsx') {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(err)
return
}
if (data.includes('use client')) {
console.log(`Skipped ${filePath}`)
return
}
const newData = `'use client'\n\n${data}`
fs.writeFile(filePath, newData, (err) => {
if (err) {
console.error(err)
return
}
console.log(`Updated ${filePath}`)
})
})
}
})
})
}
updateFilesInFolder(folderPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment