Uncaught ReferenceError: React is not defined

前端 未结 12 1798
予麋鹿
予麋鹿 2020-11-30 02:17

I am trying to make ReactJS work with rails using this tutorial. I am getting this error:


Uncaught ReferenceError: React is not defined

相关标签:
12条回答
  • 2020-11-30 02:46

    If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".

    0 讨论(0)
  • 2020-11-30 02:48

    If you are using Webpack, you can have it load React when needed without having to explicitly require it in your code.

    Add to webpack.config.js:

    plugins: [
       new webpack.ProvidePlugin({
          "React": "react",
       }),
    ],
    

    See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin

    0 讨论(0)
  • 2020-11-30 02:48

    If you are using Babel and React 17, you might need to add "runtime2: "automatic" to config.

     {
         "presets": ["@babel/preset-env", ["@babel/preset-react", {
            "runtime": "automatic"
         }]]
     }
    
    0 讨论(0)
  • 2020-11-30 02:54

    Adding to Santosh :

    You can load React by

    import React from 'react'
    
    0 讨论(0)
  • 2020-11-30 02:58

    I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json:

    externals: {
        'react': 'React'
    },
    

    This above configuration tells webpack to not resolve require('react') by loading an npm module, but instead to expect a global variable (i.e. on the window object) called React. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React exists).

    0 讨论(0)
  • 2020-11-30 02:58

    Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.

    P.S

    Possible solutions.

    1. If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
    2. Make sure you have the line import React from 'react';
    0 讨论(0)
提交回复
热议问题