├── .eslintignore ├── .prettierignore ├── .babelrc ├── CONTRIBUTING.md ├── __tests__ ├── __fixtures__ │ ├── shared │ │ ├── 03-theme provider │ │ │ ├── code.js │ │ │ └── output.js │ │ ├── 01-styled-already-present │ │ │ ├── code.js │ │ │ └── output.js │ │ └── 02-factories │ │ │ ├── code.js │ │ │ └── output.js │ ├── mode-className │ │ └── 01-jsx-className │ │ │ ├── code.js │ │ │ └── output.js │ ├── mode-withJsxPragma │ │ └── 01-jsx-withJsxPragma │ │ │ ├── code.js │ │ │ └── output.js │ └── mode-withBabelPlugin │ │ └── 01-jsx-withBabelPlugin │ │ ├── code.js │ │ └── output.js └── index.js ├── PULL_REQUEST_TEMPLATE.md ├── .eslintrc ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── LICENSE ├── package.json ├── CODE_OF_CONDUCT.md ├── README.md └── index.js /.eslintignore: -------------------------------------------------------------------------------- 1 | __fixtures__ 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | __fixtures__ 2 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["env", "react"] 3 | } 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Simply open an issue or file a PR as needed. 2 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/shared/03-theme provider/code.js: -------------------------------------------------------------------------------- 1 | import g, { ThemeProvider } from "glamorous"; 2 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/shared/03-theme provider/output.js: -------------------------------------------------------------------------------- 1 | import { ThemeProvider } from "emotion-theming"; 2 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # In this PR 2 | 3 | -- summary of changes -- 4 | 5 | # Demo 6 | 7 | -- Link to AST explorer -- 8 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "env": {"node": true, "es6": true}, 4 | "extends": "eslint:recommended", 5 | "rules": { 6 | "no-console": 0 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/shared/01-styled-already-present/code.js: -------------------------------------------------------------------------------- 1 | import glamorous from "glamorous"; 2 | 3 | const styled = "already present"; 4 | 5 | const ComponentReference = glamorous(MyComponent); 6 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/shared/01-styled-already-present/output.js: -------------------------------------------------------------------------------- 1 | import _styled from "@emotion/styled"; 2 | const styled = "already present"; 3 | 4 | const ComponentReference = _styled(MyComponent); 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/shared/02-factories/code.js: -------------------------------------------------------------------------------- 1 | import glamorous from "glamorous"; 2 | 3 | const CommonCase = glamorous.div({ 4 | display: "none", 5 | content: "", 6 | fontFamily: '"Arial", Helvetica, sans-serif', 7 | fontSize: 20 8 | }); 9 | 10 | const FilterProps = glamorous(Comp, {filterProps: something})(styles); 11 | 12 | const FilterSingleProps = glamorous(Comp, {filterProps: ["one"]})(styles); 13 | const FilterManyProps = glamorous(Comp, {filterProps: ["one", "two"]})(styles); 14 | 15 | const ForwardSingleProps = glamorous(Comp, {forwardProps: ["one"]})(styles); 16 | const ForwardManyProps = glamorous(Comp, {forwardProps: ["one", "two"]})(styles); 17 | 18 | const ForwardAndFilterProps = glamorous(Comp, {forwardProps: ["one"], filterProps: ["two"]})(styles); 19 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/shared/02-factories/output.js: -------------------------------------------------------------------------------- 1 | import styled from "@emotion/styled"; 2 | const CommonCase = styled("div")({ 3 | display: "none", 4 | content: "\"\"", 5 | fontFamily: '"Arial", Helvetica, sans-serif', 6 | fontSize: 20 7 | }); 8 | const FilterProps = styled(Comp, { 9 | shouldForwardProp: prop => something.indexOf(prop) === -1 10 | })(styles); 11 | const FilterSingleProps = styled(Comp, { 12 | shouldForwardProp: prop => prop !== "one" 13 | })(styles); 14 | const FilterManyProps = styled(Comp, { 15 | shouldForwardProp: prop => ["one", "two"].indexOf(prop) === -1 16 | })(styles); 17 | const ForwardSingleProps = styled(Comp, { 18 | shouldForwardProp: prop => prop === "one" 19 | })(styles); 20 | const ForwardManyProps = styled(Comp, { 21 | shouldForwardProp: prop => ["one", "two"].indexOf(prop) > -1 22 | })(styles); 23 | const ForwardAndFilterProps = styled(Comp, { 24 | shouldForwardProp: prop => prop === "one" && prop !== "two" 25 | })(styles); 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Desktop (please complete the following information):** 24 | - OS: [e.g. iOS] 25 | - Browser [e.g. chrome, safari] 26 | - Version [e.g. 22] 27 | 28 | **Smartphone (please complete the following information):** 29 | - Device: [e.g. iPhone6] 30 | - OS: [e.g. iOS8.1] 31 | - Browser [e.g. stock browser, safari] 32 | - Version [e.g. 22] 33 | 34 | **Additional context** 35 | Add any other context about the problem here. 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Tejas Kumar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/mode-className/01-jsx-className/code.js: -------------------------------------------------------------------------------- 1 | import g, {Div, Span as StyledSpan} from "glamorous"; 2 | 3 | const GDot1 = props => Hi, I’m a Span!; 4 | const GDot2 = props => ; 5 | const GDot3 = props => ; 6 | const GDot4 = props => ; 7 | const GDot5 = props => ; 8 | const GDot6 = props => ; 9 | const GDot7 = props => ; 10 | const GDot8 = props => ; 11 | const GDot9 = props => ; 12 | const GDot10 = props => ; 13 | const GDot11 = props => ; 14 | const GDot12 = props => ; 15 | const GDot13 = props =>
; 16 | const GDot14 = props => content; 17 | const GDot15 = props => ; 18 | const GDot16 = props => ; 19 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/mode-withJsxPragma/01-jsx-withJsxPragma/code.js: -------------------------------------------------------------------------------- 1 | import g, {Div, Span as StyledSpan} from "glamorous"; 2 | 3 | const GDot1 = props => Hi, I’m a Span!; 4 | const GDot2 = props => ; 5 | const GDot3 = props => ; 6 | const GDot4 = props => ; 7 | const GDot5 = props => ; 8 | const GDot6 = props => ; 9 | const GDot7 = props => ; 10 | const GDot8 = props => ; 11 | const GDot9 = props => ; 12 | const GDot10 = props => ; 13 | const GDot11 = props => ; 14 | const GDot12 = props => ; 15 | const GDot13 = props =>
; 16 | const GDot14 = props => content; 17 | const GDot15 = props => ; 18 | const GDot16 = props => ; 19 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/mode-withBabelPlugin/01-jsx-withBabelPlugin/code.js: -------------------------------------------------------------------------------- 1 | import g, {Div, Span as StyledSpan} from "glamorous"; 2 | 3 | const GDot1 = props => Hi, I’m a Span!; 4 | const GDot2 = props => ; 5 | const GDot3 = props => ; 6 | const GDot4 = props => ; 7 | const GDot5 = props => ; 8 | const GDot6 = props => ; 9 | const GDot7 = props => ; 10 | const GDot8 = props => ; 11 | const GDot9 = props => ; 12 | const GDot10 = props => ; 13 | const GDot11 = props => ; 14 | const GDot12 = props => ; 15 | const GDot13 = props =>
; 16 | const GDot14 = props => content; 17 | const GDot15 = props => ; 18 | const GDot16 = props => ; 19 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "babel-plugin-glamorous-to-emotion", 3 | "version": "1.2.0", 4 | "description": "A codemod to migrate existing React or Preact codebases from glamorous to emotion.", 5 | "main": "index.js", 6 | "repository": "https://github.com/tejasq/babel-plugin-glamorous-to-emotion", 7 | "author": "Tejas Kumar ", 8 | "contributors": [ 9 | "Daniel Berndt (http://danielberndt.net/)" 10 | ], 11 | "license": "MIT", 12 | "scripts": { 13 | "test": "jest", 14 | "eslint": "eslint index.js __tests__/**/*.js" 15 | }, 16 | "jest": { 17 | "testURL": "http://localhost/", 18 | "testPathIgnorePatterns": [ 19 | "/__fixtures__/", 20 | "/node_modules/" 21 | ] 22 | }, 23 | "devDependencies": { 24 | "@babel/core": "^7.0.0-beta.55", 25 | "babel-core": "^7.0.0-bridge.0", 26 | "babel-eslint": "^8.2.6", 27 | "babel-jest": "^23.4.2", 28 | "babel-plugin-tester": "^5.4.0", 29 | "babel-preset-env": "^7.0.0-beta.3", 30 | "babel-preset-react": "^7.0.0-beta.3", 31 | "eslint": "4.x", 32 | "jest": "^23.4.2" 33 | }, 34 | "dependencies": { 35 | "react-html-attributes": "^1.4.3" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/mode-withBabelPlugin/01-jsx-withBabelPlugin/output.js: -------------------------------------------------------------------------------- 1 | const GDot1 = props => Hi, I’m a Span!; 2 | 3 | const GDot2 = props =>
; 6 | 7 | const GDot3 = props =>
; 10 | 11 | const GDot4 = props =>
; 16 | 17 | const GDot5 = props => ; 18 | 19 | const GDot6 = props => ; 22 | 23 | const GDot7 = props => ; 26 | 27 | const GDot8 = props => ; 28 | 29 | const GDot9 = props => ; 30 | 31 | const GDot10 = props => ; 32 | 33 | const GDot11 = props => ; 36 | 37 | const GDot12 = props =>
; 40 | 41 | const GDot13 = props =>
; 44 | 45 | const GDot14 = props => content; 48 | 49 | const GDot15 = props => ; 50 | 51 | const GDot16 = props =>
; 54 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/mode-withJsxPragma/01-jsx-withJsxPragma/output.js: -------------------------------------------------------------------------------- 1 | /** @jsx jsx */ 2 | import { jsx } from "@emotion/core"; 3 | 4 | const GDot1 = props => Hi, I’m a Span!; 5 | 6 | const GDot2 = props =>
; 9 | 10 | const GDot3 = props =>
; 13 | 14 | const GDot4 = props =>
; 19 | 20 | const GDot5 = props => ; 21 | 22 | const GDot6 = props => ; 25 | 26 | const GDot7 = props => ; 29 | 30 | const GDot8 = props => ; 31 | 32 | const GDot9 = props => ; 33 | 34 | const GDot10 = props => ; 35 | 36 | const GDot11 = props => ; 39 | 40 | const GDot12 = props =>
; 43 | 44 | const GDot13 = props =>
; 47 | 48 | const GDot14 = props => content; 51 | 52 | const GDot15 = props => ; 53 | 54 | const GDot16 = props =>
; 57 | -------------------------------------------------------------------------------- /__tests__/__fixtures__/mode-className/01-jsx-className/output.js: -------------------------------------------------------------------------------- 1 | import { css } from "@emotion/core"; 2 | import { cx } from "emotion"; 3 | 4 | const GDot1 = props => Hi, I’m a Span!; 5 | 6 | const GDot2 = props =>
; 9 | 10 | const GDot3 = props =>
; 13 | 14 | const GDot4 = props =>
; 19 | 20 | const GDot5 = props => ; 21 | 22 | const GDot6 = props => ; 25 | 26 | const GDot7 = props => ; 29 | 30 | const GDot8 = props => ; 31 | 32 | const GDot9 = props => ; 33 | 34 | const GDot10 = props => ; 35 | 36 | const GDot11 = props => ; 39 | 40 | const GDot12 = props =>
; 43 | 44 | const GDot13 = props =>
; 47 | 48 | const GDot14 = props => content; 51 | 52 | const GDot15 = props => ; 53 | 54 | const GDot16 = props =>
; 57 | -------------------------------------------------------------------------------- /__tests__/index.js: -------------------------------------------------------------------------------- 1 | import pluginTester from "babel-plugin-tester"; 2 | import glamorousToEmotion, {MODES} from "../index.js"; 3 | import path from "path"; 4 | 5 | const sharedOptions = { 6 | plugin: glamorousToEmotion, 7 | babelOptions: { 8 | // taken from https://github.com/square/babel-codemod/blob/00ae5984e1b2ca2fac923011ce16157a29b12b39/src/AllSyntaxPlugin.ts 9 | parserOpts: { 10 | sourceType: "module", 11 | allowImportExportEverywhere: true, 12 | allowReturnOutsideFunction: true, 13 | allowSuperOutsideMethod: true, 14 | ranges: false, 15 | plugins: [ 16 | "jsx", 17 | "asyncGenerators", 18 | "classProperties", 19 | "doExpressions", 20 | "exportExtensions", 21 | "functionBind", 22 | "functionSent", 23 | "objectRestSpread", 24 | "dynamicImport", 25 | "decorators", 26 | ], 27 | }, 28 | babelrc: false, 29 | compact: false, 30 | }, 31 | }; 32 | 33 | pluginTester({ 34 | ...sharedOptions, 35 | fixtures: path.join(__dirname, "__fixtures__", "shared"), 36 | }); 37 | 38 | pluginTester({ 39 | ...sharedOptions, 40 | fixtures: path.join(__dirname, "__fixtures__", "mode-withBabelPlugin"), 41 | pluginOptions: { 42 | mode: MODES.withBabelPlugin, 43 | }, 44 | }); 45 | 46 | pluginTester({ 47 | ...sharedOptions, 48 | fixtures: path.join(__dirname, "__fixtures__", "mode-withJsxPragma"), 49 | pluginOptions: { 50 | mode: MODES.withJsxPragma, 51 | }, 52 | }); 53 | 54 | pluginTester({ 55 | ...sharedOptions, 56 | fixtures: path.join(__dirname, "__fixtures__", "mode-className"), 57 | pluginOptions: { 58 | mode: MODES.className, 59 | }, 60 | }); 61 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at tejas@tejas.qa. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 💄 glamorous → 👩‍🎤 emotion 2 | This codemod was created to help migrate an existing React or Preact codebase from [glamorous](https://github.com/paypal/glamorous) to [emotion](https://github.com/emotion-js/emotion) in light of [this issue](https://github.com/paypal/glamorous/issues/419) on glamorous. 3 | 4 | ## Features 5 | This codemod follows the [glamorous to emotion migration guide](https://github.com/paypal/glamorous/blob/master/other/EMOTION_MIGRATION.md) on the glamorous repo. Particularly, it rewrites the following: 6 | 7 | - ✅ All import statements, including ThemeProvider inclusion. 8 | - ✅ All glamorous function calls to emotion function calls. 9 | - ✅ The content property to be emotion friendly. 10 | 11 | ## Usage 12 | You'll need to use [`babel-codemod`](https://github.com/square/babel-codemod) to apply this codemod to your existing codebase. It should be pretty straightforward: 13 | 14 | - First, install this plugin: `yarn add babel-plugin-glamorous-to-emotion -D` 15 | 16 | - Then run it: `npx babel-codemod --plugin babel-plugin-glamorous-to-emotion "src/**/*.js"` or a similar variation depending on your directory structure. 17 | 18 | This will put you fully in emotion-land. 19 | 20 | ### Options 21 | 22 | You may also pass `--plugin-options` to the `babel-codemod` command. Here's a sample call: 23 | 24 | ``` 25 | npx babel-codemod --plugin babel-plugin-glamorous-to-emotion --plugin-options glamorousToEmotion='{"mode": "withBabelPlugin"}' src/**/*.js 26 | ``` 27 | 28 | - #### `mode` 29 | 30 | This plugin offers three modes to convert your glamorous code. 31 | 32 | Let's compare them based on this glamorous snippet 33 | 34 | ```jsx 35 | 36 | ``` 37 | 38 | ##### `{"mode": "withJsxPragma"}` (default) 39 | 40 | If you can't or don't want to add emotion's [@emotion/babel-preset-css-prop](https://emotion.sh/docs/@emotion/babel-preset-css-prop), you can use emotion via setting the jsx pragma. This will create code like this: 41 | 42 | ```jsx 43 | /** @jsx jsx */ 44 | import { jsx } from "@emotion/core"; 45 | 46 |
47 | ``` 48 | 49 | ##### `{"mode": "withBabelPlugin"}` 50 | 51 | Use this option if you are able to use the babel plugin. The resulting code will look like this: 52 | 53 | ```jsx 54 |
55 | ``` 56 | 57 | ##### `{"mode": "className"}` 58 | 59 | If neither is an option for you, this codemod allows you to directly set the `className` instead: 60 | 61 | ```jsx 62 | import { css } from "@emotion/core"; 63 | 64 |
65 | ``` 66 | 67 | 68 | - #### `{"preact": true}` 69 | 70 | Uses `import styled from "@emotion/preact-styled"` instead of `import styled from "@emotion/styled"` 71 | 72 | 73 | ## Contributing 74 | ### ALL CONTRIBUTIONS WELCOME! 75 | I sincerely hope it helps you migrate your codebase! Please open issues for areas where it doesn't quite help and we'll sort it out. 76 | 77 | ## Acknowledgements 78 | The following people are awesome for their open source work and should be acknowledged as such. 79 | 80 | - [@tkh44](https://github.com/tkh44) for writing emotion. 81 | - [@kentcdodds](https://github.com/kentcdodds) for writing glamorous. 82 | - [@cbhoweth](https://github.com/cbhoweth), [@coldpour](https://github.com/coldpour), [@mitchellhamilton](https://github.com/mitchellhamilton), [@roystons](https://github.com/roystons) for writing the migration guide. 83 | - [@jamiebuilds](https://github.com/jamiebuilds) for an incredible [Babel handbook](https://github.com/jamiebuilds/babel-handbook/blob/master/README.md). 84 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Glamorous to Emotion codemod 3 | * 4 | * This babel plugin should migrate any existing codebase 5 | * using React or Preact and glamorous to one using 6 | * emotion (emotion.sh). 7 | * 8 | * It follows the glamorous to emotion migration guide 9 | * found at https://github.com/paypal/glamorous/blob/master/other/EMOTION_MIGRATION.md 10 | * 11 | * Check out the README for how to use it. 12 | */ 13 | 14 | const htmlElementAttributes = require("react-html-attributes"); 15 | 16 | const validElementNames = new Set([ 17 | ...htmlElementAttributes.elements.html, 18 | ...htmlElementAttributes.elements.svg, 19 | ]); 20 | 21 | const MODES = { 22 | withJsxPragma: "withJsxPragma", 23 | withBabelPlugin: "withBabelPlugin", 24 | className: "className", 25 | }; 26 | 27 | module.exports = function(babel) { 28 | const {types: t} = babel; 29 | 30 | // try to convert filterProps etc into something emotion understands 31 | const processOptions = options => { 32 | if (!t.isObjectExpression(options)) { 33 | const name = t.isIdentifier(options) ? options.name : options.type; 34 | console.warn( 35 | `codemod received '${name}' as an options argument. This is left in place, but will probably contain content that emotion won't understand` 36 | ); 37 | 38 | return options; 39 | } else { 40 | const transformedOptions = []; 41 | let forwardPropsExpr = []; 42 | options.properties.forEach(prop => { 43 | const {key, value} = prop; 44 | switch (key.name) { 45 | case "filterProps": { 46 | // filterProps: ["one"] ---> prop !== "one" 47 | if (t.isArrayExpression(value) && value.elements.length === 1) { 48 | forwardPropsExpr.push( 49 | t.binaryExpression("!==", t.identifier("prop"), value.elements[0]) 50 | ); 51 | } else { 52 | // filterProps: ["one", "two"] ---> ["one", "two"].indexOf(prop) === -1 53 | forwardPropsExpr.push( 54 | t.binaryExpression( 55 | "===", 56 | t.callExpression(t.memberExpression(value, t.identifier("indexOf")), [ 57 | t.identifier("prop"), 58 | ]), 59 | t.numericLiteral(-1) 60 | ) 61 | ); 62 | } 63 | break; 64 | } 65 | case "forwardProps": { 66 | // forwardProps: ["one"] ---> prop === "one" 67 | if (t.isArrayExpression(value) && value.elements.length === 1) { 68 | forwardPropsExpr.push( 69 | t.binaryExpression("===", t.identifier("prop"), value.elements[0]) 70 | ); 71 | } else { 72 | // forwardProps: ["one", "two"] ---> ["one", "two"].indexOf(prop) > -1 73 | forwardPropsExpr.push( 74 | t.binaryExpression( 75 | ">", 76 | t.callExpression(t.memberExpression(value, t.identifier("indexOf")), [ 77 | t.identifier("prop"), 78 | ]), 79 | t.numericLiteral(-1) 80 | ) 81 | ); 82 | } 83 | break; 84 | } 85 | default: { 86 | console.warn( 87 | `codemod received '${key}' as an option. This is left in place, but will probably not be undestood by emotion` 88 | ); 89 | transformedOptions.push(prop); 90 | } 91 | } 92 | }); 93 | if (forwardPropsExpr.length) { 94 | // concatenate all expressions via "&&" 95 | const reducedExpr = forwardPropsExpr.reduce((existing, expr) => 96 | t.logicalExpression("&&", existing, expr) 97 | ); 98 | // create `{shouldForwardProp: prop => [reducedExpr]}` expression 99 | transformedOptions.push( 100 | t.objectProperty( 101 | t.identifier("shouldForwardProp"), 102 | t.arrowFunctionExpression([t.identifier("prop")], reducedExpr) 103 | ) 104 | ); 105 | } 106 | return t.objectExpression(transformedOptions); 107 | } 108 | }; 109 | 110 | const processGlamorousArgs = args => { 111 | if (args.length === 0) throw new Error("Can't handle glamorous call with 0 arguments"); 112 | if (args.length > 2) throw new Error("Can't handle glamorous call with more than 2 arguments"); 113 | if (args.length === 1) return args; 114 | return [args[0], processOptions(args[1])]; 115 | }; 116 | 117 | // glamorous and emotion treat the css attribute "content" differently. 118 | // we need to put its content inside a string. 119 | // i.e. turn {content: ""} into {content: '""'} 120 | const fixContentProp = glamorousFactoryArguments => { 121 | return glamorousFactoryArguments.map(arg => { 122 | if (t.isObjectExpression(arg)) { 123 | arg.properties = arg.properties.map(prop => 124 | prop.key.name === "content" 125 | ? {...prop, value: t.stringLiteral(`"${prop.value.value}"`)} 126 | : prop 127 | ); 128 | } 129 | // TODO: if `arg` is a function, we might want to inspect its return value 130 | return arg; 131 | }); 132 | }; 133 | 134 | // transform to
135 | const transformJSXAttributes = ({tagName, jsxAttrs, mode, getCssFn, getCxFn, useJsxPragma}) => { 136 | if (!jsxAttrs) return []; 137 | const stylesArguments = []; 138 | let classNameAttr = null; 139 | const spreadsAttrs = []; 140 | let originalCssValue; 141 | 142 | /* 143 | We go through all jsx attributes and filter out all style-specific props. E.g `css` or `marginTop`. 144 | All style-specific props are gathered within `stylesArguments` and processed below 145 | */ 146 | const transformedJsxAttrs = jsxAttrs.filter(attr => { 147 | if (t.isJSXSpreadAttribute(attr)) { 148 | spreadsAttrs.push(attr); 149 | return true; 150 | } 151 | const {value, name: jsxKey} = attr; 152 | if (jsxKey.name === "css") { 153 | originalCssValue = value; 154 | // move properties of css attribute to the very front via unshift 155 | if (!t.isObjectExpression(value.expression)) { 156 | stylesArguments.unshift(t.spreadElement(value.expression)); 157 | } else { 158 | stylesArguments.unshift(...value.expression.properties); 159 | } 160 | if (mode === MODES.withJsxPragma) useJsxPragma(); 161 | return mode !== MODES.className; 162 | } else if (jsxKey.name === "className") { 163 | classNameAttr = attr; 164 | } else if (jsxKey.name === "innerRef") { 165 | // turn `innerRef` into `ref` 166 | jsxKey.name = "ref"; 167 | } else { 168 | // ignore event handlers 169 | if (jsxKey.name.match(/on[A-Z]/)) return true; 170 | if (jsxKey.name === "key") return true; 171 | 172 | // ignore generic attributes like 'id' 173 | if (htmlElementAttributes["*"].includes(jsxKey.name)) return true; 174 | 175 | // ignore tag specific attrs like 'disabled' 176 | const tagSpecificAttrs = htmlElementAttributes[tagName]; 177 | if (tagSpecificAttrs && tagSpecificAttrs.includes(jsxKey.name)) return true; 178 | 179 | stylesArguments.push( 180 | t.objectProperty( 181 | t.identifier(jsxKey.name), 182 | t.isJSXExpressionContainer(value) ? value.expression : value 183 | ) 184 | ); 185 | return false; 186 | } 187 | return true; 188 | }); 189 | 190 | if (stylesArguments.length > 0) { 191 | // if the css property was the only object, we don't need to use it's spreaded version 192 | const stylesObject = 193 | originalCssValue && stylesArguments.length === 1 194 | ? originalCssValue.expression 195 | : t.objectExpression(stylesArguments); 196 | 197 | if (mode !== MODES.className) { 198 | // if we allow using the css prop, use
syntax 199 | if (originalCssValue) { 200 | originalCssValue.expression = stylesObject; 201 | } else { 202 | transformedJsxAttrs.push( 203 | t.jsxAttribute(t.jsxIdentifier("css"), t.jsxExpressionContainer(stylesObject)) 204 | ); 205 | } 206 | } else { 207 | // if we don't allow using the css prop, use
syntax 208 | let classNameValue; 209 | if (!classNameAttr && !spreadsAttrs.length) { 210 | const cssCall = t.callExpression(getCssFn(), [stylesObject]); 211 | classNameValue = t.jsxExpressionContainer(cssCall); 212 | } else { 213 | let args = []; 214 | if (classNameAttr) { 215 | // if className is already present use
syntax 216 | args.push(classNameAttr.value); 217 | } else { 218 | // if spreads are present use
syntax 219 | spreadsAttrs.forEach(attr => { 220 | args.push(t.memberExpression(attr.argument, t.identifier("className"))); 221 | }); 222 | } 223 | args.push(stylesObject); 224 | const cxCall = t.callExpression(getCxFn(), args); 225 | classNameValue = t.jsxExpressionContainer(cxCall); 226 | } 227 | if (classNameAttr) { 228 | classNameAttr.value = classNameValue; 229 | } else { 230 | transformedJsxAttrs.push(t.jsxAttribute(t.jsxIdentifier("className"), classNameValue)); 231 | } 232 | } 233 | } 234 | return transformedJsxAttrs; 235 | }; 236 | 237 | const glamorousVisitor = { 238 | // for each reference to an identifier... 239 | ReferencedIdentifier(path, {getStyledFn, oldName, mode, getCssFn, getCxFn, useJsxPragma}) { 240 | // skip if the name of the identifier does not correspond to the name of glamorous default import 241 | if (path.node.name !== oldName) return; 242 | 243 | switch (path.parent.type) { 244 | // replace `glamorous()` with `styled()` 245 | case "CallExpression": { 246 | const transformedArguments = processGlamorousArgs(path.parent.arguments); 247 | path.parentPath.replaceWith(t.callExpression(getStyledFn(), transformedArguments)); 248 | break; 249 | } 250 | 251 | // replace `glamorous.div()` with `styled("div")()` 252 | case "MemberExpression": { 253 | const grandParentPath = path.parentPath.parentPath; 254 | if (t.isCallExpression(grandParentPath.node)) { 255 | grandParentPath.replaceWith( 256 | t.callExpression( 257 | t.callExpression(getStyledFn(), [ 258 | t.stringLiteral(grandParentPath.node.callee.property.name), 259 | ]), 260 | fixContentProp(grandParentPath.node.arguments) 261 | ) 262 | ); 263 | } else { 264 | throw new Error( 265 | `Not sure how to deal with glamorous within MemberExpression @ ${path.node.loc}` 266 | ); 267 | } 268 | break; 269 | } 270 | 271 | // replace with `
` 272 | case "JSXMemberExpression": { 273 | const grandParent = path.parentPath.parent; 274 | const tagName = grandParent.name.property.name.toLowerCase(); 275 | grandParent.name = t.identifier(tagName); 276 | if (t.isJSXOpeningElement(grandParent)) { 277 | grandParent.attributes = transformJSXAttributes({ 278 | tagName, 279 | jsxAttrs: grandParent.attributes, 280 | mode, 281 | getCssFn, 282 | getCxFn, 283 | useJsxPragma, 284 | }); 285 | } 286 | break; 287 | } 288 | 289 | default: { 290 | console.warning("Found glamorous being used in an unkonwn context:", path.parent.type); 291 | } 292 | } 293 | }, 294 | }; 295 | 296 | return { 297 | name: "glamorousToEmotion", 298 | visitor: { 299 | ImportDeclaration(path, {opts}) { 300 | const {value: libName} = path.node.source; 301 | const mode = MODES[opts.mode] || MODES.withJsxPragma; 302 | if (libName !== "glamorous" && libName !== "glamorous.macro") { 303 | return; 304 | } 305 | 306 | // use "name" as identifier, but only if it's not already used in the current scope 307 | const createUniqueIdentifier = name => 308 | path.scope.hasBinding(name) ? path.scope.generateUidIdentifier(name) : t.identifier(name); 309 | 310 | // this object collects all the imports we'll need to add 311 | let imports = {}; 312 | 313 | const getStyledFn = () => { 314 | if (!imports["@emotion/styled"]) { 315 | imports["@emotion/styled"] = { 316 | default: t.importDefaultSpecifier(createUniqueIdentifier("styled")), 317 | }; 318 | } 319 | return imports["@emotion/styled"].default.local; 320 | }; 321 | 322 | const getCssFn = () => { 323 | if (!imports["@emotion/core"]) imports["@emotion/core"] = {}; 324 | if (!imports["@emotion/core"].css) { 325 | const specifier = t.importSpecifier(t.identifier("css"), createUniqueIdentifier("css")); 326 | imports["@emotion/core"].css = specifier; 327 | } 328 | return imports["@emotion/core"].css.local; 329 | }; 330 | 331 | const getCxFn = () => { 332 | if (!imports["emotion"]) imports["emotion"] = {}; 333 | if (!imports["emotion"].cx) { 334 | const specifier = t.importSpecifier(t.identifier("cx"), createUniqueIdentifier("cx")); 335 | imports["emotion"].cx = specifier; 336 | } 337 | return imports["emotion"].cx.local; 338 | }; 339 | 340 | const useJsxPragma = () => { 341 | if (!imports["@emotion/core"]) imports["@emotion/core"] = {}; 342 | if (!imports["@emotion/core"].jsx) { 343 | t.addComment(path.parent, "leading", "* @jsx jsx "); 344 | const specifier = t.importSpecifier(t.identifier("jsx"), createUniqueIdentifier("jsx")); 345 | imports["@emotion/core"].jsx = specifier; 346 | } 347 | }; 348 | 349 | // only if the default import of glamorous is used, we're gonna apply the transforms 350 | path.node.specifiers 351 | .filter(s => t.isImportDefaultSpecifier(s)) 352 | .forEach(s => { 353 | path.parentPath.traverse(glamorousVisitor, { 354 | getStyledFn, 355 | oldName: s.local.name, 356 | mode, 357 | getCssFn, 358 | getCxFn, 359 | useJsxPragma, 360 | }); 361 | }); 362 | 363 | /* 364 | `import {Span, Div as StyledDiv} from "glamorous"` 365 | will be represented as `importedTags = {"Span": "span", "StyledDiv": "div"}` 366 | */ 367 | const importedTags = {}; 368 | 369 | path.node.specifiers 370 | .filter(s => t.isImportSpecifier(s)) 371 | .forEach(({imported, local}) => { 372 | const tagName = imported.name.toLowerCase(); 373 | if (validElementNames.has(tagName)) { 374 | importedTags[local.name] = tagName; 375 | } 376 | }); 377 | 378 | // transform corresponding JSXElements if any html element imports were found 379 | if (Object.keys(importedTags).length) { 380 | path.parentPath.traverse({ 381 | "JSXOpeningElement|JSXClosingElement": path => { 382 | const componentIdentifier = path.node.name; 383 | // exclude MemberEpressions 384 | if (!t.isJSXIdentifier(componentIdentifier)) return; 385 | 386 | const targetTagName = importedTags[componentIdentifier.name]; 387 | if (!targetTagName) return; 388 | 389 | componentIdentifier.name = targetTagName; 390 | if (t.isJSXOpeningElement(path)) { 391 | path.node.attributes = transformJSXAttributes({ 392 | targetTagName, 393 | jsxAttrs: path.node.attributes, 394 | mode, 395 | getCssFn, 396 | getCxFn, 397 | useJsxPragma, 398 | }); 399 | } 400 | }, 401 | }); 402 | } 403 | 404 | const themeProvider = path.node.specifiers.find( 405 | specifier => specifier.local.name === "ThemeProvider" 406 | ); 407 | 408 | if (themeProvider) { 409 | path.insertBefore( 410 | t.importDeclaration( 411 | [t.importSpecifier(t.identifier("ThemeProvider"), t.identifier("ThemeProvider"))], 412 | t.stringLiteral("emotion-theming") 413 | ) 414 | ); 415 | } 416 | 417 | const preactLibs = { 418 | "@emotion/styled": "@emotion/preact-styled", 419 | }; 420 | 421 | // if we used any emotion imports, we add them before the glamorous import path 422 | Object.entries(imports).forEach(([rawLibName, libImports]) => { 423 | const libName = (opts.preact && preactLibs[rawLibName]) || rawLibName; 424 | path.insertBefore( 425 | t.importDeclaration(Object.values(libImports), t.stringLiteral(libName)) 426 | ); 427 | }); 428 | 429 | path.remove(); 430 | }, 431 | }, 432 | }; 433 | }; 434 | 435 | module.exports.MODES = MODES; 436 | --------------------------------------------------------------------------------