2

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

不是我想为整个应用程序添加引导程序。在我添加 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>
    );
  }
}
4

1 回答 1

6

我自己找到了解决方案。把它贴在这里,也许有一天有人会需要它:

在 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']
}
于 2018-09-12T12:00:48.740 回答