【问题标题】:styled-jsx works inline but not as modulestyled-jsx 内联工作,但不作为模块
【发布时间】:2022-01-25 03:38:55
【问题描述】:

我已将 styled-jsx 添加到我的 Preact(使用此 TS template 设置)项目中,并且可以通过 <style> 标记内联样式,没有任何问题,例如:

    <div>
      <h1>Hello{name && `, ${name}`}!</h1>
      <form onSubmit={handleNameSubmit}>
        <input type="text" value={input} onInput={handleInput} />
        <button type="submit" className="test">
          Update {input && `as ${input}`}
        </button>
      </form>
      <style jsx>
        {`
          h1 {
            color: red;
          }

          .test {
            color: blue;
          }
        `}
      </style>
    </div>

但是,如果我在关注 their instructions 时将该样式提取到单独的 css 变量中(在同一文件中或外部),则会收到以下错误:

if you are getting this error it means that your `css` tagged template literals were not transpiled.

SOGithub 上有一些答案/解决方案,但它们都涉及更改 webpack 配置——而且我没有 webpack 配置。看起来没有一个开箱即用的preact-cli。我已按照建议将 babel 规则添加到我的babelrc

{
  "presets": ["preact-cli/babel"],
  "plugins": [["styled-jsx/babel", { "optimizeForSpeed": true }]]
}

但是,我没有安装任何额外的 macros 或 babel 插件,因为那不在 styled-jsx 自述文件的原始说明中。

【问题讨论】:

    标签: webpack babeljs preact css-in-js styled-jsx


    【解决方案1】:

    目前 Preact-CLI 不支持使用 .babelrc,尽管这是由于我还没有找到一个奇怪的错误造成的。对此感到抱歉。

    但是,您仍然可以通过 preact.config.jsthe docs for which can be found here 来编辑 Webpack 配置。在您的情况下,您需要的是以下内容:

    preact.config.js

    export default (config, env, helpers) => {
        const { rule } = helpers.getLoadersByName(config, 'babel')[0];
        const babelConfig = rule.options;
    
        babelConfig.plugins.push(['styled-jsx/babel', { 'optimizeForSpeed': true }]);
    }
    

    如果这能解决您的问题,请告诉我。

    【讨论】:

    • 这行得通!谢谢。不过我有点困惑,因为 preact cli 文档特别提到了 babelrc,而 typescript 模板包括一个。那么为什么不支持 babelrc 呢?还是 styled-jsx 不支持?
    • 因此应该支持它,因此应该支持文档,但我不相信它目前正在按预期工作。这是上周才向我提出的,我不确定它被破坏了多长时间。需要再调查一下。具有一个的 TS 模板是我需要删除的遗物,并且永远不会在它所在的位置被拾取。我们只会在根文件夹中自动检测到.babelrc。很抱歉,我会把它放在我需要解决的问题列表的前面。感谢您提醒我有关 TS 模板的信息!
    • 在进行一些挖掘后,这实际上是按预期工作的。文档确实说,如果您想修改配置,.babelrc 不是这样做的方法。使用您的preact.config.js。无论出于何种原因,Babel 无法正确解析预设(我无法辨别这是为什么,这让我感到困惑),所以使用 .babelrc 仅适用于您想要覆盖默认配置的情况。至于为什么模板中存在.babelrc,本来是为了Jest。但是jest-preset-preact 库现在可以处理这个问题。
    最近更新 更多