【问题标题】:How to use custom style loader in Vite如何在 Vite 中使用自定义样式加载器
【发布时间】:2022-12-01 16:46:07
【问题描述】:

我们有一个反应项目并使用 webpack 进行捆绑,但我们也想尝试 vite。 Webpack 也捆绑了来自 style-loader.js 的 css 文件。在 style-loader.js 中,我们有一些与组件相关的规则,组件被添加到节点模块中。我的规则的目的主要是从 node_modules 组件导入 css 文件。当我们用 vite 运行我们的项目时,我们自定义的 scss 文件不会覆盖来自组件的 css。是否有任何覆盖解决方案或是否有任何方法可以在 vite 中使用自定义样式加载器?

我们的自定义样式加载器 webpack-dev 是;

module: {
 rules: [
   {
     test: /\.js?$/,
     exclude: /(node_modules|bower_components)/,
     loader: './config/webpack/style-loader'
   },
]}

我们的 style-loader.js 文件是;

const babylon = require('babylon');
const traverse = require('babel-traverse').default;
const fs = require('fs');

module.exports = function (source) {
    var astResult = babylon.parse(source, {
        sourceType: "module",
        ranges: true,
        plugins: [
            "jsx",
            "objectRestSpread",
            "flow",
            "typescript",
            "decorators",
            "doExpressions",
            "classProperties",
            "classPrivateProperties",
            "classPrivateMethods",
            "exportExtensions",
            "asyncGenerators",
            "functionBind",
            "functionSent",
            "dynamicImport",
            "numericSeparator",
            "optionalChaining",
            "importMeta",
            "bigInt",
            "optionalCatchBinding"
        ]
    });
    let addedIndexCounter = 0;
    let isViewDirty = false; 

    traverse(astResult, { 
        enter: function (path) {
            let node = path.node;
            if (node.type == 'ImportDeclaration' && 
                node.source && 
                node.source.type == 'StringLiteral' &&
                node.source.value &&
                node.source.value.indexOf('@packagename') >= 0 && 
                node.source.value.indexOf('core') < 0 && 
                node.source.value.indexOf('.css') < 0) {    
                if(fs.existsSync('./node_modules/' + node.source.value + '/styles.css')) {
                    let starting = node.end;
                    starting += addedIndexCounter;
                    let targettacCss = "; import '" + node.source.value + "/styles.css';"
                    addedIndexCounter += targettacCss.length;
                    source = source.substring(0, starting) + targettacCss + source.substring(starting);
                    isViewDirty = true;
                }
            }
        }
    });
    /*if(isViewDirty){
        let fileName = "view_" + (new Date()).toISOString().slice(0, 10)+"_" + Math.random().toString(35).substr(2,10);
        fs.writeFileSync('./logs/views/' + fileName, source);
    }*/
    return source;
};

【问题讨论】:

    标签: reactjs webpack vite


    【解决方案1】:

    您可以使用插件来实现您的功能,以下是我的总体思路。

    // vite.config.js
    
    import { defineConfig } from "vite";
    import customerPlugin from "./plugin/customer-plugin";
    
    export default defineConfig(() => {
      return {
        // ..
        plugins: [customerPlugin()] // Put your plugin here
      };
    });
    
    // ./plugin/customer-plugin.js
    
    const customerPlugin = () => {
      return {
        name: "customer-transform",
        transform(code, id) {
          // id = "/some/path/xxx.js"
          if (!id.endsWith(".js")) return; // Only transform js file.
    
          let resultCode = "";
          // Paste your transform logic here.
          return resultCode;
        }
      };
    };
    export default customerPlugin;
    

    参考:https://vitejs.dev/guide/api-plugin.html

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2013-08-11
      • 2020-03-14
      相关资源
      最近更新 更多