Symfony4+Webpack Encore+Vue单文件组件样式不生效问题
Hey there! Let's get your Vue component's scoped styles working properly. After checking your setup, I've found two main issues that are causing the problem, plus a small optimization to make things more reliable:
1. You've got conflicting Vue versions installed
Looking at your package.json, you have two different Vue packages installed:
vue@2.5.13(in devDependencies)vuejs@3.0.1(in dependencies)
The vuejs package is a deprecated/incorrect package name (the official one is just vue), and having two versions clashing will break Vue's runtime—including how scoped styles are injected into the DOM.
Fix this:
Uninstall the wrong package first:
yarn remove vuejs
Then re-install your dependencies to clean things up:
yarn install
2. You're missing vue-style-loader
Vue's single-file components (especially scoped styles) rely on vue-style-loader to handle injecting styles into the page and adding those unique data-v-* attributes that make scoped styles work. Your project doesn't have this dependency installed right now, so the scoped styles aren't being processed correctly.
Fix this:
Install vue-style-loader as a dev dependency:
yarn add vue-style-loader --dev
3. Optional: Explicitly configure Vue Loader for SCSS (recommended)
While Symfony Encore's enableVueLoader() does basic setup, explicitly defining the loader chain for SCSS styles ensures everything works as expected. Update your webpack.config.js:
let Encore = require('@symfony/webpack-encore'); Encore .setOutputPath('public/build/') .setPublicPath('/build') .cleanupOutputBeforeBuild() .addEntry('app', './assets/scripts/app.js') .addEntry('style', './assets/styles/style.scss') .enableSassLoader() // Update this part .enableVueLoader(options => { options.loaders.scss = [ 'vue-style-loader', 'css-loader', 'sass-loader' ]; }) .autoProvidejQuery() .enableSourceMaps(!Encore.isProduction()) .enableBuildNotifications() .enablePostCssLoader() .createSharedEntry('vendor', [ 'knacss/css/knacss.css' ]) ; module.exports = Encore.getWebpackConfig();
4. Double-check your component registration
Make sure your ingredient-search.vue is properly imported and registered in your app.js file, like this:
// assets/scripts/app.js import Vue from 'vue'; import IngredientSearch from './components/ingredient-search.vue'; Vue.component('ingredient-search', IngredientSearch); new Vue({ el: '#app' });
This ensures the component's styles are bundled into app.js and injected when the component mounts.
After making these changes, re-run yarn run encore dev (or dev-server with --hot) and your scoped styles should start working as expected!
内容的提问来源于stack exchange,提问作者JohnnyC

