Skip to content

Instantly share code, notes, and snippets.

@revskill10
Created May 17, 2024 17:00
Show Gist options
  • Select an option

  • Save revskill10/778721edab856e825c2ae13edc92ab6c to your computer and use it in GitHub Desktop.

Select an option

Save revskill10/778721edab856e825c2ae13edc92ab6c to your computer and use it in GitHub Desktop.

Revisions

  1. revskill10 created this gist May 17, 2024.
    72 changes: 72 additions & 0 deletions preprocess-use-client.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    const fs = require('fs');
    const path = require('path');
    const acorn = require('acorn');
    const walk = require('acorn-walk');

    // List of React hooks to look for
    const hooks = ['useState', 'useEffect', 'useContext', 'useReducer', 'useCallback', 'useMemo', 'useRef', 'useImperativeHandle', 'useLayoutEffect', 'useDebugValue'];

    // Function to check if a file contains React hooks
    const containsReactHooks = (code) => {
    let containsHook = false;

    try {
    const ast = acorn.parse(code, { ecmaVersion: 'latest', sourceType: 'module' });

    walk.simple(ast, {
    CallExpression(node) {
    if (hooks.includes(node.callee.name)) {
    containsHook = true;
    }
    },
    });
    } catch (error) {
    console.error('Error parsing code:', error);
    }

    return containsHook;
    };

    // Function to process files
    const processFile = (filePath) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
    return console.error('Error reading file:', err);
    }

    if (containsReactHooks(data)) {
    if (!data.startsWith("'use client'\n")) {
    const updatedData = `'use client'\n${data}`;
    fs.writeFile(filePath, updatedData, 'utf8', (writeErr) => {
    if (writeErr) {
    return console.error('Error writing file:', writeErr);
    }
    console.log(`Updated file: ${filePath}`);
    });
    }
    }
    });
    };

    // Function to read directories recursively
    const readDirectory = (dir) => {
    fs.readdir(dir, { withFileTypes: true }, (err, files) => {
    if (err) {
    return console.error('Error reading directory:', err);
    }

    files.forEach((file) => {
    const filePath = path.join(dir, file.name);

    if (file.isDirectory()) {
    readDirectory(filePath);
    } else if (file.isFile() && file.name.endsWith('.js')) {
    processFile(filePath);
    }
    });
    });
    };

    // Start reading from the target directory
    const targetDirectory = path.resolve(__dirname, 'src'); // Change 'src' to your target directory
    readDirectory(targetDirectory);