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

React项目中从外部文件导入JavaScript函数失败求助

React组件导入失败问题排查

我参考Stack Overflow相关问题及网上同类代码后仍未解决。尝试将sample.js中的JavaScript函数导入至主文件index.js中,但无法正常运行,请问哪里操作有误?提前感谢帮助!

相关代码

sample.js

// sample.js
export default function SampleFunc() {
    return (
        <h1>
            Some Text
        </h1>
    )
}

index.js

import SampleFunc from "./sample.js"

// function SampleFunc() {
//  return (
//      <h1>
//          Some Text
//      </h1>
//  )
// }

function My_App() {
    return (
        <SampleFunc/>
    )
}

ReactDOM.createRoot( document.getElementById("root") ).render( < My_App /> )

index.html

<html>

    <head>

        <link rel="stylesheet" href="index.css">

        <!-- React 18 + Babel 6 -->
        <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js">
        </script>
        <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js">
        </script>
        <script src="https://unpkg.com/babel-standalone@6/babel.min.js">
        </script>

    </head>

    <body>

        <div id="root"></div>
        
        <!-- JavaScript Code -->
        <script src="index.js" type="text/babel"></script>

    </body>

</html>

问题原因及解决办法

核心问题是babel-standalone在浏览器直接运行的场景下,默认不支持ES模块的import/export语法,浏览器无法识别这种模块导入方式,导致组件无法被正确加载。

快速解决方法

放弃模块导入,直接将sample.js作为全局脚本引入:

  1. 在index.html中,index.js的脚本标签前添加sample.js的引入:
<script src="sample.js" type="text/babel"></script>
<script src="index.js" type="text/babel"></script>
  1. 修改sample.js,去掉export default,直接定义全局函数:
// sample.js
function SampleFunc() {
    return (
        <h1>
            Some Text
        </h1>
    )
}
  1. 删除index.js中的import SampleFunc from "./sample.js"语句,直接使用SampleFunc组件即可。

另一种模块方式(稍复杂)

如果坚持使用ES模块,需要修改脚本的type为module,同时配置babel-standalone处理模块:

  1. 将index.html中的脚本标签改为:
<script type="module">
    import React from 'https://unpkg.com/react@18/umd/react.development.js';
    import ReactDOM from 'https://unpkg.com/react-dom@18/umd/react-dom.development.js';
    import SampleFunc from './sample.js';

    function My_App() {
        return React.createElement(SampleFunc);
    }

    ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(My_App));
</script>

不过这种方式需要处理JSX的编译,可能需要额外配置,不如第一种方法直接高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:15:25