How to use the @angular/compiler-cli.createCompilerHost function in @angular/compiler-cli

To help you get started, we’ve selected a few @angular/compiler-cli 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 angular / components / src / dev-app / rollup-bundles.js View on Github external
async function main() {
  const config = ngc.readConfiguration(path.join(__dirname, 'tsconfig-build.json'));
  const host = ngc.createCompilerHost({options: config.options});
  const program = new NgtscProgram(config.rootNames, config.options, host);

  // Determine all lazy routes in the dev-app and setup their entry-point in
  // the  rollup inputs object.
  program.listLazyRoutes().forEach(route => {
    console.log('>>> Building route entry-point:', route.route);

    rollupInputs[route.route.split('#')[0]] = `${devAppOut}/${path
      .relative(__dirname, route.referencedModule.filePath.split('#')[0])
      .replace('.ts', '.js')}`;
  });

  const build = await rollup.rollup({
    input: rollupInputs,
    plugins: [
      require('rollup-plugin-commonjs')({ignore: [ 'conditional-runtime-dependency' ]}),
github angular / angular / packages / bazel / src / ngc-wrapped / index.ts View on Github external
// Also handle the case the target is in an external repository.
    // Pull the workspace name from the target which is formatted as `@wksp//package:target`
    // if it the target is from an external workspace. If the target is from the local
    // workspace then it will be formatted as `//package:target`.
    const targetWorkspace = bazelOpts.target.split('/')[0].replace(/^@/, '');

    if (targetWorkspace &&
        fileName ===
            path.posix.join(compilerOpts.baseUrl, 'external', targetWorkspace, flatModuleOutPath))
      return true;

    return origBazelHostShouldNameModule(fileName) || NGC_GEN_FILES.test(fileName);
  };

  const ngHost = ng.createCompilerHost({options: compilerOpts, tsHost: bazelHost});
  const fileNameToModuleNameCache = new Map();
  ngHost.fileNameToModuleName = (importedFilePath: string, containingFilePath: string) => {
    // Memoize this lookup to avoid expensive re-parses of the same file
    // When run as a worker, the actual ts.SourceFile is cached
    // but when we don't run as a worker, there is no cache.
    // For one example target in g3, we saw a cache hit rate of 7590/7695
    if (fileNameToModuleNameCache.has(importedFilePath)) {
      return fileNameToModuleNameCache.get(importedFilePath);
    }
    const result = doFileNameToModuleName(importedFilePath);
    fileNameToModuleNameCache.set(importedFilePath, result);
    return result;
  };

  function doFileNameToModuleName(importedFilePath: string): string {
    try {
github angular / angular-cli / packages / ngtools / webpack / src / angular_compiler_plugin.ts View on Github external
throw new Error('An @ngtools/webpack plugin already exist for this compilation.');
    }

    // If there is no compiler host at this point, it means that the environment hook did not run.
    // This happens in child compilations that inherit the parent compilation file system.
    // Node: child compilations also do not run most webpack compiler hooks, including almost all
    // we use here. The child compiler will always run as if it was the first build.
    if (this._compilerHost === undefined) {
      const inputFs = compilation.compiler.inputFileSystem as VirtualFileSystemDecorator;
      if (!inputFs.getWebpackCompilerHost) {
        throw new Error('AngularCompilerPlugin is running in a child compilation, but could' +
          'not find a WebpackCompilerHost in the parent compilation.');
      }

      // Use the existing WebpackCompilerHost to ensure builds and rebuilds work.
      this._compilerHost = createCompilerHost({
        options: this._compilerOptions,
        tsHost: inputFs.getWebpackCompilerHost(),
      }) as CompilerHost & WebpackCompilerHost;
    }

    // Set a private variable for this plugin instance.
    // tslint:disable-next-line:no-any
    (compilation as any)._ngToolsWebpackPluginInstance = this;

    // Update the resource loader with the new webpack compilation.
    if (this._resourceLoader) {
      this._resourceLoader.update(compilation);
    }

    try {
      await this._update();
github ng-packagr / ng-packagr / src / lib / steps / ngc.ts View on Github external
export async function ngc(entryPoint: NgEntryPoint, artefacts: NgArtefacts) {
  log.debug(`ngc (v${ng.VERSION.full}): ${entryPoint.entryFile}`);

  // ng.CompilerHost
  const tsConfig = artefacts.tsConfig;
  const ngCompilerHost = ng.createCompilerHost({
    options: tsConfig.options,
    tsHost: createCompilerHostForSynthesizedSourceFiles(artefacts.tsSources.transformed, artefacts.tsConfig.options)
  });

  // ng.Program
  const ngProgram = ng.createProgram({
    rootNames: [...tsConfig.rootNames],
    options: tsConfig.options,
    host: ngCompilerHost
  });

  // ngc
  const result = ng.performCompilation({
    rootNames: [...tsConfig.rootNames],
    options: tsConfig.options,
    emitFlags: tsConfig.emitFlags,
github ng-packagr / ng-packagr / src / lib / steps / ngc.ts View on Github external
const transformSources = (
  tsConfig: TsConfig,
  transformers: ts.TransformerFactory[]
): ts.TransformationResult => {
  const compilerHost: ng.CompilerHost = ng.createCompilerHost({
    options: tsConfig.options
  });
  const program: ng.Program = ng.createProgram({
    rootNames: [...tsConfig.rootNames],
    options: tsConfig.options,
    host: compilerHost
  });

  const sourceFiles = program.getTsProgram().getSourceFiles();
  const transformationResult: ts.TransformationResult = ts.transform(
    // XX: circumvent tsc compile error in 2.6
    Array.from((sourceFiles as any) as ts.SourceFile[]),
    transformers,
    tsConfig.options
  );
github johandb / svg-drawing-tool / node_modules / @ngtools / webpack / src / type_checker.js View on Github external
this._rootNames = _rootNames;
        benchmark_1.time('TypeChecker.constructor');
        const host = new core_1.virtualFs.AliasHost(new node_1.NodeJsSyncHost());
        // Add file replacements.
        for (const from in hostReplacementPaths) {
            const normalizedFrom = core_1.resolve(core_1.normalize(_basePath), core_1.normalize(from));
            const normalizedWith = core_1.resolve(core_1.normalize(_basePath), core_1.normalize(hostReplacementPaths[from]));
            host.aliases.set(normalizedFrom, normalizedWith);
        }
        const compilerHost = new compiler_host_1.WebpackCompilerHost(_compilerOptions, _basePath, host, true);
        // We don't set a async resource loader on the compiler host because we only support
        // html templates, which are the only ones that can throw errors, and those can be loaded
        // synchronously.
        // If we need to also report errors on styles then we'll need to ask the main thread
        // for these resources.
        this._compilerHost = compiler_cli_1.createCompilerHost({
            options: this._compilerOptions,
            tsHost: compilerHost,
        });
        benchmark_1.timeEnd('TypeChecker.constructor');
    }
    _update(rootNames, changedCompilationFiles) {
github shlomiassaf / ngc-webpack / src / cli / perform_compile_async.ts View on Github external
.then( () => {
      if (!host) {
        host = createCompilerHost({options});
      }
      program = createProgram({rootNames, host, options, oldProgram});
      return program.loadNgStructureAsync()
    })
    .then( () => {
github ionic-team / ionic-native / scripts / build / ngx.ts View on Github external
export function getProgram(rootNames: string[] = createSourceFiles()) {
  const options: ngc.CompilerOptions = clone(COMPILER_OPTIONS);
  options.basePath = ROOT;
  options.moduleResolution = ts.ModuleResolutionKind.NodeJs;
  options.module = ts.ModuleKind.ES2015;
  options.target = ts.ScriptTarget.ES5;
  options.lib = ['dom', 'es2017'];
  options.inlineSourceMap = true;
  options.inlineSources = true;
  delete options.baseUrl;

  const host: ngc.CompilerHost = ngc.createCompilerHost({ options });

  return ngc.createProgram({
    rootNames,
    options,
    host
  });
}