封装一个超级简单的loader

190 阅读1分钟

index.css

body{
    background-color: red;
    color: yellow;
}

封装一个loader把上面代码,能够添加到浏览器上

webpack.config.js

let path = require("path");

module.exports = {
    // mode环境配置 生产环境:production 开发环境:development
    mode: "development",
    // 入口文件 
    entry: "./src/index.js",
    // 默认是放到dist目录下的,可以改变
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name]-[chunkhash:5].js"
    },
    // 源码地图
    devtool: "eval-source-map",
    //配置loader
    module: { //loader是从后往前运行的,规则也是
        rules: [{
            test: /\.css$/,
            use: ["./loaders/style-loader"]
        }], //模块的匹配规则
        // noParse: "" //是否不要解析某个模块
    }
}

style-loader.js

/**
 * 样式处理loader
 * @param {符合规则的源代码} sourceCode 
 * @returns 返回处理后的代码
 */
module.exports = function (sourceCode) {
    let result = `var style = document.createElement("style");
    style.innerHTML = \`${sourceCode}\`;
    document.head.appendChild(style);`
    return result;
}

最后把webpack打包后的代码,引入到html文件中