样式化的jsx可以内联工作,但不能作为模块工作



我已经将样式化的jsx添加到我的Preact(使用此TS模板设置(项目中,并且可以通过<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>

但是,如果我按照他们的指示将该样式提取到一个单独的css变量中(在同一文件中或外部(,我会得到以下错误:

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

在SO和Github上有一些答案/解决方案,但它们都涉及到更改webpack配置——而我没有webpack的配置。看起来preact-cli没有现成的。我已经按照建议将babel规则添加到我的babelrc中:

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

然而,我没有从babel安装任何额外的macros或插件,因为这不在样式化的jsx自述文件的原始说明中。

Preact CLI目前不支持使用.babelrc,尽管这是由于一个我尚未找到的奇怪错误造成的。很抱歉。

然而,您仍然有一种编辑Webpack配置的方法,那就是使用preact.config.js,其文档可以在这里找到。在您的情况下,您想要的是以下内容:

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 }]);
}

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

相关内容

最新更新