【问题标题】:How to remove imported css in reactjs如何在reactjs中删除导入的css
【发布时间】:2018-06-11 08:32:34
【问题描述】:

我已经使用以下代码导入css

componentWillMount() {
    import('./patient-summary.css');
}

如何在组件不使用时从 react 中删除导入的 css。当我回到前一个屏幕时,这个 css 被应用在那里。有什么想法吗?

更新:: Webpack 配置

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  output: {
  filename: 'bundle.js',
  path: path.resolve(__dirname, 'public/dist')
},
module: {
  rules: [
      {
          test: /\.js?$/, 
          loader: 'babel-loader',
          exclude: /node_modules/
      },
      {
          test: /\.css$/,
          use: [ 'style-loader', 'css-loader' ]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        loader: "file-loader"
      }
      ,
      {
        test: /\.(png|jpeg|jpg|gif|svg)$/,
        loader: "file-loader"
      }
  ]
  },
  devServer: {
  contentBase: path.resolve(__dirname, "public"),
  historyApiFallback: true,
  port: 3000,
  watchOptions: {
    // Delay the rebuild after the first change
    aggregateTimeout: 300,

    // Poll using interval (in ms, accepts boolean too)
    poll: 1000,
  },
  },
  plugins: [
   // Ignore node_modules so CPU usage with poll
   // watching drops significantly.
   new webpack.WatchIgnorePlugin([
      path.join(__dirname, "node_modules")
   ])
 ],
 };

【问题讨论】:

  • 请发布您的 webpack 配置。我认为您将所有 css 文件连接在一起。
  • 为什么要删除导入。它们将在本地缓存中。让它在那里
  • @M.R.Safari 更新
  • 所以...我猜你还没有找到任何解决方案
  • @Denny 我找到了。在组件顶部导入所有 css 文件。 webpack 中的 Atlast 将所有 css 构建到一个文件中。所以它不是单独的css文件。只有一个文件

标签: javascript css reactjs import redux


【解决方案1】:

首先,AFAIK,您不应该在 componentWillMount 中调用任何导入。这意味着每次要挂载新组件时,都会一遍又一遍地加载这个 css。相反,它必须放在模块的开头。

避免不必要的 css 导入的方法是避免不必要的组件导入。因此,如果你的组件没有在任何地方被调用,那么这个 css 将不会被加载。

对于路由,我认为您需要进行一些代码拆分,但我不确定这是否简单或正确的做法。

Link 1 Link 2

【讨论】:

  • 既然要路由,如何避免导入模块
  • 我认为您需要进行一些代码拆分,但我不确定这是否简单或正确的方法。我添加了两个链接。
  • 感谢您的信息。我已经划分了代码。但是,如果一旦添加了 css,如果我回到上一个屏幕,它就会受到以后添加的 css 的影响
【解决方案2】:

我在 React 中找到了一种(某种)合理的方法来做到这一点。简而言之,您可以在包含import './style.css'lazy-load React components 中,当它加载时,您可以捕获导入的StyleSheet,以便稍后切换其StyleSheet.disabled 属性。

这是主要代码,下面有更多解释。这是我的Gist

useDisableImportedStyles.tsx

import { useEffect } from 'react'

// global list of all the StyleSheets that are touched in useDisableImportedStyles
const switchableGlobalStyleSheets: StyleSheet[] = []

// just to clarify what createUseDisableImportedStyles() returns
type useDisableImportedStyles = () => void

export const createUseDisableImportedStyles = (
    immediatelyUnloadStyle: boolean = true
    // if true: immediately unloads the StyleSheet when the component is unmounted
    // if false: waits to unloads the StyleSheet until another instance of useDisableImportedStyles is called.This avoids a flash of unstyled content
): useDisableImportedStyles => {
    let localStyleSheet: StyleSheet
    return () => {
        useEffect(() => {

            // if there are no stylesheets, you did something wrong...
            if (document.styleSheets.length < 1) return

            // set the localStyleSheet if this is the first time this instance of this useEffect is called
            if (localStyleSheet == null) {
                localStyleSheet = document.styleSheets[document.styleSheets.length - 1]
                switchableGlobalStyleSheets.push(localStyleSheet)
            }

            // if we are switching StyleSheets, disable all switchableGlobalStyleSheets
            if (!immediatelyUnloadStyle) {
                switchableGlobalStyleSheets.forEach(styleSheet => styleSheet.disabled = true)
            }

            // enable our StyleSheet!
            localStyleSheet.disabled = false

            // if we are NOT switching StyleSheets, disable this StyleSheet when the component is unmounted
            if (immediatelyUnloadStyle) return () => {
                if (localStyleSheet != null) localStyleSheet.disabled = true
            }

        })
    }
}

警告:这是相当挑剔的。您必须准确设置,否则可能会产生意想不到的后果

条件:

  1. createUseDisableImportedStyles 必须在与目标导入的 css 和要延迟加载的组件相同的 tsx 文件中的全局范围内调用
import React from 'react'
import { createUseDisableImportedStyles } from './useDisableImportedStyles'
import './global-styles.css'
const useDisableImportedStyles = createUseDisableImportedStyles()
export const CssComponent: React.FC<{}> = () => {
    useDisableImportedStyles()
    return null
}
export default CssComponent
  1. 使用此钩子的组件应该延迟加载:
LazyCssComponent = React.lazy(() => import('./cssComponent'))
...
<React.Suspense fallback={<></>}>
    {condition && <LazyCssComponent/>}
</React.Suspense>
  1. 延迟加载的一个例外可能是在单个、正常、非延迟的组件中使用它,以便在第一次渲染时加载样式
  • 注意:InitialCssComponent 不需要实际渲染,只需要导入即可
  • 但是:这只有在全局导入一个 .css 文件时才有效,否则,我不知道会发生什么
import InitialCssComponent  from './initialCssComponent'
LazyCssComponent = React.lazy(() => import('./cssComponent'))
//...
{false && <InitialCssComponent/>}
<React.Suspense fallback={<></>}>
    {condition && <LazyCssComponent/>}
</React.Suspense>

祝你好运!

【讨论】:

  • 像魅力一样工作。我不得不添加一个循环来选择第一个真正的本地样式表,但是一些谷歌字体导入一直爬到 document.styleSheets 的末尾。
猜你喜欢
  • 2018-07-03
  • 2021-01-06
  • 2018-10-14
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2017-11-26
相关资源
最近更新 更多