没有服务器端渲染功能的导入模块

时间:2021-01-07 13:00:00

标签: next.js surveyjs

我对 Next.js 有问题。当我尝试导入节点模块时, 该模块使用 window 对象并且 Next.js 抛出错误:window is not defined

模块是这样导入的:

import * as widgets from 'survey-widgets';

widgets.autocomplete(Survey);

我想 Next.js 动态导入在我的情况下不起作用。有什么办法吗?

2 个答案:

答案 0 :(得分:1)

尝试将所有使用 router.post('/', async (req, res) => { //check for validation errors const { error } = validate(req.body); if (error) return res.status(400).send(error.details[0].message); let user = await User.findOne({ email: req.body.email }); if (!user) return res.status(404).send("Invalid email or password"); const validPassword = await bcrypt.compare(req.body.password, user.password); if (!validPassword) return res.status(400).send("Invalid email or password"); res.json({ token: user.generateAuthToken(), status: "User is logged in" }) }); const validate = (req) => { const schema = Joi.object({ email: Joi.string().min(6).max(255).email().required(), password: Joi.string().min(6).max(255).required(), }); return schema.validate(req); }; module.exports = router; 或任何其他仅限浏览器的 window 的代码推迟到 api 中,因为 useEffect 中的代码仅在浏览器。

如果您不能这样做,那么制作一个 useEffect 模块,您将使用它来导入 intermediary 并重新导出您需要的内容。所以最后,您动态导入该 survey-widgets 模块。

intermediary

答案 1 :(得分:0)

有关任何人寻找此溶液中,我解决它NextJs Dynamic imports with no SSR

我做了什么,而不是使用动态导入这样的导入我的顶级组件:

const MyComponent= dynamic(
() => import('../components/hello3'),
  { ssr: false }
)

因此,{1} {}部件将不再在服务器侧渲染中使用,而是它将呈现在客户端侧上。

然后,只需使用它是这样的:

hello3