@alicloud/console-toolkit-plugin-docs
Version:
console toolkit plugin for build docs
336 lines • 20.4 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var path = __importStar(require("path"));
var webpack_virtual_modules_1 = __importDefault(require("webpack-virtual-modules"));
var connect_history_api_fallback_1 = __importDefault(require("connect-history-api-fallback"));
var http_proxy_middleware_1 = require("http-proxy-middleware");
var open_1 = __importDefault(require("open"));
var fs = __importStar(require("fs-extra"));
var console_toolkit_shared_utils_1 = require("@alicloud/console-toolkit-shared-utils");
var runScript_1 = require("../scripts/runScript");
function generateVirtualPath(category, key) {
if (!['static-meta', 'entry'].includes(category)) {
throw new Error("invalid category \"".concat(category, "\""));
}
return path.resolve(__dirname, '_virtual_module_', "_".concat(category, "_"), key, 'virtual.js');
}
module.exports = function (api, opts) {
var virtualModules = {};
var entryListItemCode = [];
var entryListImportCode = [];
var isBuild = !(0, console_toolkit_shared_utils_1.getEnv)().isDev();
var demoContainerPath = opts.demoContainerPath ||
path.resolve(__dirname, '../../src2/DemoContainer');
var demoContainerCssPath = path.resolve(__dirname, '../../src2/DemoContainer/index.css');
if (opts.demoType === 'mobile') {
demoContainerPath = require.resolve('@ali/xmobile-demo-docs-layout');
var cssPath = path.resolve(demoContainerPath, '../../dist/index.css');
if (fs.pathExistsSync(cssPath)) {
demoContainerCssPath = cssPath;
}
}
virtualModules['/@DemoContainer'] = "export { default } from '".concat(demoContainerPath, "';");
virtualModules['/@DemoContainerCss'] = "export { default } from '".concat(demoContainerCssPath, "';");
var demoWrapperPath = opts.demoWrapperPath || path.resolve(__dirname, '../../src2/DemoWrapper');
virtualModules['/@DemoWrapper'] = "export { default } from '".concat(demoWrapperPath, "';");
var demoOptsPath = opts.demoOptsPath || path.resolve(__dirname, '../../src2/demoOpts');
virtualModules['/@demoOpts'] = "export { default } from '".concat(demoOptsPath, "';");
virtualModules['/@initializer'] = opts.initializerPath
? "import \"".concat(opts.initializerPath, "\"")
: '';
virtualModules['/@codesandboxModifier'] = opts.codesandboxModifierPath
? "export { default } from '".concat(opts.codesandboxModifierPath, "';")
: "export default (files) => files";
if (typeof opts.getDemos === 'function') {
opts.getDemos().forEach(function (_a, idx) {
var key = _a.key, demoPath = _a.path, _b = _a.staticMeta, staticMeta = _b === void 0 ? {} : _b;
var staticMetaVirtualModulePath = generateVirtualPath('static-meta', key);
if (opts.demoType === 'mobile' && isBuild && !staticMeta.url && !!opts.storeUrl) {
// 生成移动端 demo OSS url 地址,注入到 meta 中
staticMeta.url = "https://xconsole.aliyun-inc.com/demo-playground?consoleOSId=".concat(opts.consoleOSId, "&servePath=").concat(opts.storeUrl, "&entryKey=").concat(key, "&demoOnly=true");
}
virtualModules[staticMetaVirtualModulePath] = "\n import { staticMeta as staticMetaFromFile } from \"!!js-file-static-meta-loader!".concat(demoPath, "\";\n const staticMetaFromFindAPI = ").concat(JSON.stringify(staticMeta), ";\n export const staticMeta = Object.assign({}, staticMetaFromFile, staticMetaFromFindAPI, {_type:\"demo\"});\n ");
var virtualModulePath = generateVirtualPath('entry', key);
if (virtualModules[virtualModulePath]) {
throw new Error("duplicate key \"".concat(key, "\""));
}
virtualModules[virtualModulePath] = "\n import * as m from \"".concat(demoPath, "\";\n import { imports, code, deps } from \"!!demo-info-loader!").concat(demoPath, "\";\n\n // \u907F\u514Dwebpack\u505A\u7F16\u8BD1\u65F6\u5206\u6790\uFF0C\u53D1\u73B0demoPath\u91CC\u9762\u6CA1\u6709export meta\u9020\u6210warning\n const { default:demo, meta = {} } = (void 0, m);\n export { demo, meta, code, imports, deps };\n ");
entryListImportCode.push("\n import { staticMeta as demoStaticMeta".concat(idx, " } from \"").concat(staticMetaVirtualModulePath, "\";\n "));
entryListItemCode.push("{key: '".concat(key, "', staticMeta: demoStaticMeta").concat(idx, ", load: () => import('").concat(virtualModulePath, "')}"));
});
}
if (typeof opts.getMarkdownEntries === 'function') {
opts
.getMarkdownEntries()
.forEach(function (_a, idx) {
var key = _a.key, entryPath = _a.path, _b = _a.staticMeta, staticMeta = _b === void 0 ? {} : _b;
var staticMetaVirtualModulePath = generateVirtualPath('static-meta', key);
virtualModules[staticMetaVirtualModulePath] = "\n import { staticMeta as staticMetaFromFile } from \"!!md-file-static-meta-loader!".concat(entryPath, "\";\n const staticMetaFromFindAPI = ").concat(JSON.stringify(staticMeta), ";\n export const staticMeta = Object.assign({}, staticMetaFromFile, staticMetaFromFindAPI, {_type:\"md\"});\n ");
entryListImportCode.push("\n import { staticMeta as mdStaticMeta".concat(idx, " } from \"").concat(staticMetaVirtualModulePath, "\";\n "));
var virtualModulePath = generateVirtualPath('entry', key);
if (virtualModules[virtualModulePath]) {
throw new Error("duplicate key \"".concat(key, "\""));
}
virtualModules[virtualModulePath] = "\n import markdownSource from \"".concat(entryPath, "\";\n import React from \"react\";\n // \u5728\u8FD9\u4E2A\u6A21\u5757\u624D\u5F15\u5165markdown-renderer\uFF0C\u800C\u4E0D\u662F\u5728Loader\u5F15\u5165\n // \u907F\u514D\u6240\u6709\u4F7F\u7528loader\u7684\u7528\u6237\u90FD\u88AB\u8FEB\u52A0\u8F7Dmarkdown-renderer\uFF08\u4ED6\u53EF\u80FD\u4E0D\u9700\u8981\uFF09\n import { MarkdownRenderer } from \"@alicloud/console-toolkit-markdown-renderer\";\n\n export default (props) => {\n return React.createElement(MarkdownRenderer, Object.assign({ source: markdownSource }, props));\n };\n ");
entryListItemCode.push("{key: '".concat(key, "', staticMeta: mdStaticMeta").concat(idx, ", load: () => import('").concat(virtualModulePath, "')}"));
});
}
if (typeof opts.getTypeInfoEntries === 'function') {
opts.getTypeInfoEntries().forEach(function (_a, idx) {
var key = _a.key, typePath = _a.path;
var virtualModulePath = generateVirtualPath('entry', key);
if (virtualModules[virtualModulePath]) {
throw new Error("duplicate key \"".concat(key, "\""));
}
virtualModules[virtualModulePath] = "\n import typeInfo from \"!!type-info-loader!".concat(typePath, "\";\n export { typeInfo };\n ");
entryListItemCode.push("{key: '".concat(key, "', staticMeta: {_type:\"typeInfo\"}, load: () => import('").concat(virtualModulePath, "')}"));
});
}
if (typeof opts.getNormalEntries === 'function') {
opts
.getNormalEntries()
.forEach(function (_a, idx) {
var key = _a.key, entryPath = _a.path, _b = _a.staticMeta, staticMeta = _b === void 0 ? {} : _b;
var staticMetaVirtualModulePath = generateVirtualPath('static-meta', key);
virtualModules[staticMetaVirtualModulePath] = "\n import { staticMeta as staticMetaFromFile } from \"!!js-file-static-meta-loader!".concat(entryPath, "\";\n const staticMetaFromFindAPI = ").concat(JSON.stringify(staticMeta), ";\n export const staticMeta = Object.assign({}, staticMetaFromFile, staticMetaFromFindAPI, {_type:\"normal\"});\n ");
entryListImportCode.push("\n import { staticMeta as normalStaticMeta".concat(idx, " } from \"").concat(staticMetaVirtualModulePath, "\";\n "));
var virtualModulePath = generateVirtualPath('entry', key);
if (virtualModules[virtualModulePath]) {
throw new Error("duplicate key \"".concat(key, "\""));
}
virtualModules[virtualModulePath] = "\n export * from \"".concat(entryPath, "\";\n export { default } from \"").concat(entryPath, "\";\n ");
entryListItemCode.push("{key: '".concat(key, "', staticMeta: normalStaticMeta").concat(idx, ", load: () => import('").concat(virtualModulePath, "')}"));
});
}
virtualModules['/@entry-list'] = "\n ".concat(entryListImportCode.join('\n'), "\n export default [").concat(entryListItemCode.join(','), "];");
// 仅用于本地开发的 id => ServePath 解析逻辑
// 以便本地开发的时候能够从本地加载当前微应用
virtualModules['/@resolveAppServePathForLocalDev'] = "export default undefined;";
// 开发者配置微应用的 id => ServePath 解析逻辑
if (opts.resolveAppServePath) {
virtualModules['/@resolveAppServePathFromDeveloper'] = "export {default} from \"".concat(opts.resolveAppServePath, "\";");
}
else {
virtualModules['/@resolveAppServePathFromDeveloper'] = "export default undefined;";
}
var subScriptEnv = {
CONSOLEOS_ID: opts.consoleOSId,
OUTPUT_PATH: opts.output,
// externals参数会经过序列化传递给子进程,所以只能使用支持json化的值
EXTERNALS: JSON.stringify(opts.externals),
};
if (isBuild) {
api.dispatchSync('registerBeforeBuildStart', function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// 构建被微应用external掉的依赖,以便在demo-viewer上加载渲染
return [4 /*yield*/, (0, runScript_1.runScript)('deps-build', {
env: subScriptEnv,
})];
case 1:
// 构建被微应用external掉的依赖,以便在demo-viewer上加载渲染
_a.sent();
return [2 /*return*/];
}
});
}); });
}
api.on('onChainWebpack', function (config, env) {
config
.entry('index')
.clear()
.add(path.resolve(__dirname, '../../src2/index.tsx'))
.end()
.context(path.resolve(__dirname, '../../src2'))
.plugin('demos-module')
.use(webpack_virtual_modules_1.default, [virtualModules])
.end()
// `/@demos/${key}` 中的模块查找 raw-loader 时,
// 按照正常的node_modules查找算法,会直接去找/node_modules然后放弃
// 我们要让webpack能在/@demos虚拟路径中找到loader
.resolveLoader.alias.set('demo-info-loader', path.resolve(__dirname, '../loaders/demo-info-loader'))
.set('js-file-static-meta-loader', path.resolve(__dirname, '../loaders/js-file-static-meta-loader'))
.set('md-file-static-meta-loader', path.resolve(__dirname, '../loaders/md-file-static-meta-loader'))
.set('type-info-loader', path.resolve(__dirname, '../loaders/type-info-loader'))
.end()
.end()
.module.rule('md')
.test(/\.md$/)
.rule('raw-loader')
.use('raw-loader')
.loader(require.resolve('raw-loader'))
.end()
.end()
.end();
config.output.publicPath('');
config.output.path(path.resolve(process.cwd(), opts.output || 'doc-dist'));
config.externals((function () {
var _a;
var externals = {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom',
},
'@alicloud/breezr-docs-environment': '@alicloud/breezr-docs-environment',
'@breezr-doc-internals/externaled-deps': '@breezr-doc-internals/externaled-deps',
};
(_a = opts.externals) === null || _a === void 0 ? void 0 : _a.forEach(function (item) {
if (typeof item === 'string') {
externals[item] = item;
}
else {
externals[item.moduleName] = item.moduleName;
}
});
return externals;
})());
if (env.isDev()) {
config.plugins.delete('openBrowser');
config.devServer.disableHostCheck(true);
config.devServer.headers({
'Access-Control-Allow-Origin': '*',
});
config.devServer.open(false);
config.devServer.hot(false);
config.devtool('cheap-source-map');
var port = config.devServer.get('port');
var https = config.devServer.get('https');
var host = config.devServer.get('host');
var servePath_1 = "http".concat(https ? 's' : '', "://").concat(host, ":").concat(port, "/");
console.log('servePath', servePath_1);
config.devServer.historyApiFallback(false);
config.devServer.writeToDisk(true);
var hostPort_1;
var depsPort_1;
config.devServer.before(function (app, server, compiler) {
// webpack dev server自带的fallback和proxy一起使用时,
// 会有bug(多次apply webpack-dev-middleware):
// https://github.com/webpack/webpack-dev-server/issues/2716
// 因此我们自己配置fallback和proxy
app.use((0, connect_history_api_fallback_1.default)({
index: '/host/index.html',
}));
app.use('/deps', (0, http_proxy_middleware_1.createProxyMiddleware)({
target: 'http://localhost:8889',
// ws: true,
router: function (req) {
if (!depsPort_1) {
throw new Error('childProcess is not ready yet');
}
return "http://localhost:".concat(depsPort_1);
},
}));
app.use('/host', (0, http_proxy_middleware_1.createProxyMiddleware)({
target: 'http://localhost:8889',
// ws: true,
router: function (req) {
if (!hostPort_1) {
throw new Error('childProcess is not ready yet');
}
return "http://localhost:".concat(hostPort_1);
},
}));
});
(0, runScript_1.runScript)('deps-serve', {
env: __assign(__assign({}, subScriptEnv), { SERVE_PATH: servePath_1 }),
onGetPort: function (p) {
depsPort_1 = p;
},
});
(0, runScript_1.runScript)('host-serve', {
env: __assign(__assign({}, subScriptEnv), { SERVE_PATH: servePath_1 }),
onGetPort: function (p) {
hostPort_1 = p;
(0, open_1.default)(servePath_1);
},
});
virtualModules['/@resolveAppServePathForLocalDev'] = "\n export default function resolveAppServePath(appId) {\n if (appId === \"".concat(opts.consoleOSId, "\") {\n return \"").concat(servePath_1, "\";\n }\n }\n ");
}
if (typeof opts.chainWebpack === 'function') {
opts.chainWebpack(config, env);
}
});
};
//# sourceMappingURL=main-plugin.js.map
;