Using reactjs with requirejs

后端 未结 2 692
轮回少年
轮回少年 2020-12-12 10:20

Recently, I started using reactjs along with a backbonejs router to build an application.

I usually use use requirejs for depe

相关标签:
2条回答
  • 2020-12-12 10:44

    So I figured it out myself.

    I got the necessary files and instructions from this repo: jsx-requirejs-plugin.

    Once I had jsx plugin and modified version of JSXTransformer, I changed my code as instructed in the repository :

    require.config({
      // ...
    
      paths: {
        "react": "path/to/react",
        "JSXTransformer": "path/to/JSXTransformer",
        "jsx": "path/to/jsx plugin"
        ...
      }
    
      // ...
    });
    

    Then, I could reference JSX files via the jsx! plugin syntax. For example, to load the Timer.jsx file that is in a components directory:

    require(['react', 'jsx!components/Timer'], function (React, Timer) {
       ...
       React.renderComponent(<Timer />, document.getElementById('timer'));
       ...
    });
    

    I could also access .js files that had jsx syntax in them using the same code:

    require(['react', 'jsx!components/Timer'], function (React, Timer) {
       ...
       React.renderComponent(<Timer />, document.getElementById('timer'));
       ...
    });
    

    Also, I did not need to put /** @jsx React.DOM */ at the top of files using jsx syntax.

    Hope it helps.

    0 讨论(0)
  • 2020-12-12 10:55

    React tools (JSX included) have been deprecated in favor of Babel (https://facebook.github.io/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html). I cannot find a way to do this without a "transpiling" step, so this is my solution with grunt.

    You can instal grunt-babel (npm install grunt-babel) and configure a task like the following:

    babel: {
        options: {
            sourceMap: false,
            modules: "common"
        },
        dist: {
            files: [{
                expand: true,
                src: ['js/components/*.jsx'],
                dest: 'dist',
                ext:'.js'
           }]
        }
    }
    

    Just add it to your list of grunt tasks:

    grunt.registerTask('default', ['clean', 'copy', 'babel', 'http-server']);
    

    Babel will transpile your JSX to JS files that can be specified as RequireJS dependencies with no additional configuration.

    0 讨论(0)
提交回复
热议问题