Как использовать sass в приложении VUE? - PullRequest
6 голосов
/ 07 августа 2020

enter image description hereI am developing my first application in VUE I have created a styles file at the root of the project and another with the fonts I want to use globally. I'm trying to modify the styles of the components to be able to declare "" and thus be able to use these styles globally. Following the official documentation and articles on the subject I do not see the solution to a bug that launches the console

"ERROR in ./node_modules/css-loader?sourceMap!./node_modules/vue-loader/lib/style-compiler?{"vue":true,"id":"data-v-7ba5bd90","scoped":false,"hasInlineConfig":false}!./node_modules/sass-loader/dist/cjs.js!./node_modules/vue-loader/lib/selector.js?type=styles&index=0!./src/App.vue"

here is my vue.config.js

module.exports = {
    css: {
        loaderOptions: {
            sass: {
                prependData: `@import "@/styles/_variables.scss";`
            }
        }
    },
}


and here my webpack.config.js

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader',
          {
            loader: 'sass-loader',
            options: {
              prependData:
              `@import "@/styles/_variables.scss";`
            }
          }
        ],
      }, 
      {
        test: /\.scss$/,
        use: [
          'vue-style-loader',
          'css-loader',
          {
            loader: 'sass-loader',
            options: {
              // prependData:
              // `@import "@/styles/_variables.scss";`
              resources: [
                path.resolve(__dirname, '../src/styles/_variables.scss')
              ]
            }
          }
        ],
      },       
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}


and here my App.vue


      импортировать заголовок из './components/Shared/Header'; импортировать нижний колонтитул из './components/Shared/Footer.vue'; экспорт по умолчанию {name: 'app', компоненты: {'ciev-app-header': Header, 'ciev-app-footer': Footer}, created () {this. $ store.dispatch ('tryAutoLogin')}} 

Ответы [ 2 ]

6 голосов
/ 07 августа 2020

errorYou can use style-resources-loader plugin like this in vue.config.js file

vue.config.js

const path = require('path');

module.exports = {
  ...
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      // load which style file you want to import globally
      patterns: [path.resolve(__dirname, './src/styles/_variables.scss')],
    },
  }
};

Изменить: если это не сработает, добавьте это в свой массив webpack.config module.rules. Он скажет webpack использовать загрузчик sass для ваших .scss файлов

{
   test: /\/.scss$/,
   loaders: ['style', 'css', 'sass']
}
0 голосов
/ 11 августа 2020

После долгих поисков и опробования различных решений я нашел эту статью, и ее пошаговое выполнение сработало идеально для меня. Только установив файловый загрузчик и добавив выделенные поля в статье в свой веб-пакет, я решил проблему.

Я оставляю вам ссылку на случай, если кто-то окажется в такой же ситуации.

https://chriscourses.com/blog/loading-fonts-webpack

Спасибо за вашу помощь.

...