Here is another practical use of Babel, used in Webpack source code to get dependencies on entry files

// Find an entry file
// Parse the entry file to find its dependencies
// Parse the dependencies of the entry file, recursively create a dependency graph of the file, describing the dependencies of all files
// Pack all the files into one file
const fs = require('fs')
const babylon = require('babylon')
const traverse = require('babel-traverse').default
let ID =0
function createAsset(filename){
    const content = fs.readFileSync(filename,'utf-8')
    //console.log(content)
    const ast = babylon.parse(content,{
        sourceType: "module"
    })
    const dependencies = []
    traverse(ast,{
        ImportDeclaration:({node}) = >{
            dependencies.push(node.source.value)
            //console.log(dependencies)}})const id = ID++
    return {
        id,
        filename,
        dependencies
    }
    //0 ./source/entry.js [ './message' ]
}
function createGraph(entry){
    const mainAsset = createAsset(entry)
}
const graph = createGraph('./source/entry.js')
console.log(graph)
Copy the code