.demo-1{颜色:红色;.demo-1-1{颜色:蓝色;}}前端的朋友应该对Sass或Scss(以下统称Sass)不陌生。它是一种CSS预处理语言。使用Sass可以大大简化CSS代码的编写和维护。通常,我们在webpackdevserver或Gulp环境中的开发环境中使用Sass实时编译Sass,通过监听文件修改输出CSS到浏览器。接下来要给大家介绍一种独特的方式,就是在开发环境中通过Nginx编译Sass,实时向浏览器输出CSS。下面简单介绍一下如何搭建环境:(如果不想自己配置环境,文末提供了Docker镜像,可以一键搭建环境)Nginx设置为了支持Sass编译,需要NginxLua模块,也就是openresty,安装方法可以参考官网:https://openresty.org/cn/inst...或者https://github.com/openresty/……Ubuntu系统可以直接通过apt包管理安装:aptinstallnginxlibnginx-mod-http-lua确保安装了Lua模块后,我们还需要一些处理Sass的Lua脚本,可以从以下地址下载:https://github.com/hex-ci/doc...,把代码解压到一个目录,比如:/your/path/lua,然后我们配置nginx.conf:http{#其他配置....lua_package_path'/你的/路径/lua/?.lua;;';#其他配置....server{#其他配置...location/{header_filter_by_lua_block{ngx.header.content_length=nilngx.header.content_encoding=""}body_filter_by_lua_file/your/path/lua/body.lua;try_files$uri$uri/=404;}location~\.php${#其他配置...header_filter_by_lua_block{ngx.header.content_length=nilngx.header.content_encoding=""}body_filter_by_lua_file/your/path/lua/body.lua;}location~^.*\.scss${设置$sass_output_style扩展;设置$sass_sourcee_map_embedon;设置$sass_source_map_contents;将$sass_is_indented_syntax_src关闭;content_by_lua_file/your/path/lua/resty/sass/autocompile.lua;}location~^.*\.sass${设置$sass_output_style扩展;设置$sass_source_map_contents;设置$sass_is_indented_syntax_srcon;content_by_lua_file/your/path/lua/resty/sass/autocompile.lua;}#其他配置...}}安装依赖编译Sass,系统需要安装libsass和lua-zlib。Ubuntu可以通过apt安装:aptinstalllibsass-devlua-zlib-dev如果需要自己编译,请参考https://github.com/sass/libsass和https://github.com/brimworks/...使用上面的配置,Nginx将支持.scss和.sass文件的实时编译,以及.html、.php等的内联Sass编译,例如:.demo-1{颜色:红色;.demo-1-1{颜色:蓝色;}}navulmargin:0padding:0list-style:nonelidisplay:inline-blockadisplay:blockpadding:6px12pxtext-decoration:noneDocker镜像为了方便搭建环境,做了一个Docker镜像,可以方便的构建支持Sass的Nginx镜像github:https://github.com/hex-ci/doc...启动容器:dockerrun--nameyour-name-v/your/html/path:/usr/share/nginx/html-pyour-port:80-dcodeigniter/nginx-lua-sass:3使用自定义配置启动容器:dockerrun--nameyour-name-v/your/html/path:/usr/share/nginx/html-v/your/path/default.conf:/etc/nginx/conf.d/default.conf-pyour-port:80-dcodeigniter/nginx-lua-sass:3最后,欢迎交流有趣的技术与你~谢谢~