使用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();
相关推荐
swear0114 分钟前
VSCODE 插件 rust-analyzer 使用遇到的问题 快捷键查看定义
ide·vscode·rust
天黑请闭眼32 分钟前
视频文件上传至服务器后浏览器无法在线播放
前端
一位搞嵌入式的 genius33 分钟前
前端实战开发(四):从迭代器到异步编程:ES6 Generator 全面解析 + 实战问题排查
开发语言·前端·es6·前端实战
拉不动的猪39 分钟前
# 关于初学者对于JS异步编程十大误区
前端·javascript·面试
玖釉-44 分钟前
解决PowerShell执行策略导致的npm脚本无法运行问题
前端·npm·node.js
Larcher1 小时前
新手也能学会,100行代码玩AI LOGO
前端·llm·html
徐子颐2 小时前
从 Vibe Coding 到 Agent Coding:Cursor 2.0 开启下一代 AI 开发范式
前端
小月鸭2 小时前
如何理解HTML语义化
前端·html
微小冷2 小时前
Rust图形界面教程:egui基础组件的使用
后端·rust·gui·egui·button·panel·用户图形界面
jump6802 小时前
url输入到网页展示会发生什么?
前端