从生产构建中剥离的 React 样式组件 [英] React Styled Components stripped out from production build

查看:69
本文介绍了从生产构建中剥离的 React 样式组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用样式化组件作为我的 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 元素(样式不'不适用于元素).相反,您需要为 inputbutton 创建额外的程式化组件.

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 和class methods 控制.最重要的是,将您的 form 变成一个 受控组件,将 getWeather 方法修正为:不允许空提交,如果 AJAX 调用失败,它会 catch 错误(而不是破坏您的应用),并在成功提交后重置表单输入.
  • 添加了 prop-types 以确保 props 在声明中保持一致(字符串仍然是字符串,数字仍然是数字,依此类推).
  • Moved any styled components to the components folder for modularity
  • Any sort of global stylization was put into a styles folder
  • Moved assets to images and imported them into the styled component that needed them (eliminating the need to use require('../path/to/image'))
  • Simplified the App.js file. Children are controlled by state and class methods. Most importantly, turned your form into a controlled component, fixed the getWeather method to: Not allow an empty submission, if the AJAX calls fails, it'll catch the error (instead of breaking your app), and reset the form inputs on successful submission.
  • Added prop-types to ensure props were consistent in declaration (string remains a string, number remains a number, and so on).

这篇关于从生产构建中剥离的 React 样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆