CSS, SCSS, and Less support in Visual Studio Code

文章推薦指數: 80 %
投票人數:10人

Go to Declaration and Find References#. This is supported for Sass and Less variables in the same file. CSS variables per the draft standards proposal are also ... Skiptocontent  VisualStudioCode Docs Updates Blog API Extensions FAQ Learn Search Download Version1.67isnowavailable!ReadaboutthenewfeaturesandfixesfromApril. Dismissthisupdate Overview Setup Overview Linux macOS Windows RaspberryPi Network AdditionalComponents Uninstall GetStarted IntroVideos TipsandTricks UserInterface Themes Settings KeyBindings DisplayLanguage Telemetry UserGuide BasicEditing ExtensionMarketplace IntelliSense CodeNavigation Refactoring Debugging VersionControl WorkingwithGitHub VSCodefortheWeb IntegratedTerminal Tasks SettingsSync Snippets Emmet CommandLine WorkspaceTrust Multi-rootWorkspaces Accessibility Languages Overview JavaScript JSON HTML CSS,SCSSandLess TypeScript Markdown PowerShell C++ Java PHP Python Julia R Rust Go T-SQL C# .NET Node.js/JavaScript WorkingwithJavaScript Node.jsTutorial Node.jsDebugging Node.jsDeployment BrowserDebugging AngularTutorial ReactTutorial VueTutorial EmberTutorial DebuggingRecipes Extensions TypeScript Tutorial Compiling Debugging Python Tutorial EditingCode Linting Debugging Environments Testing DataScience PythonInteractive DjangoTutorial FlaskTutorial Createcontainers PythononAzure SettingsReference Java GettingStarted NavigateandEdit Refactoring FormattingandLinting ProjectManagement BuildTools RunandDebug Testing SpringBoot ApplicationServers JavaonAzure GUIApplications Extensions FAQ C++ IntroVideos GCConLinux GCConWindows GCConWindowsSubsystemforLinux ClangonmacOS MicrosoftC++onWindows BuildwithCMake CMakeToolsonLinux Debugging Editing Settings ConfigureIntelliSenseforcross-compiling FAQ Containers Overview Node.js Python ASP.NETCore Debug DockerCompose Registries DeploytoAzure Chooseadevenvironment Customize DevelopwithKubernetes TipsandTricks DataScience Overview JupyterNotebooks DataScienceTutorial PythonInteractive PyTorchSupport AzureMachineLearning Azure Extensions Deployment RemoteDebuggingforNode.js Docker MongoDB Kubernetes AzureKubernetesService Remote Overview SSH Containers WindowsSubsystemforLinux GitHubCodespaces SSHTutorial ContainersTutorial WSLTutorial AttachtoContainer CreateaDevContainer AdvancedContainers devcontainerCLI devcontainer.json TipsandTricks FAQ Topics Overview Overview Linux macOS Windows RaspberryPi Network AdditionalComponents Uninstall IntroVideos TipsandTricks UserInterface Themes Settings KeyBindings DisplayLanguage Telemetry BasicEditing ExtensionMarketplace IntelliSense CodeNavigation Refactoring Debugging VersionControl WorkingwithGitHub VSCodefortheWeb IntegratedTerminal Tasks SettingsSync Snippets Emmet CommandLine WorkspaceTrust Multi-rootWorkspaces Accessibility Overview JavaScript JSON HTML CSS,SCSSandLess TypeScript Markdown PowerShell C++ Java PHP Python Julia R Rust Go T-SQL C# .NET WorkingwithJavaScript Node.jsTutorial Node.jsDebugging Node.jsDeployment BrowserDebugging AngularTutorial ReactTutorial VueTutorial EmberTutorial DebuggingRecipes Extensions Tutorial Compiling Debugging Tutorial EditingCode Linting Debugging Environments Testing DataScience PythonInteractive DjangoTutorial FlaskTutorial Createcontainers PythononAzure SettingsReference GettingStarted NavigateandEdit Refactoring FormattingandLinting ProjectManagement BuildTools RunandDebug Testing SpringBoot ApplicationServers JavaonAzure GUIApplications Extensions FAQ IntroVideos GCConLinux GCConWindows GCConWindowsSubsystemforLinux ClangonmacOS MicrosoftC++onWindows BuildwithCMake CMakeToolsonLinux Debugging Editing Settings ConfigureIntelliSenseforcross-compiling FAQ Overview Node.js Python ASP.NETCore Debug DockerCompose Registries DeploytoAzure Chooseadevenvironment Customize DevelopwithKubernetes TipsandTricks Overview JupyterNotebooks DataScienceTutorial PythonInteractive PyTorchSupport AzureMachineLearning Extensions Deployment RemoteDebuggingforNode.js Docker MongoDB Kubernetes AzureKubernetesService Overview SSH Containers WindowsSubsystemforLinux GitHubCodespaces SSHTutorial ContainersTutorial WSLTutorial AttachtoContainer CreateaDevContainer AdvancedContainers devcontainerCLI devcontainer.json TipsandTricks FAQ  Edit CSS,SCSSandLess VisualStudioCodehasbuilt-insupportforeditingstylesheetsinCSS.css,SCSS.scssandLess.less.Inaddition,youcaninstallanextensionforgreaterfunctionality. Tip:Clickonanextensiontileabovetoreadthedescriptionandreviewstodecidewhichextensionisbestforyou.SeemoreintheMarketplace. IntelliSense VSCodehassupportforselectors,propertiesandvalues.Use⌃Space(Windows,LinuxCtrl+Space)togetalistofcontextspecificoptions. Proposalscontainextensivedocumentation,includingalistofbrowsersthatsupporttheproperty.Toseethefulldescriptiontextoftheselectedentry,use⌃Space(Windows,LinuxCtrl+Space). Syntaxcoloring&colorpreview Asyoutype,thereissyntaxhighlightingaswellasincontextpreviewofcolors. Clickingonacolorpreviewwilllaunchtheintegratedcolorpickerwhichsupportsconfigurationofhue,saturationandopacity. Tip:Youcantriggerbetweendifferentcolormodesbyclickingonthecolorstringatthetopofthepicker. YoucanhideVSCode'scolorpreviewsbysettingthefollowingsetting: "editor.colorDecorators":false Tojustdisableitforcss,LessandSCSS,use "[css]":{ "editor.colorDecorators":false } Folding Youcanfoldregionsofsourcecodeusingthefoldingiconsonthegutterbetweenlinenumbersandlinestart.Foldingregionsareavailableforalldeclarations(forexample,ruledeclarations)andformultilinecommentsinthesourcecode. Additionallyyoucanusethefollowingregionmarkerstodefineafoldingregion: /*#region*/and/*#endregion*/inCSS/SCSS/Lessor//#regionand//#endregionInSCSS/Less. IfyouprefertoswitchtoindentationbasedfoldingforCSS,LessandSCSS,use: "[css]":{ "editor.foldingStrategy":"indentation" }, Emmetsnippets EmmetabbreviationsupportisbuiltintoVSCode,suggestionsarelistedalongwithothersuggestionsandsnippetsintheeditorauto-completionlist. Tip:SeetheCSSsectionoftheEmmetcheatsheetforvalidabbreviations. VSCodealsosupportsUserDefinedSnippets. SyntaxVerification&Linting ThereissupportforCSSversion<=2.1,Sassversion<=3.2andLessversion<=2.3. Note:YoucandisableVSCode'sdefaultCSS,SassorLessvalidationbysettingthecorresponding.validateUserorWorkspacesettingtofalse. "css.validate":false GotoSymbolinfile YoucanquicklynavigatetotherelevantCSSsymbolinthecurrentfilebypressing⇧⌘O(Windows,LinuxCtrl+Shift+O). Hovers HoveringoveraselectororpropertywillprovideanHTMLsnippetthatismatchedbytheCSSrule. GotoDeclarationandFindReferences ThisissupportedforSassandLessvariablesinthesamefile.CSSvariablesperthedraftstandardsproposalarealsosupported. Thereisjumptodefinitionfor@importandurl()linksinCSS,SCSSandLess. CSScustomdata YoucanextendVSCode'sCSSsupportthroughadeclarativecustomdataformat.Bysettingcss.customDatatoalistofJSONfilesfollowingthecustomdataformat,youcanenhanceVSCode'sunderstandingofnewCSSproperties,at-directives,pseudo-classesandpesudo-elements.VSCodewillthenofferlanguagesupportsuchascompletion&hoverinformationfortheprovidedproperties,at-directives,pseudo-classesandpesudo-elements. Youcanreadmoreaboutusingcustomdatainthevscode-custom-datarepository. Formatting TheCSSLanguagesFeaturesextensionalsoprovidesaformatter.TheformatterworkswithCSS,LESSandSCSS.ItisimplementedbytheJSBeautifylibraryandcomeswiththefollowingsettings: css.format.enable-Enable/disabledefaultCSSformatter. css.format.newlineBetweenRules-Separaterulesetsbyablankline. css.format.newlineBetweenSelectors-Separateselectorswithanewline. css.format.spaceAroundSelectorSeparator-Ensureaspacecharacteraroundselectorseparators'>','+','~'(forexample,a>b). Thesamesettingsalsoexistforlessandscss. TranspilingSassandLessintoCSS VSCodecanintegratewithSassandLesstranspilersthroughourintegratedtaskrunner.Wecanusethistotranspile.scssor.lessfilesinto.cssfiles.Let'swalkthroughtranspilingasimpleSass/Lessfile. Step1:InstallaSassorLesstranspiler Forthiswalkthrough,let'suseeitherthesassorlessNode.jsmodule. Note:Ifyoudon'thaveNode.jsandthenpmpackagemanageralreadyinstalled,you'llneedtodosoforthiswalkthrough.InstallNode.jsforyourplatform.TheNodePackageManager(npm)isincludedintheNode.jsdistribution.You'llneedtoopenanewterminal(commandprompt)fornpmtobeonyourPATH. npminstall-gsassless Step2:CreateasimpleSassorLessfile OpenVSCodeonanemptyfolderandcreateastyles.scssorstyles.lessfile.Placethefollowingcodeinthatfile: $padding:6px; nav{ ul{ margin:0; padding:$padding; list-style:none; } li{display:inline-block;} a{ display:block; padding:$padding12px; text-decoration:none; } } FortheLessversionoftheabovefile,justchange$paddingto@padding. Note:Thisisaverysimpleexample,whichiswhythesourcecodeisalmostidenticalbetweenbothfiletypes.Inmoreadvancedscenarios,thesyntaxesandconstructswillbemuchdifferent. Step3:Createtasks.json Thenextstepistosetupthetaskconfiguration.Todothis,runTerminal>ConfigureTasksandclickCreatetasks.jsonfilefromtemplate.Intheselectiondialogthatshowsup,selectOthers. Thiswillcreateasampletasks.jsonfileintheworkspace.vscodefolder.Theinitialversionoffilehasanexampletorunanarbitrarycommand.WewillmodifythatconfigurationfortranspilingSass/Lessinstead: //Sassconfiguration { //Seehttps://go.microsoft.com/fwlink/?LinkId=733558 //forthedocumentationaboutthetasks.jsonformat "version":"2.0.0", "tasks":[ { "label":"SassCompile", "type":"shell", "command":"sassstyles.scssstyles.css", "group":"build" } ] } //Lessconfiguration { //Seehttps://go.microsoft.com/fwlink/?LinkId=733558 //forthedocumentationaboutthetasks.jsonformat "version":"2.0.0", "tasks":[ { "label":"LessCompile", "type":"shell", "command":"lesscstyles.lessstyles.css", "group":"build" } ] } Step4:RuntheBuildTask Asthisistheonlycommandinthefile,youcanexecuteitbypressing⇧⌘B(Windows,LinuxCtrl+Shift+B)(RunBuildTask).ThesampleSass/Lessfileshouldnothaveanycompileproblems,sobyrunningthetaskallthathappensisacorrespondingstyles.cssfileiscreated. Sinceinmorecomplexenvironmentstherecanbemorethanonebuildtaskwepromptyoutopickthetasktoexecuteafterpressing⇧⌘B(Windows,LinuxCtrl+Shift+B)(RunBuildTask).Inaddition,weallowyoutoscantheoutputforcompileproblems(errorsandwarnings).Dependingonthecompiler,selectanappropriateentryinthelisttoscanthetooloutputforerrorsandwarnings.Ifyoudon'twanttoscantheoutput,selectNeverscanthebuildoutputfromthepresentedlist. Atthispoint,youshouldseeanadditionalfileshowupinthefileliststyles.css. IfyouwanttomakethetaskthedefaultbuildtasktorunexecuteConfigureDefaultBuildTaskfromtheglobalTerminalmenuandselectthecorrespondingSassorLesstaskfromthepresentedlist. Note:Ifyourbuildfailsoryouseeanerrormessagesuchas"Anoutputdirectorymustbespecifiedwhencompilingadirectory",besurethefilenamesinyourtasks.jsonmatchthefilenamesondisk.Youcanalwaystestyourbuildbyrunningsassstyles.scssstyles.cssfromthecommandline. AutomatingSass/Lesscompilation Let'stakethingsalittlefurtherandautomateSass/LesscompilationwithVSCode.Wecandosowiththesametaskrunnerintegrationasbefore,butwithafewmodifications. Step1:InstallGulpandsomeplug-ins WewilluseGulptocreateataskthatwillautomateSass/Lesscompilation.Wewillalsousethegulp-sassplug-intomakethingsalittleeasier.TheLessplug-inisgulp-less. Weneedtoinstallgulpbothglobally(-gswitch)andlocally: npminstall-ggulp npminstallgulpgulp-sassgulp-less Note:gulp-sassandgulp-lessareGulpplug-insforthesassandlesscmoduleswewereusingbefore.TherearemanyotherGulpSassandLessplug-insyoucanuse,aswellasplug-insforGrunt. Youcantestthatyourgulpinstallationwassuccessfulbytypinggulp-vintheterminal.Youshouldseeaversiondisplayedforboththeglobal(CLI)andlocalinstallations. Step2:CreateasimpleGulptask OpenVSCodeonthesamefolderfrombefore(containsstyles.scss/styles.lessandtasks.jsonunderthe.vscodefolder),andcreategulpfile.jsattheroot. Placethefollowingcodeinthegulpfile.jsfile: //Sassconfiguration vargulp=require('gulp'); varsass=require('gulp-sass')(require('sass')); gulp.task('sass',function(cb){ gulp .src('*.scss') .pipe(sass()) .pipe( gulp.dest(function(f){ returnf.base; }) ); cb(); }); gulp.task( 'default', gulp.series('sass',function(cb){ gulp.watch('*.scss',gulp.series('sass')); cb(); }) ); //Lessconfiguration vargulp=require('gulp'); varless=require('gulp-less'); gulp.task('less',function(cb){ gulp .src('*.less') .pipe(less()) .pipe( gulp.dest(function(f){ returnf.base; }) ); cb(); }); gulp.task( 'default', gulp.series('less',function(cb){ gulp.watch('*.less',gulp.series('less')); cb(); }) ); Whatishappeninghere? Ourdefaultgulptaskfirstrunsthesassorlesstaskoncewhenitstartsup. ItthenwatchesforchangestoanySCSS/Lessfileattherootofourworkspace,forexamplethecurrentfolderopeninVSCode. IttakesthesetofSCSS/Lessfilesthathavechangedandrunsthemthroughourrespectivecompiler,forexamplegulp-sass,gulp-less. WenowhaveasetofCSSfiles,eachnamedrespectivelyaftertheiroriginalSCSS/Lessfile.Wethenputthesefilesinthesamedirectory. Step3:Runthegulpdefaulttask TocompletethetasksintegrationwithVSCode,wewillneedtomodifythetaskconfigurationfrombeforetorunthedefaultGulptaskwejustcreated.Youcaneitherdeletethetasks.jsonfileoremptyitonlykeepingthe"version":"2.0.0"property.NowexecuteRunTaskfromtheglobalTerminalmenu.Observethatyouarepresentedwithapickerlistingthetasksdefinedinthegulpfile.Selectgulp:defaulttostartthetask.Weallowyoutoscantheoutputforcompileproblems.Dependingonthecompiler,selectanappropriateentryinthelisttoscanthetooloutputforerrorsandwarnings.Ifyoudon'twanttoscantheoutput,selectNeverscanthebuildoutputfromthepresentedlist.Atthispoint,ifyoucreateand/ormodifyLessorSASSfiles,youseetherespectiveCSSfilesgeneratedand/orchangesreflectedonsave.YoucanalsoenableAutoSavetomakethingsevenmorestreamlined. Ifyouwanttomakethegulp:defaulttaskthedefaultbuildtaskexecutedwhenpressing⇧⌘B(Windows,LinuxCtrl+Shift+B)runConfigureDefaultBuildTaskfromtheglobalTerminalmenuandselectgulp:defaultfromthepresentedlist. Step4:TerminatethegulpdefaultTask Thegulp:defaulttaskrunsinthebackgroundandwatchesforfilechangestoSass/Lessfiles.Ifyouwanttostopthetask,youcanusetheTerminateTaskfromtheglobalTerminalmenu. CustomizingCSS,SCSSandLessSettings YoucanconfigurethefollowinglintwarningsasUserandWorkspaceSettings. Thevalidatesettingallowsyouturnoffthebuilt-invalidation.Youwoulddothisifyouratheruseadifferentlinter. Id Description Default css.validate Enablesordisablesallcssvalidations true less.validate Enablesordisablesalllessvalidations true scss.validate Enablesordisablesallscssvalidations true ToconfigureanoptionforCSS,usecss.lint.astheprefixtotheid;forSCSSandLess,usescss.lint.andless.lint.. Setasettingtowarningorerrorifyouwanttoenablelintchecking,useignoretodisableit.Lintchecksareperformedasyoutype. Id Description Default validate Enablesordisablesallvalidations true compatibleVendorPrefixes Whenusingapropertywithavendor-specificprefix(forexample-webkit-transition),makesuretoalsoincludeallothervendor-specificpropertiese.g.-moz-transition,-ms-transitionand-o-transition ignore vendorPrefix Whenusingapropertywithavendor-specificprefixforexample-webkit-transition,makesuretoalsoincludethestandardpropertyifitexistse.g.transition warning duplicateProperties Warnaboutduplicatepropertiesinthesameruleset ignore emptyRules Warnaboutemptyrulesets warning importStatement Warnaboutusinganimportstatementasimportstatementsareloadedsequentiallywhichhasanegativeimpactonwebpageperformance ignore boxModel Donotusewidthorheightwhenusingpaddingorborder ignore universalSelector Warnwhenusingtheuniversalselector*asitisknowntobeslowandshouldbeavoided ignore zeroUnits Warnwhenhavingzerowithaunite.g.0emaszerodoesnotneedaunit. ignore fontFaceProperties Warnwhenusing@font-facerulewithoutdefiningasrcandfont-familyproperty warning hexColorLength Warnwhenusinghexnumbersthatdon'tconsistofthreeorsixhexnumbers error argumentsInColorFunction Warnwhenaninvalidnumberofparametersincolorfunctionse.g.rgb error unknownProperties Warnwhenusinganunknownproperty warning ieHack WarnwhenusinganIEhack*propertyNameor_propertyName ignore unknownVendorSpecificProperties Warnwhenusinganunknownvendor-specificproperty ignore propertyIgnoredDueToDisplay Warnwhenusingapropertythatisignoredduetothedisplay.Forexample,withdisplay:inline,thewidth,height,margin-top,margin-bottom,andfloatpropertieshavenoeffect. warning important Warnwhenusing!importantasitisanindicationthatthespecificityoftheentireCSShasgottenoutofcontrolandneedstoberefactored. ignore float WarnwhenusingfloatasfloatsleadtofragileCSSthatiseasytobreakifoneaspectofthelayoutchanges. ignore idSelector Warnwhenusingselectorsforanid#idasselectorsshouldnotcontainIDsbecausetheserulesaretootightlycoupledwiththeHTML. ignore Nextsteps Readontofindoutabout: ConfigureTasks-DigintoTaskstohelpyoutranspileyourSCSSandLesstoCSS. BasicEditing-LearnaboutthepowerfulVSCodeeditor. CodeNavigation-Movequicklythroughyoursourcecode. HTML-CSSisjustthestart,HTMLisalsoverywellsupportedinVSCode. Commonquestions DoesVSCodeprovideacolorpicker? Yes,hoveroveraCSScolorreferenceandthecolorpickerisdisplayed. IstheresupportfortheindentationbasedSasssyntax(.sass)? No,butthereareseveralextensionsintheMarketplacesupportingtheindentedflavorofSass,forexample,theSassextensionoriginallycreatedbyRobinBentley,nowmaintainedbyLeonardGrosoli. 5/5/2022 Inthisarticlethereare15sectionsInthisarticle IntelliSense Syntaxcoloring&colorpreview Folding Emmetsnippets SyntaxVerification&Linting GotoSymbolinfile Hovers GotoDeclarationandFindReferences CSScustomdata Formatting TranspilingSassandLessintoCSS AutomatingSass/Lesscompilation CustomizingCSS,SCSSandLessSettings Nextsteps Commonquestions



請為這篇文章評分?