【问题标题】:How to avoid bundling ReactJs multiple times using Gulp?如何避免使用 Gulp 多次捆绑 ReactJs?
【发布时间】:2016-10-04 04:22:01
【问题描述】:

我正在尝试使用 ReactJS 作为客户端的视图库渲染。此外,我从 Material-UI 导入了许多组件作为组件。 一个问题是我需要使用 gulp 来设置 browserify(用于在浏览器中使用模块)和 babelify(将 JSX 编译为 Javascript)。 但我发现如果 React 被捆绑多次,UI 会在行为和样式上出现错误。 根据this article,我将 gulpfile.js 设置如下。

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

var dependencies = [
  'react',
  'react-dom',
  'material-ui',
  'react-tap-event-plugin'
];

var scriptsCount = 0;

gulp.task('scripts', function () {
    bundleApp(false);
});

gulp.task('deploy', function (){
  bundleApp(true);
});

gulp.task('watch', function () {
  gulp.watch(['./app/*.js'], ['scripts']);
});

gulp.task('default', ['scripts','watch']);

function bundleApp(isProduction) {
  scriptsCount++;
  var appBundler = browserify({
      entries: './app/app.js',
      debug: true
    })
  if (!isProduction && scriptsCount === 1){
    browserify({
      require: dependencies,
      debug: true
    })
    .bundle()
    .on('error', gutil.log)
    .pipe(source('vendors.js'))
    .pipe(gulp.dest('./web/js/'));
  }
  if (!isProduction){
    dependencies.forEach(function(dep){
      appBundler.external(dep);
    })
  }
  appBundler
  .transform("babelify", {presets: ["es2015", "react"]})
  .bundle()
  .on('error',gutil.log)
  .pipe(source('bundle.js'))
  .pipe(gulp.dest('./web/js/'));
}

如果我跑:

gulp scripts

不止一次,UI 会在控制台中出现一些问题和错误。

那么我应该如何修改 gulpfile 以避免捆绑 React?请帮忙。

【问题讨论】:

    标签: javascript reactjs gulp browserify material-ui


    【解决方案1】:

    您需要将react-addons-transition-group 包含到您的外部依赖项列表中。我面临着同样的问题。 这是我为解决它所做的。

    1. 清理了 node_modules rm -rf node_modules
    2. npm install react-addons-transition-group --save
    3. npm install
    4. 运行gulp scripts

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多