【问题标题】:Import custom JS in create-react-app在 create-react-app 中导入自定义 JS
【发布时间】:2017-06-01 09:30:14
【问题描述】:

我正在为我的项目使用最新的create-ract-appversion,并且我有一个custom.js 文件,其中包含CustomFunction 函数。 我需要的是从我的一个组件访问CustomFunctionfunction。

实现这一目标的最佳方法是什么? 将文件导入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】:

    您需要做的是将函数形式导出到您的 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';
    

    【讨论】:

    • 我需要从我的自定义文件中导出每个变量和函数吗?有很多这样的......这是正确的方式吗?
    • 请不要将 CommonJS 语法 (module.exports) 与 ES6 语法 (import) 混用。要么使用其中一个,要么同时使用。
    • 好的@DanAbramov,我一到家就会更新答案
    • 另外,您不需要导出 every 变量。您只需要导出您将使用的内容(本例中的组件)。看看src/App.js 是如何导出一个组件,src/index.js 是如何在新创建的项目中导入它的。用户指南还包括有关导入文件的说明:github.com/facebookincubator/create-react-app/blob/master/…
    • @DanAbramov,是的,您只需要导出稍后将使用的变量,我虽然很明显并且没有明确地将其添加到答案中
    猜你喜欢
    • 2020-08-18
    • 2020-05-02
    • 2018-02-22
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 2017-11-20
    • 2019-08-23
    • 2021-12-03
    相关资源
    最近更新 更多