如何使用babel / parser解析可能无效的javascript片段,转换为AST?

时间:2019-02-18 17:39:41

标签: javascript parsing babeljs babel abstract-syntax-tree

我正在尝试使用public void selectDrawerItem(MenuItem menuItem) { // Create a new fragment and specify the fragment to show based on nav item clicked Fragment fragment = null; Class fragmentClass; switch(menuItem.getItemId()) { case R.id.nav_first_fragment: fragmentClass = FirstFragment.class; getSupportFragmentManager().beginTransaction().replace(R.id.flContent, new FirstFragment()).commit(); break; case R.id.nav_second_fragment: fragmentClass = SecondFragment.class; getSupportFragmentManager().beginTransaction().replace(R.id.flContent, new SecondFragment()).commit(); break; case R.id.nav_third_fragment: fragmentClass = ThirdFragment.class; getSupportFragmentManager().beginTransaction().replace(R.id.flContent, new ThirdFragment()).commit(); break; default: fragmentClass = FirstFragment.class; } try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); // Highlight the selected item has been done by NavigationView menuItem.setChecked(true); // Set action bar title setTitle(menuItem.getTitle()); // Close the navigation drawer mDrawer.closeDrawers(); } // ... 从Javascript片段生成AST:

@babel/parser

...产生的结果:

const parse = require('@babel/parser').parse;

const fragment = 'if (x > 3) {';

const ast = parse(fragment, {
  allowImportExportEverywhere: true,
  allowAwaitOutsideFunction: true,
  allowReturnOutsideFunction: true,
  allowSuperOutsideMethod: true,
  sourceType: 'unambiguous',
  plugins: ['jsx'],
});

...或引发的异常。

是否可以强制解析器接受这些片段?还是可以使用babel解析替代方案来解决此问题?

我意识到生成的AST也将无效,但这与我的用例无关。

0 个答案:

没有答案