megawac / acorn-umd

Parse acorn ast for AMD, CommonJS, and ES6 definitions.
MIT License
4 stars 1 forks source link

Getting modules reguardless of javascript AST syntax #6

Open reggi opened 8 years ago

reggi commented 8 years ago

I have a repo here with some demo code It's written with babel so you'd need to use babel-node ./parse.js to run it. https://github.com/reggi/test-acorn-umd

The issue is that acorn builds an AST of a file, and when it encounters a syntax it's not familiar with it's not sure how to parse it.

getDeps('./typescript.ts')
  .then(console.log)
  .catch(console.error.bind(console))
/*
{ [SyntaxError: The keyword 'public' is reserved (4:16)] pos: 55, loc: Position { line: 4, column: 16 }, raisedAt: 61 }
*/

getDeps('./parse.js')
  .then(console.log)
  .catch(console.error.bind(console))
/*
{ [SyntaxError: Unexpected token (11:6)]
  pos: 312,
  loc: Position { line: 11, column: 6 },
  raisedAt: 320 }
*/

Here's two examples, one with typescript, and one using babel and async / await.

@megawac tell me how you feel about this, but I don't think I need to build an AST at all. A complicated regex could look for the module definition. It's hard because you have to allow for ", ', ` and get the contents of the definition, and you have to ensure the definition is not within a comment.

import x from 'x'
require('something')

Thoughts on how I can get the module definitions of any file.

I just want to pass this in and get ['x', 'lodash', 'bluebird'].

import x from 'x'
// import y from 'y'
blah blah blah invalid ( javascript ] should not function matter get 
require("lodash")
this should work as well
require(`bluebird`)

This is a crazy case, and may be over the top. Alternatively I might be comfortable with a syntax declaration.

getDeps('./typescript.ts', 'typescript')
getDeps('./file.js', 'babel')
getDeps('./file.js', 'coffeescript')
getDeps('./file.js', 'flow')

Or even run down the list and hope one doesn't throw an error.

reggi commented 8 years ago

Just created this https://github.com/reggi/babylon-module-definitons

It gets module definitions using babylon, at least I have babel and technically flow working now.