[英]Import custom JS in create-react-app
我为我的项目使用了最新的create-ract-app
版本,并且我有一个带有CustomFunction
函数的custom.js
文件。 我需要从我的组件之一访问CustomFunction
函数。
哪个是实现此目标的最佳方法? 如下所示将文件导入index.html
,我有'CustomFunction' is not defined no-undef'
错误:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!-- jQuery import -->
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<!-- Custom Style and JS import -->
<link rel="stylesheet" href="./CustomComponent/custom.css">
<script src="./CustomComponent/custom.js"></script>
这是项目结构:
10 ├── public
11 │ ├── customComponent
12 │ │ ├── custom.js
13 │ │ └── custom.css
14 │ ├── favicon.ico
15 │ ├── index.html
16 │ └── manifest.json
您需要做的是将您的custom.js文件导出为函数形式
const CustomFunction = () => {
}
export {CustomFunction};
现在,您可以将其导入任何组件中,例如
import {CustomFunction} from './path/to/custom.js';
如果要在其他组件中使用的component.js中有多个组件,则可以将其导出,例如
export {
CustomFunction,
CustomVariable,
CustomVar2,
CustomFunction2
}
和进口一样
import {CustomFunction, CustomVariable, CustomVar2, CustomFunction2} from './path/to/custom.js';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.