如何在reactjs中删除导入的css

问题描述 投票:3回答:1

我使用以下代码导入css

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

如何在组件未使用时从反应中删除导入的css。当我回到上一个屏幕时,这个css会在那里应用。任何的想法 ?

UPDATE :: 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")
   ])
 ],
 };
javascript css reactjs import redux
1个回答
0
投票

首先,AFAIK,你不应该在componentWillMount中调用任何导入。这意味着每次要安装新组件时,都会反复加载此css。相反,它必须放在模块的开头。

避免不必要的css导入的方法是避免不必要的组件导入。因此,如果您的组件未在任何地方调用,则不会加载此css。

对于路由,我认为你需要进行一些代码拆分,但我不确定它是直接的还是正确的方法。

Link 1 Link 2

© www.soinside.com 2019 - 2024. All rights reserved.