How to use typescript-to-proptypes - 8 common examples

To help you get started, we’ve selected a few typescript-to-proptypes examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mui-org / material-ui / docs / scripts / formattedTSDemos.js View on Github external
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;
github mui-org / material-ui / scripts / generateProptypes.ts View on Github external
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) => {
github mui-org / material-ui / docs / scripts / formattedTSDemos.js View on Github external
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;
  }
}
github mui-org / material-ui / scripts / generateProptypes.ts View on Github external
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;
github mui-org / material-ui / scripts / generateProptypes.ts View on Github external
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.';
github mui-org / material-ui / docs / scripts / formattedTSDemos.js View on Github external
(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;
github mui-org / material-ui / scripts / generateProptypes.ts View on Github external
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;
github mui-org / material-ui / docs / scripts / formattedTSDemos.js View on Github external
*/

/**
 * 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'),

typescript-to-proptypes

Generate proptypes from typescript declarations

MIT
Latest version published 3 years ago

Package Health Score

48 / 100
Full package analysis