Skip to content

Instantly share code, notes, and snippets.

@msvargas
Last active October 28, 2022 15:20
Show Gist options
  • Save msvargas/a574a57e618247f03177ed838aeee40a to your computer and use it in GitHub Desktop.
Save msvargas/a574a57e618247f03177ed838aeee40a to your computer and use it in GitHub Desktop.
Import to React Lazy
const { execSync } = require('child_process');
const os = require('os');
const path = require('path');
const fs = require('fs');
const tempFile = path.resolve(os.tmpdir(), 'importFile.js');
const IMPORT_REGEX = /import\s+(\S+)\s+from\s+['|"](\S+)['|"]/gm;
let result;
let output = '';
fs.writeFileSync(tempFile, '');
execSync(`vi ${tempFile}`, { stdio: 'inherit' });
const inputImports = fs.readFileSync(tempFile).toString();
const kebabCase = (string) =>
string
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase();
while ((result = IMPORT_REGEX.exec(inputImports)) !== null) {
const componentName = result[1];
const filePath = result[2];
const out = `const ${componentName} = React.lazy(()=> import(/* webpackChunkName: '${kebabCase(
componentName
)}'*/ '${filePath}'));`;
output += out + '\n';
}
fs.writeFileSync(tempFile, output, { encoding: 'utf-8' });
execSync(`pbcopy < ${tempFile}`);
console.log('Sucessful, copied to clipboard!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment