在create-react-app中导入自定义JS

问题描述 投票:1回答:1

我为我的项目使用了最新的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
reactjs webpack create-react-app
1个回答
2
投票

您需要做的是将您的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';
© www.soinside.com 2019 - 2024. All rights reserved.