其实React Import scss 是非常简单的,比如一般写法import './PromotionPage.scss';,今天遇到一个样式需要覆盖,那么修改后的代码变成了:
import './PromotionPage.scss';
import { config } from "../../../common/config";
if (config.spec == "venetian") {
import '../../../requirement/venetian/stuff/PromotionPage.scss';
}
很明显程序报错了:'import' and 'export' may only appear at the top level
最后修改为
import { config } from "../../../common/config"; if (config.spec == "venetian") { import ('../../../requirement/venetian/stuff/PromotionPage.scss'); }
但是在webpack 打包的时候,会把requirement/xxx/stuff/PromotionPage.scss路径下的文件一起打包,会比较麻烦,所以需要在打包前去替换文件中变量,这里的变量也就是一个占位符,
在根目录新建一个prebuild.js文件
var glob = require("glob") var fs = require("fs"); function readFile(path) { return fs.readFileSync(path).toString(); } function writeFile(path, content) { fs.writeFileSync(path, content, {encoding:"utf8",flag:"w"}); } function readConfig() { var configContent = readFile("src/common/config.js"); var i = configContent.indexOf("{"); configContent = configContent.substring(i); return JSON.parse(configContent); } var config = readConfig(); const startTag = "//__start"; const endTag = "//__end"; function replaceVariables(content) { var tag = false; var ret = ""; var off = 0; while (true) { var i = content.indexOf(startTag, off); if (i < 0) { if (tag) { ret += content.substring(off); return ret; } else { return false; } } else { tag = true; } var j = content.indexOf(" ", i + startTag.length) var tem = content.substring(i + startTag.length, j).trim(); tem = tem.replace("#{spec}", config.spec); var k = content.indexOf(endTag, j); ret += content.substring(off, j) + " "; ret += tem + " "; off = k; } } glob("src/**/*.js", {}, function (er, files) { for (var i = 0; i < files.length; i++) { var file = files[i]; var content = readFile(file); content = replaceVariables(content); if (content) { console.log("prebuild中文的" + file); // console.log(content); writeFile(file, content); } } });
再修改package.json
"scripts": { "prebuild": "node prebuild.js", "start": "node prebuild.js && webpack-dev-server -d --progress --colors", "build": " node prebuild.js && webpack --progress --color --verbose --config ./webpack.prd.config.js" },
使用例子:
//__start import "./themes/#{spec}/skin.scss"; import "./themes/xxx/skin.scss"; //__end