当Angular应用重新加载时,css文件可能会被浏览器缓存或通过webpack的Tree Shaking功能排除。这可能会导致应用程序在重新加载后失去样式。
解决此问题的一种方法是将CSS文件转换为JavaScript,以便在应用程序重新加载时不会丢失样式。
以下是使用CSS-in-JS库styled-components将CSS文件转换为JavaScript的示例:
npm install styled-components --save
// styles.css
export const styles = {
button: background-color: blue; color: white; padding: 10px; border: none; border-radius: 3px; cursor: pointer;
,
}
import { styles } from './styles.css'; import styled, { css } from 'styled-components';
const Button = styled.button ${css
${styles.button}
}
;