Class RewriteDynamicImports

  • All Implemented Interfaces:
    CompilerPass, NodeTraversal.Callback

    public class RewriteDynamicImports
    extends NodeTraversal.AbstractPostOrderCallback
    implements CompilerPass
    Rewrite dynamic import expressions to account for bundling and module rewriting. Since dynamic imports cannot be fully polyfilled, optionally support replacing the expression with a function call (alias function) which indicates an external polyfill is utilized.

    If the import specifier is a string literal and the module resolver recognizes the target, the pass retargets the specifier to the correct output chunk.

    Example from:

       import('./input-module1.js');
     
    To:
       imprt_('./output-chunk0.js').then(function() { return module$output$chunk0; });
     

    Unlike other "rewrite" passes for which the DefaultPassConfig checks the output language level using options.needsTranspilationOf(feature) before adding a pass, it does not check the language level before adding this particular pass. Even when supported by the output level, we still invoke this pass if options.shouldAllowDynamicImport() is set. The only difference is that for ES2020, the dynamic imports syntax can pass through if aliasing is not requested, while for < ES2020 they must get rewritten using the alias call.

     

    options.shouldAllowDynamicImport() === false? ForbidDynamicImportUsage : (output >= ES2020) ? don't *really* rewrite it unless aliasing is requested : rewrite it using the alias call

    TODO: b/291319705 For the above reason, the pass should be better named as MaybeRewriteDynamicImports.

    • Method Detail

      • process

        public void process​(Node externs,
                            Node root)
        Description copied from interface: CompilerPass
        Process the JS with root node root. Can modify the contents of each Node tree
        Specified by:
        process in interface CompilerPass
        Parameters:
        externs - Top of external JS tree
        root - Top of JS tree
      • visit

        public void visit​(NodeTraversal t,
                          Node n,
                          Node parent)
        Description copied from interface: NodeTraversal.Callback
        Visits a node in postorder (after its children). A node is visited in postorder iff NodeTraversal.Callback.shouldTraverse(NodeTraversal, Node, Node) returned true for its parent. In particular, the root node is never visited in postorder.

        Siblings are always visited left-to-right.

        Implementations can have side-effects (e.g. modify the parse tree). Removing the current node is legal, but removing or reordering nodes above the current node may cause nodes to be visited twice or not at all.

        Specified by:
        visit in interface NodeTraversal.Callback
        Parameters:
        t - The current traversal.
        n - The current node.
        parent - The parent of the current node.