Code Monkey home page Code Monkey logo

kentcdodds / asts-workshop Goto Github PK

View Code? Open in Web Editor NEW
299.0 8.0 79.0 1.24 MB

Improved productivity ๐Ÿ’ฏ with the practical ๐Ÿค“ use of the power ๐Ÿ’ช of Abstract Syntax Trees ๐ŸŒณ to lint โš ๏ธ and transform ๐Ÿ”€ your code

Home Page: http://kcd.im/asts-workshop-slides

License: MIT License

JavaScript 99.93% Handlebars 0.07%
workshop javascript asts abstract-syntax-tree babel eslint codemod kcd-edu

asts-workshop's Introduction

JavaScript ASTs Workshop

Improved productivity ๐Ÿ’ฏ with the practical ๐Ÿค“ use of the power ๐Ÿ’ช of Abstract Syntax Trees ๐ŸŒณ to lint โš ๏ธ and transform ๐Ÿ”€ your code

slides-badge chat-badge Build Status Dependencies MIT License All Contributors

PRs Welcome Donate Code of Conduct Watch on GitHub Star on GitHub Tweet

Sponsor

Before You Start

I've used this repo to teach about ASTs in various settings. I've branched the repo for each one of them. Reference those branches based on what you're following along with:

  • Frontend Masters: fem

To checkout that branch run: git checkout <branch name>. From there on you should be good.

You may also want to check out the Changes section in the README below.

Welcome

By coding along with us in this workshop youโ€™ll:

  • Learn what can be done with Abstract Syntax Trees.
  • Explore what tools are available for learning about and developing with ASTs.
  • Discover what ASTs are.
  • Understand why and how to write custom ESLint rules
  • Write custom Babel plugins
  • Learn why and how to write a codemod with Babel

Workshop workflow

The workflow of this workshop is fairly simple and based on Make It Stick methodologies:

  1. Learn a few concepts via demos
  2. Apply the concepts via exercises
  3. Write down three core concepts you learned and provide feedback on the exercise (elaboration and reflection)

Project

System Requirements

  • git v2.10.2 or greater
  • NodeJS v6.9.5 or greater
  • yarn v0.20.3 or greater (or npm v4.2.0 or greater)

All of these must be available in your PATH. To verify things are set up properly, you can run this:

git --version
node --version
yarn --version

If you have trouble with any of these, learn more about the PATH environment variable and how to fix it here for windows or mac/linux.

Setup

After you've made sure to have the correct things (and versions) installed, you should be able to just run a few commands to get set up:

git clone https://github.com/kentcdodds/asts-workshop.git
cd asts-workshop
yarn run setup --silent
node scripts/autofill-feedback-email.js [email protected]
git commit -am "ready to go"

Replace [email protected] with your email address

This may take a few minutes. If you get any errors, please read the error output and see whether there's any instructions to fix things and try again. If you're still getting errors or need any help at all, then please file an issue.

If this finishes without issues, great ๐Ÿ‘! However, if you have problems, please file an issue on this repo here.

Note on yarn

If you don't have yarn installed and don't want to use it for some reason, you can use npm as well. Instead of yarn start setup, run node ./scripts/install && npm start validate and enjoy waiting (and hopefully things don't break for you). May be a good idea to still run node ./scripts/verify to verify you have the right version of other things too.

Running the workshop

The workshop is set up to place the right exercise in the exercises directory when you run a special script. This way you always know exactly where to go. For example, to start the first ESLint exercise:

npm start exercise.eslint.0

You'll notice that this will create an exercises directory with the source file and tests in it. Your job is to make that test pass! To run the tests, run:

npm start

Tip: You could run npm start in a separate terminal window, and use another one to run the npm start exercise... scripts

On your own

This workshop is intended to be grouped with a lecture, but if you're unable to watch a recording or have a lecture, then you can feel free to run through the workshop yourself. The solutions are all in the other/final directory if you get stuck. Good luck! ๐ŸŽ‰ To get a primer on ASTs, you may find this talk recording helpful: ASTs for Beginners

Contributing

If you have any questions, let me know.

If you want to edit/update anything in the exercises, please see (and follow) the contributing guidelines!

Events

If you use this workshop, please make a Pull Request this README with a link to your event.

Changes

The community and tools move fast. Here's a list of changes since I first gave this workshop:

Contributors

Thanks goes to these wonderful people (emoji key):

Kent C. Dodds
Kent C. Dodds

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ
Joรฃo Marques
Joรฃo Marques

๐Ÿ›
Mircea Staicu
Mircea Staicu

๐Ÿ’ป โš ๏ธ
Stanimira Vlaeva
Stanimira Vlaeva

๐Ÿ’ป
Justin Dorfman
Justin Dorfman

๐Ÿ”

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

asts-workshop's People

Contributors

allcontributors[bot] avatar andrewmcodes avatar huchenme avatar jdorfman avatar mstaicu avatar sis0k0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

asts-workshop's Issues

question about `no-console-5`

Hi,
I have written the nos-console-5 solution like this:

const disallowedMethods = ['log', 'info', 'warn', 'error', 'dir']
const disallowedNames = ['console']

module.exports = {
  meta: {
    schema: [
      {
        type: 'object',
        properties: {
          allowedMethods: {
            type: 'array',
            items: {
              enum: ['log', 'info', 'warn', 'error', 'dir'],
            },
            minItems: 1,
            uniqueItems: true,
          },
        },
      },
    ],
  },
  create(context) {
    const config = context.options[0] || {}
    const allowedMethods = config.allowedMethods || []
    return {
      Identifier(node) {
        if (isConsoleAssignToIdentifier(node)) {
          disallowedNames.push(node.name)
        }
        if (
          !looksLike(node, {
            name: name => disallowedNames.includes(name),
            parent: {
              type: 'MemberExpression',
              parent: {type: 'CallExpression'},
              property: {
                name: val =>
                  !allowedMethods.includes(val) &&
                  disallowedMethods.includes(val),
              },
            },
          })
        ) {
          return
        }
        context.report({
          node: node.parent.property,
          message: 'Using console is not allowed',
        })
      },
    }
  },
}

function isConsoleAssignToIdentifier(node) {
  return looksLike(node, {
    parent: {
      type: 'VariableDeclarator',
      init: {
        name: name => disallowedNames.includes(name),
      },
    },
  })
}

function looksLike(a, b) {
  return (
    a &&
    b &&
    Object.keys(b).every(bKey => {
      const bVal = b[bKey]
      const aVal = a[bKey]
      if (typeof bVal === 'function') {
        return bVal(aVal)
      }
      return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal)
    })
  )
}

function isPrimitive(val) {
  return val == null || /^[sbn]/.test(typeof val)
}

it's much simpler than the way kent did it, but I was wondering if there is anything wrong with doing it in this way?
does kent solution has any advantage over mine?

I didn't know where to ask it, so I just open up an issue here, hope it's alright.
Thank you. :)

Extend ex.es.5's final solution

Hello โœ‹๐Ÿป, I'm trying to make a PR to present to you an extended solution on the fifth ESLint exercise, but I can't seem to understand how exactly split-guide works. I've created the (with the split-guide markup) exercise file and its test file inside the templates directory (which is on the root of the project) and I've issued yarn start split but nothing happens, nothing updates on the file system, even though I get this output:

yarn start v0.27.5
$ nps "split"
nps is executing `split` : node node_modules/concurrently/src/main.js --kill-others-on-fail --prefix-colors "bgBlue.bold,bgMagenta.bold" --prefix "[{name}]" --names "split.exercises,split.demos" 'nps split.exercises' 'nps split.demos'
[split.exercises] nps is executing `split.exercises` : split-guide generate --templates-dir other/old-exercises/templates --exercises-dir other/old-exercises/exercises --exercises-final-dir other/old-exercises/exercises-final --silent-success
[split.demos] nps is executing `split.demos` : split-guide generate --templates-dir other/old-demos/templates --exercises-dir other/old-demos/start --exercises-final-dir other/old-demos/final --silent-success
[split.demos] nps split.demos exited with code 0
[split.exercises] nps split.exercises exited with code 0
Done in 2.31s.

What am I doing wrong?

Add new ESLint exercise

I propose the addition of a new exercise as part of the ESLint challenges. This new exercise checks for new variables that refer to previously assigned variables with the console object.

verify requires yarn

ฮป node ./scripts/verify
'yarn' is not recognized as an internal or external command,

npm run setup seems to work; tests passed!

Yarn does not work on my Windows10 system. Could be a combo of PATHs & ConEmu, but I'm not going to take the time to mess with that beta software.

Babel and AST - reg exp variableDeclarator

In the video that introduces Babel and AST it is suggested to use t.variableDeclarator(newIdentifier, path.node), my initial idea was to do t.variableDeclarator(newIdentifier, t.regExpLiteral(path.node.pattern, path.node.flags)) instead. This would fail with following error:

TypeError: unknown: undefined is not an object (evaluating 'n.extra.raw')
genericPrintNoParens โ€” 8-b12b22d8d7b33937e14f-12.js:1587:8752
genericPrint โ€” 8-b12b22d8d7b33937e14f-12.js:1587:1349
r โ€” 8-b12b22d8d7b33937e14f-12.js:1587:582
n โ€” 8-b12b22d8d7b33937e14f-12.js:1587:522
a โ€” 8-b12b22d8d7b33937e14f-12.js:1587:449
printComments โ€” 8-b12b22d8d7b33937e14f-12.js:2133:3525
t โ€” 8-b12b22d8d7b33937e14f-12.js:1587:220
call โ€” 8-b12b22d8d7b33937e14f-12.js:4811:1780

Do you have idea why this would not work?
According to docs t.regExpLiteral(pattern, flags) should be ok

My babel plugin code:

export default function (babel) {
  const { types: t } = babel;
  
  return {
    name: "regexHoister", // not required
    visitor: {
      RegExpLiteral(path) {
        const oldName = path.parent.id.name;
        const newIdentifier = path.scope.generateUidIdentifier(oldName);
        //const hoistedVar = t.variableDeclarator(newIdentifier, path.node);
        const hoistedVar = t.variableDeclarator(newIdentifier, t.regExpLiteral(path.node.pattern, path.node.flags));
        const varDeclaration = t.variableDeclaration('const', [hoistedVar]);
        const program = path.findParent(t.isProgram);

        
        path.scope.rename(oldName, newIdentifier.name)
        program.node.body.unshift(varDeclaration)
        path.parentPath.remove()
      }
    }
  };
}

Node version issue when setting up

Hi,

I looked at the preview for your ast course and it made me signup for frontendmasters' account. I am trying to setup ast project and I get following error when I run 'yarn run setup --silent':

You must have node version 6 installed.

I have node v10.9.0 installed. Any ideas?

Installed fine but "yarn test" fails

Here are the first few errors.

tom:asts-workshop Tom$ yarn test
yarn test v0.22.0
$ nps test
nps executing: jest --config=exercises/jest.config.json --coverage
FAIL exercises/01_eslint.test.js
โ— I submitted my elaboration and feedback

expect(received).toBe(expected)

Expected value to be (using ===):
  false
Received:
  true

  at Object.<anonymous>.test (exercises/01_eslint.test.js:16:16)

FAIL exercises/02_eslint.test.js
โ— I submitted my elaboration and feedback

expect(received).toBe(expected)

Expected value to be (using ===):
  false
Received:
  true

  at Object.<anonymous>.test (exercises/02_eslint.test.js:25:16)

FAIL exercises/03_eslint.test.js
โ— no-blockless-if โ€บ invalid โ€บ if (foo) foo()

AssertionError: Should have 1 error but had 0: []

  at testInvalidTemplate (node_modules/eslint/lib/testers/rule-tester.js:472:24)
  at Object.RuleTester.it (node_modules/eslint/lib/testers/rule-tester.js:557:25)

โ— no-blockless-if โ€บ invalid โ€บ if (foo)
foo()

AssertionError: Should have 1 error but had 0: []

  at testInvalidTemplate (node_modules/eslint/lib/testers/rule-tester.js:472:24)
  at Object.RuleTester.it (node_modules/eslint/lib/testers/rule-tester.js:557:25)

โ— no-blockless-if โ€บ invalid โ€บ if (foo && bar)
foo()
bar()

Issues Setting Up: Problem with Jest tests

Hi,

I'm currently setting up the workshop, and I'm facing an issue where the unit tests on the other\final are not passing. However, the error message shows a strange output, because the expected and actual value do match, unless the problem is a special character (like the linebreak). A screenshot of the error is below.

image

I've tried running the tests with the -u flag to replace the snapshots. If I do this and after that rerun the tests, the problem reappears.

I'm running this on a Windows machine, so I guess the linebreak could be one of the issues. Any ideas? I've checked Jest repo for issues with \r and they indeed had issues, but those should be fixed in the version that's configured for the workshop.

Node Version: 6.10.1
Yarn Version: 0.23.2
Git Version: 2.12.2.windows.1

Thanks a lot!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.