inject.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* eslint-disable no-underscore-dangle */
  2. export default function injectDynamicImport(acorn) {
  3. const tt = acorn.tokTypes;
  4. // NOTE: This allows `yield import()` to parse correctly.
  5. tt._import.startsExpr = true;
  6. function parseDynamicImport() {
  7. const node = this.startNode();
  8. this.next();
  9. if (this.type !== tt.parenL) {
  10. this.unexpected();
  11. }
  12. return this.finishNode(node, 'Import');
  13. }
  14. function peekNext() {
  15. return this.input[this.pos];
  16. }
  17. // eslint-disable-next-line no-param-reassign
  18. acorn.plugins.dynamicImport = function dynamicImportPlugin(instance) {
  19. instance.extend('parseStatement', nextMethod => (
  20. function parseStatement(...args) {
  21. const node = this.startNode();
  22. if (this.type === tt._import) {
  23. const nextToken = peekNext.call(this);
  24. if (nextToken === tt.parenL.label) {
  25. const expr = this.parseExpression();
  26. return this.parseExpressionStatement(node, expr);
  27. }
  28. }
  29. return nextMethod.apply(this, args);
  30. }
  31. ));
  32. instance.extend('parseExprAtom', nextMethod => (
  33. function parseExprAtom(refDestructuringErrors) {
  34. if (this.type === tt._import) {
  35. return parseDynamicImport.call(this);
  36. }
  37. return nextMethod.call(this, refDestructuringErrors);
  38. }
  39. ));
  40. };
  41. return acorn;
  42. }