|
| 1 | +import { transform } from 'babel-core'; |
| 2 | +import resolveRc from 'babel-core/lib/babel/tools/resolve-rc'; |
| 3 | +import * as babelUtil from 'babel-core/lib/babel/util'; |
| 4 | +import glob from 'glob'; |
| 5 | +import fs from 'fs'; |
| 6 | +import path from 'path'; |
| 7 | +import outputFileSync from 'output-file-sync'; |
| 8 | + |
| 9 | +export function buildContent(content, filename, destination, babelOptions={}) { |
| 10 | + const result = transform(content, resolveRc(filename, babelOptions)); |
| 11 | + outputFileSync(destination, result.code, {encoding: 'utf8'}); |
| 12 | +} |
| 13 | + |
| 14 | +export function buildFile(filename, destination, babelOptions={}) { |
| 15 | + const content = fs.readFileSync(filename, {encoding: 'utf8'}); |
| 16 | + if(babelUtil.canCompile(filename)) { |
| 17 | + // Get file basename without the extension (in case not .js) |
| 18 | + let outputName = path.basename(filename, path.extname(filename)); |
| 19 | + // append the file basename with extension .js |
| 20 | + let outputPath = path.join(destination, outputName + '.js'); |
| 21 | + // console.log('%s => %s', filename, outputPath); |
| 22 | + buildContent(content, filename, outputPath, babelOptions); |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +export function buildFolder(folderPath, destination, babelOptions={}, firstFolder=true) { |
| 27 | + let stats = fs.statSync(folderPath); |
| 28 | + |
| 29 | + if(stats.isFile()) { |
| 30 | + buildFile(folderPath, destination, babelOptions); |
| 31 | + } else if(stats.isDirectory()) { |
| 32 | + let outputPath = firstFolder ? destination : path.join(destination, path.basename(folderPath)); |
| 33 | + let files = fs.readdirSync(folderPath).map(file => path.join(folderPath, file)); |
| 34 | + files.forEach(filename => buildFolder(filename, outputPath, babelOptions, false)); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +export function buildGlob(filesGlob, destination, babelOptions={}) { |
| 39 | + let files = glob.sync(filesGlob); |
| 40 | + if (!files.length) { |
| 41 | + files = [filesGlob]; |
| 42 | + } |
| 43 | + files.forEach(filename => buildFolder(filename, destination, babelOptions, true)); |
| 44 | +} |
| 45 | + |
0 commit comments