sucrase icon indicating copy to clipboard operation
sucrase copied to clipboard

esbuild `onResolve` equivalent in sucrase

Open itismoej opened this issue 1 year ago • 3 comments

Is there anything like the onResolve callback of esbuild in sucrase?

Based on documentation of esbuild:

A callback added using onResolve will be run on each import path in each module that esbuild builds. The callback can customize how esbuild does path resolution.

itismoej avatar Aug 02 '22 10:08 itismoej

Hi @mjafari98 , sorry, Sucrase doesn't have an option like that. To be clear, Sucrase isn't by itself a bundler, so I think the equivalent in Sucrase would be a function to modify import paths in the output code. Generally I've viewed import path transformation as out of scope for Sucrase, since Sucrase is primarily focused on just turning TypeScript/JSX/Flow code into regular JavaScript. Often times you can customize import behavior in your bundler or using Node hooks.

Would you mind sharing your use case? I'm hesitant to add a feature like onResolve because it's more configuration complexity than I want Sucrase to have, but it could be doable as an advanced option if the use case is compelling enough.

alangpierce avatar Aug 02 '22 20:08 alangpierce

I am creating an in-browser bundler like codesandbox and I would like to use Sucrase. But the require functions won't work since they are not accessible in browser.

itismoej avatar Aug 03 '22 05:08 itismoej

Cool, makes sense. Yeah, Sucrase doesn't have an external-facing way to expose import/require usages within a file, but it should be possible to hack something together yourself by importing Sucrase's internal/unstable parse function, which gives you a list of tokens to work with. Since it's internal and unstable, you might see breaking changes on any Sucrase version, so you should pin to a specific version, but you're still welcome to use it.

Here's an example in the node repl:

> parse = require('sucrase/dist/parser').parse;
[Function: parse]
> parse('const x = 1;', true, true, false);
File {
  tokens: [
    Token {
      type: 79888,
      contextualKeyword: 0,
      start: 0,
      end: 5,
      scopeDepth: 0,

From there, you could identify require calls by finding the pattern (tt.name && ContextualKeyword._require), tt.parenL, tt.string, tt.parenR, and I think you could identify static imports by finding the pattern (tt.name && ContextualKeyword._from), tt.string. To be clear, that's just my informal way of describing what to match on, tt is the TokenType enum, and you'd need to write your own code to loop through the tokens and find ones with those token types and contextual keywords.

You might have better luck finding another tool, just calling out how you might be able to get something working using Sucrase. Good luck with the project!

alangpierce avatar Aug 03 '22 18:08 alangpierce