【问题标题】:Import JavaScript file and call functions using webpack, ES6, ReactJS使用 webpack、ES6、ReactJS 导入 JavaScript 文件和调用函数
【发布时间】:2016-11-22 21:10:35
【问题描述】:

尝试做一些我认为非常简单的事情。我想导入一个现有的 JavaScript 库,然后调用它的函数。例如,我想导入 blah.js,然后调用 blah()。

import React from 'react';
import {blah} from 'blah/js/blah.js';

class MyClass extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        window.addEventListener('resize', this.handleResize);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.handleResize);
    }

    handleResize() {
        blah.blah();
    }

    render() {
          ....
    }
}

export default MyClass;

只是想知道我必须做哪些神奇的事情才能完成这项工作。也许我只是错过了重点。该示例给出了错误“TypeError: _blah.blah is undefined”。

【问题讨论】:

标签: reactjs ecmascript-6 webpack


【解决方案1】:

命名导出:

假设您创建了一个名为 utils.js 的文件,其中包含您希望其他模块(例如 React 组件)可用的实用程序功能。然后你会让每个函数成为一个命名的导出

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

假设 utils.js 与您的 React 组件位于同一目录中,您可以像这样使用它的导出:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

或者,如果您愿意,可以将整个模块的内容放在一个公共命名空间下:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

默认导出:

另一方面,如果你有一个只做一件事的模块(可能是一个 React 类、一个普通函数、一个常量或其他任何东西)并且想要让其他人可以使用那个东西,你可以使用 默认导出。假设我们有一个文件log.js,只有一个函数可以记录调用它的任何参数:

export default function log(message) {
  console.log(message);
}

现在可以这样使用:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

您不必在导入时调用它log,实际上您可以随意调用它:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

综合:

一个模块可以同时具有默认导出(最多 1 个)和命名导出(一个一个导入,或使用带有别名的 *)。 React 实际上有这个,考虑一下:

import React, { Component, PropTypes } from 'react';

【讨论】:

  • 有道理,但现在我收到这样的错误:SyntaxError: export declarations may only appear at top level of a module
  • 那么您可能正在导出其他块中的内容。读取错误时,您需要在顶层(即在任何块之外)执行此操作。
  • 如何只导入 util 并调用 util.add()、util.multiply() 等函数?
  • @jiawen 你可以这样做:import * as util from './utils.js'; (我也将这个添加到答案中)。
  • 哦,我错过了。谢谢!
【解决方案2】:
import * as utils from './utils.js'; 

如果做到以上几点,就可以将utils.js中的函数当作

utils.someFunction()

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 2015-10-14
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2017-07-11
    • 2018-01-15
    相关资源
    最近更新 更多