React-table css 未加载是 webpack 的问题吗? [英] React-table css not loading is webpack the issue?

查看:20
本文介绍了React-table css 未加载是 webpack 的问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 webpack 不太熟悉,但我认为它会引起问题.我正在使用 react 样板并安装了 react-table 作为依赖项.添加了代码,所有内容都在显示,但 css 没有.如果有人能指出我正确的方向,我将不胜感激!

I'm not too familiar with webpack but I think it's causing a problem. I'm using a react boilerplate and have installed react-table as a dependancy. Added the code and all is displaying but the css is not. If anyone can point me in the right direction I would be very grateful!

这是我如何将它添加到我的组件

This is how I added it to my component

import ReactTable from 'react-table';
import 'react-table/react-table.css';

在我的渲染中,我正在执行以下操作

In my render, I'm doing the following

  <ReactTable
    noDataText="No data available"
    data={this.state.rows}
    columns={[
      {
        columns: this.state.columns
      }
    ]}
  getTdProps={(state, rowInfo, column, instance) => ({
    onMouseEnter: e =>
      console.log('Cell - onMouseEnter', {
        state,
        rowInfo,
        column,
        instance,
        event: e,
      }),
  })}
    defaultPageSize={10}
  className="-striped -highlight"
  />

这就是我的 webpack.config.js 的样子

This is what my webpack.config.js looks like

  resolve: {
    // Allow absolute paths in imports, e.g. import Button from 'components/Button'
    // Keep in sync with .flowconfig and .eslintrc
    modules: ['node_modules', 'src'],
  },

  module: {
    // Make missing exports an error instead of warning
    strictExportPresence: true,

    rules: [
      // Rules for JS / JSX
      {
        test: reScript,
        include: [SRC_DIR, resolvePath('tools')],
        loader: 'babel-loader',
        options: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            [
              '@babel/preset-env',
              {
                targets: {
                  browsers: pkg.browserslist,
                },
                forceAllTransforms: !isDebug, // for UglifyJS
                modules: false,
                useBuiltIns: false,
                debug: false,
              },
            ],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            ['@babel/preset-stage-2', { decoratorsLegacy: true }],
            // Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-flow
            '@babel/preset-flow',
            // JSX
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            ['@babel/preset-react', { development: isDebug }],
          ],
          plugins: [
            // Treat React JSX elements as value types and hoist them to the highest scope
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-constant-elements
            ...(isDebug ? [] : ['@babel/transform-react-constant-elements']),
            // Replaces the React.createElement function with one that is more optimized for production
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-inline-elements
            ...(isDebug ? [] : ['@babel/transform-react-inline-elements']),
            // Remove unnecessary React propTypes from the production build
            // https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types
            ...(isDebug ? [] : ['transform-react-remove-prop-types']),
          ],
        },
      },

      // Rules for Style Sheets
      {
        test: reStyle,
        rules: [
          // Convert CSS into JS module
          {
            issuer: { not: [reStyle] },
            use: 'isomorphic-style-loader',
          },

          // Process external/third-party styles
          {
            exclude: SRC_DIR,
            loader: 'css-loader',
            options: {
              sourceMap: isDebug,
              minimize: isDebug ? false : minimizeCssOptions,
            },
          },

          // Process internal/project styles (from src folder)
          {
            include: SRC_DIR,
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug
                ? '[name]-[local]-[hash:base64:5]'
                : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/
              minimize: isDebug ? false : minimizeCssOptions,
            },
          },

          // Apply PostCSS plugins including autoprefixer
          // {
          //   exclude: ['react-table/react-table.css'],
          //   loader: 'postcss-loader',
          //   options: {
          //     config: {
          //       path: './tools/postcss.config.js',
          //     },
          //   },
          // },

          // Compile Less to CSS
          // https://github.com/webpack-contrib/less-loader
          // Install dependencies before uncommenting: yarn add --dev less-loader less
          // {
          //   test: /\.less$/,
          //   loader: 'less-loader',
          // },

          // Compile Sass to CSS
          // https://github.com/webpack-contrib/sass-loader
          // Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
          // {
          //   test: /\.(scss|sass)$/,
          //   loader: 'sass-loader',
          // },
        ],
      },

      // Rules for images
      {
        test: reImage,
        oneOf: [
          // Inline lightweight images into CSS
          {
            issuer: reStyle,
            oneOf: [
              // Inline lightweight SVGs as UTF-8 encoded DataUrl string
              {
                test: /\.svg$/,
                loader: 'svg-url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },

              // Inline lightweight images as Base64 encoded DataUrl string
              {
                loader: 'url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },
            ],
          },

          // Or return public URL to image resource
          {
            loader: 'file-loader',
            options: {
              name: staticAssetName,
            },
          },
        ],
      },

      // Convert plain text into JS module
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },

      // Convert Markdown into HTML
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },

      // Return public URL for all assets unless explicitly excluded
      // DO NOT FORGET to update `exclude` list when you adding a new loader
      //
      {
        exclude: [reScript, reStyle, reImage, /\.json$/, /\.txt$/, /\.md$/],
        loader: 'file-loader',
        options: {
          name: staticAssetName,
        },
      },

      // Exclude dev modules from production build
      ...(isDebug
        ? []
        : [
            {
              test: resolvePath(
                'node_modules/react-deep-force-update/lib/index.js',
              ),
              loader: 'null-loader',
            },
          ]),
    ],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  // Specify what bundle information gets displayed
  // https://webpack.js.org/configuration/stats/
  stats: {
    cached: isVerbose,
    cachedAssets: isVerbose,
    chunks: isVerbose,
    chunkModules: isVerbose,
    colors: true,
    hash: isVerbose,
    modules: isVerbose,
    reasons: isDebug,
    timings: true,
    version: isVerbose,
  },

  // Choose a developer tool to enhance debugging
  // https://webpack.js.org/configuration/devtool/#devtool
  devtool: isDebug ? 'cheap-module-inline-source-map' : 'source-map',
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['@babel/polyfill', './src/client.js'],
    client_config: './src/appSettings.config'
  },

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': true,
      __DEV__: isDebug,
      C_API: JSON.stringify(C_API),
    }),

    // Emit a file with assets paths
    // https://github.com/webdeveric/webpack-assets-manifest#options
    new WebpackAssetsManifest({
      output: `${BUILD_DIR}/asset-manifest.json`,
      publicPath: true,
      writeToDisk: true,
      customize: ({ key, value }) => {
        // You can prevent adding items to the manifest by returning false.
        if (key.toLowerCase().endsWith('.map')) return false;
        return { key, value };
      },
      done: (manifest, stats) => {
        // Write chunk-manifest.json.json
        const chunkFileName = `${BUILD_DIR}/chunk-manifest.json`;
        try {
          const fileFilter = file => !file.endsWith('.map');
          const addPath = file => manifest.getPublicPath(file);
          const chunkFiles = stats.compilation.chunkGroups.reduce((acc, c) => {
            acc[c.name] = [
              ...(acc[c.name] || []),
              ...c.chunks.reduce(
                (files, cc) => [
                  ...files,
                  ...cc.files.filter(fileFilter).map(addPath),
                ],
                [],
              ),
            ];
            return acc;
          }, Object.create(null));
          fs.writeFileSync(chunkFileName, JSON.stringify(chunkFiles, null, 2));
        } catch (err) {
          console.error(`ERROR: Cannot write ${chunkFileName}: `, err);
          if (!isDebug) process.exit(1);
        }
      },
    }),

    ...(isDebug
      ? []
      : [
          // Webpack Bundle Analyzer
          // https://github.com/th0r/webpack-bundle-analyzer
          ...(isAnalyze ? [new BundleAnalyzerPlugin()] : []),
        ]),
  ],

  // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
        },
      },
    },
  },

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.js.org/configuration/node/
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['@babel/polyfill', './src/server.js'],
  },

  output: {
    ...config.output,
    path: BUILD_DIR,
    filename: '[name].js',
    chunkFilename: 'chunks/[name].js',
    libraryTarget: 'commonjs2',
  },

  // Webpack mutates resolve object, so clone it to avoid issues
  // https://github.com/webpack/webpack/issues/4817
  resolve: {
    ...config.resolve,
  },

  module: {
    ...config.module,

    rules: overrideRules(config.module.rules, rule => {
      // Override babel-preset-env configuration for Node.js
      if (rule.loader === 'babel-loader') {
        return {
          ...rule,
          options: {
            ...rule.options,
            presets: rule.options.presets.map(
              preset =>
                preset[0] !== '@babel/preset-env'
                  ? preset
                  : [
                      '@babel/preset-env',
                      {
                        targets: {
                          node: pkg.engines.node.match(/(\d+\.?)+/)[0],
                        },
                        modules: false,
                        useBuiltIns: false,
                        debug: false,
                      },
                    ],
            ),
          },
        };
      }

      // Override paths to static assets
      if (
        rule.loader === 'file-loader' ||
        rule.loader === 'url-loader' ||
        rule.loader === 'svg-url-loader'
      ) {
        return {
          ...rule,
          options: {
            ...rule.options,
            emitFile: false,
          },
        };
      }

      return rule;
    }),
  },

  externals: [
    './chunk-manifest.json',
    './asset-manifest.json',
    nodeExternals({
      whitelist: [reStyle, reImage],
    }),
  ],

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.js.org/plugins/banner-plugin/
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  // Do not replace node globals with polyfills
  // https://webpack.js.org/configuration/node/
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
};

export default [clientConfig, serverConfig];

更新修改后的 webpack.config

UPDATE MODIFIED webpack.config

 // Rules for Style Sheets
  {
    test: reStyle,
    rules: [
      // Convert CSS into JS module
      {
        issuer: { not: [reStyle] },
        use: 'isomorphic-style-loader',
      },

      // Process external/third-party styles
      {
        exclude: SRC_DIR,
        loader: 'css-loader',
        options: {
          sourceMap: isDebug,
          minimize: isDebug ? false : minimizeCssOptions,
        },
      },

      // Process internal/project styles (from src folder)
      {
        include: SRC_DIR,
        loader: 'css-loader',
        options: {
          // CSS Loader https://github.com/webpack/css-loader
          importLoaders: 1,
          sourceMap: isDebug,
          // CSS Modules https://github.com/css-modules/css-modules
          modules: true,
          localIdentName: isDebug
            ? '[name]-[local]-[hash:base64:5]'
            : '[hash:base64:5]',
          // CSS Nano http://cssnano.co/
          minimize: isDebug ? false : minimizeCssOptions,
        },
      },
      {
         loader: 'style-loader' 
      },

推荐答案

经过几天的反复试验,终于弄明白了.HTH别人!

Finally figured it out after days and days of trial and error. HTH someone else!

在你的组件中确保您正在导入从 'isomorphic-style-loader/lib/withStyles' 导入 withStyles;

In your component make sure you are importing import withStyles from 'isomorphic-style-loader/lib/withStyles';

然后导入你的模块 css 并给它一个别名.从'react-datepicker/dist/react-datepicker.css'导入rdatescss;

Then import your module css and give it an alias. import rdatescss from 'react-datepicker/dist/react-datepicker.css';

使用以下内容结束您的组件导出默认 withStyles(rdatescss)(NAMEOFCOMPONENT);

End your component with the following export default withStyles(rdatescss)(NAMEOFCOMPONENT);

要添加多种样式,请使用导出默认 withStyles(rdatescss, other_style_alias)(NAMEOFCOMPONENT);

To add multiple styles use the export default withStyles(rdatescss, other_style_alias)(NAMEOFCOMPONENT);

这是我的 webpack (4.12.0) 中的规则

Here are the rules in my webpack (4.12.0)

  {
    test: reStyle,
    rules: [
      // Convert CSS into JS module
      {
        issuer: { not: [reStyle] },
        use: 'isomorphic-style-loader',
      },


      // Process internal/project styles (from src folder)
      {
        include: SRC_DIR,
        loader: 'css-loader',
        options: {
          // CSS Loader https://github.com/webpack/css-loader
          importLoaders: 1,
          sourceMap: isDebug,
          // CSS Modules https://github.com/css-modules/css-modules
          modules: true,
          localIdentName: isDebug
            ? '[name]-[local]-[hash:base64:5]'
            : '[hash:base64:5]',
          // CSS Nano http://cssnano.co/
          minimize: isDebug ? false : minimizeCssOptions,
        },
      },

      // Apply PostCSS plugins including autoprefixer
      {
        loader: 'postcss-loader',
        options: {
          config: {
            path: './tools/postcss.config.js',
          },
        },
      }
      //{ //this rule will only be used for any vendors
      //  test: /\.css$/,
      //  loaders: ['style-loader', 'css-loader'],
      //  include: [/node_modules/]
      //},
      // Compile Less to CSS
      // https://github.com/webpack-contrib/less-loader
      // Install dependencies before uncommenting: yarn add --dev less-loader less
      // {
      //   test: /\.less$/,
      //   loader: 'less-loader',
      // },

      // Compile Sass to CSS
      // https://github.com/webpack-contrib/sass-loader
      // Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
      // {
      //   test: /\.(scss|sass)$/,
      //   loader: 'sass-loader',
      // },
    ],
  },

这篇关于React-table css 未加载是 webpack 的问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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