[英]Import custom JS in create-react-app
I'm using the latest create-ract-app
version for my project and I have a custom.js
file with a CustomFunction
function in it. 我为我的项目使用了最新的
create-ract-app
版本,并且我有一个带有CustomFunction
函数的custom.js
文件。 I need is to access to the CustomFunction
function from one of my components. 我需要从我的组件之一访问
CustomFunction
函数。
Which is the best way to achieve this? 哪个是实现此目标的最佳方法? Importing the file into
index.html
like below, I have 'CustomFunction' is not defined no-undef'
error: 如下所示将文件导入
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>
This is the project structure: 这是项目结构:
10 ├── public
11 │ ├── customComponent
12 │ │ ├── custom.js
13 │ │ └── custom.css
14 │ ├── favicon.ico
15 │ ├── index.html
16 │ └── manifest.json
What you need to do is export the function form you custom.js file like 您需要做的是将您的custom.js文件导出为函数形式
const CustomFunction = () => {
}
export {CustomFunction};
Now you can import it in any of the component like 现在,您可以将其导入任何组件中,例如
import {CustomFunction} from './path/to/custom.js';
If you have multiple of them in component.js, which you want to use in other components then you can export them like 如果要在其他组件中使用的component.js中有多个组件,则可以将其导出,例如
export {
CustomFunction,
CustomVariable,
CustomVar2,
CustomFunction2
}
And import like 和进口一样
import {CustomFunction, CustomVariable, CustomVar2, CustomFunction2} from './path/to/custom.js';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.