如何配置gulp来编译.jsx和.ts文件?

时间:2017-11-18 08:12:46

标签: reactjs typescript gulp

我有我的客户端代码反应本机,即.jsx文件,我正在使用gulp来编译它们。我想将我的项目转换为开始使用typescript但一次只使用1个文件。这意味着我需要能够使用gulp编译jsx和ts。

我正在使用以下gulp -

/// <binding AfterBuild='default' />
"use strict";

var gulp = require("gulp"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    merge = require("merge-stream"),
    del = require("del"),
    bundleconfig = require("./bundleconfig.json"),
    runSequence = require('run-sequence');

var runSequence = require('run-sequence');

var sass = require('gulp-sass');

var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

var webroot = "./wwwroot/";
var paths = {
    scss: webroot + "sass/**/*.scss",
    scssDest: webroot + "css/"
};

// 1. react
gulp.task('react', function () {
    return browserify({ entries: './wwwroot/clientapp/root', extensions: [ '.jsx', '.js'], debug: true })
        .transform('babelify', { presets: ['es2015', 'react'] })
        .bundle()
        .pipe(source('index.js'))
        .pipe(gulp.dest('./wwwroot/'));
});

// 2. sass
gulp.task('compile:sass', function () {
    gulp.src(paths.scss)
        .pipe(sass())
        .pipe(gulp.dest(paths.scssDest));
});
gulp.task("sass", ["compile:sass"]);

// minify sass output
function getBundles(regexPattern) {
    return bundleconfig.filter(function (bundle) {
        return regexPattern.test(bundle.outputFileName);
    });
}
gulp.task("css",  function () {
    var tasks = getBundles(/\.css$/).map(function (bundle) {
        return gulp.src(bundle.inputFiles, { base: "." })
            .pipe(concat(bundle.outputFileName))
            .pipe(cssmin())
            .pipe(gulp.dest("."));
    });
    return merge(tasks);
});

gulp.task("clean", function () {
    return del(['wwwroot/css/*', 'wwwroot/index.js']);
});

gulp.task("default", function (cb) {
    runSequence(
        ['clean', 'sass'],
        ['react'],
        ['css'],
        cb);
});

我需要对gulp配置进行哪些更改,以确保.jsx和.ts文件都能正常工作和编译。

1 个答案:

答案 0 :(得分:0)

为响应任务添加.ts扩展名。根据您的代码,您还必须配置babelify以使用ts

gulp.task('react', function () {
    return browserify({ entries: './wwwroot/clientapp/root', extensions: [ '.jsx', '.js', '.ts'], debug: true })
        .transform('babelify', { presets: ['es2015', 'react'], extensions: [ '.jsx', '.js', '.ts'] })
        .bundle()
        .pipe(source('index.js'))
        .pipe(gulp.dest('./wwwroot/'));
});

你可以尝试不添加扩展到babelify,但我认为它不会起作用。

希望有所帮助!