• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript node.createConsoleLogger函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中@angular-devkit/core/node.createConsoleLogger函数的典型用法代码示例。如果您正苦于以下问题:TypeScript createConsoleLogger函数的具体用法?TypeScript createConsoleLogger怎么用?TypeScript createConsoleLogger使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了createConsoleLogger函数的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: function

export default async function(options: { testing?: boolean, cliArgs: string[] }) {
  const logger = createConsoleLogger(
    false,
    process.stdout,
    process.stderr,
    {
      warn: s => terminal.bold(terminal.yellow(s)),
      error: s => terminal.bold(terminal.red(s)),
      fatal: s => terminal.bold(terminal.red(s)),
    },
  );

  let projectDetails = getWorkspaceDetails();
  if (projectDetails === null) {
    const [, localPath] = getWorkspaceRaw('local');
    if (localPath !== null) {
      logger.fatal(`An invalid configuration file was found ['${localPath}'].`
                 + ' Please delete the file before running the command.');

      return 1;
    }

    projectDetails = { root: process.cwd() };
  }

  try {
    const maybeExitCode = await runCommand(options.cliArgs, logger, projectDetails);
    if (typeof maybeExitCode === 'number') {
      console.assert(Number.isInteger(maybeExitCode));

      return maybeExitCode;
    }

    return 0;
  } catch (err) {
    if (err instanceof Error) {
      logger.fatal(err.message);
      if (err.stack) {
        logger.fatal(err.stack);
      }
    } else if (typeof err === 'string') {
      logger.fatal(err);
    } else if (typeof err === 'number') {
      // Log nothing.
    } else {
      logger.fatal('An unexpected error occurred: ' + JSON.stringify(err));
    }

    if (options.testing) {
      debugger;
      throw err;
    }

    return 1;
  }
}
开发者ID:angular,项目名称:angular-cli,代码行数:56,代码来源:index.ts


示例2: main

async function main(args: string[]): Promise<number> {
  /** Parse the command line. */
  const argv = minimist(args, { boolean: ['help'] });

  /** Create the DevKit Logger used through the CLI. */
  const logger = createConsoleLogger(argv['verbose']);

  // Check the target.
  const targetStr = argv._[0] || '';
  if (!targetStr || argv.help) {
    // Show architect usage if there's no target.
    usage(logger);
  }

  // Load workspace configuration file.
  const currentPath = process.cwd();
  const configFileNames = [
    'angular.json',
    '.angular.json',
    'workspace.json',
    '.workspace.json',
  ];

  const configFilePath = findUp(configFileNames, currentPath);

  if (!configFilePath) {
    logger.fatal(`Workspace configuration file (${configFileNames.join(', ')}) cannot be found in `
      + `'${currentPath}' or in parent directories.`);

    return 3;
  }

  const root = path.dirname(configFilePath);
  const configContent = readFileSync(configFilePath, 'utf-8');
  const workspaceJson = JSON.parse(configContent);

  const registry = new schema.CoreSchemaRegistry();
  registry.addPostTransform(schema.transforms.addUndefinedDefaults);

  const host = new NodeJsSyncHost();
  const workspace = new experimental.workspace.Workspace(normalize(root), host);

  await workspace.loadWorkspaceFromJson(workspaceJson).toPromise();

  // Clear the console.
  process.stdout.write('\u001Bc');

  return await _executeTarget(logger, workspace, root, argv, registry);
}
开发者ID:angular,项目名称:angular-cli,代码行数:49,代码来源:architect.ts


示例3: createConsoleLogger

});


/**
 * Set the error code of the process to 255.  This is to ensure that if something forces node
 * to exit without finishing properly, the error code will be 255. Right now that code is not used.
 *
 * - 1 When tests succeed we already call `process.exit(0)`, so this doesn't change any correct
 * behaviour.
 *
 * One such case that would force node <= v6 to exit with code 0, is a Promise that doesn't resolve.
 */
process.exitCode = 255;


const logger = createConsoleLogger(argv.verbose);
const logStack = [logger];
function lastLogger() {
  return logStack[logStack.length - 1];
}

// This code doesn't work and I have no idea why and no intention to investigate at this point.
// (console as any).debug = (msg: string, ...args: any[]) => {
//   const logger = lastLogger();
//   if (logger) {
//     logger.debug(msg, { args });
//   }
// };
// console.log = (msg: string, ...args: any[]) => {
//   const logger = lastLogger();
//   if (logger) {
开发者ID:nickroberts,项目名称:angular-cli,代码行数:31,代码来源:e2e_runner.ts


示例4: minimist

        --help              Show available options for project target.
                            Shows this message instead when ran without the run argument.


    Any additional option is passed the target, overriding existing options.
  `);

  process.exit(exitCode);
  throw 0;  // The node typing sometimes don't have a never type for process.exit().
}

/** Parse the command line. */
const argv = minimist(process.argv.slice(2), { boolean: ['help'] });

/** Create the DevKit Logger used through the CLI. */
const logger = createConsoleLogger(argv['verbose']);

// Check the target.
const targetStr = argv._.shift();
if (!targetStr && argv.help) {
  // Show architect usage if there's no target.
  usage();
}

// Split a target into its parts.
let project: string, targetName: string, configuration: string;
if (targetStr) {
  [project, targetName, configuration] = targetStr.split(':');
}

// Load workspace configuration file.
开发者ID:DevIntent,项目名称:angular-cli,代码行数:31,代码来源:architect.ts


示例5: main

export async function main({
  args,
  stdout = process.stdout,
  stderr = process.stderr,
}: MainOptions): Promise<0 | 1> {

  const argv = parseArgs(args);

  /** Create the DevKit Logger used through the CLI. */
  const logger = createConsoleLogger(argv['verbose'], stdout, stderr);
  if (argv.help) {
    logger.info(getUsage());

    return 0;
  }

  /** Get the collection an schematic name from the first argument. */
  const {
    collection: collectionName,
    schematic: schematicName,
  } = parseSchematicName(argv._.shift() || null);
  const isLocalCollection = collectionName.startsWith('.') || collectionName.startsWith('/');

  /** If the user wants to list schematics, we simply show all the schematic names. */
  if (argv['list-schematics']) {
    try {
      const engineHost = new NodeModulesEngineHost();
      const engine = new SchematicEngine(engineHost);
      const collection = engine.createCollection(collectionName);
      logger.info(engine.listSchematicNames(collection).join('\n'));
    } catch (error) {
      logger.fatal(error.message);

      return 1;
    }

    return 0;
  }

  if (!schematicName) {
    logger.info(getUsage());

    return 1;
  }

  /** Gather the arguments for later use. */
  const debug: boolean = argv.debug === null ? isLocalCollection : argv.debug;
  const dryRun: boolean = argv['dry-run'] === null ? debug : argv['dry-run'];
  const force = argv['force'];
  const allowPrivate = argv['allow-private'];

  /** Create a Virtual FS Host scoped to where the process is being run. **/
  const fsHost = new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(process.cwd()));

  /** Create the workflow that will be executed with this run. */
  const workflow = new NodeWorkflow(fsHost, { force, dryRun });

  // Indicate to the user when nothing has been done. This is automatically set to off when there's
  // a new DryRunEvent.
  let nothingDone = true;

  // Logging queue that receives all the messages to show the users. This only get shown when no
  // errors happened.
  let loggingQueue: string[] = [];
  let error = false;

  /**
   * Logs out dry run events.
   *
   * All events will always be executed here, in order of discovery. That means that an error would
   * be shown along other events when it happens. Since errors in workflows will stop the Observable
   * from completing successfully, we record any events other than errors, then on completion we
   * show them.
   *
   * This is a simple way to only show errors when an error occur.
   */
  workflow.reporter.subscribe((event: DryRunEvent) => {
    nothingDone = false;

    switch (event.kind) {
      case 'error':
        error = true;

        const desc = event.description == 'alreadyExist' ? 'already exists' : 'does not exist';
        logger.warn(`ERROR! ${event.path} ${desc}.`);
        break;
      case 'update':
        loggingQueue.push(tags.oneLine`
        ${terminal.white('UPDATE')} ${event.path} (${event.content.length} bytes)
      `);
        break;
      case 'create':
        loggingQueue.push(tags.oneLine`
        ${terminal.green('CREATE')} ${event.path} (${event.content.length} bytes)
      `);
        break;
      case 'delete':
        loggingQueue.push(`${terminal.yellow('DELETE')} ${event.path}`);
        break;
      case 'rename':
//.........这里部分代码省略.........
开发者ID:cexbrayat,项目名称:angular-cli,代码行数:101,代码来源:schematics.ts


示例6: Error

const init: any = (config: any, emitter: any, customFileHandlers: any) => {
  if (!config.buildWebpack) {
    throw new Error(`The '@angular-devkit/build-angular/plugins/karma' karma plugin is meant to` +
    ` be used from within Angular CLI and will not work correctly outside of it.`
    )
  }
  const options = config.buildWebpack.options;
  const logger: logging.Logger = config.buildWebpack.logger || createConsoleLogger();
  successCb = config.buildWebpack.successCb;
  failureCb = config.buildWebpack.failureCb;

  config.reporters.unshift('@angular-devkit/build-angular--event-reporter');

  // When using code-coverage, auto-add coverage-istanbul.
  config.reporters = config.reporters || [];
  if (options.codeCoverage && config.reporters.indexOf('coverage-istanbul') === -1) {
    config.reporters.unshift('coverage-istanbul');
  }

  // Add a reporter that fixes sourcemap urls.
  if (options.sourceMap) {
    config.reporters.unshift('@angular-devkit/build-angular--sourcemap-reporter');

    // Code taken from https://github.com/tschaub/karma-source-map-support.
    // We can't use it directly because we need to add it conditionally in this file, and karma
    // frameworks cannot be added dynamically.
    const smsPath = path.dirname(require.resolve('source-map-support'));
    const ksmsPath = path.dirname(require.resolve('karma-source-map-support'));

    addKarmaFiles(config.files, [
      { pattern: path.join(smsPath, 'browser-source-map-support.js'), watched: false },
      { pattern: path.join(ksmsPath, 'client.js'), watched: false }
    ], true);
  }

  // Add webpack config.
  const webpackConfig = config.buildWebpack.webpackConfig;
  const webpackMiddlewareConfig = {
    // Hide webpack output because its noisy.
    logLevel: 'error',
    stats: false,
    watchOptions: { poll: options.poll },
    publicPath: '/_karma_webpack_/',
  };

  const compilationErrorCb = (error: string | undefined, errors: string[]) => {
    // Notify potential listeners of the compile error
    emitter.emit('compile_error', errors);

    // Finish Karma run early in case of compilation error.
    emitter.emit('run_complete', [], { exitCode: 1 });

    // Unblock any karma requests (potentially started using `karma run`)
    unblock();
  }
  webpackConfig.plugins.push(new KarmaWebpackFailureCb(compilationErrorCb));

  // Use existing config if any.
  config.webpack = Object.assign(webpackConfig, config.webpack);
  config.webpackMiddleware = Object.assign(webpackMiddlewareConfig, config.webpackMiddleware);

  // Our custom context and debug files list the webpack bundles directly instead of using
  // the karma files array.
  config.customContextFile = `${__dirname}/karma-context.html`;
  config.customDebugFile = `${__dirname}/karma-debug.html`;

  // Add the request blocker and the webpack server fallback.
  config.beforeMiddleware = config.beforeMiddleware || [];
  config.beforeMiddleware.push('@angular-devkit/build-angular--blocker');
  config.middleware = config.middleware || [];
  config.middleware.push('@angular-devkit/build-angular--fallback');

  // The webpack tier owns the watch behavior so we want to force it in the config.
  webpackConfig.watch = !config.singleRun;
  if (config.singleRun) {
    // There's no option to turn off file watching in webpack-dev-server, but
    // we can override the file watcher instead.
    webpackConfig.plugins.unshift({
      apply: (compiler: any) => { // tslint:disable-line:no-any
        compiler.hooks.afterEnvironment.tap('karma', () => {
          compiler.watchFileSystem = { watch: () => { } };
        });
      },
    });
  }
  // Files need to be served from a custom path for Karma.
  webpackConfig.output.path = '/_karma_webpack_/';
  webpackConfig.output.publicPath = '/_karma_webpack_/';
  webpackConfig.output.devtoolModuleFilenameTemplate = '[namespace]/[resource-path]?[loaders]';

  let compiler: any;
  try {
    compiler = webpack(webpackConfig);
  } catch (e) {
    logger.error(e.stack || e)
    if (e.details) {
      logger.error(e.details)
    }
    throw e;
  }
//.........这里部分代码省略.........
开发者ID:DevIntent,项目名称:angular-cli,代码行数:101,代码来源:karma.ts



注:本文中的@angular-devkit/core/node.createConsoleLogger函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript node.resolve函数代码示例发布时间:2022-05-28
下一篇:
TypeScript core.virtualFs类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap