NextJS 页面中导入的 Turborepo“外部”包组件中没有样式

问题描述 投票:0回答:1

我有一系列小型原子包,我希望能够独立发布和版本控制,所有这些都在使用 TurboRepo 的 monorepo 中。

当这些组件用作“内部”组件时,没有问题。

但是,当我尝试执行构建时,我发现在我的 Next.js 应用程序 (/apps/web) 中导入并使用这些组件时,我无法将任何 CSS 样式应用于这些组件。

例如,Button 包包含一个名为

Button.tsx
的单个文件和一个名为
Button.module.scss
的文件。

import styles from './Button.module.scss';

const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  (
    {
      className,
      ...restProps
    },
    ref
  ) => {
    return (
      <button className={styles.base} ref={ref} {...restProps}>
         ...
      </button>
    );
  }
);

我的

vite.config.js
看起来像:

import path from 'path';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';

export default defineConfig({
  build: {
    minify: 'terser',
    lib: {
      formats: ['es', 'cjs'],
      entry: path.resolve(__dirname, 'src/index.ts'),
      name: 'Button',
      fileName: format => `button.${format}.js`,
    },
    rollupOptions: {
      // externalize deps that shouldn't be bundled
      // into your library
      external: ['react', 'react-dom'],
      output: {
        exports: 'named',
        sourcemap: true,
        format: 'es',
        preserveModules: true,
      },
      treeshake: true,
    },
  },
  plugins: [
    react(),
    dts({
      copyDtsFiles: true,
      exclude: ['**/node_modules'],
      insertTypesEntry: true,
    }),
  ],
});

package.json:

  "name": "@company/components__button",
  "version": "0.0.1",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/button.es.js",
      "require": "./dist/button.cjs.js"
    }
  },
  "files": ["dist/**"],

Here is a partial view of the output dist files.

然后,我将包导入到我的下一个应用程序(apps/web)中,如下所示:

"@company/components__button": "workspace:*",

现在,我可以导入它,但是**在运行时没有应用样式**!

但是,如果我检查 DOM,我可以在按钮 DOM 节点上看到该类:

<button class="_base_3rp5a_4" type="submit">create an account</button>

检查网络选项卡后,会出现一个获取页面 CSS 的 GET 请求。但是,有效负载仅包含在 Next.js 应用程序级别定义并在同一页面上使用的 CSS,但导入的包中不包含任何样式...

它不应该还包括从我的包中导入的按钮的CSS吗?

Next.js 是否正在努力在运行时协调动态类与其关联的样式。我的做法是否错误?我是否遗漏了配置中的某些内容?

我希望正确应用与导入的包关联的样式。

我遵循了本指南:https://turbo.build/repo/docs/handbook/publishing-packages/bundling

next.js sass vite css-modules turborepo
1个回答
0
投票

由于您通过

esbuild
捆绑 UI 库,因此在
esbuild
目录中将有几个由
dist
生成的文件。

  1. index.js
  2. index.js.map
    (仅当您启用源映射时)
  3. style.css
    (这个很重要)

这里的问题是,您需要在使用上述 UI 库的 Next.js 应用程序中导入

style.css

import '<path to the style.css>';

这就是为什么即使您的 HTML 元素中有 CSS 类(来自 UI 库的

index.js
部分),也不会应用任何样式(因为这些 CSS 类在您的 DOM 中不存在)

© www.soinside.com 2019 - 2024. All rights reserved.