reactjs / react-codemod Goto Github PK
View Code? Open in Web Editor NEWReact codemod scripts
License: MIT License
React codemod scripts
License: MIT License
If I have separate file for proptypes, it still imports react
-import { PropTypes } from 'react'
+import 'react';
Transforming a file with a template literal that contains a non-ASCII character will not work.
Any two-byte character seems to bump rightBackTickPos
(determined by node.loc.end
) 1 higher than what this assert in recast
's util.fixTemplateLiteral expects.
The parser seems to count the position of multibyte chars several times in a way that recast
doesn't handle properly. At first sight the parser chosen by jscodeshift
seems to be babel-core
.
Example of a file that won't be transformed:
import React from 'react';
const Foo = React.createClass({
render() {
return <div>{`æøåß`}</div>;
},
});
export default Foo;
Output:
$ jscodeshift -t react-codemod/transforms/class.js ../Foo.js
Processing 1 files...
Spawning 1 workers...
Sending 1 files to free worker...
ERR ../Foo.js Transformation error
AssertionError: 'd' === '`'
at fixTemplateLiteral (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/util.js:257:10)
at Object.util.fixFaultyLocations (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/util.js:167:5)
at TreeCopier.TCp.copy (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/parser.js:108:8)
at TreeCopier.TCp.copy (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/parser.js:151:24)
at Array.map (native)
at TreeCopier.TCp.copy (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/parser.js:101:17)
at TreeCopier.TCp.copy (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/parser.js:151:24)
at TreeCopier.TCp.copy (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/parser.js:151:24)
at Array.map (native)
at TreeCopier.TCp.copy (/home/misund/.nvm/versions/node/v7.9.0/lib/node_modules/jscodeshift/node_modules/recast/lib/parser.js:101:17)
All done.
Results:
1 errors
0 unmodified
0 skipped
0 ok
Time elapsed: 1.376seconds
I'm probably not going to bother to look any more at this, especially if I'm the only one having this issue.
If you're reading this in search for a quick and dirty fix, you can try to comment out the assert in recast
and hope for the best. (That worked out just fine for me, but your milage may vary.)
Hi, when I run sort-comp
transformation, it throws following error:
Error: Cannot read config package: eslint-config-airbnb
Error: Cannot find module 'eslint-config-airbnb'
Referenced from: C:\projects\client\.eslintrc
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at loadPackage (C:\projects\react-codemod\node_modules\eslint\lib\config\config-file.js:168:16)
at loadConfigFile (C:\projects\react-codemod\node_modules\eslint\lib\config\config-file.js:212:1
8)
at load (C:\projects\react-codemod\node_modules\eslint\lib\config\config-file.js:385:18)
at C:\projects\react-codemod\node_modules\eslint\lib\config\config-file.js:326:36
at Array.reduceRight (native)
at applyExtends (C:\projects\react-codemod\node_modules\eslint\lib\config\config-file.js:309:28)
I've run npm install
within react-codemod
directory but it didn't help.
import {Component, PropTypes} from 'react';
converted to:
import { Component } from 'react';
and didn't create 'import PropTypes from 'prop-types';'
using the fixed: https://github.com/solidwareio/react-codemod/commit/7eb11895bcf5148754f159ddbd6364cf1d87e828
Update:
Also:
import {PropTypes} from 'react';
converted to:
import 'react';
Invalid
MyComponent.jsx:
const React = require("react");
const MyComponent = React.createClass({
render: function () {
return (
<label title={(true ? "T1" + "•" : "T2") + "T3"} />
);
},
});
jscodeshift -t ../../react-codemod/transforms/class.js MyComponent.jsx
output:
const React = require("react");
class MyComponent extends React.Component {
render() {
return (
<label title={(((true ? "T1" + "•" : : 2") ))+ "T3"} />
);
}
}
I noticed that this will transform React.createElement
, but not React.DOM.div
, which is just a convenience wrapper. I have a large codebase that I'm going to need to transform very soon and it's all using React.DOM.div
(or span
, a
, etc). It sounds like it would be easy to make that work the same as React.createElement
. What do you think?
Files are simply skipped due this code:
root
.find(j.CallExpression)
.filter(p => isRequire(p, coreModuleName))
In order to workaround es6 imports there should be something like:
root
.find(j.ImportDeclaration)
I'm dumb in AST, so I can't make a PR.
Hey there!
So our codebase has a component like this
import React, { PropTypes } from 'react';
import classnames from 'classnames';
const propTypes = {
children: PropTypes.node,
className: PropTypes.string,
};
const Accordion = ({ children, className, ...other }) => {
const classNames = classnames('bx--accordion', className);
return (
<ul className={classNames} {...other}>
{children}
</ul>
);
};
Accordion.propTypes = propTypes;
export default Accordion;
The codemod currently breaks on the destructured parameter - if I swap it over to
const Accordion = props => {
const { children, className, ...other } = props;
const classNames = classnames('bx--accordion', className);
return (
<ul className={classNames} {...other}>
{children}
</ul>
);
};
The codemod runs perfectly fine and outputs as expected.
The error is below
ERR components/Accordion.js Transformation error
TypeError: Cannot read property 'name' of undefined
at /Users/chrisdhanaraj/bluemix/react-codemod/transforms/React-PropTypes-to-prop-types.js:103:7
at Array.filter (native)
at Collection.filter (/Users/chrisdhanaraj/.config/yarn/global/node_modules/jscodeshift/dist/Collection.js:65:46)
at removeDestructuredPropTypeStatements (/Users/chrisdhanaraj/bluemix/react-codemod/transforms/React-PropTypes-to-prop-types.js:102:6)
at module.exports (/Users/chrisdhanaraj/bluemix/react-codemod/transforms/React-PropTypes-to-prop-types.js:175:22)
A component can only be converted into a stateless component if it does not use refs on its children. The current codemod does not check for it.
Still amazed by these codemods, but this could be a great improvement...
Looks like regular expression values in this eslint property are ignored. For example:
"react/sort-comp": [2, {
order: [
"/^render/",
"/^on/",
"everything-else"
]
}]
gives the same output as
"react/sort-comp": [2, {
order: [
"everything-else"
]
}]
From the most recent travis-ci build:
...
[{kind: method, key: [object Object], value: [object Object], static: false, loc: null, type: MethodDefinition, comments: undefined, computed: false, decorators: null}] does not match field "body": [ClassMethod | ClassProperty] of type ClassBody
at add (node_modules/jscodeshift/node_modules/recast/node_modules/ast-types/lib/types.js:580:31)
at node_modules/jscodeshift/node_modules/recast/node_modules/ast-types/lib/types.js:593:21
at Array.forEach (native)
at Function.Object.defineProperty.value [as classBody] (node_modules/jscodeshift/node_modules/recast/node_modules/ast-types/lib/types.js:592:34)
at createESClass (transforms/class.js:957:7)
at NodePath.updateToClass (transforms/class.js:1068:5)
at node_modules/jscodeshift/dist/Collection.js:76:36
at Array.forEach (native)
at Collection.forEach (node_modules/jscodeshift/dist/Collection.js:75:18)
at apply (transforms/class.js:1137:264)
...
I saw the same failures when running npm install
locally.
Looking at the build history it appears that 84ef7b7 is good but 5093980 even though the latter didn't introduce any changes into class.js.
I thought maybe it was an issue with the version of jscodeshift I had so I installed 0.3.28 which is what the last passing build installed. That did not fix the situation so I'm guessing it's some other dependency (or sub-dependency) that's causing the issue.
I want to leave mixins and use them with a 3rd party lib.
When i try to convert components that have mixins in them they get skipped, can i somehow ignore that and still convert components to classes?
Should not add semicolons like below:
- import React, { Component, PropTypes } from 'react'
+ import React, { Component } from 'react';
+ import PropType from 'prop-types';
It would be nice to pick up the specific sort order defined in .eslintrc if not provided through the CLI options before falling back to the airbnb order.
I have some components that transform incorrectly as blow:
TypeError: Cannot read property 'parent' of undefined
at addPropTypesImport (/Users/ltchronus/Documents/workspace4air/react-codemod/transforms/React-PropTypes-to-prop-types.js:95:7)
at module.exports (/Users/ltchronus/Documents/workspace4air/react-codemod/transforms/React-PropTypes-to-prop-types.js:182:5)
My component example is
import React, { Component, PropTypes } from 'react';
import Message from './Message';
if (process.env.BROWSER) {
require('./style/index.scss'); // eslint-disable-line
}
...
related code
function addPropTypesImport(j, root) {
if (useImportSyntax(j, root)) {
const importStatement = j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('PropTypes'))],
j.literal('prop-types')
);
const path = findImportAfterPropTypes(j, root);
j(path).insertBefore(importStatement);
} else {
const requireStatement = useVar(j, root)
? j.template.statement`var PropTypes = require('prop-types');\n`
: j.template.statement`const PropTypes = require('prop-types');\n`;
// I have require but don't use require to PropTypes
const path = findRequireAfterPropTypes(j, root) ;
j(path.parent.parent).insertBefore(requireStatement);
}
}
Let's take this scenario into consideration:
(...)
class AwesomeComponent extends React.Component {
(...)
}
(...)
class Test extends AwesomeComponent {
(...)
}
When using e.g. sort-comp
it skips components extending other component extending React.Component.
My temporary fix was changing:
// Finds all classes that extend React.Component
const findReactES6ClassDeclaration = path => {
const componentImport = findReactComponentName(path);
const selector = componentImport
? {
superClass: {
type: 'Identifier',
name: componentImport,
},
}
: {
superClass: {
type: 'MemberExpression',
object: {
type: 'Identifier',
name: 'React',
},
property: {
type: 'Identifier',
name: 'Component',
},
},
};
return path
.find(j.ClassDeclaration, selector);
};
to
// Finds all classes that extend React.Component
const findReactES6ClassDeclaration = path => {
const componentImport = findReactComponentName(path);
const selector = componentImport
? {
superClass: {
type: 'Identifier',
name: componentImport,
},
}
: {
superClass: {
type: 'Identifier',
name: 'AwesomeComponent',
},
};
return path
.find(j.ClassDeclaration, selector);
};
This class that is using class property initializers
import React, { PropTypes } from 'react';
export default class StringControl extends React.Component {
handleChange = (e) => {
this.props.onChange(e.target.value);
};
render() {
return <input type="text" value={this.props.value || ''} onChange={this.handleChange} />;
}
}
StringControl.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.node,
};
gets transformed to:
import React, { PropTypes } from 'react';
export default function StringControl(props) {
return <input type="text" value={props.value || ''} onChange={this.handleChange} />;
}
StringControl.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.node,
};
It should not.
The create-element-to-jsx transform attempts to make replacements like this:
- return React.createElement(Constructor, props);
+ return <Constructor />;
Expected:
- return React.createElement(Constructor, props);
+ return <Constructor {...props} />;
It looks like the create-element-to-jsx
transform silently throws away comments within React.createElement
calls. Ideally, it should find some way to preserve the comments, or maybe give an error so I can fix those files manually, but if that's too hard or out of scope, I think the behavior should at least be documented.
For example, if you run it on this file:
import React from 'react';
const render = () => {
return React.createElement('div', {
className: 'foo', // This is an important comment.
});
};
It produces this:
import React from 'react';
const render = () => {
return <div className="foo" />;
};
I'm trying to run the PropTypes transformation on my code base but the only file it (wrongly) updates is a file containing a single propType specification:
- import { PropTypes } from 'react';
+ import 'react';
export const SEPARATOR = 'separator';
export default {
type: PropTypes.oneOf([SEPARATOR]),
value: PropTypes.any,
label: PropTypes.string,
};
All my other files are simply ignored (they are very basic components):
Processing 17 files...
Spawning 3 workers...
Sending 6 files to free worker...
Sending 6 files to free worker...
Sending 5 files to free worker...
All done.
Results:
0 errors
0 unmodified
17 skipped
0 ok
What happens?
I have many components for which prop-types transformation happening correctly, but for other components its failing with following error
TypeError: Cannot read property 'name' of undefined
at /Users/z013mrq/react-codemod/transforms/React-PropTypes-to-prop-types.js:91:7
at Array.filter (native)
at Collection.filter (/Users/z013mrq/.nvm/versions/node/v6.9.0/lib/node_modules/jscodeshift/dist/Collection.js:65:46)
at removeDestructuredPropTypeStatements (/Users/z013mrq/react-codemod/transforms/React-PropTypes-to-prop-types.js:90:6)
at module.exports (/Users/z013mrq/react-codemod/transforms/React-PropTypes-to-prop-types.js:163:22)
One such component code example is
import React from 'react';
import Link from '../Link';
const Breadcrumb = ({ links }) => (
<div itemType="http://schema.org/breadcrumb" itemProp="breadcrumb">
......
</div>
);
Breadcrumb.propTypes = {
links: React.PropTypes.arrayOf(
React.PropTypes.shape({
title: React.PropTypes.string.isRequired,
href: React.PropTypes.string
})
).isRequired
};
export default Breadcrumb;
Help!
Right now they don't pass. Looks like trailing commas are getting added by the printer.
When running this command:
jscodeshift -t ~/react-codemod/transforms/class.js filename.jsx
For the files that have mixins in them I get:
filename.jsx: 'Component' was skipped because of mixins.
although the component is defined with React.createClass()
and the script should create ES2015 classes.
How should I still use the script and work around mixins?
Hi, I'm playing with this for this first time. My test file is being skipped, and nothing is being logged as to why.
jscodeshift -t react-codemod/transforms/create-element-to-jsx.js -p --dry --run-in-band -v 2 output.js
Processing 1 files...
Running in dry mode, no files will be written!
SKIP output.js
All done.
Results: 0 errors 0 unmodified 1 skipped 0 ok
Time elapsed: 0.999 seconds
Is there any way I can get more output from it?
Here's the error:
TypeError: Cannot read property 'start' of null
at reportSkipped (pure-component.js:86:28)
at pure-component.js:97:9
at Array.filter (native)
at Collection.filter (/Users/ritz078/.npm-packages/lib/node_modules/jscodeshift/dist/Collection.js:60:46)
at module.exports (pure-component.js:94:6)
Before:
let WorkspaceItemView = React.createClass({
displayName: 'WorkspaceItemView',
getInitialState() {
return {
workspaceItemManager: this._getWorkspaceItemManager(this.props.id),
workspaceItemStore: this._getWorkspaceItemStore(this.props.id)
};
},
});
After: (that's how it works now)
class WorkspaceItemView extends React.Component {
static displayName = 'WorkspaceItemView';
state = {
workspaceItemManager: this._getWorkspaceItemManager(this.props.id),
workspaceItemStore: this._getWorkspaceItemStore(this.props.id)
};
}
But it should be this:
class WorkspaceItemView extends React.Component {
static displayName = 'WorkspaceItemView';
constructor(props) {
super(props);
this.state = {
workspaceItemManager: this._getWorkspaceItemManager(this.props.id),
workspaceItemStore: this._getWorkspaceItemStore(this.props.id)
};
}
}
Would anyone be interested in an option for the pure-component transform that would destructure the props where possible - i.e. when there's no {...this.props}
or doStuff(this.props)
and only keys of this.props
are used?
I would be down to open a PR if so.
So
render() {
const { prop1 } = this.props;
return <div prop1={prop1} prop2={this.props.prop2} />;
}
Would become
({ prop1, prop2 }) => <div prop1={prop1} prop2={prop2} />;
We use
import React, { PropTypes, Component } from 'react';
export default class Foo extends Component {
and the PureComponent transform skips all of these. Even if this doesn't get fixed its worth noting here in case someone else is wondering why all their files are being skipped.
Is there a way I can see why my files are being skipped on the create-element-to-jsx
transform? I tried using astexplorer but had no luck. Any advice would be appreciated. Thanks.
The output shows:
Processing 1 files...
Spawning 1 workers...
Sending 1 files to free worker...
All done.
Results:
0 errors
0 unmodified
1 skipped
0 ok
Thanks for updating the test suite. There is currently a build warning:
Running 1 test suite...class-test.js: `MyComponent4` was skipped because of invalid field(s) `foo` on the React component. Remove any right-hand-side expressions that are not simple, like: `componentWillUpdate: createWillUpdate()` or `render: foo ? renderA : renderB`.
Why does the script convert
this.refs.injectButton.getDOMNode().focus();
into
React.findDOMNode(this.refs.injectButton).focus()
My understanding of the changes to refs
is that the original code could be transformed to
this.refs.injectButton.focus()
which if equivalent functionally seems like a better solution. In the docs it even mentions that using findDOMNode()
will be unnecessary in most cases.
Was there a specific case you are guarding against to take the more conservative approach?
Thanks
not sure why but all my code is being skipped over without explantion
this is how I call the command
jscodeshift -t react-codemod/transforms/create-element-to-jsx.js dealroom/assets/jsx/core/Dialog.js
here is a sample of one of my files that is being skipped
import React from 'react';
import ReactDOM from 'react-dom';
var Dialog = React.createClass({
getInitialState(){
return {
show: false,
onConfirm: null,
onCancel: null,
onBackgroundClick: null,
}
},
render(){
return null;
},
showDialogBox(onConfirm, onCancel, onBackgroundClick){
this.setState({
show: true,
onConfirm: onConfirm,
onCancel: onCancel,
onBackgroundClick: onBackgroundClick,
})
},
hideDialogBox(){
this.setState({
show: false,
onConfirm: null,
onCancel: null
})
},
_onConfirm(){
if(this.state.onConfirm){
this.state.onConfirm()
}
},
_onCancel(){
if(this.state.onCancel){
this.state.onCancel()
}
},
_onBackgroundClick(){
if(this.state.onBackgroundClick){
this.state.onBackgroundClick()
}
},
_renderDialog(){
const {show} = this.state;
var className = 'toast dialog';
var btn1_class = 'btn-primary';
var btn2_class = 'btn-error';
if(this.props.reverseBtnColor){
btn1_class = 'btn-error';
btn2_class = 'btn-primary';
}
ReactDOM.render(
<div className='toast-container dialog-container'>
{show?
<div>
<div className={className}>
<div>
{this.props.children}
</div>
<div className='btns'>
<a className={'btn ' + btn1_class} onClick={this._onConfirm}>
{this.props.confirm_text}
</a>
<a className={'btn ' + btn2_class} onClick={this._onCancel}>
{this.props.cancel_text}
</a>
</div>
</div>
<div className='waiting-overlay' onClick={this._onBackgroundClick}/>
</div>
:null
}
</div>
, this.portal)
},
componentDidMount(){
this.portal = document.createElement('toast');
document.getElementById('portal').appendChild(this.portal);
this._renderDialog(this.props);
},
componentWillReceiveProps(new_props){
this._renderDialog(new_props);
},
componentDidUpdate(){
this._renderDialog();
},
componentWillUnmount(){
ReactDOM.unmountComponentAtNode(this.portal);
}
});
export default Dialog
output
Processing 1 files...
Spawning 1 workers...
Sending 1 files to free worker...
All done.
Results:
0 errors
0 unmodified
1 skipped
0 ok
I've tried saving my files in various encodings both in Sublime Text and by converting using iconv
but I get encoding errors every time:
MacOS 10.11.3, node 5.7.0, npm 3.6.0
jscodeshift path/to/my/file.jsx -v 2 -t ~/react-codemod/transforms/sort-comp.js
Processing 1 files...
Spawning 1 workers...
Sending 1 files to free worker...
buffer.js:638
throw new TypeError('Unknown encoding: ' + encoding);
^
TypeError: Unknown encoding: path/to/my/file.jsx
at Buffer.write (buffer.js:638:17)
at fromString (buffer.js:113:26)
at new Buffer (buffer.js:58:12)
at createWriteReq (net.js:723:38)
at WriteStream.Socket._writeGeneric (net.js:675:11)
at WriteStream.Socket._write (net.js:698:8)
at doWrite (_stream_writable.js:301:12)
at writeOrBuffer (_stream_writable.js:287:5)
at WriteStream.Writable.write (_stream_writable.js:215:11)
at WriteStream.Socket.write (net.js:624:40)
I ran:
jscodeshift -t transforms/React-PropTypes-to-prop-types.js ../project/src/
It this error on almost every file:
ERR ../project/src/WebAPI/application.js Transformation error
TypeError: Cannot read property 'name' of undefined
at /home/user/react-codemod/transforms/React-PropTypes-to-prop-types.js:91:7
at Array.filter (native)
at Collection.filter (/home/user/.config/yarn/global/node_modules/jscodeshift/dist/Collection.js:65:46)
at removeDestructuredPropTypeStatements (/home/user/react-codemod/transforms/React-PropTypes-to-prop-types.js:90:6)
at module.exports (/home/gio/react-codemod/transforms/React-PropTypes-to-prop-types.js:163:22)
// application.js
import { callApi } from './api'
export const details = ({
ID,
hash,
page,
}) => callApi('application_view', {
params: {
id,
hash,
page,
},
})
export const add = () => {}
export const search = (params) => callApi('application_search', { params })
results:
74 errors
0 unmodified
292 skipped
0 ok
Time elapsed: 1.808seconds
I use babel-loader with this config:
['react', 'stage-1', ["env", { "targets": { "chrome": 56 }}]]
but as jscodeshift --babel
flag defaults to true, I think this shouldn't be an issue.
Is there a way to see why files are being skipped? It seems like no matter what transform I use, my .js file will be skipped. Thanks.
When a file being transformed requires styles like this but uses import
statements, the transform does not create the import PropTypes from 'prop-types';
The current version on NPM is 2.0.0 and the repo is at 4.0.0. Can we publish the current version? I want to use the sort-comp
transform without having to clone and build the repo.
jscodeshift -t transform.js <path> --printOptions='{"quote":"single"}'
is not working
Did a dry run and got the following message:
Overview
was skipped because of deprecated API calls. Remove calls to getDOMNode, isMounted, replaceProps, replaceState, setProps in your React component and re-run this script.
I do indeed use replaceState, but the context is history.replaceState (https://developer.mozilla.org/en-US/docs/Web/API/History_API), not React, so I believe there should not be a problem, the function names just happen to be the same.
In a comment in sort-comp, I noticed the following comment:
NOTE: only works on React.createClass() syntax, not ES6 class.
It would be really lovely if this worked with ES6 classes. 😺
When trying to upgrade to the latest version of React (migrating prop types and create class stuff), I found a LOT of errors with this particular codemod when running it on my codebase:
~/Developer/paypal/p2pnodeweb (pr/upgrade-react)
🚀 $ jscodeshift -t react-codemod/transforms/React-PropTypes-to-prop-types.js public/js/
Processing 691 files...
Spawning 7 workers...
Sending 50 files to free worker...
Sending 50 files to free worker...
Sending 50 files to free worker...
Sending 50 files to free worker...
Sending 50 files to free worker...
Sending 50 files to free worker...
Sending 50 files to free worker...
...
ERR public/js/calculator/containers/to-country/__tests__/skip-to-xoom.js Transformation error
TypeError: Cannot read property 'name' of undefined
at /Users/kdodds/Developer/paypal/p2pnodeweb/react-codemod/transforms/React-PropTypes-to-prop-types.js:91:7
at Array.filter (native)
at Collection.filter (/Users/kdodds/.nvm/versions/node/v4.7.0/lib/node_modules/jscodeshift/dist/Collection.js:65:46)
at removeDestructuredPropTypeStatements (/Users/kdodds/Developer/paypal/p2pnodeweb/react-codemod/transforms/React-PropTypes-to-prop-types.js:90:6)
at module.exports (/Users/kdodds/Developer/paypal/p2pnodeweb/react-codemod/transforms/React-PropTypes-to-prop-types.js:163:22)
...
All done.
Results:
168 errors
0 unmodified
436 skipped
87 ok
Here's what that __tests__/skip-to-xoom.js
file looks like:
import React from 'react'
import { render } from 'enzyme'
import SkipToXoom from '../skip-to-xoom'
test('the rendered button redirects to the proper URL when clicked', () => {
const toCountryData = { countryName: 'India', countryCode: 'IN' }
const div = renderToDiv({ toCountryData, userLang: 'en_us' })
const { attribs: { href } } = div.find('a')[0]
expect(href).toBe('#')
})
/**
* Render the <SkipToXoom /> component to a div with the given props
* We have to do some fancy footwork with the Router component to get
* the Link component in our SkipToXoom component to render out the href
* @param {Object} props - the props to apply to the component
* @returns {Element} - the div that contains the element
*/
function renderToDiv(props = {}) {
return render(<SkipToXoom {...props} dispatch={() => {}} userLang="en" />)
}
Any ideas?
Given a PropTypes
import that looks like this:
const {
PropTypes: {
shape,
bool,
number,
string
}
} = React
the prop-types
codemod will insert import PropTypes from 'prop-types';
but will remove the destructuring assignment completely, leaving shape
, bool
, number
, and string
undefined.
Hi!
So I ran into an issue where running the mod when getInitialState
is an arrow
function it breaks (code has been changed due to corporate IP...):
export default React.createClass({
displayName: 'MyComponent',
getInitialState: () => ({
stateThingOne: 'beep',
stateThingTwo: 'boop'
}),
// ...
})
The error message would be this:
TypeError: Cannot read property 'map' of undefined
at inlineGetInitialState (class.js:294:12)
at createConstructor (class.js:343:15)
at createESClass (class.js:362:11)
at updateToClass (class.js:477:7)
at NodePath.<anonymous> (class.js:507:31)
at __paths.forEach (/Users/ricard.sole/.nvm/versions/node/v6.2.2/lib/node_modules/jscodeshift/dist/Collection.js:71:36)
at Array.forEach (native)
at Collection.forEach (/Users/ricard.sole/.nvm/versions/node/v6.2.2/lib/node_modules/jscodeshift/dist/Collection.js:70:18)
at apply (class.js:507:10)
at module.exports (class.js:514:7)
We never shipped it in React.addons. It should be used from require('react-addons-shallow-compare')
.
(previously filed as facebook/react#4315).
Getting error:
ERR ./app/node_modules/components/tweet/index.jsx Transformation error
TypeError: Cannot read property 'get' of undefined
at Collection.get (/Users/eschaefer/.nvm/versions/node/v4.2.1/lib/node_modules/jscodeshift/dist/Collection.js:205:18)
at deletePureRenderMixin (/Users/eschaefer/Projects/react-codemod/transforms/pure-render-mixin.js:159:54)
at removePureRenderMixin (/Users/eschaefer/Projects/react-codemod/transforms/pure-render-mixin.js:180:7)
when running the pure-render-mixin.js
on example component:
import React from 'react';
import TranslationsMixin from 'mixins/translations';
var Tweet = React.createClass({
mixins: [TranslationsMixin],
render() {
return (
<div>
Stuff
</div>
);
}
});
export default Tweet;
I have tried passing the --mixin-name=TranslationsMixin
flag, but no luck. Any idea what could be the issue?
I'm just here to say thanks for this! I'm really amazed at how well it works and I was pleasantly surprised that it doesn't just force an import of create-react-class
but it will actually codemod to ES6 class (with public class fields) if it's not using mixins 🎉 thanks!
Results:
0 errors
495 unmodified
0 skipped
196 ok
Wasn't sure if I should report this here or with the jscodemod
folks. I ran npm -g list jscodeshift
which installed the latest jscodeshift
, then tried running:
jscodeshift -t ~/Downloads/react-codemod-master/transforms/pure-render-mixin.js ./ -d -p
Which gave me the following error:
No files selected, nothing to do.
(node:1598) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
Possible separate issue (unsure): I tried running it on a specific file, ./Components/App.jsx
, instead of a ./
path, and I got the following output:
Processing 1 files...
Spawning 1 workers...
Running in dry mode, no files will be written!
Sending 1 files to free worker...
ERR ./Components/App.jsx Transformation error
Error: You cannot call "get" on a collection with no paths. Instead, check the "length" property first to verify at least 1 path exists.
at Error (native)
at Collection.get (/usr/local/lib/node_modules/jscodeshift/dist/Collection.js:190:13)
at deletePureRenderMixin (/Users/ruben/Downloads/react-codemod-master/transforms/pure-render-mixin.js:159:54)
at removePureRenderMixin (/Users/ruben/Downloads/react-codemod-master/transforms/pure-render-mixin.js:180:7)
All done.
Results:
1 errors
0 unmodified
0 skipped
0 ok
Time elapsed: 1.130seconds
For the record, I'm on node v6.7.0, React 15.3.2, and I just downloaded react-codemod
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.