如何修复错误'FB'在create-react-app项目中没有定义no-undef?

Var*_*kul 14 facebook reactjs eslint create-react-app

我使用此链接作为我的起始文件制作了项目.

https://github.com/facebookincubator/create-react-app

但在我试图制作Facebook登录按钮后,跟随他们的官方文档.

componentDidMount(){
    console.log('login mount');
    window.fbAsyncInit = function() {
        FB.init({
            appId      : '320866754951228',
            xfbml      : true,
            version    : 'v2.6'
        });

        FB.getLoginStatus(function(response) {
            //this.statusChangeCallback(response);
        });

    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}
Run Code Online (Sandbox Code Playgroud)

所以我在刷新浏览器时遇到了这个错误.

Failed to compile.

Error in ./src/components/user_profile/LoginForm.js

/Sites/full_stack_production/xxxxx
  70:13  error  'FB' is not defined  no-undef
  76:13  error  'FB' is not defined  no-undef

? 2 problems (2 errors, 0 warnings)
Run Code Online (Sandbox Code Playgroud)

所以我猜因为ESLint导致了这个错误.我该如何解决这个问题或者为这个FB变量做例外?

谢谢!

vit*_*bal 30

ESLint不知道变量FB是全局变量.您可以通过将以下内容添加到文件顶部来声明您引用为全局的变量:

/*global FB*/

有关更多信息,请查看官方ESLint文档中的"规则详细信息"部分:http://eslint.org/docs/rules/no-undef


Dan*_*mov 12

如果您使用Create React App,则需要显式地从中获取全局变量window.
例如:

// It's a global so need to read it from window
const FB = window.FB;
Run Code Online (Sandbox Code Playgroud)

但是,如果库可用作npm包,则可以使用导入:

// It's an npm package so you can import it
import $ from 'jquery';
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!


jpe*_*lli 7

基于@ dan-abramov对另一个答案的评论中所说的:

不要使用FB,使用window.FB

这样,您可以明确地定义变量FB需要来自的位置.