browserify for mixed-style project(grunt,reactjs + plain js)

时间:2015-03-29 23:05:32

标签: javascript gruntjs reactjs browserify

在一个项目中为grunt配置browserify插件的最佳方法是什么,其中reactjs与普通的javascript一起使用? 即假设我想在我的项目和目录结构中的每个js文件中使用require(...),如下所示:

/js/model/foo.js (plain javascript)
/js/model/... (plain javascript)
/js/services/foo-service.js (plain javascript)
/js/view/foo-item-view.jsx (reactjs)
/js/view/... (reactjs)
/js/main.js (plain javascript, entry point)
etc.

我想对/ js / view / ... dir中的所有文件应用reactjs变换,然后使用browserify转换所有文件。我找不到干净的方法。

有可能吗?

更新

好吧,我认为我的问题有点不清楚。我明白这绝对可行,这就是我现在正在做的事情(看起来像是对我的黑客攻击):

// Project configuration.
grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  watch: {
    scripts: {
      files: ['web/js/**/*.js', 'web/html/index.html'],
      tasks: ['copy', 'react', 'browserify']
    }
  },
  copy: {
    main: {
      files: [
        {
          src: 'web/html/index.html',
          dest: 'target/web/index.html'
        },
        {
          cwd: 'web/js',                // source js dir
          src: ['**', '!**/*.jsx'],     // copy all files and subfolders to the temporary dor, except for jsx
          dest: 'target/web/tmp/js',    // destination folder, used by browserify
          expand: true                  // required when using cwd
        }
      ]
    }
  },
  react: {
    dynamic_mappings: {
      files: [
        {
          expand: true,
          cwd: 'web/js/view',
          src: ['**/*.jsx'],
          dest: 'target/web/tmp/js/view',
          ext: '.js'
        }
      ]
    }
  },
  browserify: {
    dist: {
      files: {
        'target/web/js/app.js': ['target/web/tmp/js/main.js'],
      }
    }
  }
});

这对我来说并不优雅,因为在browserify任务中需要额外的复制而不是'重新'来源。可能是我遗漏了一些东西,这个解决方案可以简化了吗?

1 个答案:

答案 0 :(得分:2)

您可以对所有内容运行jsx转换。它不会对常规JavaScript代码做任何事情。

jsx compiler with bizare code

除此之外的任何事情都是优化,但只需使用watchify(或watchify grunt插件),您就不会注意到。


回应评论和编辑......你真的需要咕噜咕噜吗?

npm i -D browserify watchify reactify

然后在你的package.json中:

  "scripts": {
    "build": "browserify src/main.js -o dist/bundle.js",
    "watch": "watchify src/main.js -o dist/bundle.js"
  },
  "browserify": {
    "transform": ["reactify"]
  }

你也可以拥有一切.js,它更简单的imo。如果您需要其他一些东西,如css预处理器,图像压缩,精灵表,运行测试等,你应该使用像grunt / gulp这样的工具。

对于browserify,我发现自己使用watchify要容易得多。