This will trigger the build as well (not using yarn since yarn pack is bugy) Except that on npm < 4.0.0 the prepare doesn't exists
963792
function createBundle(log = logger.log.bind(logger)) {
  if (!npm.can.prepare()) {
    log('building ts-jest')
    npm.spawnSync(['-s', 'run', 'build'], { cwd: rootDir })
  }
  log('creating ts-jest bundle')
  const res = npm.spawnSync(['-s', 'pack'], { cwd: rootDir })
  return join(rootDir, res.stdout.toString().trim())
}
1004483
def build(ctx, less=False, docs=False, js=False, force=False):
    
    specified = any([less, docs, js])
    buildall = not specified

    if buildall or less:
        less_fname = ctx.pkg.source_less / ctx.pkg.name + '.less'
        if less_fname.exists():
            lessc.LessRule(
                ctx,
                src='{pkg.source_less}/{pkg.name}.less',
                dst='{pkg.django_static}/{pkg.name}/css/{pkg.name}-{version}.min.css',
                force=force
            )
        elif less:
            print("WARNING: build --less specified, but no file at:", less_fname)

    if buildall or docs:
        if WARN_ABOUT_SETTINGS:
            warnings.warn(
                "autodoc might need a dummy settings file in the root of "
                "your package. Since it runs in a separate process you cannot"
                "use settings.configure()"
            )
        doctools.build(ctx, force=force)

    if buildall or js:
        build_js(ctx, force)

    if HAVE_SETTINGS and (force or changed(ctx.pkg.django_static)):
        collectstatic(ctx, DJANGO_SETTINGS_MODULE)
8379
async function _import(modulePath) {
  let m
  for (const mp of [ path.resolve(localNodeModules, modulePath), modulePath ]) {
    try {
      m = await import(mp)
    } catch (e) {
      /* istanbul ignore next */
      if (e.code !== 'MODULE_NOT_FOUND') {
        throw e
      } else if (mp === modulePath) {
        consola.fatal(
          `Module ${modulePath} not found.\n\n`,
          `Please install missing dependency:\n\n`,
          `Using npm:  npm i ${modulePath}\n\n`,
          `Using yarn: yarn add ${modulePath}`
        )
      }
    }
  }
  return m
}
1267929
function createMozBuildFiles() {
  const builds = {};

  getFiles()
    .filter(file => file.match(/.js$/))
    .filter(file => {
      if (file.match(/\/workers\.js/)) {
        return true;
      }

     // We exclude worker files because they are bundled and we include
     // worker/index.js files because are required by the debugger app in order
     // to communicate with the worker.
     if (file.match(/\/workers/)) {
       return file.match(/workers\/(\w|-)*\/index.js/);
     }

     return !file.match(/(test|types|packages)/)

   })
    .forEach(file => {
      // console.log(file)
      let dir = path.dirname(file);
      builds[dir] = builds[dir] || { files: [], dirs: [] };

      // Add the current file to its parent dir moz.build
      builds[dir].files.push(path.basename(file));

      // There should be a moz.build in every folder between the root and this
      // file. Climb up the folder hierarchy and make sure a each folder of the
      // chain is listing in its parent dir moz.build.
      while (path.dirname(dir) != ".") {
        const parentDir = path.dirname(dir);
        const dirName = path.basename(dir);

        builds[parentDir] = builds[parentDir] || { files: [], dirs: [] };
        if (!builds[parentDir].dirs.includes(dirName)) {
          builds[parentDir].dirs.push(dirName);
        }
        dir = parentDir;
      }
    });

  Object.keys(builds).forEach(build => {
    const { files, dirs } = builds[build];

    const buildPath = path.join(mcDebuggerPath, build);
    shell.mkdir("-p", buildPath);

    // Files and folders should be alphabetically sorted in moz.build
    const fileStr = files
      .sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
      .map(file => `    '${file}',`)
      .join("\n");

    const dirStr = dirs
      .sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
      .map(dir => `    '${dir}',`)
      .join("\n");

    const src = MOZ_BUILD_TEMPLATE.replace("__DIRS__", dirStr).replace(
      "__FILES__",
      fileStr
    );

    fs.writeFileSync(path.join(buildPath, "moz.build"), src);
  });
}
602107
async function deploy() {
  // Initialize a new repository
  await makeDir('build');
  await spawn('git', ['init', '--quiet'], options);

  // Changing a remote's URL
  let isRemoteExists = false;
  try {
    await spawn(
      'git',
      ['config', '--get', `remote.${remote.name}.url`],
      options,
    );
    isRemoteExists = true;
  } catch (error) {
    /* skip */
  }
  await spawn(
    'git',
    ['remote', isRemoteExists ? 'set-url' : 'add', remote.name, remote.url],
    options,
  );

  // Fetch the remote repository if it exists
  let isRefExists = false;
  try {
    await spawn(
      'git',
      ['ls-remote', '--quiet', '--exit-code', remote.url, remote.branch],
      options,
    );
    isRefExists = true;
  } catch (error) {
    await spawn('git', ['update-ref', '-d', 'HEAD'], options);
  }
  if (isRefExists) {
    await spawn('git', ['fetch', remote.name], options);
    await spawn(
      'git',
      ['reset', `${remote.name}/${remote.branch}`, '--hard'],
      options,
    );
    await spawn('git', ['clean', '--force'], options);
  }

  // Build the project in RELEASE mode which
  // generates optimized and minimized bundles
  process.argv.push('--release');
  if (remote.static) process.argv.push('--static');
  await run(require('./build').default); // eslint-disable-line global-require
  if (process.argv.includes('--static')) {
    await cleanDir('build/*', {
      nosort: true,
      dot: true,
      ignore: ['build/.git', 'build/public'],
    });
    await moveDir('build/public', 'build');
  }

  // Push the contents of the build folder to the remote server via Git
  await spawn('git', ['add', '.', '--all'], options);
  try {
    await spawn('git', ['diff', '--cached', '--exit-code', '--quiet'], options);
  } catch (error) {
    await spawn(
      'git',
      ['commit', '--message', `Update ${new Date().toISOString()}`],
      options,
    );
  }
  await spawn(
    'git',
    ['push', remote.name, `master:${remote.branch}`, '--set-upstream'],
    options,
  );

  // Check if the site was successfully deployed
  const response = await fetch(remote.website);
  console.info(
    `${remote.website} => ${response.status} ${response.statusText}`,
  );
}
1120728
function polymerBuild(config) {
	const skipRootFolder = function(file) {
		const rootFolder = config.root || '.';
		file.dirname = path.relative(rootFolder, file.dirname);
	};

	const project = new build.PolymerProject(config);

	const bundler = project.bundler({
		// XXX: sourcemaps makes V8 run out of memory
		sourcemaps: false,
		stripComments: true,
	}).on('error', e => console.error(e));

	return merge(project.sources(), project.dependencies())
		.pipe(bundler)
		.pipe(size({title: 'polymer-bundler'}))
		.pipe(rename(skipRootFolder));
}
508248
async function build(file) {
  const { code, map, assets } = await ncc(file, options);

  if (Object.keys(assets).length)
    console.error("New unexpected assets are being emitted for", file);

  const name = basename(file, ".js");
  await mkdirp(resolve(DIST_DIR, name));
  write(resolve(DIST_DIR, name, "index.js"), code);
  write(resolve(DIST_DIR, name, "index.map.js"), map);
}
875121
function watchCompiler(compiler, options={}){
  let watching = false
  log('Watch Building')
  const startWatchTime = Date.now()
  const watchConfig = { // watch options:
    //aggregateTimeout: 300, // wait so long for more changes
    //poll: true // use polling instead of native watchers
    // pass a number to set the polling interval
  }

  options.onRebuild = options.onRebuild || function(){}

  return new Promise(function(res,rej){  
    //webpack watch functionality
    compiler.watch(watchConfig, function(err,stats){
      if(err)return rej(err)

      if(watching){
        log('Rebuilt '+getServerTime())
        options.onRebuild(stats)
      }else{
        watching = true
        log('Watching '+(Date.now()-startWatchTime)/1000+' seconds')
        res( this )
      }
    });
  })
}
1216993
function bindServe() {
  return new Promise((resolve, reject) => {

    // Logging "warnings" but not rejecting test
    webpackServer.stderr.on('data', data => log(data));
    webpackServer.stdout.on('data', data => {
      const dataAsString = log(data);
      if (dataAsString.indexOf('webpack: Compiled successfully.') > -1) {
        resolve(_port);
      }
      if (dataAsString.indexOf('webpack: Failed to compile.') > -1) {
        reject(dataAsString);
      }
    });
  });
}
204426
async function start() {
  await run(clean);
  await run(copy.bind(undefined, { watch: true }));
  await new Promise(resolve => {
    // Patch the client-side bundle configurations
    // to enable Hot Module Replacement (HMR) and React Transform
    webpackConfig.filter(x => x.target !== 'node').forEach(config => {
      /* eslint-disable no-param-reassign */
      if (Array.isArray(config.entry)) {
        config.entry.unshift('webpack-hot-middleware/client');
      } else {
        config.entry = ['webpack-hot-middleware/client', config.entry];
      }

      config.output.filename = config.output.filename.replace('[chunkhash]', '[hash]');
      config.output.chunkFilename = config.output.chunkFilename.replace('[chunkhash]', '[hash]');
      config.plugins.push(new webpack.HotModuleReplacementPlugin());
      config.plugins.push(new webpack.NoErrorsPlugin());
      config
        .module
        .loaders
        .filter(x => x.loader === 'babel-loader')
        .forEach(x => (x.query = {
          ...x.query,

          // Wraps all React components into arbitrary transforms
          // https://github.com/gaearon/babel-plugin-react-transform
          plugins: [
            ...(x.query ? x.query.plugins : []),
            ['react-transform', {
              transforms: [
                {
                  transform: 'react-transform-hmr',
                  imports: ['react'],
                  locals: ['module'],
                }, {
                  transform: 'react-transform-catch-errors',
                  imports: ['react', 'redbox-react'],
                },
              ],
            },
            ],
          ],
        }));
      /* eslint-enable no-param-reassign */
    });

    const bundler = webpack(webpackConfig);
    const wpMiddleware = webpackMiddleware(bundler, {

      // IMPORTANT: webpack middleware can't access config,
      // so we should provide publicPath by ourselves
      publicPath: webpackConfig[0].output.publicPath,

      // Pretty colored output
      stats: webpackConfig[0].stats,

      // For other settings see
      // https://webpack.github.io/docs/webpack-dev-middleware
    });
    const hotMiddlewares = bundler
      .compilers
      .filter(compiler => compiler.options.target !== 'node')
      .map(compiler => webpackHotMiddleware(compiler));

    let handleServerBundleComplete = () => {
      runServer((err, host) => {
        if (!err) {
          const bs = Browsersync.create();
          bs.init({
            ...(DEBUG ? {} : { notify: false, ui: false }),

            proxy: {
              target: host,
              middleware: [wpMiddleware, ...hotMiddlewares],
            },

            // no need to watch '*.js' here, webpack will take care of it for us,
            // including full page reloads if HMR won't work
            files: ['build/content/**/*.*'],
          }, resolve);
          handleServerBundleComplete = runServer;
        }
      });
    };

    bundler.plugin('done', () => handleServerBundleComplete());
  });
}
1362753
function build() {
  console.log('Creating an optimized production build...\n');

  webpack(config)
    .run((err, stats) => {
      if (err) {
        printErrors('Failed to compile.', [err]);
        process.exit(1);
      }

      if (stats.compilation.errors.length) {
        printErrors('Failed to compile.', stats.compilation.errors);
        process.exit(1);
      }

      if (process.env.CI && stats.compilation.warnings.length) {
        printErrors('Failed to compile.', stats.compilation.warnings);
        process.exit(1);
      }

      logSuccess('Compiled successfully.\n');

      console.log('Bundle size details:\n');
      printFileSizes(stats);

      console.log(`\nThe ${chalk.green('build')} folder is ready to be deployed.\n`);
    });
}
386839
function build (config) {
  return new Promise((resolve, reject) => {
    const compiler = webpack(Object.assign(config, {
      output: { filename: 'file' },
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': '"production"',
          'process.browser': true
        })
      ]
    }), (err, stats) => {
      if (err || stats.hasErrors()) reject(err || new Error(stats.toString('errors-only')))
      const compilation = stats.compilation
      const compiler = compilation.compiler
      const memoryFs = compiler.outputFileSystem
      const outputFile = compilation.assets.file.existsAt
      resolve(memoryFs.readFileSync(outputFile, 'utf8'))
    })
    compiler.outputFileSystem = new MemoryFs()
  })
}
967724
function build(/* previousSizeMap */) {
  console.log('Creating an optimized production build...');
  webpack(config).run((err) => {
    if (err) {
      console.error('Failed to create a production build. Reason:');
      console.error(err.message || err);
      process.exit(1);
    }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    // console.log('File sizes after gzip:');
    // console.log();
    // printFileSizes(stats, previousSizeMap);
    // console.log();

    // Copy static files to dist folder
    // eslint-disable-next-line no-use-before-define
    copyToDistFolder();

    const openCommand = process.platform === 'win32' ? 'start' : 'open';
    const homepagePath = require(paths.appPackageJson).homepage;
    const publicPath = config.output.publicPath;

    if (homepagePath && homepagePath.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log(`The project was built assuming it is hosted at ${chalk.green(publicPath)}.`);
      console.log(`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`);
      console.log();
      console.log(`The ${chalk.cyan('dist')} folder is ready to be deployed.`);
      console.log(`To publish it at ${chalk.green(homepagePath)}, run:`);
      console.log();
      console.log(`  ${chalk.cyan('git')} commit -am ${chalk.yellow('"Save local changes"')}`);
      console.log(`  ${chalk.cyan('git')} checkout -B gh-pages`);
      console.log(`  ${chalk.cyan('git')} add -f dist`);
      console.log(`  ${chalk.cyan('git')} commit -am ${chalk.yellow('"Rebuild website"')}`);
      console.log(`  ${chalk.cyan('git')} filter-branch -f --prune-empty --subdirectory-filter dist`);
      console.log(`  ${chalk.cyan('git')} push -f origin gh-pages`);
      console.log(`  ${chalk.cyan('git')} checkout -`);
      console.log();
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log(`The project was built assuming it is hosted at ${chalk.green(publicPath)}.`);
      console.log(`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`);
      console.log();
      console.log(`The ${chalk.cyan('dist')} folder is ready to be deployed.`);
      console.log();
    } else {
      // no homepage or "homepage": "http://mywebsite.com"
      console.log('The project was built assuming it is hosted at the server root.');
      if (homepagePath) {
        // "homepage": "http://mywebsite.com"
        console.log(`You can control this with the ${chalk.green('homepage')} field in your ${chalk.cyan('package.json')}.`);
        console.log();
      } else {
        // no homepage
        console.log(`To override this, specify the ${chalk.green('homepage')} in your ${chalk.cyan('package.json')}.`);
        console.log('For example, add this to build it for GitHub Pages:');
        console.log();
        console.log(`  ${chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(',')}`);
        console.log();
      }
      console.log(`The ${chalk.cyan('dist')} folder is ready to be deployed.`);
      console.log('You may also serve it locally with a static server:');
      console.log();
      console.log(`  ${chalk.cyan('npm')} install -g pushstate-server`);
      console.log(`  ${chalk.cyan('pushstate-server')} build`);
      console.log(`  ${chalk.cyan(openCommand)} http://localhost:9000`);
      console.log();
    }
  });
}
56808
function (buildConfig) {
        var configFile;
        var suffix = 'karma';
        if (buildConfig.nodeProject) {
            suffix = 'mocha';
        }

        configFile = path.join(currentDirectory, '../lint/eslint/eslintrc-' + suffix + '.js');

        return configFile;
    }
8763
function build(previousSizeMap) {
  console.log('Creating an optimized production build...');
  webpack(config).run((err, stats) => {
    if (err) {
      printErrors('Failed to compile.', [err]);
      process.exit(1);
    }

    if (stats.compilation.errors.length) {
      printErrors('Failed to compile.', stats.compilation.errors);
      process.exit(1);
    }

    if (process.env.CI && stats.compilation.warnings.length) {
     printErrors('Failed to compile.', stats.compilation.warnings);
     process.exit(1);
   }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    console.log('File sizes after gzip:');
    console.log();
    printFileSizes(stats, previousSizeMap);
    console.log();

    var openCommand = process.platform === 'win32' ? 'start' : 'open';
    var appPackage  = require(paths.appPackageJson);
    var homepagePath = appPackage.homepage;
    var publicPath = config.output.publicPath;
    if (homepagePath && homepagePath.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('To publish it at ' + chalk.green(homepagePath) + ', run:');
      // If script deploy has been added to package.json, skip the instructions
      if (typeof appPackage.scripts.deploy === 'undefined') {
        console.log();
        if (useYarn) {
          console.log('  ' + chalk.cyan('yarn') +  ' add --dev gh-pages');
        } else {
          console.log('  ' + chalk.cyan('npm') +  ' install --save-dev gh-pages');
        }
        console.log();
        console.log('Add the following script in your ' + chalk.cyan('package.json') + '.');
        console.log();
        console.log('    ' + chalk.dim('// ...'));
        console.log('    ' + chalk.yellow('"scripts"') + ': {');
        console.log('      ' + chalk.dim('// ...'));
        console.log('      ' + chalk.yellow('"deploy"') + ': ' + chalk.yellow('"npm run build&&gh-pages -d build"'));
        console.log('    }');
        console.log();
        console.log('Then run:');
      }
      console.log();
      console.log('  ' + chalk.cyan(useYarn ? 'yarn' : 'npm') +  ' run deploy');
      console.log();
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log();
    } else {
      // no homepage or "homepage": "http://mywebsite.com"
      console.log('The project was built assuming it is hosted at the server root.');
      if (homepagePath) {
        // "homepage": "http://mywebsite.com"
        console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
        console.log();
      } else {
        // no homepage
        console.log('To override this, specify the ' + chalk.green('homepage') + ' in your '  + chalk.cyan('package.json') + '.');
        console.log('For example, add this to build it for GitHub Pages:')
        console.log();
        console.log('  ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(','));
        console.log();
      }
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('You may also serve it locally with a static server:')
      console.log();
      if (useYarn) {
        console.log('  ' + chalk.cyan('yarn') +  ' global add pushstate-server');
      } else {
        console.log('  ' + chalk.cyan('npm') +  ' install -g pushstate-server');
      }
      console.log('  ' + chalk.cyan('pushstate-server') + ' build');
      console.log('  ' + chalk.cyan(openCommand) + ' http://localhost:9000');
      console.log();
    }
  });
}
123421
function afterBuild(options) {
  var install = process.sass.binaryPath;
  var target = path.join(__dirname, '..', 'build', options.debug ? 'Debug' : 'Release', 'binding.node');

  mkdir(path.dirname(install), function(err) {
    if (err && err.code !== 'EEXIST') {
      console.error(err.message);
      return;
    }

    fs.stat(target, function(err) {
      if (err) {
        console.error('Build succeeded but target not found');
        return;
      }

      fs.rename(target, install, function(err) {
        if (err) {
          console.error(err.message);
          return;
        }

        console.log('Installed in `', install, '`');
      });
    });
  });
}
651980
function hooks(compiler, options) {
  return Promise.resolve()
    .then(() => require('./HmrServer'))
    .then(({ default: HmrServer }) =>
      new HmrServer({
        ...options,
        compiler, // webpack compiler
      }).run()
    );
}