How to include local javascript on a Gatsby page?

后端 未结 7 552
深忆病人
深忆病人 2020-11-30 07:48

I\'m a total React newbie and I guess there is something fundamental I don\'t quite understand here. A default Gatsby page looks like this. Is there a way to use a local .js

相关标签:
7条回答
  • 2020-11-30 08:40

    If you'd like to use a Gatsby plugin, which to me is no different from using an external library like Helmet (plugins are npm packages after all), you could use gatsby-plugin-load-script.

    You can provide either the url to the src attribute or a local path. If you're going to store your JS in a local file such as some-minified-js.min.js - make sure to store in the static directory at the root of your project.

    Once you do this, you can access via the global object:

    global.<object or func name here>
    

    For example, I was trying to include a very small JS library via a minified file, so I stored the file in /static/my-minified-library.min.js and then:

    1. Installed the plugin: npm i --save gatsby-plugin-load-script
    2. Added this to my gatsby-config.js
    plugins: [
        {
          resolve: "gatsby-plugin-load-script",
          options: {
            src: "/my-minified-library.min.js",
          },
        },
      ],
    
    1. Accessed in my react component like so:
    useEffect(() => {
      const x = new global.MyImportedLibraryObject();
    }, []}
    
    0 讨论(0)
提交回复
热议问题