【问题标题】:Using gulp-browserify for my React.js modules I'm getting 'require is not defined' in the browser对我的 React.js 模块使用 gulp-browserify 我在浏览器中得到“require is not defined”
【发布时间】:2014-08-03 03:06:38
【问题描述】:

我正在尝试使用 gulp-browserify 生成一个 bundle.js 文件,该文件可以包含到客户端的浏览器中并开始渲染 React 组件。

这是我的 App.js 文件:

/** @jsx React.DOM */
var React = require('react');

var App = React.createClass({
  render: function() {
    return <h1>Hello {this.props.name}!</h1>;
  }
});

module.exports = App;

还有我的 package.json:

  "name":"hellosign-gulp",
  "version":"0.1.1",
  "dependencies": {
    "gulp": "3.5.x",
    "gulp-browserify": "0.5.0",
    "reactify": "~0.8.1",
    "react": "^0.10.0",
    "gulp-react": "0.2.x"
  }
}

还有我的 gulpfile

var   gulp = require('gulp'),
  react = require('gulp-react'),
  browserify = require('gulp-browserify');


gulp.task('brow-test', function() {
    // Single entry point to browserify
    gulp.src('./src/App.js', {read: false})
        .pipe(browserify({
          insertGlobals : true,
          transform: ['reactify'],
          extensions: ['.jsx'],
          debug :false.
        }))
        .pipe(gulp.dest('.'))
});

现在,当我运行“brow-test”时,我将输出文件重命名为 bundle.js,并将其包含在浏览器的 HTTP 响应中。 bundle.js 文件很大,所以我不会在这里包含它,但浏览器最终会抛出错误

Uncaught ReferenceError: require is not defined

我使用这些命令在普通版本的 browserify 中正确运行了完全相同的设置

browserify -t reactify -r react -r ./src/App > ../webapp/static/bundle.js

然后我没有得到错误。为什么 gulp-browserify 没有正确创建 require shim?

【问题讨论】:

  • 我不相信设置是一样的,因为你在命令行上做-r react -r ./src/App,(对gulp不太熟悉)。
  • 您可以使用vinyl-source-stream 和gulp-buffer 在gulp 中运行常规的browserify。这就是我们所做的,因为 gulp-browserify 对我们来说一直不够好。
  • 我仍然无法获得暴露的全局要求。我简化了问题并在这里发布了一个新问题:stackoverflow.com/questions/24329690/…
  • 使用带有乙烯基源流的 browserify 是否改善了您的工作流程?

标签: javascript node.js gulp reactjs browserify


【解决方案1】:

我没有直接看到你的代码有什么问题,但我正在使用这个

gulp.src('./src/js/index.js') .pipe(browserify()) .on('prebundle', function(bundle) { // React Dev Tools tab won't appear unless we expose the react bundle bundle.require('react'); }) .pipe(concat('bundle.js'))

我使用https://www.npmjs.org/package/gulp-react 来转换 .jsx,但现在我更喜欢使用常规 javascript。

让我知道这是否适合您,如果不适合我可以提取示例模板...

【讨论】:

  • 此代码失败并出现错误 TypeError: Object # has no method 'pipe'
【解决方案2】:

直接在你的文件上运行 browserify,不要使用使用 gulp-browserify 插件。

此处引用:https://github.com/gulpjs/plugins/issues/47

“Browserify 应该作为一个独立的模块使用。它返回一个流并计算出你的依赖关系图。如果你需要乙烯基对象,请使用 browserify +vinyl-source-stream”

你可以这样实现你想要的结果:

var source = require('vinyl-source-stream'), //<--this is the key
    browserify = require('browserify');

    function buildEverything(){
        return browserify({
               //do your config here
                entries: './src/js/index.js',
            })
            .bundle()
            .pipe(source('index.js')) //this converts to stream
             //do all processing here.
             //like uglification and so on.
            .pipe(gulp.dest('bundle.js'));
        }
    }

    gulp.task('buildTask', buildEverything);

现在,在您的 Json 包中,正如您所拥有的 - 需要 react、browsierify 等等。您还可以在此处填充 browserify,使用转换或其他方式。

  "dependencies": {
    "react": "^0.10.0",  
  },
  "devDependencies": {
     "browserify": "3.46.0",
    "browserify-shim": "3.x.x",
   }
  "browserify": {
    "transform": [
      "browserify-shim"
    ]
  },
  "browserify-shim": {
     "react": "React", 
  }

或者像你一样做,并在你使用它的页面上包含反应

var React = require('react');

或者如果你想要一些方便的助手的话,可以这样做:

var React = require('react/addons');

但底线是直接在 gulp 中使用 browserify 并使用vinyl-source-stream 进入 gulp 管道。

【讨论】:

    【解决方案3】:

    这是使用 browserify(与 vinyl-transform 和朋友一起)实现完全等效的 gulp 配方

    browserify -t reactify -r react -r ./src/App > ../webapp/static/bundle.js`
    

    src/App.js

    /** @jsx React.DOM */
    var React = require('react');
    
    var App = React.createClass({
      render: function() {
        return <h1>Hello {this.props.name}!</h1>;
      }
    });
    
    module.exports = App;
    

    gulpfile.js

    var gulp = require('gulp');
    var browserify = require('browserify');
    var transform = require('vinyl-transform');
    var reactify = require('reactify');
    var rename = require("gulp-rename");
    
    gulp.task('build', function () {
    
      // browserify -t reactify -r react -r ./src/App > ../webapp/static/bundle.js
    
      var browserified = transform(function(filename) {
        return browserify()
    
          // -t reactify
          .transform(reactify)
    
          // -r react
          // update below with the correct path to react/react.js node_module
          .require('./node_modules/react/react.js', { expose: 'react'})
    
          // -r ./src/App
          // filename = <full_path_to>/src/App.js
          .require(filename, {expose: 'src/App'})
          .bundle();
      });
      return gulp.src('./src/App.js')
        .pipe(browserified)
        .pipe(rename('bundle.js'))
        .pipe(gulp.dest('../webapp/static/'));
    });
    
    gulp.task('default', ['build']);
    

    【讨论】:

      【解决方案4】:

      更新:我为此写了一篇新文章,使用不同的打包工具。还包含一个browserify的优化示例:Choosing the correct packaging tool for React JS

      致任何阅读这篇文章以启动和运行 React JS 工作流的人:

      我在让它工作时遇到了很多问题,最后写了一篇关于它的帖子:React JS and a browserify workflow。这是我的解决方案,确保您可以转换 JSX 并处理对其他文件的单独监视。

      var gulp = require('gulp');
      var source = require('vinyl-source-stream'); // Used to stream bundle for further handling etc.
      var browserify = require('browserify');
      var watchify = require('watchify');
      var reactify = require('reactify'); 
      var concat = require('gulp-concat');
      
      gulp.task('browserify', function() {
          var bundler = browserify({
              entries: ['./app/main.js'], // Only need initial file, browserify finds the deps
              transform: [reactify], // We want to convert JSX to normal javascript
              debug: true, // Gives us sourcemapping
              cache: {}, packageCache: {}, fullPaths: true // Requirement of watchify
          });
          var watcher  = watchify(bundler);
      
          return watcher
          .on('update', function () { // When any files update
              var updateStart = Date.now();
              console.log('Updating!');
              watcher.bundle() // Create new bundle that uses the cache for high performance
              .pipe(source('main.js'))
              // This is where you add uglifying etc.
              .pipe(gulp.dest('./build/'));
              console.log('Updated!', (Date.now() - updateStart) + 'ms');
          })
          .bundle() // Create the initial bundle when starting the task
          .pipe(source('main.js'))
          .pipe(gulp.dest('./build/'));
      });
      
      // I added this so that you see how to run two watch tasks
      gulp.task('css', function () {
          gulp.watch('styles/**/*.css', function () {
              return gulp.src('styles/**/*.css')
              .pipe(concat('main.css'))
              .pipe(gulp.dest('build/'));
          });
      });
      
      // Just running the two tasks
      gulp.task('default', ['browserify', 'css']);
      

      要解决在 chrome 中使用 React JS DEV-TOOLS 的问题,您必须在 main.js 文件中执行以下操作:

      /** @jsx React.DOM */
      
      var React = require('react');
      // Here we put our React instance to the global scope. Make sure you do not put it 
      // into production and make sure that you close and open your console if the 
      // DEV-TOOLS does not display
      window.React = React; 
      
      var App = require('./App.jsx');
      React.renderComponent(<App/>, document.body);
      

      我希望这会帮助你继续前进!

      【讨论】:

      • 我在我的项目中使用你的帖子,谢谢!我正在努力弄清楚如何让 reactify 接受和谐 jsx 的东西。我试过变换:[[reactify, {"harmony": true}]] .. 不走运?
      • 嗯,你可能要绑定它​​? [reactify.bind(null, {harmony: true}]。很高兴能帮上忙:-)
      • 不确定/app/main.jsmain.js 之间的区别是什么...它们是不同的文件吗?
      • 为此提供您的 package.json 会很棒。
      • 查看提到的文章 :-) 它还有一个样板文件,里面有你需要的一切
      【解决方案5】:

      我用这个来做我的反应工作。

      var gulp = require('gulp');
      var source = require('vinyl-source-stream'); 
      var browserify = require('browserify');
      var watchify = require('watchify');
      var reactify = require('reactify'); 
      var concat = require('gulp-concat');
       
      gulp.task('browserify', function() {
          var bundler = browserify({
              entries: ['./assets/react/main.js'], 
              transform: [reactify],
              debug: true, 
              cache: {}, packageCache: {}, fullPaths: true 
          });
          var watcher  = watchify(bundler);
      
          return watcher
          .on('update', function () { 
              var updateStart = Date.now();
              console.log('Updating!');
              watcher.bundle() 
              .pipe(source('main.js'))
          
              .pipe(gulp.dest('./assets/js/'));
              console.log('Updated!', (Date.now() - updateStart) + 'ms');
          })
          .bundle() 
          .pipe(source('main.js'))
          .pipe(gulp.dest('./assets/js/'));
      });
      
      
      
      gulp.task('default', ['browserify']);

      【讨论】:

        【解决方案6】:

        package.json:

        {
          "devDependencies": {
            "gulp": "^3.8.11",
            "gulp-browserify": "^0.5.1",
            "reactify": "^1.1.0"
          },
          "browserify": {
            "transform": [["reactify", { "es6": true }]],
            "insertGlobals": true,
            "debug": true
          }
        }
        

        gulpfile.js:

        var gulp = require('gulp');
        var browserify = require('gulp-browserify');
        
        gulp.task('browserify', function() {
            return gulp.src("./assets/index.js")
                .pipe(browserify())
                .pipe(gulp.dest("./www/assets"));
        });
        

        【讨论】:

        • 不建议使用gulp-browserify,因为它目前已被列入黑名单。你最好改用browserify 包。
        【解决方案7】:

        定义

        React=require('react');
        ReactDOM = require('react-dom');
        

        App.js 中的那些全局 javascript 值,而不是放这个

        var stream = require('vinyl-source-stream');
        var browserify = require('browserify');
            browserify(source + '/app/app.js')
                // bundles it and creates a file called main.js
                .bundle()
                .pipe(stream('main.js'))
                // saves it the dest directory
                .pipe(gulp.dest(destination +'/assets/js'));
        

        在 Gulpfile.js 中。

        最后,将 main.js 放入 HTML,它应该可以工作。

        问题是如果我们使用 var React=require('react'),React 对象在其他脚本中是不可见的,但是 React=require('react') 定义了一个全局值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-26
          • 1970-01-01
          • 1970-01-01
          • 2012-06-13
          • 2021-06-11
          • 2015-08-11
          • 2016-10-12
          • 2022-12-11
          相关资源
          最近更新 更多