Skip to content

Instantly share code, notes, and snippets.

@kugimiya
Created February 20, 2024 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kugimiya/83cf18f4e4f288c1e3dbc71655d323ab to your computer and use it in GitHub Desktop.
Save kugimiya/83cf18f4e4f288c1e3dbc71655d323ab to your computer and use it in GitHub Desktop.
Fixer of unemitted imports processed by TS with "paths"
/**
* Специальный скрипт, который фиксит отсутствие emit'а тс-импортов
* А так же копирует в dist такие вещи как assets
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires,no-undef
const fs = require('node:fs');
console.log('INFO: Start postbuild.js');
const fixEsImports = (fileContent = '', level = 0) => {
let lines = fileContent.split('\n');
lines = lines.map((line) => {
if (/import.*from/.test(line) || /import '.*'/.test(line)) {
const backpath = (new Array(level).fill('../')).join('');
return line.replace('~/', backpath);
}
return line;
});
return lines.join('\n');
};
const fixScssImports = (fileContent = '', level = 0) => {
let lines = fileContent.split('\n');
lines = lines.map((line) => {
if (/@import.*/.test(line) || /url\(.*\)/.test(line)) {
const backpath = (new Array(level).fill('../')).join('');
return line.replace('src/', backpath);
}
return line;
});
return lines.join('\n');
};
const readDirRecursively = (root = 'dist') => {
const result = {};
const readResult = fs.readdirSync(root);
readResult.forEach((path) => {
result[path] = {
isDir: fs.statSync(`${root}/${path}`).isDirectory(),
contents: []
};
if (result[path].isDir) {
result[path].contents = readDirRecursively(`${root}/${path}`);
} else {
result[path].contents = null;
}
});
return result;
};
const traverseRecursive = (tree = {}, cb, level = 0, prevPath = 'dist') => {
Object.entries(tree).forEach(([ path, { isDir, contents } ]) => {
const allPath = `${prevPath}/${path}`;
if (isDir) {
traverseRecursive(contents, cb, level + 1, allPath);
} else {
cb(allPath, level);
}
});
};
// Копирование прочих файлов
fs.cpSync('src/assets', 'dist/assets', { recursive: true });
fs.cpSync('src/mocks', 'dist/mocks', { recursive: true });
const srcStructure = readDirRecursively('src');
traverseRecursive(srcStructure, (allPath) => {
if (allPath.includes('.scss')) {
fs.copyFileSync(allPath, allPath.replace('src', 'dist'));
}
}, 0, 'src');
// Фикс путей (es modules + scss imports)
const structure = readDirRecursively();
traverseRecursive(structure, (allPath, level) => {
if (allPath.includes('.scss')) {
const file = fs.readFileSync(allPath).toString();
const fixed = fixScssImports(file, level);
fs.writeFileSync(allPath, fixed);
} else {
const file = fs.readFileSync(allPath).toString();
const fixed = fixEsImports(file, level);
fs.writeFileSync(allPath, fixed);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment