【问题标题】:Import external javascript in React component在 React 组件中导入外部 javascript
【发布时间】:2022-09-22 21:10:22
【问题描述】:

我有一个 Javascript 模块,如下所示:

export function test() {
  return \"Hello\";
}

我需要在 React 中导入这个脚本。

这是我尝试过的:

  1. 定义了一个 useScript 方法:
    const useScript = ({ onLoad } : { onLoad: any }) => {
      useEffect(() => {
        const script = document.createElement(\'script\');
        script.type = \"module\";
        script.src = \"path/to/test.js\";
        script.onload = onLoad
        document.body.appendChild(script);
        return () => {
          document.body.removeChild(script);
        }
      }, [onLoad]);
    };
    
    1. 使用它在 React 组件中加载脚本:
    const getTest = () => {
        window[\"test\"]();
      }
    
    useScript({
      onLoad: getTest
    });
    

    这给了我错误:

    window.test is not a function
    

    请注意,如果我从 JS 文件中删除 export 则它可以工作。但是,我需要 export 并且不确定为什么添加导出会破坏它。 有什么线索吗?

    标签: javascript reactjs webpack module es6-modules


    【解决方案1】:

    export 将您的文件转换为一个模块,该模块有自己的范围,而不是添加到window 对象。如果您需要按需文件,请考虑使用import()

    import() 调用,通常称为动态 import,是一个类似函数的表达式,允许将 ECMAScript 模块异步动态加载到潜在的非模块环境中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多