天天看點

webpack Import 動态檔案

其實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');
}
           

參考:ES6: Conditional & Dynamic Import Statements

但是在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("\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.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