Angular 6监听程序不编译main.less中导入的Less文件
Hey there, I’ve dealt with this exact problem when migrating from older Angular versions to Angular 6 with Less—super frustrating when your imported styles don’t update without a full restart! Let’s walk through the root cause and the fixes:
What’s Going On?
Angular 6’s CLI changed how it handles style file watching compared to the old angular-cli.json setup. By default, when you add a single main.less file to the styles array in angular.json, the dev server only watches that specific file for changes. It doesn’t automatically track the Less files you import into main.less, hence why you have to restart the server to see updates in those imported files.
Step-by-Step Fixes
Ensure Less Dependencies Are Installed
First, double-check thatlessandless-loaderare installed (sometimes they can get missed during upgrades):npm install less less-loader --save-devUpdate
angular.jsonStyles Configuration
Instead of addingmain.lessas a simple string in thestylesarray, use an object format to explicitly define the input. This helps the CLI properly resolve and track dependencies:"projects": { "your-project-name": { "architect": { "build": { "options": { "styles": [ { "input": "src/main.less", "inject": true } ], // ... other build options } }, "serve": { "options": { // Make sure serve uses the same styles config "styles": [ { "input": "src/main.less", "inject": true } ] } } } } }Add Style Preprocessor Options (Optional but Recommended)
To simplify your Less imports and help the CLI reliably track all style files, addstylePreprocessorOptionsto your build config. This lets you define base paths for your Less files:"build": { "options": { "stylePreprocessorOptions": { "includePaths": [ "src/styles" // Adjust this to your main styles directory ] }, // ... other options } }Now you can import files in
main.lesswithout long relative paths:// Before: @import './styles/variables.less'; // After: @import 'variables.less';Verify Import Paths
Make sure all your@importstatements inmain.lessuse correct relative paths (starting with./or../if needed). Incorrect paths can prevent the CLI from detecting file changes.
Test It Out
After making these changes, stop your dev server and restart it with ng serve. Now when you edit any Less file imported into main.less, the dev server should automatically recompile and refresh the page—no more restarts needed!
内容的提问来源于stack exchange,提问作者Rohit Dubey

