使用sass开发web-components组件

思路:借助chokidar监听变化,将scss编译成css后插入

同时执行chokidar监听和webpack server

powershell 复制代码
    "start": "npm run watch:css & webpack serve",
    "watch:css" : "node chokidarStyles.js",
javascript 复制代码
// chokidarStyles.js
const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');
const sass = require('sass');
const autoprefixer = require('autoprefixer');
const postcss = require('postcss');

// 要监听的文件或目录路径
const filePath = './src/styles.scss';
const templatePath = './src/ComponentLoadingTemplate.ts';

// 监听文件或目录变化
const watcher = chokidar.watch(filePath);

const changeCss = () => {
    // 编译 SCSS 文件
    const scssFilePath = path.resolve(__dirname, filePath);
    try {
        const result = sass.renderSync({file: scssFilePath, outputStyle: 'expanded'});
        const cssContent = result.css.toString();
        // 浏览器兼容
        postcss([autoprefixer({overrideBrowserslist: ['last 30 versions', '> 0.5%', 'Firefox ESR', 'not dead']})])
            .process(cssContent, {from: undefined})
            .then(_result => {
                // 添加样式后的css
                const prefixedCss = _result.css;

                // 读取模板文件
                const templateContent = fs.readFileSync(templatePath, 'utf-8');

                const regex = /<style>([\s\S]*?)<\/style>/;

                const cssText = templateContent.match(regex);

                if (cssText && cssText[1] !== prefixedCss) {
                    // 将 CSS 内容插入模板中
                    const modifiedTemplateContent = templateContent.replace(regex, `<style>${prefixedCss}</style>`);
                    // 更新输出文件
                    const outputFilePath = path.resolve(__dirname, templatePath);
                    fs.writeFileSync(outputFilePath, modifiedTemplateContent);
                }
            })
            .catch(error => {
                console.error('Error processing CSS:', error);
            });
    } catch (e) {
        console.log(e);
    }
}

// 监听文件或目录变化事件
watcher.on('change', (path) => {
    console.log(`File ${path} has been changed`);
    changeCss();
});

watcher.on('add', (path) => {
    console.log(`File ${path} has been added`);
});

watcher.on('unlink', (path) => {
    console.log(`File ${path} has been removed`);
});

// 监听错误事件
watcher.on('error', (error) => {
    console.error(`Watcher error: ${error}`);
});

// 在需要的时候停止监听
// watcher.close();
相关推荐
阿珊和她的猫3 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
加班是不可能的,除非双倍日工资7 小时前
css预编译器实现星空背景图
前端·css·vue3
wyiyiyi8 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
gnip8 小时前
vite和webpack打包结构控制
前端·javascript
excel8 小时前
在二维 Canvas 中模拟三角形绕 X、Y 轴旋转
前端
阿华的代码王国9 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
一条上岸小咸鱼9 小时前
Kotlin 基本数据类型(三):Booleans、Characters
android·前端·kotlin
Jimmy9 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
ZXT9 小时前
promise & async await总结
前端
Jerry说前后端9 小时前
RecyclerView 性能优化:从原理到实践的深度优化方案
android·前端·性能优化