首页 > 解决方案 > Stencil - 全局 CSS 没有集成到 React

问题描述

按照此处的 Stencil 文档,我在 src/global/variables.css 中创建了一些全局 CSS 变量。这是目前该目录中唯一的 CSS 文件。

我正在尝试在 React 中使用我的组件。当在 Stencil 项目中开发以及将 www/build/ 目录复制到 vanilla JS/HTML 项目时,组件/CSS 变量工作得非常好,但当我在 React 中导入和使用它们时却不行。组件工作并清晰呈现,但 global/ 目录中的 CSS 显然没有呈现。

在组件 CSS 文件中定义和使用 CSS 变量有效,但不适用于全局 CSS 文件。

我猜我的构建方式有问题,但我不知道我做错了什么。

我已经尝试更新到最新的 Stencil 版本并更新了所有其他包。

我也尝试添加:

styleUrls: [
    "local-component.css",
    "../../global/variables.css"
]

但这也没有用。

它仅在添加引用 UNPKG CDN 的 CSS 标记时才有效,如下所示:

<link rel="stylesheet" type="text/css" href="https://unpkg.com/uwe-ds-poc@0.0.9/dist/poc/poc.css"/>

但如果我尝试执行这样的本地路径,则会失败:

<link rel="stylesheet" type="text/css" href="../node_modules/uwe-ds-poc/dist/poc/poc.css"/>.

这是唯一/最好的方法还是我缺少什么?

这是我的 stencil.config.ts:

import { Config } from '@stencil/core';

export const config: Config = {
  namespace: 'poc',
  globalStyle: 'src/global/variables.css',
  outputTargets: [
    {
      type: 'dist',
      esmLoaderPath: 'loader'
    },
    {
      type: 'docs-readme'
    },
    {
      type: 'www',
      serviceWorker: null // disable service workers
    }
  ],
  copy: [
    { src: 'global' }
  ]
};

copy 属性将全局目录复制到 dist/collection/。这也不能解决问题。

这是我的 package.json:

{
  "name": "uwe-ds-poc",
  "version": "0.0.9",
  "description": "Stencil Component Starter",
  "main": "dist/index.js",
  "module": "dist/index.mjs",
  "es2015": "dist/esm/index.mjs",
  "es2017": "dist/esm/index.mjs",
  "types": "dist/types/index.d.ts",
  "collection": "dist/collection/collection-manifest.json",
  "collection:main": "dist/collection/index.js",
  "unpkg": "dist/poc/poc.js",
  "files": [
    "dist/",
    "loader/"
  ],
  "scripts": {
    "build": "stencil build --docs",
    "start": "stencil build --dev --watch --serve",
    "test": "stencil test --spec --e2e",
    "test.watch": "stencil test --spec --e2e --watchAll",
    "generate": "stencil generate"
  },
  "devDependencies": {
    "@stencil/core": "^1.8.1",
    "@types/jest": "^24.0.23",
    "@types/puppeteer": "1.20.2",
    "jest": "^24.9.0",
    "jest-cli": "24.8.0",
    "puppeteer": "1.20.0"
  },
  "license": "MIT"
}

整个 Stencil 项目都在这里

提前致谢。

标签: javascriptcssreactjsstenciljsstencil-component

解决方案


导入 unpkg cdn 是一个有效的选项。

但是,如果您使用的是捆绑程序(webpack、parcel 等),您可以使用类似import 'my-package/dist/path/to/global.css'.


推荐阅读