typescript#CompilerOptions TypeScript Examples

The following examples show how to use typescript#CompilerOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: tsutil.ts    From estrella with ISC License 7 votes vote down vote up
export function getTSConfigForConfig(config :BuildConfig) :CompilerOptions|null {
  let tsconfig = config[TS_CONFIG]
  if (tsconfig === undefined) {
    const file = getTSConfigFileForConfig(config)
    if (file) try {
      tsconfig = jsonparseFile(file)
    } catch(err) {
      log.warn(()=> `failed to parse ${file}: ${err.stack||err}`)
    }
    if (!tsconfig) {
      tsconfig = null
    }
    Object.defineProperty(config, TS_CONFIG, { value: tsconfig })
  }
  return tsconfig
}
Example #2
Source File: utils.ts    From typescript-strict-plugin with MIT License 6 votes vote down vote up
export function turnOnStrictMode(info: PluginInfo, currentOptions: CompilerOptions): void {
  info.project.setCompilerOptions({
    ...currentOptions,
    strict: true,
  });
}
Example #3
Source File: utils.ts    From typescript-strict-plugin with MIT License 6 votes vote down vote up
export function turnOffStrictMode(info: PluginInfo, currentOptions: CompilerOptions): void {
  info.project.setCompilerOptions({
    ...currentOptions,
    strict: false,
  });
}
Example #4
Source File: createLanguageServiceHost.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
export function createLanguageServiceHost(
  ts: typeof import("typescript"),
  compilerOptions: CompilerOptions,
  testPaths: string[]
): LanguageServiceHost {
  let version = 0;
  return {
    directoryExists: ts.sys.directoryExists,
    getCompilationSettings: () => compilerOptions,
    getCurrentDirectory: ts.sys.getCurrentDirectory,
    getDefaultLibFileName: () => require.resolve("typescript/lib/lib.d.ts"),
    getNewLine: () => ts.sys.newLine,
    getScriptFileNames: () => testPaths,
    fileExists: ts.sys.fileExists,
    getDirectories: ts.sys.getDirectories,
    getScriptSnapshot: (fileName) => ts.ScriptSnapshot.fromString(ts.sys.readFile(ensureExists(fileName))!),
    getScriptVersion: () => (version++).toString(),
  };
}
Example #5
Source File: index.ts    From swc-node with MIT License 6 votes vote down vote up
export function loader(
  this: LoaderContext<{
    compilerOptions?: CompilerOptions
    configFile?: string
    fastRefresh?: boolean
  }>,
  source: string,
) {
  const callback = this.async()
  const { compilerOptions, configFile, fastRefresh } = this.getOptions() ?? {}
  const options = convertCompilerOptionsFromJson(compilerOptions, '').options ?? readDefaultTsConfig(configFile)
  const swcOptions = tsCompilerOptionsToSwcConfig(options, this.resourcePath)
  if (fastRefresh) {
    if (swcOptions.react) {
      swcOptions.react.refresh = true
    } else {
      swcOptions.react = {
        refresh: true,
      }
    }
  }
  transform(source, this.resourcePath, swcOptions)
    .then(({ code, map }) => callback(null, code, map))
    .catch((err) => callback(err))
}
Example #6
Source File: create-sourcemap-option.spec.ts    From swc-node with MIT License 5 votes vote down vote up
FIXTURES: [CompilerOptions, Config['sourceMaps']][] = [
  [{ sourceMap: true, inlineSourceMap: true }, 'inline'],
  [{ sourceMap: false, inlineSourceMap: true }, 'inline'],
  [{ sourceMap: true, inlineSourceMap: false }, true],
  [{ sourceMap: false, inlineSourceMap: false }, false],
  [{ inlineSourceMap: true }, 'inline'],
  [{ inlineSourceMap: false }, true],
]
Example #7
Source File: mini-program-application-analysis.service.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
private augmentResolveModuleNames(
    host: ts.CompilerHost,
    compilerOptions: CompilerOptions
  ) {
    const moduleResolutionCache = ts.createModuleResolutionCache(
      host.getCurrentDirectory(),
      host.getCanonicalFileName.bind(host),
      compilerOptions
    );
    const oldResolveModuleNames = host.resolveModuleNames;
    if (oldResolveModuleNames) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      host.resolveModuleNames = (moduleNames: string[], ...args: any[]) => {
        return moduleNames.map((name) => {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const result = (oldResolveModuleNames! as any).call(
            host,
            [name],
            ...args
          );
          this.saveModuleDependency(args[0], name, result);

          return result;
        });
      };
    } else {
      host.resolveModuleNames = (
        moduleNames: string[],
        containingFile: string,
        _reusedNames: string[] | undefined,
        redirectedReference: ts.ResolvedProjectReference | undefined,
        options: ts.CompilerOptions
      ) => {
        return moduleNames.map((name) => {
          const result = ts.resolveModuleName(
            name,
            containingFile,
            options,
            host,
            moduleResolutionCache,
            redirectedReference
          ).resolvedModule;
          if (!containingFile.includes('node_modules')) {
            this.saveModuleDependency(containingFile, name, result!);
          }
          return result;
        });
      };
    }
  }
Example #8
Source File: checks.ts    From DefinitelyTyped-tools with MIT License 4 votes vote down vote up
export function checkTsconfig(options: CompilerOptions, dt: DefinitelyTypedInfo | undefined): void {
  if (dt) {
    const { relativeBaseUrl } = dt;

    const mustHave = {
      module: "commonjs",
      noEmit: true,
      forceConsistentCasingInFileNames: true,
      baseUrl: relativeBaseUrl,
      typeRoots: [relativeBaseUrl],
      types: [],
    };

    for (const key of Object.getOwnPropertyNames(mustHave) as (keyof typeof mustHave)[]) {
      const expected = mustHave[key];
      const actual = options[key];
      if (!deepEquals(expected, actual)) {
        throw new Error(
          `Expected compilerOptions[${JSON.stringify(key)}] === ${JSON.stringify(expected)}, but got ${JSON.stringify(
            actual
          )}`
        );
      }
    }

    for (const key in options) {
      switch (key) {
        case "lib":
        case "noImplicitAny":
        case "noImplicitThis":
        case "strict":
        case "strictNullChecks":
        case "noUncheckedIndexedAccess":
        case "strictFunctionTypes":
        case "esModuleInterop":
        case "allowSyntheticDefaultImports":
        case "paths":
        case "target":
        case "jsx":
        case "jsxFactory":
        case "experimentalDecorators":
        case "noUnusedLocals":
        case "noUnusedParameters":
        case "exactOptionalPropertyTypes":
          break;
        default:
          if (!(key in mustHave)) {
            throw new Error(`Unexpected compiler option ${key}`);
          }
      }
    }
  }

  if (!("lib" in options)) {
    throw new Error('Must specify "lib", usually to `"lib": ["es6"]` or `"lib": ["es6", "dom"]`.');
  }

  if ("strict" in options) {
    if (options.strict !== true) {
      throw new Error('When "strict" is present, it must be set to `true`.');
    }

    for (const key of ["noImplicitAny", "noImplicitThis", "strictNullChecks", "strictFunctionTypes"]) {
      if (key in options) {
        throw new TypeError(`Expected "${key}" to not be set when "strict" is \`true\`.`);
      }
    }
  } else {
    for (const key of ["noImplicitAny", "noImplicitThis", "strictNullChecks", "strictFunctionTypes"]) {
      if (!(key in options)) {
        throw new Error(`Expected \`"${key}": true\` or \`"${key}": false\`.`);
      }
    }
  }
  if ("exactOptionalPropertyTypes" in options) {
    if (options.exactOptionalPropertyTypes !== true) {
      throw new Error('When "exactOptionalPropertyTypes" is present, it must be set to `true`.');
    }
  }

  if (options.types && options.types.length) {
    throw new Error(
      'Use `/// <reference types="..." />` directives in source files and ensure ' +
        'that the "types" field in your tsconfig is an empty array.'
    );
  }
}
Example #9
Source File: measurePerf.ts    From DefinitelyTyped-tools with MIT License 4 votes vote down vote up
export async function measurePerf({
  packageName,
  packageVersion,
  typeScriptVersion,
  definitelyTypedRootPath,
  allPackages,
  maxRunSeconds = Infinity,
  progress,
  nProcesses,
  iterations,
  tsPath,
  ts,
  batchRunStart,
  failOnErrors,
}: MeasurePerfOptions) {
  let duration = NaN;
  const sourceVersion = execSync("git rev-parse HEAD", { cwd: definitelyTypedRootPath, encoding: "utf8" }).trim();
  const observer = new PerformanceObserver((list) => {
    const totalMeasurement = list.getEntriesByName("benchmark")[0];
    duration = totalMeasurement.duration;
  });

  observer.observe({ entryTypes: ["measure"] });
  performance.mark("benchmarkStart");
  const typesPath = path.join(definitelyTypedRootPath, "types");

  const typings = allPackages.getTypingsData({
    name: packageName,
    version: packageVersion,
  });
  const packagePath = path.join(typesPath, typings.subDirectoryPath);
  const typesVersion = getLatestTypesVersionForTypeScriptVersion(typings.typesVersions, typeScriptVersion);
  const latestTSTypesDir = path.resolve(packagePath, typesVersion ? `ts${typesVersion}` : ".");
  await installDependencies(allPackages, typings.id, typesPath);

  const commandLine = getParsedCommandLineForPackage(ts, latestTSTypesDir);
  const testPaths = getTestFileNames(commandLine.fileNames);

  let done = 0;
  let lastUpdate = Date.now();
  let languageServiceCrashed = false;
  const testMatrix = createLanguageServiceTestMatrix(testPaths, latestTSTypesDir, commandLine.options, iterations);
  if (progress) {
    updateProgress(
      `${toPackageKey(packageName, packageVersion)}: benchmarking over ${nProcesses} processes`,
      0,
      testMatrix.inputs.length
    );
  }

  await runWithListeningChildProcesses({
    inputs: testMatrix.inputs,
    commandLineArgs: [],
    workerFile: measureLanguageServiceWorkerFilename,
    nProcesses,
    crashRecovery: !failOnErrors,
    cwd: process.cwd(),
    softTimeoutMs: maxRunSeconds * 1000,
    handleCrash: (input) => {
      languageServiceCrashed = true;
      console.error("Failed measurement on request:", JSON.stringify(input, undefined, 2));
    },
    handleOutput: (measurement: LanguageServiceSingleMeasurement) => {
      testMatrix.addMeasurement(measurement);
      done++;
      if (progress) {
        updateProgress(
          `${toPackageKey(packageName, packageVersion)}: benchmarking over ${nProcesses} processes`,
          done,
          testMatrix.inputs.length
        );
      } else if (Date.now() - lastUpdate > 1000 * 60 * 5) {
        // Log every 5 minutes or so to make sure Pipelines doesn’t shut us down
        console.log(((100 * done) / testMatrix.inputs.length).toFixed(1) + "% done...");
        lastUpdate = Date.now();
      }
    },
  });

  if (progress && done !== testMatrix.inputs.length) {
    updateProgress(`${toPackageKey(packageName, packageVersion)}: timed out`, done, testMatrix.inputs.length);
    process.stdout.write(os.EOL);
  }

  const batchCompilationInput: MeasureBatchCompilationChildProcessArgs = {
    tsPath,
    fileNames: commandLine.fileNames,
    options: commandLine.options,
  };

  let batchCompilationResult: MeasureBatchCompilationChildProcessResult | undefined;
  await runWithChildProcesses({
    inputs: [batchCompilationInput],
    workerFile: measureBatchCompilationWorkerFilename,
    commandLineArgs: [],
    nProcesses: 1,
    handleOutput: (result: MeasureBatchCompilationChildProcessResult) => {
      batchCompilationResult = result;
    },
  });

  if (!batchCompilationResult) {
    throw new Error("Failed to get batch compilation metrics");
  }

  performance.mark("benchmarkEnd");
  performance.measure("benchmark", "benchmarkStart", "benchmarkEnd");

  const measurement: PackageBenchmark = {
    ...batchCompilationResult,
    benchmarkDuration: duration,
    sourceVersion,
    packageName,
    packageVersionMajor: packageVersion.major,
    packageVersionMinor: packageVersion.minor,
    typeScriptVersion,
    typeScriptVersionMajorMinor: ts.versionMajorMinor,
    languageServiceBenchmarks: testMatrix.getAllBenchmarks(),
    requestedLanguageServiceTestIterations: iterations,
    languageServiceCrashed,
    testIdentifierCount: testMatrix.uniquePositionCount,
    batchRunStart,
  };

  return measurement;

  function getIdentifiers(sourceFile: SourceFile) {
    const identifiers: Node[] = [];
    ts.forEachChild(sourceFile, function visit(node) {
      if (ts.isIdentifier(node)) {
        identifiers.push(node);
      } else {
        ts.forEachChild(node, visit);
      }
    });
    return identifiers;
  }

  function getTestFileNames(fileNames: readonly string[]) {
    return fileNames.filter((name) => {
      const ext = path.extname(name);
      return (ext === Extension.Ts || ext === Extension.Tsx) && !name.endsWith(Extension.Dts);
    });
  }

  function createLanguageServiceTestMatrix(
    testPaths: string[],
    packageDirectory: string,
    compilerOptions: CompilerOptions,
    iterations: number
  ) {
    const fileMap = new Map<string, Map<number, LanguageServiceBenchmark>>();
    const inputs: MeasureLanguageServiceChildProcessArgs[] = [];
    let uniquePositionCount = 0;
    for (const testPath of testPaths) {
      const positionMap = new Map<number, LanguageServiceBenchmark>();
      fileMap.set(testPath, positionMap);
      const sourceFile = ts.createSourceFile(
        testPath,
        ts.sys.readFile(testPath)!,
        compilerOptions.target || ts.ScriptTarget.Latest
      );
      // Reverse: more complex examples are usually near the end of test files,
      // so prioritize those.
      const identifiers = getIdentifiers(sourceFile).reverse();
      uniquePositionCount += identifiers.length;
      // Do the loops in this order so that a single child process doesn’t
      // run iterations of the same exact measurement back-to-back to avoid
      // v8 optimizing a significant chunk of the work away.
      for (let i = 0; i < iterations; i++) {
        for (const identifier of identifiers) {
          const start = identifier.getStart(sourceFile);
          if (i === 0) {
            const lineAndCharacter = ts.getLineAndCharacterOfPosition(sourceFile, start);
            const benchmark: LanguageServiceBenchmark = {
              fileName: path.relative(definitelyTypedRootPath, testPath),
              start,
              end: identifier.getEnd(),
              identifierText: identifier.getText(sourceFile),
              line: lineAndCharacter.line + 1,
              offset: lineAndCharacter.character + 1,
              completionsDurations: [],
              quickInfoDurations: [],
            };
            positionMap.set(start, benchmark);
          }
          inputs.push({
            fileName: testPath,
            start,
            packageDirectory,
            tsPath,
          });
        }
      }
    }
    return {
      inputs,
      uniquePositionCount,
      addMeasurement: (measurement: LanguageServiceSingleMeasurement) => {
        const benchmark = fileMap.get(measurement.fileName)!.get(measurement.start)!;
        benchmark.completionsDurations.push(measurement.completionsDuration);
        benchmark.quickInfoDurations.push(measurement.quickInfoDuration);
      },
      getAllBenchmarks: () => {
        return Array.prototype.concat
          .apply(
            [],
            Array.from(fileMap.values()).map((map) => Array.from(map.values()))
          )
          .filter(
            (benchmark: LanguageServiceBenchmark) =>
              benchmark.completionsDurations.length > 0 || benchmark.quickInfoDurations.length > 0
          );
      },
    };
  }
}