webpack配置转换jsconfig.json的实现,使webpack/vscode可以读取到项目路径配置信息

390 阅读1分钟
const path = require("path");
const fs = require("fs");
module.exports = {
    resolve:{
        alias:{
            "src"       :  path.resolve(__dirname, "./src"),
            "@"         :  path.resolve(__dirname, "./src"),
            "com"       :  path.resolve(__dirname, "./src/com-common"),
            "comp"      :  path.resolve(__dirname, "./src/com-project"),
            "utils"     :  path.resolve(__dirname, "./src/utils"),
            "libs"      :  path.resolve(__dirname, "./src/libs"),
            "const"     :  path.resolve(__dirname, "./src/const"),
            "plugins"   :  path.resolve(__dirname, "./src/plugins"),
            "_"         :  path.resolve(__dirname, "./node_modules/lodash"),
            "iview"     :  path.resolve(__dirname, "./node_modules/view-design"),
        }
    },
}
const generate_jsconfig_json = function () {
    let pathDic = module.exports?.resolve?.alias;
    const paths = Object.keys(pathDic).reduce((paths, key) => {
        const path1 = pathDic[key];
        var relativePath = path.relative(__dirname, path1)
        let _key = `${key}/*`;
        let _value = [`${relativePath}/*`];
        paths[_key] = _value;
        return paths;
    }, {});
    const result = {
        "compilerOptions": {
            "baseUrl": ".",
            paths,
        }
    }
    fs.writeFile("jsconfig.json", JSON.stringify(result, 4, 4), err => {
        if (err) {
            console.error("保存文件失败", err);
        }
    });
};
generate_jsconfig_json();