Skip to content

Instantly share code, notes, and snippets.

@lahmatiy
Last active July 9, 2018 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lahmatiy/4e6d3781f844643f36ce0daa2952ea19 to your computer and use it in GitHub Desktop.
Save lahmatiy/4e6d3781f844643f36ce0daa2952ea19 to your computer and use it in GitHub Desktop.
webpack loader to patch the prop-types to get an information about the propTypes definition in a runtime (UPD: you can use ready to use package https://github.com/avito-tech/prop-types-definition)
// UPDATE: you can use ready to use package prop-types-definition
// https://github.com/avito-tech/prop-types-definition
module.exports = function(content) {
return content + `
(function(ReactPropTypes) {
function unwrapValueItem(value) {
if (value) {
if (typeof value.getTypeDefinition === 'function') {
return value.getTypeDefinition();
}
if (typeof value === 'function') {
return { name: 'custom' };
}
}
return { name: 'unknown' };
}
function wrapFunction(fn, name, value, getTypeDefinition) {
fn.getTypeDefinition = getTypeDefinition.bind(null, name, false, value);
if (fn.isRequired) {
fn.isRequired.getTypeDefinition = getTypeDefinition.bind(null, name, true, value);
}
return fn;
}
function wrapMethod(dict, name, getTypeDefinition) {
var orig = dict[name];
dict[name] = function(value) {
return wrapFunction(orig.apply(this, arguments), name, value, getTypeDefinition);
};
}
for (var method in ReactPropTypes) {
switch (method) {
case 'any':
case 'array':
case 'bool':
case 'func':
case 'number':
case 'object':
case 'string':
case 'symbol':
case 'node':
case 'element':
wrapFunction(ReactPropTypes[method], method, null, function(name, required) {
return {
type: { name: name },
required: required
};
});
break;
case 'instanceOf':
case 'oneOf':
wrapMethod(ReactPropTypes, method, function(name, required, value) {
return {
type: {
name: name,
value: value
},
required: required
};
});
break;
case 'oneOfType':
wrapMethod(ReactPropTypes, method, function(name, required, value) {
return {
type: {
name: name,
value: Array.isArray(value) ? value.map(unwrapValueItem) : []
},
required: required
};
});
break;
case 'arrayOf':
case 'objectOf':
wrapMethod(ReactPropTypes, method, function(name, required, value) {
return {
type: {
name: name,
value: unwrapValueItem(value)
},
required: required
};
});
break;
case 'shape':
wrapMethod(ReactPropTypes, method, function(name, required, value) {
var unwrapped = {};
for (var key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
unwrapped[key] = unwrapValueItem(value[key]);
}
}
return {
type: {
name: name,
value: unwrapped
},
required: required
};
});
break;
}
}
})(module.exports);`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment