[英]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.