【问题标题】:browserify for mixed-style project (grunt, reactjs + plain js)browserify 用于混合风格项目(grunt,reactjs + plain js)
【发布时间】:2015-03-29 23:05:31
【问题描述】:

对于使用 reactjs 和纯 javascript 的项目,在 grunt 中配置 browserify 插件的最佳方法是什么? IE。假设我想在我的项目中的每个 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/... 目录中的所有文件应用 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 任务中需要额外的副本而不是“反应”源。可能是我遗漏了什么,这个解决方案可以简化吗?

【问题讨论】:

    标签: javascript gruntjs reactjs browserify


    【解决方案1】:

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

    除此之外的任何东西都是优化,但只需使用 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 要容易得多。

    【讨论】:

    • 好吧,我想我问这个问题时不是很清楚。这绝对是可行的 - 问题是它是否可以仅在“浏览器”任务中完成,或者我应该求助于帮助任务在运行浏览器之前使用“反应”源创建适当的布局?另请参阅我的帖子的更新 - 我概述了我现在正在遵循的步骤,这对我来说似乎是一个 hack。
    • 是的,这更简单。我有一个简单的应用程序,但它会增长
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多