【发布时间】: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;
};
【问题讨论】: