从生产构建中剥离的 React 样式组件 [英] React Styled Components stripped out from production build
问题描述
我使用样式化组件作为我的 React 应用程序的 CSS 替代品.在开发中一切正常(第一个屏幕截图),但是当我运行生产构建(npm build
)时,样式标签中的样式被删除(第二个屏幕截图).因此,生产版本中没有样式.
I use Styled Components as CSS alternative for my React App. In development everything works fine (first screenshot), but when I run a production build (npm build
), styles within style tags are stripped out (second screenshot). As a result, there're no styles in the production build.
这是生产版本:http://projects.loratadin.com.s3-website-us-east-1.amazonaws.com/weather-app/
这是源代码:https://github.com/Loratadin/weather-app一个>
推荐答案
我能够复制您的问题,看起来当应用程序在生产中时,它无法选择样式组件中的 html 元素(样式不'不适用于元素).相反,您需要为 input
和 button
创建额外的程式化组件.
I was able to replicate your issue and it looks like when the application is in production, it can't select html elements within a styled component (the styles don't apply to the element). Instead, you'll need to create additional stylized components for input
and button
.
工作示例:https://github.com/mattcarlotta/Weather-应用
我重构了您的应用程序以简化其结构.请阅读 README
以获取有关如何在开发和生产中运行它的说明(请勿将上述存储库用于生产,因为非常没有必要拥有 express
后端 -- 我这样做只是为了让您可以运行本地生产版本).
I refactored your application to simplify its structure. Please read the README
for instructions on how to run it in development and in production (DO NOT use the above repository for production, as it's highly unnecessary to have an express
backend -- I only did this so that you can run a local production build).
我改变了什么:
- 将任何
styled
组件移动到components
文件夹以实现模块化 - 任何类型的全局样式都被放入一个
styles
文件夹 - 将
assets
移动到images
并将它们导入到需要它们的styled
组件中(消除了使用require('../path/to/image')
) - 简化了
App.js
文件.孩子由state
和classmethods
控制.最重要的是,将您的form
变成一个 受控组件,将getWeather
方法修正为:不允许空提交,如果AJAX
调用失败,它会catch
错误(而不是破坏您的应用),并在成功提交后重置表单输入. - 添加了
prop-types
以确保props
在声明中保持一致(字符串仍然是字符串,数字仍然是数字,依此类推).
- Moved any
styled
components to thecomponents
folder for modularity - Any sort of global stylization was put into a
styles
folder - Moved
assets
toimages
and imported them into thestyled
component that needed them (eliminating the need to userequire('../path/to/image')
) - Simplified the
App.js
file. Children are controlled bystate
and classmethods
. Most importantly, turned yourform
into a controlled component, fixed thegetWeather
method to: Not allow an empty submission, if theAJAX
calls fails, it'llcatch
the error (instead of breaking your app), and reset the form inputs on successful submission. - Added
prop-types
to ensureprops
were consistent in declaration (string remains a string, number remains a number, and so on).
这篇关于从生产构建中剥离的 React 样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!