Lc0rE
Lc0rE

Reputation: 2346

Import custom JS in create-react-app

I'm using the latest create-ract-appversion for my project and I have a custom.js file with a CustomFunction function in it. I need is to access to the CustomFunctionfunction from one of my components.

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:

<!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

Upvotes: 1

Views: 4925

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

What you need to do is export the function form you custom.js file like

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

export {
    CustomFunction,
    CustomVariable,
    CustomVar2,
    CustomFunction2
}

And import like

import {CustomFunction, CustomVariable, CustomVar2, CustomFunction2} from './path/to/custom.js';

Upvotes: 4

Related Questions