[英]Dynamic Imports - NextJS
I have a simple function which loads a script:我有一个加载脚本的简单函数:
const creditCardScript = (
onReadyCB,
onErrorCB,
) => {
let script = document.createElement("script");
script.type = "text/javascript";
script.src = process.CREDIT_CARD_SCRIPT;
document.head.appendChild(script);
script.onload = function() {
...
};
};
export default creditCardScript;
Before I migrated to NextJS, I was importing the script with: import creditCardScript from "./creditCardScript"
.在迁移到 NextJS 之前,我使用以下命令
import creditCardScript from "./creditCardScript"
脚本: import creditCardScript from "./creditCardScript"
。
Sine NextJS renders components server side in Node, care needs to be taken to ensure that any code with a reference to window
(which is browser specific), doesn't get called until componentDidMount
. Sine NextJS 在 Node 中呈现组件服务器端,需要注意确保任何引用
window
(特定于浏览器)的代码在componentDidMount
之前不会被调用。
NextJS solves this issue by providing dynamic imports (a wrapper around react-loadable ) which: NextJS 通过提供动态导入(围绕react-loadable的包装器)解决了这个问题:
ssr: false
).ssr: false
)。 I went ahead and implemented dynamic imports:我继续实施动态导入:
const creditCardScript = dynamic(import("./creditCardScript"), { ssr: false });
In componentDidMount
:在
componentDidMount
:
componentDidMount = () => {
creditCardScript(
this.onReadyCB,
this.onErrorCB
);
};
But I'm getting this: Uncaught TypeError: Cannot call a class as a function
但我得到了这个:
Uncaught TypeError: Cannot call a class as a function
I've tried to convert the function to a class and use the constructor to pass in args
, but my code now fails silently.我试图将函数转换为类并使用构造函数传入
args
,但我的代码现在无声无息地失败了。
Export default only work with import from
statement, you can try导出默认仅适用于
import from
语句,您可以尝试
export creditCardScript;
And on import, u can use like this在导入时,你可以这样使用
const {creditCardScript} = dynamic(import("./creditCardScript"), { ssr: false });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.