How to use the prettier.format function in prettier

To help you get started, we’ve selected a few prettier 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 tangdrew / fhir-ts / packages / fhir-ts-codegen / scripts / download.ts View on Github external
complexTypeDefinitions.map(async structureDefinition => {
      const filename = `${structureDefinition.name.toLowerCase()}.profile.canonical.json`;
      return writeFileAsync(
        `../structure-definitions/${version}/${filename}`,
        format(JSON.stringify(structureDefinition), { parser: "json" })
      ).then(() => {
        // tslint:disable-next-line:no-console
        console.log(`Downloaded ${structureDefinition.name}`);
      });
    })
  );
github graphprotocol / graph-cli / src / type-generator.js View on Github external
async spinner => {
        // Generate TypeScript module from schema
        let codeGenerator = schema.codeGenerator()
        let code = prettier.format(
          [
            GENERATED_FILE_NOTE,
            ...codeGenerator.generateModuleImports(),
            ...codeGenerator.generateTypes(),
          ].join('\n'),
          {
            parser: 'typescript',
          },
        )

        let outputFile = path.join(this.options.outputDir, 'schema.ts')
        step(spinner, 'Write types to', this.displayPath(outputFile))
        fs.mkdirsSync(path.dirname(outputFile))
        fs.writeFileSync(outputFile, code)
      },
    )
github prettier / eslint-plugin-prettier / lib / rules / prettier.js View on Github external
Program() {
        // This isn't really very performant (prettier needs to reparse the text).
        // However, I don't think it's possible to run `prettier` on an ESTree AST.
        const desiredText = prettier.format(
          sourceCode.text,
          context.options[0]
        );

        if (sourceCode.text !== desiredText) {
          // Find the first character that differs
          const firstBadIndex = Array.from(desiredText).findIndex(
            (char, index) => char !== sourceCode.text[index]
          );
          const expectedChar = firstBadIndex === -1
            ? 'EOF'
            : desiredText[firstBadIndex];
          const foundChar = firstBadIndex >= sourceCode.text.length
            ? 'EOF'
            : firstBadIndex === -1
                ? sourceCode.text[desiredText.length]
github Tencent / omi / packages / omip / taro-cli / src / convertor.js View on Github external
const entryJSON = JSON.stringify(this.entryJSON)
      const entryDistJSPath = this.getDistFilePath(this.entryJSPath)
      const taroizeResult = taroize({
        json: entryJSON,
        script: entryJS,
        path: path.dirname(entryJS)
      })
      const { ast, scriptFiles } = this.parseAst({
        ast: taroizeResult.ast,
        sourceFilePath: this.entryJSPath,
        outputFilePath: entryDistJSPath,
        importStylePath: this.entryStyle ? this.entryStylePath.replace(path.extname(this.entryStylePath), OUTPUT_STYLE_EXTNAME) : null,
        isApp: true
      })
      const jsCode = generateMinimalEscapeCode(ast)
      this.writeFileToTaro(entryDistJSPath, prettier.format(jsCode, prettierJSConfig))
      printLog(pocessTypeEnum.GENERATE, '入口文件', this.generateShowPath(entryDistJSPath))
      if (this.entryStyle) {
        this.traverseStyle(this.entryStylePath, this.entryStyle)
      }
      this.generateScriptFiles(scriptFiles)
      if (this.entryJSON.tabBar) {
        this.generateTabBarIcon(this.entryJSON.tabBar)
      }
    } catch (err) {
      console.log(err)
    }
  }
github Atomic-Reactor / Reactium / .core / .cli / commands / toolkit / theme / index.js View on Github external
.then(input => {
            let params = CONFORM({ input, props });

            message('A new theme will be created with the following options:');
            const preflight = { ...params };
            preflight['menuOrder'] = Number(input['menuOrder']);

            console.log(
                prettier.format(JSON.stringify(preflight), {
                    parser: 'json-stringify',
                }),
            );

            return CONFIRM({ props, params });
        })
        .then(params => {
github aws / aws-sdk-js-v3 / packages / service-types-generator / src / SmokeTestGenerator.ts View on Github external
const fileName =
        this.runtime === "universal" ? "node.spec.ts" : "index.spec.ts";
      yield [
        join("test", "smoke", fileName),
        prettier.format(this.generateNodeSmokeTestFile(), {
          parser: "typescript"
        })
      ];
    }
    if (this.runtime === "browser" || this.runtime === "universal") {
      yield ["karma.conf", this.generateKarmaConfiguration()];
      const fileName =
        this.runtime === "universal" ? "browser.spec.ts" : "index.spec.ts";
      yield [
        join("test", "smoke", fileName),
        prettier.format(this.generateBrowserSmokeTestFile(), {
          parser: "typescript"
        })
      ];
    }
  }
github umijs / umi / packages / umi-build-dev / src / plugins / commands / config / setConfig.js View on Github external
}
            if (!hasFound) {
              properties.push(
                t.objectProperty(t.identifier(keys[i]), buildExpression(keys.slice(i + 1), value)),
              );
              break;
            } else {
              i += 1;
            }
          }
        });
      }
    },
  });
  const newCode = generate(ast, {}).code;
  return prettier.format(newCode, {
    singleQuote: true,
    trailingComma: 'es5',
    printWidth: 100,
    parser: 'typescript',
  });
}
github Atomic-Reactor / Reactium / .core / .cli / commands / reactium / library / actions.js View on Github external
const fpath = path.join(source, 'package.json');
            const dpath = path.join(destination, 'package.json');

            let pkg;

            try {
                message(`Updating ${chalk.cyan('package.json')}...`);
                pkg = require(fpath);
            } catch (err) {
                message(`Creating ${chalk.cyan('package.json')}...`);
                pkg = {};
            }

            pkg = { ...pkg, ...newPackage };

            const content = prettier.format(JSON.stringify(pkg), {
                parser: 'json-stringify',
            });

            fs.writeFileSync(fpath, content);
            fs.ensureDirSync(destination);
            fs.copySync(fpath, dpath);
        },
        assets: ({ action, params, props }) => {
github treenotation / jtree / built / jtree.node.js View on Github external
const isNodeJs = CompileTarget.nodejs === target;
        const grammarCode = jtree_1.default.TreeNode.fromDisk(pathToGrammar);
        const program = new GrammarLanguage_1.GrammarProgram(grammarCode.toString());
        let name = program.getGrammarName();
        const pathToJtree = __dirname + "/../index.js";
        const outputFilePath = outputFolder + `${name}.${target}.js`;
        let result = isNodeJs ? program.toNodeJsJavascript(pathToJtree) : program.toBrowserJavascript();
        if (isNodeJs)
            result =
                "#! /usr/bin/env node\n" +
                    result.replace(/}\s*$/, `
if (!module.parent) new ${name}(jtree.TreeNode.fromDisk(process.argv[2]).toString()).execute()
}
`);
        if (usePrettier)
            result = require("prettier").format(result, { semi: false, parser: "babel", printWidth: 160 });
        fs.writeFileSync(outputFilePath, result, "utf8");
        if (isNodeJs)
            fs.chmodSync(outputFilePath, 0o755);
        return outputFilePath;
    }
    static compileGrammarForBrowser(pathToGrammar, outputFolder, usePrettier = true) {
github DavidWells / analytics / scripts / docs.js View on Github external
function formatCode(code, type = 'babel') {
  return prettier.format(code, { semi: false, singleQuote: true, parser: type })
}