使用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();
相关推荐
Benaso32 分钟前
Rust 快速入门(一)
开发语言·后端·rust
寻找09之夏1 小时前
【Vue3实战】:用导航守卫拦截未保存的编辑,提升用户体验
前端·vue.js
多多米10052 小时前
初学Vue(2)
前端·javascript·vue.js
柏箱2 小时前
PHP基本语法总结
开发语言·前端·html·php
新缸中之脑2 小时前
Llama 3.2 安卓手机安装教程
前端·人工智能·算法
hmz8562 小时前
最新网课搜题答案查询小程序源码/题库多接口微信小程序源码+自带流量主
前端·微信小程序·小程序
看到请催我学习2 小时前
内存缓存和硬盘缓存
开发语言·前端·javascript·vue.js·缓存·ecmascript
blaizeer3 小时前
深入理解 CSS 浮动(Float):详尽指南
前端·css
编程老船长3 小时前
网页设计基础 第一讲:软件分类介绍、工具选择与课程概览
前端
编程老船长3 小时前
网页设计基础 第二讲:安装与配置 VSCode 开发工具,创建第一个 HTML 页面
前端