【问题标题】:How to bundle a JS script with Vite + React如何将 JS 脚本与 Vite + React 捆绑在一起
【发布时间】:2022-09-27 18:03:50
【问题描述】:

我有一个带有 Vite 的 React 应用程序,我正在其上实现一个外部 JS 脚本。

我在index.html 上加载脚本,它在开发中完美运行,但是当我将它捆绑用于生产时,脚本没有加载。 起初,我收到一个错误,我需要在加载脚本时包含type=\"module\" 并修复了错误,但是当我转到使用该脚本的应用程序部分时,我得到了未定义的错误。

脚本位于/vendors/faceio/fio.js

<body>
    <!-- <script src=\"https://cdn.faceio.net/fio.js\"></script> -->
    <script type=\"module\" src=\"/vendors/faceio/fio.js\"></script>
    <div id=\"root\"></div>
    <script type=\"module\" src=\"/src/index.jsx\"></script>
    <script>
        const global = globalThis;
    </script>
    <!--
        This HTML file is a template.
        If you open it directly in the browser, you will see an empty page.

        You can add webfonts, meta tags, or analytics to this file.
        The build step will place the bundled scripts into the <body> tag.

        To begin the development, run `npm start` or `yarn start`.
        To create a production bundle, use `npm run build` or `yarn build`.
    -->
</body>

任何人都可以指出如何使这项工作。

    标签: javascript reactjs bundle vite


    【解决方案1】:

    在您的 index.html 文件中,&lt;body&gt;&lt;/body&gt; 标记内的代码应如下所示。

     <script src="https://cdn.faceio.net/fio.js"></script>
     <div id="root"></div>
     <script type="module" src="/src/main.jsx"></script>
    

    现在在你的 main.jsx 文件中,或者你想初始化 faceIO 的任何地方,使用一个名为 useEffect() 的反应钩子。

    import { useEffect } from "react";
    
    function App(){
       let faceio;
    
      useEffect(() => {
        faceio = new faceIO("fioa414d");
      }, []);
    }
    

    要构建您的 vite 应用程序,请运行 npm run build。您可以使用npm run preview 命令在部署之前预览构建。

    希望这能解决你所有的问题。谢谢。

    要了解有关 faceIO 的更多信息,请访问official documentation 页面。

    【讨论】:

      猜你喜欢
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2018-12-19
      • 2011-10-27
      • 2018-05-16
      • 2017-05-12
      相关资源
      最近更新 更多