webpack Import 動態文件

其實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
相關文章
相關標籤/搜索