How to use absolute path to import custom scss, when using react + webpack?

后端 未结 4 1428
北恋
北恋 2021-02-05 04:47

Inside a scss file, I\'m trying to import custom, widely used chunk of scss (in a React/SASS/Webpack stack).

So that I can use a shared mixin.

Let\'s say I\'m cr

相关标签:
4条回答
  • 2021-02-05 05:27

    You could add stylesheets to the Webpack modules with resolve.modules

    // webpack.config.js
    const path = require('path')
    
    module.exports = {
      // ...
      resolve: {
        modules: [
          'node_modules',
          path.join(__dirname, 'path/to/stylesheets'),
        ],
      },
    }
    

    And sass-loader allows you to import _common-btn-styles.scss from the modules. https://webpack.js.org/loaders/sass-loader/#resolving-import-at-rules

    @import "~_common-btn-styles.scss";
    
    .my-admin-btn {
      // Use the shared mixins
    }
    
    0 讨论(0)
  • 2021-02-05 05:30

    I had to do so more research to solve this issue using other answers so here is my working solution:

    // Webpack config
    {
      test: /\.scss$/,
      loader: 'sass-loader',
      options: {
        includePaths: [path.resolve(__dirname, '<path to styles>')],
      },
    },
    

    Then in your scss file:

    @import 'filename.scss'; // Imported from <path to styles> folder.
    
    .style {
      //...
    }
    
    0 讨论(0)
  • 2021-02-05 05:32

    Found. Actually you can configure sass-loader in webpack.config.json, as described here : https://github.com/jtangelder/sass-loader

    Here is the relevant part :

    sassLoader: {
       includePaths: [path.resolve(__dirname, "./some-folder")]
    }
    
    0 讨论(0)
  • 2021-02-05 05:32

    If you use Create React App v3 which allows absolute imports you can use the tilde

    @import "~theme/colors";
    
    0 讨论(0)
提交回复
热议问题