其实React Import scss 是很是简单的,好比通常写法import './PromotionPage.scss';,今天遇到一个样式须要覆盖,那么修改后的代码变成了:css
import './PromotionPage.scss';node
import { config } from "../../../common/config";
if (config.spec == "venetian") {
import '../../../requirement/venetian/stuff/PromotionPage.scss';
}webpack
很明显程序报错了:'import' and 'export' may only appear at the top level
最后修改成web
import { config } from "../../../common/config"; if (config.spec == "venetian") { import ('../../../requirement/venetian/stuff/PromotionPage.scss'); }
可是在webpack 打包的时候,会把requirement/xxx/stuff/PromotionPage.scss路径下的文件一块儿打包,会比较麻烦,因此须要在打包前去替换文件中变量,这里的变量也就是一个占位符,json
在根目录新建一个prebuild.js文件app
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("\n", 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) + "\n"; ret += tem + "\n"; 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.jsonwebpack-dev-server
"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" },
使用例子:ui
//__start import "./themes/#{spec}/skin.scss"; import "./themes/xxx/skin.scss"; //__end