webpack 如何在从服务器运行时忽略“仅服务器”

a6b3iqyw  于 5个月前  发布在  Webpack
关注(0)|答案(1)|浏览(60)

我有一个NextJS应用程序,其中包含一个库,我想确保没有在客户端导入。我用import 'server-only'这样做,但我也想将此文件用于本地脚本。然而,当我运行tsx scripts/test.ts时,我得到服务器组件错误。
如何确保库未导入到客户端上?
我的文件夹结构是:

- app
   - ...
 - lib
   - server-only-library.ts
 - scripts
   - local-script.ts

字符串
档案:

# server-only-library.ts
import 'server-only'
...
# local-script.ts
import Library from 'lib/server-only-library'
...

的数据
试验项目:

$ tsx scripts/local-script.ts
/Users/michael/my-app/node_modules/server-only/index.js:1
throw new Error(
      ^
Error: This module cannot be imported from a Client Component module. It should only be used from a Server Component.


我尝试使用webpackMap它,但错误只会在运行时出现在客户端,而不会在构建时出现。

# next.config.js
const nextConfig = {
  // doesn't work :( the import is mapped, but only throws in runtime
  webpack: (config, { isServer, webpack }) => {
    if (!isServer) {
      config.resolve.alias = {
        ...config.resolve.alias,
        '@secret/library': 'next/../server-only',
      }
    }
    return config
  },
}

lokaqttq

lokaqttq1#

最近我在Next.js项目中遇到了类似的挑战,需要将某些导入限制为服务器组件和CLI脚本。为了解决这个问题,我开发了一个名为server-cli-only的NPM包。与server-only不同,允许在Next.js服务器组件和CLI环境中导入。此解决方案应允许您在服务器组件中使用server-only-library.ts,在CLI中使用scripts/local-script.ts,而无需导入错误.
安装程序
首先,通过npm安装软件包:

npm i server-cli-only

字符串

用法

在Next.js服务器组件中,将此导入放在仅服务器库的顶部。ts:

import "server-cli-only";
// Your server-side code follows...


对于像scripts/local-script.ts这样的本地脚本,请将RUNNING_IN_CLI环境变量设置为true。这会向server-cli-only发出信号,以允许导入,而不引发错误:

RUNNING_IN_CLI=true tsx scripts/local-script.ts

更多信息

**编辑:**内部工作(可选)

server-cli-only软件包专为React Server组件和CLI环境量身定制,可防止将其包含在客户端组件中。

***React服务器环境:**在"react-server"环境指定的环境中使用空模块(./empty.js)。有关详细信息,请参阅RFC #227
***CLI环境:**在Node.js上下文中("default"导出环境中的"node"),它会检查RUNNING_IN_CLI是否设置为"true"。如果没有,它会引发错误,指导正确的CLI用法。
***客户端元件环境:**在浏览器环境中("default"汇出环境中的"browser"),./index.js会掷回错误,以永远防止在客户端转译中使用。

此配置尝试与RFC #227的React Server Module Conventions中的指导方针保持一致,但略微扩展了这些指导方针,以便在CLI上启用脚本使用。

相关问题