如何使用 Browserify 和 coffeeify 转换将 CoffeeScript 转换为 JavaScript(最后 2 个版本,即 >= 11)?

How to transpile CoffeeScript to JavaScript (last 2 versions and ie >= 11) using Browserify and coffeeify transform?

CoffeeScript 2 outputs latest, modern syntax which is not compatible with older browsers and gulp-uglify.

GulpUglifyError: unable to minify JavaScript
Caused by: SyntaxError: Unexpected token: operator «=», expected: punc «,»

很难弄清楚这个问题,所以在这里删除一些代码以防它可以帮助其他人。

Gulp 4 and CoffeeScript 2 引入了重大更改,因此更新依赖项可能很乏味。

一个重大变化是 CoffeeScript 现在输出旧版浏览器不支持的现代语法(它还打破了 gulp-uglify). To support these browsers (and to keep using gulp-uglify), transpilation 是必需的。

安装包

npm install @babel/core @babel/preset-env browserify coffeeify coffeescript glob gulp gulp-sourcemaps gulp-uglify gulp-util merge-stream vinyl-buffer vinyl-source-stream --save-dev

编辑gulpfile.js

'use strict';

const gulp = require('gulp');
const gutil = require('gulp-util');
const merge = require('merge-stream');
const browserify = require('browserify');
const glob = require('glob');
const source = require('vinyl-source-stream');
const path = require('path');
const buffer = require('vinyl-buffer');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');

var minify;
if (process.env.MINIFY === 'true') {
    minify = true;
} else {
    minify = false;
}

function browserifyTask() {
    var files = glob.sync('./app/*.coffee');
    return merge(files.map(function(file) {
        return browserify({
            entries: file,
            extensions: ['.coffee'],
            debug: true
        })
        .transform('coffeeify', {
            transpile: {
                presets: [
                    [
                        '@babel/preset-env',
                        {
                            targets: {
                                browsers: ['last 2 versions', 'ie >= 11']
                            }
                        }
                    ]
                ]
            }
        })
        .on('error', gutil.log)
        .bundle()
        .pipe(source(path.basename(file, '.coffee') + ".js"))
        .pipe(buffer())
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe((minify === true) ? uglify().on('error', gutil.log) : gutil.noop())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('public/js'));
    }));
}

const build = gulp.series(browserifyTask);

exports.default = build;