You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Vite + React打包外部JS脚本?生产环境加载问题求助

问题描述

基于Vite的React应用集成外部JS脚本(路径/vendors/faceio/fio.js)时,开发环境运行正常,但生产打包后脚本无法正常工作:

  • 初始报错提示需添加type="module",添加后该错误消失
  • 调用脚本时仍提示变量未定义

附index.html代码:

<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>
解决方法
  • 确保静态资源被正确打包
    将vendors文件夹移动到Vite项目的public目录下(Vite会把public目录下的文件原封不动复制到生产打包后的dist根目录),这样生产环境能正确访问/vendors/faceio/fio.js路径。

  • 控制脚本加载顺序
    由于type="module"脚本是异步加载的,可能React应用代码先执行导致脚本未初始化。可以在React入口文件中动态加载脚本,确保脚本加载完成后再渲染应用:

    // src/index.jsx
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    
    async function loadFaceIOScript() {
      return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = '/vendors/faceio/fio.js';
        // 根据脚本实际类型调整是否加type="module"
        // script.type = 'module';
        script.onload = resolve;
        script.onerror = reject;
        document.body.appendChild(script);
      });
    }
    
    loadFaceIOScript().then(() => {
      const root = ReactDOM.createRoot(document.getElementById('root'));
      root.render(
        <React.StrictMode>
          <App />
        </React.StrictMode>
      );
    }).catch(err => {
      console.error('加载faceIO脚本失败:', err);
      // 可添加降级逻辑
    });
    
  • 检查脚本全局变量暴露
    如果脚本以type="module"加载时未将核心变量挂载到window,需要修改脚本(如果有权限),在脚本末尾添加全局挂载代码,例如:

    // fio.js末尾添加
    window.faceIO = faceIO; // 替换为脚本实际导出的变量名
    

    若无法修改脚本,尝试移除type="module"属性,同时确保Vite不会对该脚本进行模块解析(放在public目录下即可避免)。

  • 校验Vite部署路径配置
    如果生产环境部署在子路径下,需在vite.config.js中配置正确的base路径,确保资源引用地址正确:

    // vite.config.js
    export default {
      base: './', // 或你的实际部署子路径,例如'/my-app/'
    }
    

内容的提问来源于stack exchange,提问作者Hector Toro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:18:24