03.03 webpack 工程師的自我修養:多頁面配置

注意

  • 棄用 npm run build & npm run dev & npm run dll
  • 改成 box build & box dev & box dll
  • link npm link 將 box 命令鏈接到全局

本章內容

  1. 使用
  2. 改造為腳手架
  3. 多頁面配置

使用

<code>box build # 不加參數則會編譯所有頁面,並清空 dist
box dev # 默認編譯 index 頁面/<code>

參數

<code># index2 是指定編譯的頁面。不會清空 dist
# report 開啟打包分析
box build index2 --report
box dev index2 --report/<code>

改造為腳手架

分成三個命令,進行不同操作

  • build
  • dev
  • dll


webpack 工程師的自我修養:多頁面配置

bin/box.js

<code>#!/usr/bin/env node

const chalk = require("chalk");
const program = require("commander");
const packageConfig = require("../package.json");
const { cleanArgs } = require("../lib");
const path = require("path");
const __name__ = `build,dev,dll`;

let boxConf = {};
let lock = false;

try {
boxConf = require(path.join(process.cwd(), "box.config.js"))();
} catch (error) {}

program
.usage("<command> [options]")
.version(packageConfig.version)
.command("build [app-page]")
.description(`構建開發環境`)
.option("-r, --report", "打包分析報告")
.option("-d, --dll", "合併差分包")
.action(async (name, cmd) => {
const options = cleanArgs(cmd);
const args = Object.assign(options, { name }, boxConf);
if (lock) return;
lock = true;
if (boxConf.pages) {
Object.keys(boxConf.pages).forEach(page => {
args.name = page;
require("../build/build")(args);
});
} else {
require("../build/build")(args);
}
});

program
.usage("<command> [options]")
.version(packageConfig.version)
.command("dev [app-page]")
.description(`構建生產環境`)
.option("-d, --dll", "合併差分包")
.action(async (name, cmd) => {
const options = cleanArgs(cmd);
const args = Object.assign(options, { name }, boxConf);
if (lock) return;
lock = true;
require("../build/dev")(args);
});

program
.usage("<command> [options]")
.version(packageConfig.version)
.command("dll [app-page]")
.description(`編譯差分包`)
.action(async (name, cmd) => {
const options = cleanArgs(cmd);
const args = Object.assign(options, { name }, boxConf);
if (lock) return;
lock = true;
require("../build/dll")(args);
});

program.parse(process.argv).args && program.parse(process.argv).args[0];
program.commands.forEach(c => c.on("--help", () => console.log()));

if (process.argv[2] && !__name__.includes(process.argv[2])) {
console.log();
console.log(chalk.red(` 沒有找到 ${process.argv[2]} 命令`));
console.log();
program.help();
}

if (!process.argv[2]) {
program.help();
}/<command>/<command>/<command>/<code>

多頁面配置

box.config.js

<code>module.exports = function(config) {
return {
entry: "src/main.js", // 默認入口
dist: "dist", // 默認打包目錄
publicPath: "/",
port: 8888,
pages: {
index: {
entry: "src/main.js",
template: "public/index.html",
filename: "index.html"
},
index2: {
entry: "src/main.js",
template: "public/index2.html",
filename: "index2.html"
}
},
chainWebpack(config) {}
};
};/<code>


分享到:


相關文章: