@canvases/multi-project-webpack-plugin
Version:
"A Webpack plugin that enables multi-project configuration support, allowing different code blocks to be compiled or executed based on configuration files.
82 lines (66 loc) • 3.2 kB
JavaScript
const fs = require('fs');
const path = require('path');
/**
* 多项目配置 Webpack 插件
* new MultiProjectWebpackPlugin()
* options: {
* platform: 'WX',
* entryPath: '@/manifest.json',
* exportPath: '@/public/config.json'
* }
*/
class MultiProjectWebpackPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
//没有启动值的话,直接输出错误
if(!this.options.platform){
console.log("配置环境未编写,请检查启动环境是否配置正确")
return;
}
// 根据 alias 配置解析得到配置文件的绝对路径
const resolvedEntryFile = this.resolveAlias(this.options.entryPath, compiler),
resolvedExportFile = this.resolveAlias(this.options.exportPath, compiler);
// 如果配置文件不存在,则直接抛出错误,终止构建
if (!fs.existsSync(resolvedEntryFile)) {
throw new Error(`入口配置文件未找到:${resolvedEntryFile}。请检查配置是否正确。`);
}
// 如果出口配置文件不存在,则直接抛出错误,终止构建
// if (!fs.existsSync(resolvedExportFile)) {
// throw new Error(`出口配置文件未找到:${resolvedEntryFile}。请检查配置是否正确。`);
// }
// 在 Webpack 的 `afterPlugins` 钩子中执行
compiler.hooks.afterPlugins.tap('MultiProjectWebpackPlugin', () => {
// console.log("---------",manifestPath, publicPath);
// // 读取 manifest.json
const manifest = JSON.parse(fs.readFileSync(resolvedEntryFile, 'utf8'));
let configContent = `window.CODE_CONFIG = {}`
if(manifest[this.options.platform] && manifest[this.options.platform].config) {
// 根据 manifest.config 生成 config.js 内容
configContent = `window.CODE_CONFIG = ${JSON.stringify(manifest[this.options.platform].config, null, 2)};`;
}
// 写入 public/config.js
fs.writeFileSync(resolvedExportFile, configContent, 'utf8');
});
}
// 解析 alias 的方法
resolveAlias(configFile, compiler) {
const aliases = (compiler.options.resolve && compiler.options.resolve.alias) || {};
for (const alias in aliases) {
if (configFile.startsWith(alias)) {
// 截取别名之后的部分
let relativePath = configFile.slice(alias.length);
// 如果路径以斜杠开头,则去掉,防止 path.resolve 视为绝对路径
if (relativePath.startsWith('/') || relativePath.startsWith('\\')) {
relativePath = relativePath.slice(1);
}
// 替换 alias 并返回绝对路径
return path.resolve(aliases[alias],relativePath );
}
}
// 没有匹配 alias,则默认从项目根目录查找
return path.resolve(process.cwd(), configFile);
}
}
module.exports = MultiProjectWebpackPlugin;