提问者:小点点

无法导入react中的模块


我已经制作了这个实用程序,我想把它导入到另一个文件中:

const fetch = require('node-fetch');

/**
 * @todo Add documentation
 */
class SimplicateApi { 
    constructor(key,secret){
        this._key = key; 
        this._secret = secret; 
        this.baseUrl = 'https://simplicate.nl/api/v2'; 

        this.options = {
            headers: { 
                'Content-Type': 'application/json', 
                'Authentication-Key' : this._key, 
                'Authentication-Secret' : this._secret
            }
        }
    }

    get(endpoint) {
        return fetch(`${this.baseUrl}${endpoint}`, this.options)
        .then(res => res.json())
        .then(json => json);
    }
}

export default SimplicateApi;

在另一个文件中,我像这样导入它:

import SimplicateApi from '../../utils/SimplicateApi';

我收到的错误:

(函数(exports,require,module,__filename,__dirname){import{SimplicateApi}来自“。。/。。/utils/SimplicateApi”;^

语法错误:意外令牌{at new Script(vm.js:80:7)at createScript(vm.js:274:10)at object.runinthiscontext(vm.js:326:10)at module._compile(internal/module._extensions.。js(internal/modules/cjs/loader.js:664:28)at module.load(internal/modules/cjs/loader.js:712:10)at module.load(internal/modules/cjs/loader.js:600:32)

我删除了所有内容,甚至连提取都删除了,只导出了类,如下所示:

// import fetch from 'node-fetch';

/**
 * @todo Add documentation
 */
class SimplicateApi { 

}

export default SimplicateApi; 

现在我像这样导入它:

import SimplicateApi from '../../utils/SimplicateApi';

错误看起来仍然是:

(function (exports, require, module, __filename, __dirname) { import SimplicateApi from '../../utils/SimplicateApi';
                                                                     ^^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)     
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)  
    at startup (internal/bootstrap/node.js:283:19)
PS C:\Users\klmaa\OneDrive\Bureaublad\dexhub\client\src\components\cmInf

共1个答案

匿名用户

您的代码混合了commonJS模块ES6模块

在react中,您应该使用ES6模块。 React不支持CommonJs模块。您需要为此配置Babel。

const fetch = require('node-fetch'); // this wronng import syntax in React.

更改应

// if you are in react.
    import fetch from 'node-fetch'; // for react

//if you are in Node.
class SimplicateApi { 

}

module.exports = SimplicateApi;