使用 webpack,ES6,ReactJS 导入 JavaScript 文件和调用函数

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

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.bra is unDefinition”。

171395 次浏览

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

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


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

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

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

Or if you prefer, place the entire module's contents under a common namespace:

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

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

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

This can now be used like this:

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

You don't have to call it log when you import it, you could actually call it whatever you want:

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

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';
import * as utils from './utils.js';

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

Check out the working code here :

Link to the Netlify React App using Javascript : https://paint0183.netlify.app/

Source Code of Microsoft Paint Clone: Github Source Code

Faced the same problem but the answer was simple

why not import directly?

import {file-name} from "./file-path";


For example :
import {jscolor} from "./jscolor";

The only thing which you need to add to make sure the javascript loads after the DOM has loaded :

window.onload=function() {


// your entire javascript code here


}