【问题标题】:Using `dynamic import` to fetch script from another host?使用“动态导入”从另一台主机获取脚本?
【发布时间】:2019-07-13 20:12:22
【问题描述】:

我在 localhost:3001 上运行我的 next.js 应用程序。我想从另一台主机(localhost:3000)获取脚本。我可以做到like this。至于我,更漂亮的是使用dynamic import。但我收到一个错误:'ModuleNotFoundError: Module not found: Error: Can't resolve 'http://localhost:3000/static/fileToFetch.js' in '/Users/{username}/Desktop/test-project/pages';

例子:

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

有可能吗?

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

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

另一种方法是编写一个函数,将脚本标签注入主体并返回一个承诺,类似于:

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.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2015-04-20
    • 2020-10-04
    • 2015-07-01
    相关资源
    最近更新 更多