Пример #1
0
browserify('./pwacompat.js').bundle((err, buffer) => {
  if (err) {
    throw new Error(err);
  }

  // TODO(samthor): Some of this should be done in google-closure-compiler-js.
  const externs = [
    {source: 'function require(x) {};\n'},
  ];
  const externsPath = 'node_modules/google-closure-compiler-js/externs/browser';
  fs.readdirSync(externsPath).forEach(name => {
    externs.push({
      source: fs.readFileSync(externsPath + '/' + name, 'UTF-8'),
      name: name,
    });
  });

  const source = buffer.toString();
  const opts = {
    jsCode: [{name: 'pwacompat.js', source}],
    externs,
    compilationLevel: 'ADVANCED',
    warningLevel: 'VERBOSE',
  };
  const out = compile(opts);
  function log(error) {
    process.stderr.write(JSON.stringify(error) + '\n');
  }
  out.errors.forEach(log);
  out.warnings.forEach(log);
  if (out.errors.length) {
    throw new Error(`got ${out.errors.length} errors, ${out.warnings.length} warnings`);
  }
  process.stdout.write(out.compiledCode);
});
Пример #2
0
    return new Promise((resolve, reject) => {
        const out = closureCompiler.compile({
            compilationLevel: 'SIMPLE_OPTIMIZATIONS',
            jsCode: [{
                path: filenameIn,
                src
            }],
            languageIn: 'ES5',
            languageOut: 'ES5',
            createSourceMap
        });
        const errors = out.errors;
        if (errors.length) {
            const msg = errors.map(getErrorMessage).join('\n');
            reject(msg);
        } else {
            let compiledCode = out.compiledCode;
            if (createSourceMap) {
                /**
                 * Hack to insert the file property in sourcemap, and the
                 * sourceMappingURL in the out file.
                 * TODO: the closure-compiler should likely be able to handle
                 * this if the configuration is correct.
                 */
                const sourceMappingURL = filenameOut + '.map';
                const mapJSON = JSON.parse(out.sourceMap);
                mapJSON.file = sourceMappingURL;
                compiledCode =
                    `${compiledCode}\n//# sourceMappingURL=${sourceMappingURL}`;

                // Write the source map to file.
                writeFile(outputPath + '.map', JSON.stringify(mapJSON));
            }

            writeFile(outputPath, compiledCode);
            const filesize = statSync(outputPath).size;
            const filesizeKb = (filesize / 1000).toFixed(2) + ' kB';

            if (filesize < 10) {
                const msg = 'Compiled ' + sourcePath + ' => ' + outputPath +
                    ', filesize suspiciously small (' + filesizeKb + ')';
                console.log(colors.red(msg));
                reject(msg);
                return;
            }

            console.log(
                colors.green('Compiled ' + sourcePath + ' => ' + outputPath) +
                colors.gray(' (' + filesizeKb + ')')
            );
            resolve();
        }
    });
Пример #3
0
    gcc: function minifyGCC(src, file) {
        const gcc = require('google-closure-compiler-js');
        const options = {
            jsCode: [{src: src}],
            languageIn: 'ES5'
        };

        const out = gcc.compile(options);

        if (out.errors && out.errors.length) {
            console.error(out.errors);
            throw new Error(`Minification failed for ${file}`);
        }
        return out.compiledCode;
    },
Пример #4
0
 files.forEach(path => {
     const closureCompiler = require('google-closure-compiler-js');
     // const fs = require('fs');
     const U = require('./assembler/utilities.js');
     const sourcePath = sourceFolder + path;
     const outputPath = sourcePath.replace('.src.js', '.js');
     const src = U.getFile(sourcePath);
     const out = closureCompiler.compile({
         compilationLevel: 'SIMPLE_OPTIMIZATIONS',
         jsCode: [{
             src: src
         }],
         languageIn: 'ES5',
         languageOut: 'ES5'
     });
     U.writeFile(outputPath, out.compiledCode);
     // @todo add filesize information
     console.log(colors.green('Compiled ' + sourcePath + ' => ' + outputPath));
 });
Пример #5
0
var compiler = require('google-closure-compiler-js').compile;
var fs = require('fs');
var source = fs.readFileSync('dist/xstream.js', 'utf8');

var compilerFlags = {
  jsCode: [{src: source}],
  languageIn: 'ES5',
  createSourceMap: true,
  // compilationLevel: 'ADVANCED',
};

var output = compiler(compilerFlags);
fs.writeFileSync('dist/xstream.min.js', output.compiledCode, 'utf8');
fs.writeFileSync('dist/xstream.min.js.map', output.sourceMap, 'utf8');
Пример #6
0
    rollup({entry, plugins}).then((bundle) => {
      try {
        const rollupResult = bundle.generate({
          format: 'es',
          dest: output,
          sourceMap: true,
        });

        const externsDir = path.resolve(__dirname, '../lib/externs');
        const externs = glob.sync(path.join(externsDir, '*.js'))
            .reduce((acc, cur) => acc + fs.readFileSync(cur, 'utf-8'), '');

        const closureFlags = {
          jsCode: [{
            src: rollupResult.code,
            path: path.basename(output),
          }],
          compilationLevel: 'ADVANCED',
          useTypesForOptimization: true,
          outputWrapper:
              '(function(){%output%})();\n' +
              `//# sourceMappingURL=${path.basename(output)}.map`,
          assumeFunctionWrapper: true,
          rewritePolyfills: false,
          warningLevel: 'VERBOSE',
          createSourceMap: true,
          externs: [{src: externs}],
        };

        const closureResult = compile(closureFlags);

        if (closureResult.errors.length || closureResult.warnings.length) {
          const rollupMap = new SourceMapConsumer(rollupResult.map);

          // Remap errors from the closure compiler output to the original
          // files before rollup bundled them.
          const remap = (type) => (item) => {
            let {line, column, source} = rollupMap.originalPositionFor({
              line: item.lineNo,
              column: item.charNo,
            });
            source = path.relative('.', path.resolve(__dirname, '..', source));
            return {type, line, column, source, desc: item.description};
          };

          reject({
            errors: [
              ...closureResult.errors.map(remap('error')),
              ...closureResult.warnings.map(remap('warning')),
            ],
          });
        } else {
          // Currently, closure compiler doesn't support applying its generated
          // source map to an existing source map, so we do it manually.
          const fromMap = JSON.parse(closureResult.sourceMap);
          const toMap = rollupResult.map;

          const generator = SourceMapGenerator.fromSourceMap(
              new SourceMapConsumer(fromMap));

          generator.applySourceMap(
              new SourceMapConsumer(toMap), path.basename(output));

          const sourceMap = generator.toString();

          resolve({
            code: closureResult.compiledCode,
            map: sourceMap,
          });
        }
      } catch(err) {
        reject(err);
      }
    }).catch(reject);