React - 全局使用带有css模块的Bootstrap

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

很新的反应和所有的东西,所以我需要一些帮助。我最近在我的项目中添加了https://github.com/gajus/babel-plugin-react-css-modules插件。经过一些麻烦我得到了它的工作,所以我现在可以使用我的本地css文件与我的组件。到现在为止还挺好。

不是我想为整个应用程序添加bootstrap。在我添加css-modules插件之前它工作了...

这是我的代码的相关部分(我猜...如果我错过了一些让我知道的话):

index.js(我的应用程序的入口点):

import 'bootstrap/dist/css/bootstrap.min.css';
...

.babelrc:

{
    "presets": [
        "react"
    ],
    "plugins": [
      ["react-css-modules", {
        "exclude": "node_modules"
      }]
    ]
}

webpack.config.js:

/* webpack.config.js */

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  devtool: 'eval',

  entry: [
    path.resolve('src/index.js'),
  ],

  output: {
    path: path.resolve('build'),
    filename: 'static/js/bundle.js',
    publicPath: '/',
  },

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: path.resolve('src'),
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]', // Add naming scheme
            },
          },
        ],
      },

    ],
  },

  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve('src/index.html'),
    }),
  ],
}

欢迎任何建议。感谢您的时间。

哦顺便说一下:我还想向我的应用程序介绍scss,我不知道该怎么做(没有做过任何研究,但如果有人知道怎么做,并且可以解释那个,我我真的很感激...不知道它是否有很大变化)。

编辑:我完全忘了添加我的组件:

import React, { Component } from "react";
import { Switch, Route, withRouter } from "react-router-dom";
import './style.css';

export default class HomeContainer extends Component {
  constructor() {

    super();
  }
  /* Test */
  render() {
    return (
      <div styleName="title">
        This woorks (styleprops from "title" are appliced"
        <button type="button" className="btn btn-primary">Primary</button> // Doesn't style the button :(
      </div>
    );
  }
}
reactjs bootstrap-4 css-modules babel-plugin-react-css-modules
1个回答
1
投票

我自己找到了解决方案。要在这里发布,有人可能有一天需要它:

在webpack配置中定义两个规则:

{
              test: /\.css$/,
              exclude: /node_modules/,
              use: [
                'style-loader',
                {
                  loader: 'css-loader',
                  options: {
                    importLoaders: 2,
                    modules: true,
                    localIdentName: '[path]___[name]__[local]___[hash:base64:5]', // Add naming scheme
                  },
                },
              ],
            },

            // Second CSS Loader, including node_modules, allowing to load bootstrap globally over the whole project.
            {
              test: /\.css$/,
              include: /node_modules/,
              use: ['style-loader', 'css-loader']
            }
© www.soinside.com 2019 - 2024. All rights reserved.