Vue.js 2项目配置SCSS失败,寻求正确配置方法
Hey there, let's work through this SCSS setup issue for your Vue 2 project step by step—this is super common for Vue newbies, so we’ll break it down simply:
1. Install Compatible Dependencies First
The latest versions of sass-loader and node-sass often clash with Vue 2’s default Webpack 3 setup. Instead, install versions that are guaranteed to work:
npm install sass-loader@7.3.1 node-sass@4.14.1 style-loader --save-dev
If you hit install errors with node-sass (common on some systems), swap it for the newer Dart Sass implementation:
npm uninstall node-sass && npm install sass@1.32.13 sass-loader@7.3.1 style-loader --save-dev
2. Fix Your Webpack Base Configuration
In build/webpack.base.conf.js, make sure your SCSS rule is added to the module.rules array (not a standalone loaders key—this is a common misstep). Replace your existing rule with this:
module.exports = { // ... other existing config module: { rules: [ // ... keep all your existing rules (vue, js, etc.) { test: /\.scss$/, use: [ 'style-loader', 'css-loader', 'sass-loader' ] } ] } }
3. Update the Vue Loader Config (This Is the Missing Piece!)
You mentioned vue-loader.conf.js—it pulls its loader settings from build/utils.js, so we need to modify that file to enable SCSS support for Vue components:
- Open
build/utils.js - Find the
cssLoadersfunction. Inside the return object, add these two lines for SCSS support:
scss: generateLoaders('sass'), sass: generateLoaders('sass', { indentedSyntax: true })
Your updated return block will look like this:
return { css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders('less'), sass: generateLoaders('sass', { indentedSyntax: true }), // New scss: generateLoaders('sass'), // New stylus: generateLoaders('stylus'), styl: generateLoaders('stylus') }
4. Verify Your Component’s Style Tag
Double-check your Vue component’s style tag is correctly formatted. Add lang="scss" (and scoped if you want styles to only apply to this component):
<template> <div class="container">Hello SCSS!</div> </template> <script> export default { name: 'ScssTest' } </script> <style lang="scss" scoped> $primary: #42b983; .container { background-color: $primary; padding: 20px; } </style>
5. Restart Your Dev Server
Webpack won’t pick up config changes without a restart—stop your running npm run dev command and start it again.
If you still get errors, check your terminal for specific messages (like typos in config files or invalid SCSS syntax). Most issues boil down to incompatible dependencies or misplaced config rules.
内容的提问来源于stack exchange,提问作者Nemanja G

