Article From:https://segmentfault.com/q/1010000013554286
Question:

Environmental Science:
Use the create-react-app generated project.
nodejs: v8.9.3
npm: v5.6.0

Use css-modules and babel-plugin-react-css-modules.

// home.scss
.btn {
  composes: btn from './unit.scss';
}

// unit.scss
@import './../base.scss';
.btn {
  // ...
  color: $border_color;
}

Finally, it is shown in the browser

.btn {
  color: $border_color; // The string of $border_color is displayed directly}

With the class referenced by composes, the use of a variable or @include in the source file is not effective, and the use of the postcss-px2rem plug-in can not be converted to REM.

The class that does not use composes is normal.

Configuration file:
webpack.config.dev.js

'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');

const urlLoader = require.resolve('url-loader')

// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

function resolve(dir) {
  return path.resolve(__dirname, dir)
}

// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
  // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
  // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
  devtool: 'cheap-module-source-map',
  // These are the "entry points" to our application.
  // This means they will be the "root" imports that are included in JS bundle.
  // The first two entry points enable "hot" CSS and auto-refreshes for JS.
  entry: [
    // We ship a few polyfills by default:
    require.resolve('./polyfills'),
    // Include an alternative client for WebpackDevServer. A client's job is to
    // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
    // of CSS changes), or refresh the page (in case of JS changes). When you
    // make a syntax error, this client will display a syntax error overlay.
    // Note: instead of the default WebpackDevServer client, we use a custom one
    // to bring better experience for Create React App users. You can replace
    // the line below with these two lines if you prefer the stock client:
    // require.resolve('webpack-dev-server/client') + '?/',
    // require.resolve('webpack/hot/dev-server'),
    require.resolve('react-dev-utils/webpackHotDevClient'),
    // Finally, this is your app's code:
    paths.appIndexJs,
    'react-hot-loader/patch'
    // We include the app code last so that if there is a runtime error during
    // initialization, it doesn't blow up the WebpackDevServer client, and
    // changing JS code would still trigger a refresh.
  ],
  output: {
    // Add /* filename */ comments to generated require()s in the output.
    pathinfo: true,
    // This does not produce a real file. It's just the virtual path that is
    // served by WebpackDevServer in development. This is the JS bundle
    // containing code from all our entry points, and the Webpack runtime.
    filename: 'static/js/bundle.js',
    // There are also additional JS chunk files if you use code splitting.
    chunkFilename: 'static/js/[name].chunk.js',
    // This is the URL that app is served from. We use "/" in development.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
      '@': path.join(__dirname, '..', 'src')

    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      {
        test: /\.(js|jsx|mjs)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
            },
            loader: require.resolve('eslint-loader'),
          }
        ],
        include: paths.appSrc,
      },
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
        loader: urlLoader,
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      {
        test: [/\.woff2?$/, /\.eot$/, /\.ttf$/, /\.otf$/],
        loader: urlLoader,
        options: {
          limit: 10000,
          name: 'static/fonts/[name].[hash:8].[ext]'
        }
      },
      {
        oneOf: [
          // Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              cacheDirectory: false,
              plugins: [
                [
                  "react-css-modules",
                  {
                    "generateScopedName": "[local]___[hash:base64:5]",
                    "filetypes": {
                      ".scss": {
                        "syntax": "postcss-scss",
                        "plugins": [
                          "postcss-nested"
                        ]
                      }
                    }
                  }
                ],
              ]
            },
          },
          {
            test: /\.scss$/,
            // include: [path.resolve(__dirname, 'src/styles')],
            use: [
              { loader: "style-loader" },
              { loader: "css-loader", options: { modules: true, localIdentName: '[local]___[hash:base64:5]' } },
              {
                loader: require.resolve('postcss-loader'),
                options: {
                  ident: 'postcss',
                  plugins: () => [
                    require('postcss-flexbugs-fixes'),
                    autoprefixer({
                      browsers: [
                        '>1%',
                        'last 4 versions',
                        'Firefox ESR',
                        'not ie < 9', // React doesn't support IE8 anyway
                      ],
                      flexbox: 'no-2009',
                    }),
                    require('postcss-px2rem')({ remUnit: 75 })
                  ],
                },
              },
              { loader: "sass-loader", options: {
                // data: '@import "./src/styles/public/base.scss";',
                includePaths: [
                  path.resolve(__dirname, "./src")
                ]
              } },
            ]
          },
          {
            test: /\.css$/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                  modules: true,   // New support for CSS modulesLocalIdentName:'[local]___[hash:base64:5]'},},/ / {/ / / loader: require.resolve ('postcss-loader'),/ / options: {/ / / / Necessary for external CSS imports to work/ / / / https://github.com/facebookincubator/create-react-app/issues/2677/ / /Ident:'postcss',/ / plugins: () () => [/ / require ('postCss-flexbugs-fixes'),/ / autoprefixer ({/ / browsers: [/ / /'> 1%',/ /'last 4 versions',/ / /'Firefox ESR',/ /'not ie < 9', / / React doesn't support IE8 anywaY/ /],/ / flexbox:'no-2009',/ /}),/ / require ('postcss-px2rem') ({remUnit: 75})/ /],/ /},/ /}]},{Exclude: [/ /. (J)S|jsx|mjs) $/, /\.html$/, /\.json$/],Loader: require.resolve ('file-loader'),Options: {Name:'static/media/[name].[hash:8].[ext]',},},]},/ * * * STOP * * * Are you adding a new loader?/ / / Make sure to add the newLoader (s) before the "file" loader.]},Plugins: [/ / Makes some environment variableS available in index.html./ / The public URL is available as%PUBLIC_URL% in index.html, e.g.:/ / < link rel= "shortcut icon" href= "%PUBLIC_URL%/favicon.ico" >/ / / In development, this wIll be an empty string.New InterpolateHtmlPlugin (env.raw),/ / Generates an `index.html` filE with the < script> injected.New HtmlWebpackPlugin ({Inject: true,Template:Paths.appHtml,}),/ / Add module names to factory functions so they appear in browser inEr./ / new webpack.NamedModulesPlugin (),/ / Makes some environment variables available to thE JS code, for example:/ / if (process.env.NODE_ENV = = ='development') {... {... See `./env.js`..New webpack.DefinePlugin (env.stringified),/ / / / This is necessary to emit hot updates (current)Ly CSS only):New webpack.HotModuleReplacementPlugin (),/ / / Watcher doesn't work well if youMistype casing in a path so we use/ / a plugin that prints an error when you attempt to do to/ / See https://github.com/facebookincubator/create-react-app/issues/240New CaseSensitivePaThsPlugin (),/ / If you require a missing module and then `npm install` it, install`/ / /To restart the development server for Webpack to discover it. This it./ / makes the discoverY automatic so you don't have to restart./ / See https://github.com/facebookincubator/create-reaCt-app/issues/186New WatchMissingNodeModulesPlugin (paths.appNodeModules),/ / Moment.js is aN extremely popular library that bundles large locale files/ / / / by default due to how Webpack intErprets its code. This is a practical/ / solution that requires the user to opt into importing sPecific locales./ / https://github.com/jmblog/how-to-optimize-momentjs-with-webpack/ / You CAn remove this if you don't use Moment.js:New webpack.IgnorePlugin (/^\.\/locale$/, /moment$/),]/ / Some libraries import Node modules but don't use them in the in/ / Tell Webpack toProvide empty mocks for them so importing them works.Node: {Dgram:'empty',Fs:'empty',Net:'empty',Tls:'empty',Child_process:'empty',},/ / Turn off performance HinTS during development because we don't do any/ / splitting or minification in interest of speed. THese warnings become/ / cumbersome.Performance: {Hints: false,},};

package.json

"dependencies": {
    "autoprefixer": "7.1.6",
    "babel-core": "6.26.0",
    "babel-eslint": "7.2.3",
    "babel-jest": "20.0.3",
    "babel-loader": "7.1.2",
    "babel-plugin-react-css-modules": "^3.3.3",
    "babel-preset-react-app": "^3.1.1",
    "babel-runtime": "6.26.0",
    "case-sensitive-paths-webpack-plugin": "2.1.1",
    "chalk": "1.1.3",
    "css-loader": "0.28.7",
    "dotenv": "4.0.0",
    "dotenv-expand": "4.2.0",
    "eslint": "4.10.0",
    "eslint-config-react-app": "^2.1.0",
    "eslint-loader": "1.9.0",
    "eslint-plugin-flowtype": "2.39.1",
    "eslint-plugin-import": "2.8.0",
    "eslint-plugin-jsx-a11y": "5.1.1",
    "eslint-plugin-react": "7.4.0",
    "extract-text-webpack-plugin": "3.0.2",
    "file-loader": "1.1.5",
    "fs-extra": "3.0.1",
    "html-webpack-plugin": "2.29.0",
    "jest": "20.0.4",
    "lib-flexible": "^0.3.2",
    "object-assign": "4.1.1",
    "postcss-flexbugs-fixes": "3.2.0",
    "postcss-loader": "2.0.8",
    "promise": "8.0.1",
    "raf": "3.4.0",
    "react": "^16.2.0",
    "react-dev-utils": "^5.0.0",
    "react-dom": "^16.2.0",
    "react-motion": "^0.5.2",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.2.2",
    "redux": "^3.7.2",
    "style-loader": "0.19.0",
    "sw-precache-webpack-plugin": "0.11.4",
    "url-loader": "0.6.2",
    "webpack": "3.8.1",
    "webpack-dev-server": "2.9.4",
    "webpack-manifest-plugin": "1.3.2",
    "whatwg-fetch": "2.0.3"
  },
devDependencies": {
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "node-sass": "^4.7.2",
    "postcss-nested": "^3.0.0",
    "postcss-px2rem": "^0.3.0",
    "postcss-scss": "^1.0.4",
    "px2rem-loader": "^0.1.7",
    "react-hot-loader": "^4.0.0",
    "redux-devtools": "^3.4.1",
    "sass-loader": "^6.0.6"
  }

Answer 0:

Should bescss loaderThe problem of configuration.

Similar Posts:

One Reply to “Webpack react css-modules configuration problem”

  1. This is Definitely the most complete article i have read on Webpack, Alot better than their own Docs 😀
    Thanks Man You Rock !!

Leave a Reply

Your email address will not be published. Required fields are marked *