构建闭包编译器/打字稿前端工作流的问题

时间:2016-04-08 08:08:36

标签: typescript npm gulp browserify google-closure-compiler

我正在尝试使用从私有sinopia存储库托管的npm模块,使用gulpclosure-compilertypescript构建有用的工作流程。

最终目标如下:

  • 使用browserify和typescript进行开发,并将共享代码发布到私有npm存储库。

  • 随后使用闭包编译器优化Web应用程序项目。

(Closure编译器不是可选的,UglifyJS不会在文件大小和性能方面执行我想要的优化级别)

当我的项目完全自包含在我的源代码树中时,这完全正常工作(即我没有npm install编辑任何模块。这是工作gulpfile:

var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var size = require('gulp-size');
var server = require('gulp-live-server');
var typescript = require('gulp-typescript');
var closureCompiler = require('gulp-closure-compiler');

/** No minification */
gulp.task('compile-dev', function() {
    console.log("compile-dev at "+new Date())
    var b = browserify({baseDir: "src", debug: true})
        .add("src/main.ts")
        .plugin('tsify', { noImplicitAny: true, target: "es6"});
    b.bundle()
    .on('error', function(error) {
        console.error(error.toString());
    })
    .pipe(source("out.js"))
    .pipe(gulp.dest("www"))
})

/* minify with closure */
gulp.task('compile-closure', function () {
    gulp.src('src/**/*.ts')
    .pipe(typescript({target: "es6"}))
    .pipe(gulp.dest("build"))
    .pipe(closureCompiler({
        fileName: "out.js",
        compilerFlags: {
            language_in: "ES6",
            language_out: "ES5",
            compilation_level: "ADVANCED_OPTIMIZATIONS"
        }
    }))
    .pipe(gulp.dest("www"))
    .pipe(size({gzip: true, showFiles: true }))
});

现在我使用模块遇到三个相互关联的问题:

  • 发布npm包并使用typescript的target: "es6"编译顶级项目会导致compile-dev任务中的browserify被ParseError: 'import' and 'export' may appear only with 'sourceType: module'阻塞。如果我使用typescript target: "es5"编译模块,我们又回来并为compile-dev工作,所以实际上在这个意义上 - compile-dev工作正常,假设我到处都是“es5”。 / p>

  • 向下移动到“es5”,导致闭包编译器被Error: build/main.js:2: WARNING - dangerous use of the global this object var __extends = (this && this.__extends) || function (d, b) {阻塞 - 闭包不喜欢使用打字稿产生的es5

  • 如果我坚持使用“es6”作为打字稿目标,浏览器不仅会阻塞compile-dev,而且关闭(也许可以理解)仍然无法找到我的库,因为它不知道如果我import Foo from "bar",请查看node_modules。

那我怎么能:

  • 当我需要从外部库(没有./)?
  • 时,让闭包编译器查看node_modules
  • 允许browserify在npm中使用这些es6模块吗?

1 个答案:

答案 0 :(得分:1)

封闭编译器尚无法实现这一点,因为编译器不知道如何查找命名模块。唯一的选择是使用一个bundle,它可以在编译之前消除命名的模块引用。