Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'typescript-to-proptypes' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
const [jsStat, tsxStat] = await Promise.all([fse.stat(jsPath), fse.stat(tsxPath)]);
if (jsStat.mtimeMs > tsxStat.mtimeMs) {
// JavaScript version is newer, skip transpiling
return TranspileResult.Skipped;
}
}
const source = await fse.readFile(tsxPath, 'utf8');
const { code } = await babel.transformAsync(source, { ...babelConfig, filename: tsxPath });
if (/import \w* from 'prop-types'/.test(code)) {
throw new Error('TypeScript demo contains prop-types, please remove them');
}
const propTypesAST = typescriptToProptypes.parseFromProgram(tsxPath, program, {
shouldResolveObject: ({ name }) => {
if (name === 'classes') {
return false;
}
return undefined;
},
});
const codeWithPropTypes = typescriptToProptypes.inject(propTypesAST, code);
const prettified = prettier.format(codeWithPropTypes, { ...prettierConfig, filepath: tsxPath });
const formatted = fixBabelGeneratorIssues(prettified);
const correctedLineEndings = fixLineEndings(source, formatted);
await fse.writeFile(jsPath, correctedLineEndings);
return TranspileResult.Success;
cwd: folderPath,
}),
),
);
const files = _.flatten(allFiles)
// Filter out files where the directory name and filename doesn't match
// Example: Modal/ModalManager.d.ts
.filter(filePath => {
const folderName = path.basename(path.dirname(filePath));
const fileName = path.basename(filePath, '.d.ts');
return fileName === folderName;
});
const program = ttp.createProgram(files, tsconfig);
const promises = files.map>(async tsFile => {
const jsFile = tsFile.replace('.d.ts', '.js');
if (!ignoreCache && (await fse.stat(jsFile)).mtimeMs > (await fse.stat(tsFile)).mtimeMs) {
// Javascript version is newer, skip file
return GenerateResult.Skipped;
}
return generateProptypes(tsFile, jsFile, program);
});
const results = await Promise.all(promises);
if (verbose) {
files.forEach((file, index) => {
const { code } = await babel.transformAsync(source, { ...babelConfig, filename: tsxPath });
if (/import \w* from 'prop-types'/.test(code)) {
throw new Error('TypeScript demo contains prop-types, please remove them');
}
const propTypesAST = typescriptToProptypes.parseFromProgram(tsxPath, program, {
shouldResolveObject: ({ name }) => {
if (name === 'classes') {
return false;
}
return undefined;
},
});
const codeWithPropTypes = typescriptToProptypes.inject(propTypesAST, code);
const prettified = prettier.format(codeWithPropTypes, { ...prettierConfig, filepath: tsxPath });
const formatted = fixBabelGeneratorIssues(prettified);
const correctedLineEndings = fixLineEndings(source, formatted);
await fse.writeFile(jsPath, correctedLineEndings);
return TranspileResult.Success;
} catch (err) {
console.error('Something went wrong transpiling %s\n%s\n', tsxPath, err);
return TranspileResult.Failed;
}
}
proptypes.body.forEach(component => {
component.types.forEach(prop => {
if (prop.name === 'classes' && prop.jsDoc) {
prop.jsDoc += '\nSee [CSS API](#css) below for more details.';
} else if (prop.name === 'children' && !prop.jsDoc) {
prop.jsDoc = 'The content of the component.';
} else if (!prop.jsDoc) {
prop.jsDoc = '@ignore';
}
});
});
const jsContent = await fse.readFile(jsFile, 'utf8');
const result = ttp.inject(proptypes, jsContent, {
removeExistingPropTypes: true,
comment: [
'----------------------------- Warning --------------------------------',
'| These PropTypes are generated from the TypeScript type definitions |',
'| To update them edit the d.ts file and run "yarn proptypes" |',
'----------------------------------------------------------------------',
].join('\n'),
shouldInclude: ({ prop }) => {
if (prop.name === 'children') {
return true;
}
const documentRegExp = new RegExp(/\r?\n?@document/);
if (prop.jsDoc && documentRegExp.test(prop.jsDoc)) {
prop.jsDoc = prop.jsDoc.replace(documentRegExp, '');
return true;
async function generateProptypes(
tsFile: string,
jsFile: string,
program: ttp.ts.Program,
): Promise {
const proptypes = ttp.parseFromProgram(tsFile, program, {
shouldResolveObject: ({ name }) => {
if (name.toLowerCase().endsWith('classes') || name === 'theme' || name.endsWith('Props')) {
return false;
}
return undefined;
},
});
if (proptypes.body.length === 0) {
return GenerateResult.NoComponent;
}
proptypes.body.forEach(component => {
component.types.forEach(prop => {
if (prop.name === 'classes' && prop.jsDoc) {
prop.jsDoc += '\nSee [CSS API](#css) below for more details.';
(async () => {
const tsxFiles = await getFiles(path.join(workspaceRoot, 'docs/src/pages'));
const program = typescriptToProptypes.createProgram(tsxFiles, tsConfig);
let successful = 0;
let failed = 0;
let skipped = 0;
(await Promise.all(tsxFiles.map(file => transpileFile(file, program)))).forEach(result => {
switch (result) {
case TranspileResult.Success: {
successful += 1;
break;
}
case TranspileResult.Failed: {
failed += 1;
break;
}
case TranspileResult.Skipped: {
skipped += 1;
import * as _ from 'lodash';
import { fixBabelGeneratorIssues, fixLineEndings } from '../docs/scripts/helpers';
const glob = promisify(globCallback);
const ignoreCache = process.argv.includes('--disable-cache');
const verbose = process.argv.includes('--verbose');
enum GenerateResult {
Success,
Skipped,
NoComponent,
Failed,
}
const tsconfig = ttp.loadConfig(path.resolve(__dirname, '../tsconfig.json'));
const prettierConfig = prettier.resolveConfig.sync(process.cwd(), {
config: path.join(__dirname, '../prettier.config.js'),
});
async function generateProptypes(
tsFile: string,
jsFile: string,
program: ttp.ts.Program,
): Promise {
const proptypes = ttp.parseFromProgram(tsFile, program, {
shouldResolveObject: ({ name }) => {
if (name.toLowerCase().endsWith('classes') || name === 'theme' || name.endsWith('Props')) {
return false;
}
return undefined;
*/
/**
* List of demos to ignore when transpiling
* Example: "app-bar/BottomAppBar.tsx"
*/
const ignoreList = [];
const fse = require('fs-extra');
const path = require('path');
const babel = require('@babel/core');
const prettier = require('prettier');
const typescriptToProptypes = require('typescript-to-proptypes');
const { fixBabelGeneratorIssues, fixLineEndings } = require('./helpers');
const tsConfig = typescriptToProptypes.loadConfig(path.resolve(__dirname, '../tsconfig.json'));
const babelConfig = {
presets: ['@babel/preset-typescript'],
plugins: ['unwrap-createstyles'],
generatorOpts: { retainLines: true },
babelrc: false,
configFile: false,
};
const watchMode = process.argv.some(arg => arg === '--watch');
const cacheDisabled = process.argv.some(arg => arg === '--disable-cache');
const workspaceRoot = path.join(__dirname, '../../');
const prettierConfig = prettier.resolveConfig.sync(process.cwd(), {
config: path.join(workspaceRoot, 'prettier.config.js'),