NextJS中require关键字用法及Stripe代码等价写法问询
NextJS中Stripe require写法的等价替代方案
核心等价ES模块写法
const stripe = require('stripe')('some_key');的直接等价ES模块写法如下,适用于NextJS的API路由(服务器端环境):
import Stripe from 'stripe'; const stripe = new Stripe('some_key');
也可以简化成一行调用(Stripe导出的是可调用函数,两种写法效果一致):
import Stripe from 'stripe'; const stripe = Stripe('some_key');
把你原来的代码改成ES模块版本(适配NextJS Pages Router的API路由规范):
import Stripe from 'stripe'; const stripe = new Stripe('some_key'); export default async function handler(req, res) { if (req.method === 'POST') { // 验证用户身份逻辑 const session = await stripe.billingPortal.sessions.create({ customer: '{{CUSTOMER_ID}}', return_url: 'https://example.com/account', }); res.redirect(session.url); } else { res.setHeader('Allow', ['POST']); res.status(405).end(`Method ${req.method} Not Allowed`); } }
关于你用dynamic导入的错误
dynamic导入是NextJS用来延迟加载客户端组件的工具,而Stripe SDK必须在服务器端使用(不能把密钥暴露给客户端),所以完全没必要用dynamic导入Stripe实例。
你的错误写法里,dynamic() => import(('stripe')('some_key'))逻辑完全错误:import()只能接收模块路径字符串,不能直接调用模块函数。即使非要动态导入Stripe(完全没必要),正确写法也应该是:
import dynamic from 'next/dynamic'; const getStripe = async () => { const Stripe = (await import('stripe')).default; return new Stripe('some_key'); };
但再次强调:服务器端代码直接用普通import更简单、更安全。
内容的提问来源于stack exchange,提问作者engineer-x
相关产品推荐
相关产品推荐

