Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#82 but with babel options #83

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

TikiTDO
Copy link

@TikiTDO TikiTDO commented Oct 5, 2020

Continuing from #82, with more generic handling...

What: Allows preval to parse typescript (and potentially any dialect supported by babel with some extra work)

Why: Preval currently chokes on typescript.

This PR serves as a proof-of-concept to show that a TS file can be transformed into plain JS before being handed off the the require-from-string helper.

This could be generalized with a more extensive set of transformers, or potentially even a babel option for the plugin to allow an arbitrary set of extra plugins.

How: Check for typescript files when parsing a @preval tagged file, and optionally parse it with the typescript transformer enabled.

Note, this example only handled the file comment approach, since that code already used babel for parsing the input file. Expanding this it to support the other three approaches would require some changes to use babel handlers such as transformFileSync or transformSync

@TikiTDO
Copy link
Author

TikiTDO commented Oct 5, 2020

@kentcdodds In terms of babel options, I was just thinking something like this. Fairly simple, but gives users complete control of how to parse the code they would like to preval.

@codecov
Copy link

codecov bot commented Oct 5, 2020

Codecov Report

Merging #83 into master will not change coverage.
The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff            @@
##            master       #83   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            4         4           
  Lines          106       109    +3     
  Branches        22        25    +3     
=========================================
+ Hits           106       109    +3     
Impacted Files Coverage Δ
src/index.js 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 7b0e710...f3d53ac. Read the comment docs.

Copy link
Owner

@kentcdodds kentcdodds left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add docs for how someone would configure this?

@TikiTDO
Copy link
Author

TikiTDO commented Oct 7, 2020

I added an example of how you might use this for typescript.

@TikiTDO
Copy link
Author

TikiTDO commented Oct 7, 2020

The component API is currently the only one that currently uses the babel parser, and it's the only one I actively use.

Looking at the other ones, it should be pretty straight forward to use the transform or transformSync method to also add this functionality to the other two scenarios. However it's not something I've verified so I want to make sure you're ok with this approach before I spend time on getting those working too.

If you're happy with this approach I can see about normalizing the approach for all three of them.

@kentcdodds
Copy link
Owner

I am. Thank you so much for working on this @TikiTDO :) I think normalizing it would be a good idea.

@TikiTDO
Copy link
Author

TikiTDO commented Oct 7, 2020

I tried adding a transform call conditional on having the prevalBabelOptions option. I seems to work (or at least it seems to not break existing scenarios), though a full test would require actually testing with a real plugin.

I will need to come back to it tomorrow to double check everything, and generalize the readme.

@lencioni
Copy link

lencioni commented Jan 15, 2021

@TikiTDO Thanks for your work on this so far! I am working in a codebase that we are trying to convert completely to TypeScript, and I think this PR might help me out. Have you had any luck double-checking and generalizing the readme?

@TikiTDO
Copy link
Author

TikiTDO commented Jan 15, 2021

Oh wow, sorry, totally forgot about this.

With the changes in this PR, the config passed to prevalBabelOptions should get passed into all the transform calls, so it's a matter of finding the correct set of plugins necessary to fully parse and transform your code. Most of the challenge comes from figuring out which set of plugins actually results in a viable result. If you specify the wrong set it will give you code which will make requireFromString choke.

I have a mountain of work today, but I'll leave a tab open and hopefully remember to come back to it in the evening / over the weekend.

@lencioni
Copy link

I've built this version and pushed it up here so I could more easily install it and try it out in my codebase: lencioni@cd9e6d0

I installed it by running

yarn add https://github.com/lencioni/babel-plugin-preval#cd9e6d0daebc2b3996fc88927b71f8ab8edcdc50

And then I configured it like this:

      "plugins": [
        [
          "preval",
          {
            "prevalBabelOptions": {
              "presets": [
                "@babel/typescript",
                "@babel/preset-env",
                {
                  "targets": {
                    "node": true
                  },

                  "modules": true,
                  "bugfixes": true
                }
              ],

              "plugins": [
                "inline-json-import",
                "@babel/plugin-transform-modules-commonjs",
              ]
            }
          }
        ]

I've tried it with a few other settings as well, but I can't seem to get it to work. I just end up with errors like

SyntaxError: Cannot use import statement outside a module

or

SyntaxError: Unexpected token 'export'

I expected either the preset-env or the plugin-transform-modules-commonjs to cover this, but it doesn't seem to be taking effect. Did I mess it up?

@TikiTDO
Copy link
Author

TikiTDO commented Jan 15, 2021

That looks familiar. I could never get it working with @babel/preset-env. It tries to do a lot of magic that isn't necessarily useful.

Had to use these two plugins, without any presets:

"@babel/plugin-transform-typescript", "@babel/plugin-transform-modules-commonjs"

@TikiTDO
Copy link
Author

TikiTDO commented Jan 15, 2021

Those two plugins worked for this snippet:

// @preval
import { country } from "iso-3166-2"

export default ["CA", "US"].reduce<{ [key: string]: Array<{ code: string; name: string }> }>(
  (acc, countryCode) => {
    acc[countryCode] = Object.entries((country(countryCode) || { sub: [] }).sub)
      .map(([key, value]) => ({ code: key.split("-")[1], name: value.name }))
      .sort((first, second) => {
        const firstProv = first.name.toLowerCase()
        const secondProv = second.name.toLowerCase()
        if (firstProv < secondProv) {
          return -1
        } else if (firstProv > secondProv) {
          return 1
        } else {
          return 0
        }
      })
    return acc
  },
  {},
)

@lencioni
Copy link

lencioni commented Jan 15, 2021

Yeah, those two plugins are one of the combos I tried, but got the same result. This is my entire file that I'm testing it on:

// @preval

import '../../../private/babelHelpersForPreval';

I wonder if my build or yarn install didn't get your changes somehow...

Base automatically changed from master to main January 25, 2021 23:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants