UNPKG

dn-middleware-webpack5

Version:

--- group: middleware name: webpack5 title: Webpack5 ---

250 lines (190 loc) 8.97 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatNullStringToList = formatNullStringToList; exports.formatWebpackMessages = formatWebpackMessages; exports.formatSize = formatSize; exports.makeRow = makeRow; exports.formatReglikeObject = exports.getPublicPath = exports.getExistFile = void 0; var fs = _interopRequireWildcard(require("fs")); var path = _interopRequireWildcard(require("path")); var _globby = _interopRequireDefault(require("globby")); var _getPublicUrlOrPath = _interopRequireDefault(require("react-dev-utils/getPublicUrlOrPath")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } // import type { Stats } from "webpack/types"; const getExistFile = ({ cwd, files, returnRelative }) => { for (const file of files) { const absFilePath = path.join(cwd, file); if (fs.existsSync(absFilePath)) { return returnRelative ? file : absFilePath; } } }; // We use `PUBLIC_URL` enviroinfernment variable or "homepage" field to // "public path" at which the app is served. // webpack needs to know it to put the right <script> hrefs into HTML even in // single-page apps that may serve index.html for nested URLs like /todos/42. // We can't use a relative path in HTML because we don't want to load something // like /todos/42/static/js/bundle.7289d.js. We have to know the root. exports.getExistFile = getExistFile; const getPublicPath = ctx => ctx.publicPath || ctx.publicPath === "" ? ctx.publicPath : (0, _getPublicUrlOrPath.default)(process.env.NODE_ENV === "development", process.env.PUBLIC_URL, ""); // ./src/foo.js => foo exports.getPublicPath = getPublicPath; const getFilenameByPath = f => path.basename(f).split(".")[0]; // format entry and template const formatReglikeObject = params => { const paramsMap = {}; if (typeof params === "string") { paramsMap[getFilenameByPath(params)] = params; } else if (Array.isArray(params)) { params.forEach(e => { paramsMap[getFilenameByPath(e)] = e; }); } else { Object.assign(paramsMap, params); } const nameFileList = []; Object.entries(paramsMap).forEach(([nameExpr, fileExpr]) => { const files = _globby.default.sync(fileExpr); files.forEach(file => { var _file$split$reverse; const paths = (_file$split$reverse = file.split("/").reverse()) === null || _file$split$reverse === void 0 ? void 0 : _file$split$reverse.map(getFilenameByPath); const name = nameExpr.replace(/\((\d+)\)/g, (_, index) => { return paths[index]; }); nameFileList.push({ name, file }); }); }); return nameFileList; }; exports.formatReglikeObject = formatReglikeObject; function formatNullStringToList(params) { if (!params) return [];else if (Array.isArray(params)) { return params; } return [params]; } function formatWebpackMessages({ warnings, errors }) { const result = { errors: Array.isArray(errors) ? errors === null || errors === void 0 ? void 0 : errors.map(message => typeof message === "string" ? formatMessage(message) : formatMessageObj(message)) : [], warnings: Array.isArray(warnings) ? warnings === null || warnings === void 0 ? void 0 : warnings.map(message => typeof message === "string" ? formatMessage(message) : formatMessageObj(message)) : [] }; if (result.errors.some(isLikelyASyntaxError)) { // If there are any syntax errors, show just them. // This prevents a confusing ESLint parsing error // preceding a much more useful Babel syntax error. result.errors = result.errors.filter(isLikelyASyntaxError); } return result; } /** * @param {number} size the size in bytes * @returns {string} the formatted size */ function formatSize(size) { if (typeof size !== "number" || Number.isNaN(size) === true) { return "unknown size"; } if (size <= 0) { return "0 bytes"; } const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; const index = Math.floor(Math.log(size) / Math.log(1024)); return `${+(size / 1024 ** index).toPrecision(3)} ${abbreviations[index]}`; } function makeRow(a, b) { return ` ${a}\t ${b}`; } // export function printError(stats: Stats, ctx: Dawn.Context) { // const info = stats.toJson(); // // Compilation errors (missing modules, syntax errors, etc) // if (stats.hasErrors()) { // ctx.console.error("error"); // ctx.console.error(info.errors); // } // // Compilation warnings // if (stats.hasWarnings()) { // ctx.console.error("warning"); // ctx.console.warn(info.warnings); // } // } const friendlySyntaxErrorLabel = "Syntax error:"; function isLikelyASyntaxError(message) { return message.indexOf(friendlySyntaxErrorLabel) !== -1; } // Cleans up webpack error messages. // eslint-disable-next-line no-unused-vars function formatMessage(message) { var _message, _lines$; if (!message) return ""; let lines = message ? (_message = message) === null || _message === void 0 ? void 0 : _message.split("\n") : []; if (lines.length > 2 && lines[1] === "") { // Remove extra newline. lines.splice(1, 1); } // Remove webpack-specific loader notation from filename. // Before: // ./~/css-loader!./~/postcss-loader!./src/App.css // After: // ./src/App.css if (((_lines$ = lines[0]) === null || _lines$ === void 0 ? void 0 : _lines$.lastIndexOf("!")) !== -1) { var _lines$2, _lines$3; lines[0] = (_lines$2 = lines[0]) === null || _lines$2 === void 0 ? void 0 : _lines$2.substr(((_lines$3 = lines[0]) === null || _lines$3 === void 0 ? void 0 : _lines$3.lastIndexOf("!")) + 1); } // Remove unnecessary stack added by `thread-loader` var threadLoaderIndex = -1; lines.forEach(function (line, index) { if (threadLoaderIndex !== -1) { return; } if (line.indexOf("from thread-loader (worker") !== -1) { threadLoaderIndex = index; } }); if (threadLoaderIndex !== -1) { lines = lines.slice(0, threadLoaderIndex); } lines = lines.filter(function (line) { // Webpack adds a list of entry points to warning messages: // @ ./src/index.js // @ multi react-scripts/~/react-dev-utils/webpackHotDevClient.js ... // It is misleading (and unrelated to the warnings) so we clean it up. // It is only useful for syntax errors but we have beautiful frames for them. return line.indexOf(" @ ") !== 0; }); // line #0 is filename // line #1 is the main error message if (!lines[0] || !lines[1]) { return lines.join("\n"); } // Cleans up verbose "module not found" messages for files and packages. if (lines[1].indexOf("Module not found: ") === 0) { lines = [lines[0], // Clean up message because "Module not found: " is descriptive enough. lines[1].replace("Cannot resolve 'file' or 'directory' ", "").replace("Cannot resolve module ", "").replace("Error: ", "").replace("[CaseSensitivePathsPlugin] ", "")]; } // Cleans up syntax error messages. if (lines[1].indexOf("Module build failed: ") === 0) { lines[1] = lines[1].replace("Module build failed: SyntaxError:", friendlySyntaxErrorLabel); } // Clean up export errors. // TODO: we should really send a PR to Webpack for this. const exportError = /\s*(.+?)\s*(")?export '(.+?)' was not found in '(.+?)'/; if (lines[1].match(exportError)) { lines[1] = lines[1].replace(exportError, "$1 '$4' does not contain an export named '$3'."); } // Reassemble the message. message = lines.join("\n"); // Internal stacks are generally useless so we strip them... with the // exception of stacks containing `webpack:` because they're normally // from user code generated by WebPack. For more information see // https://github.com/facebook/create-react-app/pull/1050 message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ""); // at ... ...:x:y return message.trim(); } function formatMessageObj({ moduleName, loc, message }) { return moduleName + "(" + loc + ")" + "\n" + message + "\n"; }