使用“动态导入”从另一台主机获取脚本?

Using `dynamic import` to fetch script from another host?

我 运行 我的 next.js 应用在 localhost:3001 上。我想从另一台主机 (localhost:3000) 获取脚本。我可以在 '/Users/{username}/Desktop/test-project/pages';

中做到 . As for me, much prettier would be using dynamic import. But I got an error: 'ModuleNotFoundError: Module not found: Error: Can't resolve 'http://localhost:3000/static/fileToFetch.js'

示例:

export const FetchedComponent = dynamic({
  loader: () =>
    import('http://localhost:3000/static/fileToFetch.js'),
  loading: () => 'Loading...',
  ssr: false,
});

可以吗?

使用 webpack 的动态导入仅适用于代码拆分。 您需要找出如何告诉 webpack 不要更改 import() 然后在该域中启用 CORS。

另一种方法是编写一个函数,将脚本标记注入主体和 return 一个承诺,类似这样的东西:

function importExternal(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    script.onload = () => resolve(window['external_global_component']);
    script.onerror = reject;

    document.body.appendChild(script);
  });
}

当您加载文件时,将加载的组件放在全局 (external_global_component) 上。 然后,您将能够将它与 NextJS dynamic.

一起使用
export const FetchedComponent = dynamic({
  loader: () =>
    importExternal('http://localhost:3000/static/fileToFetch.js'),
  loading: () => 'Loading...',
  ssr: false, // <- must be false, because we are using DOM.
});