pax_global_header00006660000000000000000000000064134541677270014532gustar00rootroot0000000000000052 comment=b72b96a2bc5d2c7a308d0943567e0db191d3c358 webpack-4.30.0/000077500000000000000000000000001345416772700132325ustar00rootroot00000000000000webpack-4.30.0/.editorconfig000066400000000000000000000004671345416772700157160ustar00rootroot00000000000000root = true [*] indent_style = tab indent_size = 2 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true max_line_length = 80 [*.{yml,yaml,json}] indent_style = space indent_size = 2 [test/cases/parsing/bom/bomfile.{css,js}] charset = utf-8-bom [*.md] trim_trailing_whitespace = false webpack-4.30.0/.eslintrc.js000066400000000000000000000033301345416772700154700ustar00rootroot00000000000000module.exports = { root: true, plugins: ["prettier", "node", "jest"], extends: [ "eslint:recommended", "plugin:node/recommended", "plugin:prettier/recommended" ], env: { node: true, es6: true }, parserOptions: { ecmaVersion: 2017 }, rules: { "prettier/prettier": "error", "no-undef": "error", "no-extra-semi": "error", "no-template-curly-in-string": "error", "no-caller": "error", "no-control-regex": "off", yoda: "error", eqeqeq: "error", "global-require": "off", "brace-style": "off", "eol-last": "error", "no-extra-bind": "warn", "no-process-exit": "warn", "no-use-before-define": "off", "no-unused-vars": ["error", { args: "none" }], "no-unsafe-negation": "error", "no-loop-func": "warn", indent: "off", "no-console": "off", "valid-jsdoc": [ "error", { prefer: { return: "returns", prop: "property", memberof: "DONTUSE", class: "DONTUSE", inheritdoc: "DONTUSE", description: "DONTUSE", readonly: "DONTUSE" }, preferType: { "*": "any" }, requireReturnType: true } ], "node/no-unsupported-features": "error", "node/no-deprecated-api": "error", "node/no-missing-import": "error", "node/no-missing-require": ["error", { allowModules: ["webpack"] }], "node/no-unpublished-bin": "error", "node/no-unpublished-require": "error", "node/process-exit-as-throw": "error" }, overrides: [ { files: ["lib/**/*.runtime.js", "buildin/*.js", "hot/*.js"], env: { es6: false, browser: true }, globals: { Promise: false }, parserOptions: { ecmaVersion: 5 } }, { files: ["test/**/*.js"], env: { "jest/globals": true }, globals: { nsObj: false } } ] }; webpack-4.30.0/.gitattributes000066400000000000000000000001031345416772700161170ustar00rootroot00000000000000* text=auto test/statsCases/* eol=lf examples/* eol=lf bin/* eol=lfwebpack-4.30.0/.github/000077500000000000000000000000001345416772700145725ustar00rootroot00000000000000webpack-4.30.0/.github/ISSUE_TEMPLATE.md000066400000000000000000000021071345416772700172770ustar00rootroot00000000000000 **Do you want to request a *feature* or report a *bug*?** **What is the current behavior?** **If the current behavior is a bug, please provide the steps to reproduce.** **What is the expected behavior?** **If this is a feature request, what is motivation or use case for changing the behavior?** **Please mention other relevant information such as the browser version, Node.js version, webpack version, and Operating System.** webpack-4.30.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001345416772700167555ustar00rootroot00000000000000webpack-4.30.0/.github/ISSUE_TEMPLATE/Bug_report.md000066400000000000000000000025721345416772700214150ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve --- # Bug report **What is the current behavior?** **If the current behavior is a bug, please provide the steps to reproduce.** **What is the expected behavior?** **Other relevant information:** webpack version: Node.js version: Operating System: Additional tools: webpack-4.30.0/.github/ISSUE_TEMPLATE/Feature_request.md000066400000000000000000000014121345416772700224400ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project --- ## Feature request **What is the expected behavior?** **What is motivation or use case for adding/changing the behavior?** **How should this be implemented in your opinion?** **Are you willing to work on this yourself?** yes webpack-4.30.0/.github/ISSUE_TEMPLATE/Other.md000066400000000000000000000004701345416772700203610ustar00rootroot00000000000000--- name: Other about: Something else --- webpack-4.30.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000017731345416772700204030ustar00rootroot00000000000000 **What kind of change does this PR introduce?** **Did you add tests for your changes?** **Does this PR introduce a breaking change?** **What needs to be documented once your changes are merged?** webpack-4.30.0/.gitignore000066400000000000000000000003111345416772700152150ustar00rootroot00000000000000/node_modules /test/js /test/browsertest/js /test/fixtures/temp-cache-fixture /benchmark/js /benchmark/fixtures /examples/**/dist /coverage .DS_Store *.log .idea .vscode .eslintcache package-lock.json webpack-4.30.0/.istanbul.yml000066400000000000000000000001071345416772700156520ustar00rootroot00000000000000instrumentation: excludes: - "**/*.runtime.js" - ".github/*" webpack-4.30.0/.npmrc000066400000000000000000000000221345416772700143440ustar00rootroot00000000000000package-lock=falsewebpack-4.30.0/.prettierignore000066400000000000000000000002151345416772700162730ustar00rootroot00000000000000# Ignore test fixtures test/*.* !test/*.js !test/**/webpack.config.js # Ignore example fixtures examples/*.* !examples/**/webpack.config.js webpack-4.30.0/.prettierrc.js000066400000000000000000000002301345416772700160240ustar00rootroot00000000000000module.exports = { printWidth: 80, useTabs: true, tabWidth: 2, overrides: [ { files: "*.json", options: { useTabs: false } } ] }; webpack-4.30.0/.travis.yml000066400000000000000000000041071345416772700153450ustar00rootroot00000000000000sudo: false dist: trusty language: node_js branches: only: - master - next cache: yarn: true directories: - ".jest-cache" - ".eslintcache" stages: - basic - advanced matrix: include: - os: linux node_js: "10" env: NO_WATCH_TESTS=1 JEST="--maxWorkers=2 --cacheDirectory .jest-cache" JOB_PART=basic stage: basic - os: linux node_js: "10" env: NO_WATCH_TESTS=1 JEST="--maxWorkers=2 --cacheDirectory .jest-cache" JOB_PART=lint-unit stage: advanced - os: linux node_js: "10" env: NO_WATCH_TESTS=1 JEST="--maxWorkers=2 --cacheDirectory .jest-cache" JOB_PART=integration stage: advanced - os: linux node_js: "10" env: NO_WATCH_TESTS=1 ALTERNATIVE_SORT=1 JEST="--maxWorkers=2 --cacheDirectory .jest-cache" JOB_PART=integration stage: advanced - os: linux node_js: "10" env: - NODEJS_VERSION=v12.0.0-nightly20190206686043e76e - YARN_EXTRA_ARGS="--ignore-engines" - NO_WATCH_TESTS=1 - JEST="--maxWorkers=2 --cacheDirectory .jest-cache" - JOB_PART=integration stage: advanced fast_finish: true before_install: - | if [ "$NODEJS_VERSION" != "" ]; then mkdir /opt/node curl --silent "https://nodejs.org/download/nightly/$NODEJS_VERSION/node-$NODEJS_VERSION-linux-x64.tar.gz" | tar -zxf - --directory /opt/node export PATH="/opt/node/node-$NODEJS_VERSION-linux-x64/bin:$PATH" node --version fi install: - yarn --frozen-lockfile $YARN_EXTRA_ARGS - yarn link --frozen-lockfile $YARN_EXTRA_ARGS || true - yarn link webpack --frozen-lockfile $YARN_EXTRA_ARGS script: yarn travis:$JOB_PART after_success: - cat ./coverage/lcov.info | node_modules/.bin/coveralls --verbose - bash <(curl -s https://codecov.io/bash) -F $JOB_PART -X gcov - rm -f .jest-cache/haste-map* .jest-cache/perf-cache* notifications: slack: secure: JduSdKWwbnLCwo7Z4E59SGE+Uw832UwnXzQiKEpg1BV45MYDPRiGltly1tRHmPh9OGjvGx3XSkC2tNGOBLtL4UL2SCkf012x0t7jDutKRfcv/njynl8jk8l+UhPmaWiHXDQAgGiiKdL4RfzPLW3HeVHCOWm0LKMzcarTa8tw+rE= webpack-4.30.0/CONTRIBUTING.md000066400000000000000000000051451345416772700154700ustar00rootroot00000000000000# Contributing From opening a bug report to creating a pull request: every contribution is appreciated and welcome. If you're planning to implement a new feature or change the api please create an issue first. This way we can ensure that your precious work is not in vain. ## Issues Most of the time, if webpack is not working correctly for you, it is a simple configuration issue. If you are still having difficulty after looking over your configuration carefully, please post a question to [StackOverflow with the webpack tag](http://stackoverflow.com/tags/webpack). Questions that include your webpack.config.js, relevant files, and the full error message are more likely to receive responses. **If you have discovered a bug or have a feature suggestion, please [create an issue on GitHub](https://github.com/webpack/webpack/issues/new).** Do you want to fix an issue? Look at the issues with a tag of [X5: work required (PR / Help Wanted)](https://github.com/webpack/webpack/labels/X5%3A%20work%20required%20%28PR%20%2F%20Help%20Wanted%29). Each issue should be tagged with a difficulty tag - - D0: My First Commit (Contribution Difficulty) - D1: Easy (Contribution Difficulty) - D2: Medium (Contribution Difficulty) - D3: Hard (Contribution Difficulty) ## Contributing to the webpack ecosystem If you have created your own loader/plugin please include it on the relevant documentation pages: - [List of loaders](https://webpack.js.org/loaders/) or [awesome-webpack](https://github.com/webpack-contrib/awesome-webpack#loaders) - [List of plugins](https://webpack.js.org/plugins) or [awesome-webpack](https://github.com/webpack-contrib/awesome-webpack#webpack-plugins) ## Setup [Setup your local webpack repository](_SETUP.md) ## Submitting Changes After getting some feedbacks, push to your fork and submit a pull request. We may suggest some changes or improvements or alternatives, but for small changes your pull request should be accepted quickly. Something that will increase the chance that your pull request is accepted: * [Write tests](./test/README.md) * Follow the existing coding style * Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) ## Documentation webpack is insanely feature rich and documentation is a huge time sink. We greatly appreciate any time spent fixing typos or clarifying sections in the documentation. [See a list of issues with the documentation tag.](https://github.com/webpack/webpack/labels/documentation) ## Discussions Gitter is only for small questions. To discuss a subject in detail, please send a link to your forum or blog in the Gitter chat. webpack-4.30.0/LICENSE000066400000000000000000000020571345416772700142430ustar00rootroot00000000000000Copyright JS Foundation and other contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. webpack-4.30.0/README.md000066400000000000000000002351541345416772700145230ustar00rootroot00000000000000


[![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![builds][builds]][builds-url] [![builds2][builds2]][builds2-url] [![coverage][cover]][cover-url] [![licenses][licenses]][licenses-url]
install size

webpack

webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

## Table of Contents 1. [Install](#install) 2. [Introduction](#introduction) 3. [Concepts](#concepts) 4. [Contributing](#contributing) 5. [Support](#support) 6. [Core Team](#core-team) 7. [Sponsoring](#sponsoring) 8. [Premium Partners](#premium-partners) 9. [Other Backers and Sponsors](#other-backers-and-sponsors) 10. [Gold Sponsors](#gold-sponsors) 11. [Silver Sponsors](#silver-sponsors) 12. [Bronze Sponsors](#bronze-sponsors) 13. [Backers](#backers) 14. [Special Thanks](#special-thanks-to)

Install

Install with npm: ```bash npm install --save-dev webpack ``` Install with yarn: ```bash yarn add webpack --dev ```

Introduction

webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. **TL;DR** * Bundles [ES Modules](http://www.2ality.com/2014/09/es6-modules-final.html), [CommonJS](http://wiki.commonjs.org/), and [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules (even combined). * Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time). * Dependencies are resolved during compilation, reducing the runtime size. * Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc. * Highly modular plugin system to do whatever else your application requires. ### Get Started Check out webpack's quick [**Get Started**](https://webpack.js.org/get-started/) guide and the [other guides](https://webpack.js.org/guides/). ### Browser Compatibility webpack supports all browsers that are [ES5-compliant](http://kangax.github.io/compat-table/es5/) (IE8 and below are not supported). webpack also needs `Promise` for `import()` and `require.ensure()`. If you want to support older browsers, you will need to [load a polyfill](https://webpack.js.org/guides/shimming/) before using these expressions.

Concepts

### [Plugins](https://webpack.js.org/plugins/) webpack has a [rich plugin interface](https://webpack.js.org/plugins/). Most of the features within webpack itself use this plugin interface. This makes webpack very **flexible**. |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |[mini-css-extract-plugin][mini-css]|![mini-css-npm]|![mini-css-size]|Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS.| |[compression-webpack-plugin][compression]|![compression-npm]|![compression-size]|Prepares compressed versions of assets to serve them with Content-Encoding| |[i18n-webpack-plugin][i18n]|![i18n-npm]|![i18n-size]|Adds i18n support to your bundles| |[html-webpack-plugin][html-plugin]|![html-plugin-npm]|![html-plugin-size]| Simplifies creation of HTML files (`index.html`) to serve your bundles| |[extract-text-webpack-plugin][extract]|![extract-npm]|![extract-size]|Extract text from a bundle, or bundles, into a separate file| [common-npm]: https://img.shields.io/npm/v/webpack.svg [extract]: https://github.com/webpack/extract-text-webpack-plugin [extract-npm]: https://img.shields.io/npm/v/extract-text-webpack-plugin.svg [extract-size]: https://packagephobia.now.sh/badge?p=extract-text-webpack-plugin [mini-css]: https://github.com/webpack-contrib/mini-css-extract-plugin [mini-css-npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg [mini-css-size]: https://packagephobia.now.sh/badge?p=mini-css-extract-plugin [component]: https://github.com/webpack/component-webpack-plugin [component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg [component-size]: https://packagephobia.now.sh/badge?p=component-webpack-plugin [compression]: https://github.com/webpack/compression-webpack-plugin [compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg [compression-size]: https://packagephobia.now.sh/badge?p=compression-webpack-plugin [i18n]: https://github.com/webpack/i18n-webpack-plugin [i18n-npm]: https://img.shields.io/npm/v/i18n-webpack-plugin.svg [i18n-size]: https://packagephobia.now.sh/badge?p=i18n-webpack-plugin [html-plugin]: https://github.com/ampedandwired/html-webpack-plugin [html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg [html-plugin-size]: https://packagephobia.now.sh/badge?p=html-webpack-plugin ### [Loaders](https://webpack.js.org/loaders/) webpack enables use of loaders to preprocess files. This allows you to bundle **any static resource** way beyond JavaScript. You can easily [write your own loaders](https://webpack.js.org/api/loaders/) using Node.js. Loaders are activated by using `loadername!` prefixes in `require()` statements, or are automatically applied via regex from your webpack configuration. #### Files |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |[raw-loader][raw]|![raw-npm]|![raw-size]|Loads raw content of a file (utf-8)| |[val-loader][val]|![val-npm]|![val-size]|Executes code as module and considers exports as JS code| |[url-loader][url]|![url-npm]|![url-size]|Works like the file loader, but can return a Data Url if the file is smaller than a limit| |[file-loader][file]|![file-npm]|![file-size]|Emits the file into the output folder and returns the (relative) url| [raw]: https://github.com/webpack/raw-loader [raw-npm]: https://img.shields.io/npm/v/raw-loader.svg [raw-size]: https://packagephobia.now.sh/badge?p=raw-loader [val]: https://github.com/webpack/val-loader [val-npm]: https://img.shields.io/npm/v/val-loader.svg [val-size]: https://packagephobia.now.sh/badge?p=val-loader [url]: https://github.com/webpack/url-loader [url-npm]: https://img.shields.io/npm/v/url-loader.svg [url-size]: https://packagephobia.now.sh/badge?p=url-loader [file]: https://github.com/webpack/file-loader [file-npm]: https://img.shields.io/npm/v/file-loader.svg [file-size]: https://packagephobia.now.sh/badge?p=file-loader #### JSON |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| ||![json-npm]|![json-size]|Loads a JSON file (included by default)| ||![json5-npm]|![json5-size]|Loads and transpiles a JSON 5 file| ||![cson-npm]|![cson-size]|Loads and transpiles a CSON file| [json-npm]: https://img.shields.io/npm/v/json-loader.svg [json-size]: https://packagephobia.now.sh/badge?p=json-loader [json5-npm]: https://img.shields.io/npm/v/json5-loader.svg [json5-size]: https://packagephobia.now.sh/badge?p=json5-loader [cson-npm]: https://img.shields.io/npm/v/cson-loader.svg [cson-size]: https://packagephobia.now.sh/badge?p=cson-loader #### Transpiling |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |` ``` # dist/runtime~main.[chunkhash].js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ // add entry modules from loaded chunk to deferred list /******/ deferredModules.push.apply(deferredModules, executeModules || []); /******/ /******/ // run deferred modules when all chunks ready /******/ return checkDeferredModules(); /******/ }; /******/ function checkDeferredModules() { /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ } /******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ var deferredModules = []; /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".[chunkhash].js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // run deferred modules from other chunks /******/ checkDeferredModules(); /******/ }) /************************************************************************/ ```
```javascript /******/ ([]); ``` # dist/main.[chunkhash].js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // some module __webpack_require__.e(/*! import() */ 2).then(__webpack_require__.t.bind(null, /*! ./async1 */ 1, 7)); __webpack_require__.e(/*! import() */ 3).then(__webpack_require__.t.bind(null, /*! ./async2 */ 2, 7)); /***/ }) ],[[0,0]]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 2.[chunkhash].js 269 bytes 2 [emitted] 3.[chunkhash].js 263 bytes 3 [emitted] main.[chunkhash].js 485 bytes 1 [emitted] main runtime~main.[chunkhash].js 8.71 KiB 0 [emitted] runtime~main Entrypoint main = runtime~main.[chunkhash].js main.[chunkhash].js chunk {0} runtime~main.[chunkhash].js (runtime~main) 0 bytes ={1}= >{2}< >{3}< [entry] [rendered] > ./example main chunk {1} main.[chunkhash].js (main) 55 bytes ={0}= >{2}< >{3}< [initial] [rendered] > ./example main [0] ./example.js 55 bytes {1} [built] single entry ./example main chunk {2} 2.[chunkhash].js 28 bytes <{0}> <{1}> [rendered] > ./async1 [0] ./example.js 2:0-18 [1] ./async1.js 28 bytes {2} [built] import() ./async1 [0] ./example.js 2:0-18 chunk {3} 3.[chunkhash].js 28 bytes <{0}> <{1}> [rendered] > ./async2 [0] ./example.js 3:0-18 [2] ./async2.js 28 bytes {3} [built] import() ./async2 [0] ./example.js 3:0-18 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 2.[chunkhash].js 77 bytes 2 [emitted] 3.[chunkhash].js 78 bytes 3 [emitted] main.[chunkhash].js 149 bytes 0 [emitted] main runtime~main.[chunkhash].js 2.13 KiB 1 [emitted] runtime~main Entrypoint main = runtime~main.[chunkhash].js main.[chunkhash].js chunk {0} main.[chunkhash].js (main) 55 bytes ={1}= >{2}< >{3}< [initial] [rendered] > ./example main [0] ./example.js 55 bytes {0} [built] single entry ./example main chunk {1} runtime~main.[chunkhash].js (runtime~main) 0 bytes ={0}= >{2}< >{3}< [entry] [rendered] > ./example main chunk {2} 2.[chunkhash].js 28 bytes <{0}> <{1}> [rendered] > ./async1 [0] ./example.js 2:0-18 [1] ./async1.js 28 bytes {2} [built] import() ./async1 [0] ./example.js 2:0-18 chunk {3} 3.[chunkhash].js 28 bytes <{0}> <{1}> [rendered] > ./async2 [0] ./example.js 3:0-18 [2] ./async2.js 28 bytes {3} [built] import() ./async2 [0] ./example.js 3:0-18 ``` webpack-4.30.0/examples/chunkhash/async1.js000066400000000000000000000000341345416772700205550ustar00rootroot00000000000000// some async loaded module webpack-4.30.0/examples/chunkhash/async2.js000066400000000000000000000000341345416772700205560ustar00rootroot00000000000000// some async loaded module webpack-4.30.0/examples/chunkhash/build.js000066400000000000000000000000711345416772700204570ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-4.30.0/examples/chunkhash/example.js000066400000000000000000000000671345416772700210200ustar00rootroot00000000000000// some module import("./async1"); import("./async2"); webpack-4.30.0/examples/chunkhash/template.md000066400000000000000000000030301345416772700211550ustar00rootroot00000000000000A common challenge with combining `[chunkhash]` and Code Splitting is that the entry chunk includes the webpack runtime and with it the chunkhash mappings. This means it's always updated and the `[chunkhash]` is pretty useless, because this chunk won't be cached. A very simple solution to this problem is to create another chunk which contains only the webpack runtime (including chunkhash map). This can be achieved with the `optimization.runtimeChunk` options. To avoid the additional request for another chunk, this pretty small chunk can be inlined into the HTML page. The configuration required for this is: - use `[chunkhash]` in `output.filename` (Note that this example doesn't do this because of the example generator infrastructure, but you should) - use `[chunkhash]` in `output.chunkFilename` (Note that this example doesn't do this because of the example generator infrastructure, but you should) # example.js ```javascript _{{example.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # index.html ```html ``` # dist/runtime~main.[chunkhash].js ```javascript _{{dist/runtime~main.chunkhash.js}}_ ``` # dist/main.[chunkhash].js ```javascript _{{dist/main.chunkhash.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/chunkhash/webpack.config.js000066400000000000000000000004441345416772700222440ustar00rootroot00000000000000var path = require("path"); module.exports = { // mode: "development || "production", entry: { main: "./example" }, optimization: { runtimeChunk: true }, output: { path: path.join(__dirname, "dist"), filename: "[name].chunkhash.js", chunkFilename: "[name].chunkhash.js" } }; webpack-4.30.0/examples/code-splitted-css-bundle/000077500000000000000000000000001345416772700216455ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitted-css-bundle/README.md000066400000000000000000000110611345416772700231230ustar00rootroot00000000000000 # example.js ``` javascript require("./style.css"); require(["./chunk"]); ``` # style.css ``` css body { background: url(image.png); } ``` # chunk.js ``` javascript require("./style2.css"); ``` # style2.css ``` css .xyz { background: url(image2.png); } ``` # webpack.config.js ``` javascript var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { module: { loaders: [ { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.png$/, loader: "file-loader" } ] }, plugins: [ new ExtractTextPlugin({ filename: "style.css" }) ] }; ``` # js/style.css ``` javascript body { background: url(js/ce21cbdd9b894e6af794813eb3fdaf60.png); } ``` # Info ## Uncompressed ``` Hash: 5be34b0d3c624e61c616 Version: webpack 3.11.0 Asset Size Chunks Chunk Names ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] 0.output.js 2.44 kB 0 [emitted] output.js 21.2 kB 1 [emitted] main style.css 71 bytes 1 [emitted] main Entrypoint main = output.js style.css chunk {0} 0.output.js 1.36 kB {1} [rendered] > [0] ./example.js 2:0-20 [5] ./chunk.js 26 bytes {0} [built] amd require ./chunk [0] ./example.js 2:0-20 [6] ./style2.css 1.01 kB {0} [built] cjs require ./style2.css [5] ./chunk.js 1:0-23 [7] (webpack)/node_modules/css-loader!./style2.css 236 bytes {0} [built] cjs require !!../../node_modules/css-loader/index.js!./style2.css [6] ./style2.css 4:14-78 [8] ./image2.png 82 bytes {0} [built] cjs require ./image2.png [7] (webpack)/node_modules/css-loader!./style2.css 6:58-81 chunk {1} output.js, style.css (main) 14.1 kB [entry] [rendered] > main [0] ./example.js [0] ./example.js 48 bytes {1} [built] [1] ./style.css 41 bytes {1} [built] cjs require ./style.css [0] ./example.js 1:0-22 + 3 hidden modules Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!style.css: 1 asset Entrypoint undefined = extract-text-webpack-plugin-output-filename chunk {0} extract-text-webpack-plugin-output-filename 2.58 kB [entry] [rendered] > [0] (webpack)/node_modules/css-loader!./style.css [0] (webpack)/node_modules/css-loader!./style.css 235 bytes {0} [built] [2] ./image.png 82 bytes {0} [built] cjs require ./image.png [0] (webpack)/node_modules/css-loader!./style.css 6:58-80 + 1 hidden module ``` ## Minimized (terser, no zip) ``` Hash: edbe0e91ba86d814d855 Version: webpack 3.11.0 Asset Size Chunks Chunk Names ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] 0.output.js 343 bytes 0 [emitted] output.js 6.58 kB 1 [emitted] main style.css 61 bytes 1 [emitted] main Entrypoint main = output.js style.css chunk {0} 0.output.js 1.34 kB {1} [rendered] > [0] ./example.js 2:0-20 [5] ./chunk.js 26 bytes {0} [built] amd require ./chunk [0] ./example.js 2:0-20 [6] ./style2.css 1.01 kB {0} [built] cjs require ./style2.css [5] ./chunk.js 1:0-23 [7] (webpack)/node_modules/css-loader!./style2.css 219 bytes {0} [built] cjs require !!../../node_modules/css-loader/index.js!./style2.css [6] ./style2.css 4:14-78 [8] ./image2.png 82 bytes {0} [built] cjs require ./image2.png [7] (webpack)/node_modules/css-loader!./style2.css 6:50-73 chunk {1} output.js, style.css (main) 14.1 kB [entry] [rendered] > main [0] ./example.js [0] ./example.js 48 bytes {1} [built] [1] ./style.css 41 bytes {1} [built] cjs require ./style.css [0] ./example.js 1:0-22 + 3 hidden modules Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!style.css: 1 asset Entrypoint undefined = extract-text-webpack-plugin-output-filename chunk {0} extract-text-webpack-plugin-output-filename 2.56 kB [entry] [rendered] > [0] (webpack)/node_modules/css-loader!./style.css [0] (webpack)/node_modules/css-loader!./style.css 218 bytes {0} [built] [2] ./image.png 82 bytes {0} [built] cjs require ./image.png [0] (webpack)/node_modules/css-loader!./style.css 6:50-72 + 1 hidden module ``` webpack-4.30.0/examples/code-splitted-require.context-amd/000077500000000000000000000000001345416772700235045ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitted-require.context-amd/README.md000066400000000000000000000325161345416772700247720ustar00rootroot00000000000000# example.js ``` javascript function getTemplate(templateName, callback) { require(["../require.context/templates/"+templateName], function(tmpl) { callback(tmpl()); }); } getTemplate("a", function(a) { console.log(a); }); getTemplate("b", function(b) { console.log(b); }); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { function getTemplate(templateName, callback) { __webpack_require__.e(/*! AMD require */ 1).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(1)("./"+templateName)]; (function(tmpl) { callback(tmpl()); }).apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);}).catch(__webpack_require__.oe); } getTemplate("a", function(a) { console.log(a); }); getTemplate("b", function(b) { console.log(b); }); /***/ }) /******/ ]); ``` # dist/1.output.js ``` javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */, /* 1 */ /*!**************************************************!*\ !*** ../require.context/templates sync ^\.\/.*$ ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./a": 2, "./a.js": 2, "./b": 3, "./b.js": 3, "./c": 4, "./c.js": 4 }; function webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } function webpackContextResolve(req) { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 1; /***/ }), /* 2 */ /*!*****************************************!*\ !*** ../require.context/templates/a.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 3 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 4 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 1.81 KiB 1 [emitted] output.js 8.41 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 251 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./example.js 251 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js 457 bytes <{0}> [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates sync ^\.\/.*$ 217 bytes {1} [built] amd require context ../require.context/templates [0] ./example.js 2:1-4:3 [2] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a [1] ../require.context/templates sync ^\.\/.*$ ./a context element ./a.js [1] ../require.context/templates sync ^\.\/.*$ ./a.js [3] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b [1] ../require.context/templates sync ^\.\/.*$ ./b context element ./b.js [1] ../require.context/templates sync ^\.\/.*$ ./b.js [4] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c [1] ../require.context/templates sync ^\.\/.*$ ./c context element ./c.js [1] ../require.context/templates sync ^\.\/.*$ ./c.js ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 621 bytes 1 [emitted] output.js 2.12 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 251 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./example.js 251 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js 457 bytes <{0}> [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates sync ^\.\/.*$ 217 bytes {1} [built] amd require context ../require.context/templates [0] ./example.js 2:1-4:3 [2] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a [1] ../require.context/templates sync ^\.\/.*$ ./a context element ./a.js [1] ../require.context/templates sync ^\.\/.*$ ./a.js [3] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b [1] ../require.context/templates sync ^\.\/.*$ ./b context element ./b.js [1] ../require.context/templates sync ^\.\/.*$ ./b.js [4] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c [1] ../require.context/templates sync ^\.\/.*$ ./c context element ./c.js [1] ../require.context/templates sync ^\.\/.*$ ./c.js ``` webpack-4.30.0/examples/code-splitted-require.context-amd/build.js000066400000000000000000000000331345416772700251350ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/code-splitted-require.context-amd/example.js000066400000000000000000000003731345416772700255000ustar00rootroot00000000000000function getTemplate(templateName, callback) { require(["../require.context/templates/"+templateName], function(tmpl) { callback(tmpl()); }); } getTemplate("a", function(a) { console.log(a); }); getTemplate("b", function(b) { console.log(b); });webpack-4.30.0/examples/code-splitted-require.context-amd/template.md000066400000000000000000000004171345416772700256430ustar00rootroot00000000000000# example.js ``` javascript _{{example.js}}_ ``` # dist/output.js ``` javascript _{{dist/output.js}}_ ``` # dist/1.output.js ``` javascript _{{dist/1.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitted-require.context-amd/webpack.config.js000066400000000000000000000002251345416772700267210ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/code-splitted-require.context/000077500000000000000000000000001345416772700227455ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitted-require.context/README.md000066400000000000000000000324351345416772700242330ustar00rootroot00000000000000# example.js ``` javascript function getTemplate(templateName, callback) { require.ensure([], function(require) { callback(require("../require.context/templates/"+templateName)()); }); } getTemplate("a", function(a) { console.log(a); }); getTemplate("b", function(b) { console.log(b); }); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { function getTemplate(templateName, callback) { __webpack_require__.e(/*! require.ensure */ 1).then((function(require) { callback(__webpack_require__(1)("./"+templateName)()); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); } getTemplate("a", function(a) { console.log(a); }); getTemplate("b", function(b) { console.log(b); }); /***/ }) /******/ ]); ``` # dist/1.output.js ``` javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */, /* 1 */ /*!**************************************************!*\ !*** ../require.context/templates sync ^\.\/.*$ ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./a": 2, "./a.js": 2, "./b": 3, "./b.js": 3, "./c": 4, "./c.js": 4 }; function webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } function webpackContextResolve(req) { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 1; /***/ }), /* 2 */ /*!*****************************************!*\ !*** ../require.context/templates/a.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 3 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 4 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 1.81 KiB 1 [emitted] output.js 8.35 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 266 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./example.js 266 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js 457 bytes <{0}> [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates sync ^\.\/.*$ 217 bytes {1} [built] cjs require context ../require.context/templates [0] ./example.js 3:11-64 [2] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a [1] ../require.context/templates sync ^\.\/.*$ ./a context element ./a.js [1] ../require.context/templates sync ^\.\/.*$ ./a.js [3] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b [1] ../require.context/templates sync ^\.\/.*$ ./b context element ./b.js [1] ../require.context/templates sync ^\.\/.*$ ./b.js [4] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c [1] ../require.context/templates sync ^\.\/.*$ ./c context element ./c.js [1] ../require.context/templates sync ^\.\/.*$ ./c.js ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 621 bytes 1 [emitted] output.js 2.1 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 266 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./example.js 266 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js 457 bytes <{0}> [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates sync ^\.\/.*$ 217 bytes {1} [built] cjs require context ../require.context/templates [0] ./example.js 3:11-64 [2] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a [1] ../require.context/templates sync ^\.\/.*$ ./a context element ./a.js [1] ../require.context/templates sync ^\.\/.*$ ./a.js [3] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b [1] ../require.context/templates sync ^\.\/.*$ ./b context element ./b.js [1] ../require.context/templates sync ^\.\/.*$ ./b.js [4] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c [1] ../require.context/templates sync ^\.\/.*$ ./c context element ./c.js [1] ../require.context/templates sync ^\.\/.*$ ./c.js ``` webpack-4.30.0/examples/code-splitted-require.context/build.js000066400000000000000000000000331345416772700243760ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/code-splitted-require.context/example.js000066400000000000000000000004121345416772700247330ustar00rootroot00000000000000function getTemplate(templateName, callback) { require.ensure([], function(require) { callback(require("../require.context/templates/"+templateName)()); }); } getTemplate("a", function(a) { console.log(a); }); getTemplate("b", function(b) { console.log(b); });webpack-4.30.0/examples/code-splitted-require.context/template.md000066400000000000000000000004171345416772700251040ustar00rootroot00000000000000# example.js ``` javascript _{{example.js}}_ ``` # dist/output.js ``` javascript _{{dist/output.js}}_ ``` # dist/1.output.js ``` javascript _{{dist/1.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitted-require.context/webpack.config.js000066400000000000000000000002251345416772700261620ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/code-splitting-bundle-loader/000077500000000000000000000000001345416772700225105ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-bundle-loader/README.md000066400000000000000000000264771345416772700240070ustar00rootroot00000000000000This example combines Code Splitting and Loaders. Make sure you have read the documentation of the examples that show the feature alone. The bundle loader is used to create a wrapper module for `file.js` that loads this module on demand. The wrapper module returns a function that can be called to asynchronously receive the inner module. # example.js ```javascript require("bundle-loader!./file.js")(function(fileJsExports) { console.log(fileJsExports); }); ``` # file.js ```javascript module.exports = "It works"; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! bundle-loader!./file.js */ 1)(function(fileJsExports) { console.log(fileJsExports); }); /***/ }), /* 1 */ /*!******************************************************!*\ !*** (webpack)/node_modules/bundle-loader!./file.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var cbs = [], data; module.exports = function(cb) { if(cbs) cbs.push(cb); else cb(data); } __webpack_require__.e(/*! require.ensure */ 1).then((function(require) { data = __webpack_require__(/*! !./file.js */ 2); var callbacks = cbs; cbs = null; for(var i = 0, l = callbacks.length; i < l; i++) { callbacks[i](data); } }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }) /******/ ]); ``` # dist/1.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],{ /***/ 2: /*!*****************!*\ !*** ./file.js ***! \*****************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "It works"; /***/ }) }]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 257 bytes 1 [emitted] output.js 8.78 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 375 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./example.js 94 bytes {0} [built] single entry ./example.js main [1] (webpack)/node_modules/bundle-loader!./file.js 281 bytes {0} [built] cjs require bundle-loader!./file.js [0] ./example.js 1:0-34 chunk {1} 1.output.js 28 bytes <{0}> [rendered] > [1] (webpack)/node_modules/bundle-loader!./file.js 7:0-14:2 [2] ./file.js 28 bytes {1} [built] cjs require !!./file.js [1] (webpack)/node_modules/bundle-loader!./file.js 8:8-30 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 98 bytes 1 [emitted] output.js 2.16 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 375 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./example.js 94 bytes {0} [built] single entry ./example.js main [1] (webpack)/node_modules/bundle-loader!./file.js 281 bytes {0} [built] cjs require bundle-loader!./file.js [0] ./example.js 1:0-34 chunk {1} 1.output.js 28 bytes <{0}> [rendered] > [1] (webpack)/node_modules/bundle-loader!./file.js 7:0-14:2 [2] ./file.js 28 bytes {1} [built] cjs require !!./file.js [1] (webpack)/node_modules/bundle-loader!./file.js 8:8-30 ``` webpack-4.30.0/examples/code-splitting-bundle-loader/build.js000066400000000000000000000000331345416772700241410ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/code-splitting-bundle-loader/example.js000066400000000000000000000001361345416772700245010ustar00rootroot00000000000000require("bundle-loader!./file.js")(function(fileJsExports) { console.log(fileJsExports); }); webpack-4.30.0/examples/code-splitting-bundle-loader/file.js000066400000000000000000000000341345416772700237620ustar00rootroot00000000000000module.exports = "It works";webpack-4.30.0/examples/code-splitting-bundle-loader/template.md000066400000000000000000000012151345416772700246440ustar00rootroot00000000000000This example combines Code Splitting and Loaders. Make sure you have read the documentation of the examples that show the feature alone. The bundle loader is used to create a wrapper module for `file.js` that loads this module on demand. The wrapper module returns a function that can be called to asynchronously receive the inner module. # example.js ```javascript _{{example.js}}_ ``` # file.js ```javascript _{{file.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/1.output.js ```javascript _{{dist/1.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitting-bundle-loader/webpack.config.js000066400000000000000000000002251345416772700257250ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/code-splitting-harmony/000077500000000000000000000000001345416772700214505ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-harmony/README.md000066400000000000000000000320331345416772700227300ustar00rootroot00000000000000This example show how to use Code Splitting with the ES6 module syntax. The standard `import` is sync. `import(module: string) -> Promise` can be used to load modules on demand. This acts as split point for webpack and creates a chunk. Providing dynamic expressions to `import` is possible. The same limits as with dynamic expressions in `require` calls apply here. Each possible module creates an additional chunk. In this example `import("c/" + name)` creates two additional chunks (one for each file in `node_modules/c/`). This is called "async context". # example.js ```javascript import a from "a"; import("b").then(function(b) { console.log("b loaded", b); }) function loadC(name) { return import("c/" + name); } Promise.all([loadC("1"), loadC("2")]).then(function(arr) { console.log("c/1 and c/2 loaded", arr); }); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 2: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var a__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! a */ 3); /* harmony import */ var a__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(a__WEBPACK_IMPORTED_MODULE_0__); __webpack_require__.e(/*! import() */ 3).then(__webpack_require__.t.bind(null, /*! b */ 5, 7)).then(function(b) { console.log("b loaded", b); }) function loadC(name) { return __webpack_require__(4)("./" + name); } Promise.all([loadC("1"), loadC("2")]).then(function(arr) { console.log("c/1 and c/2 loaded", arr); }); /***/ }), /* 3 */ /*!***************************!*\ !*** ./node_modules/a.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module a /***/ }), /* 4 */ /*!*******************************************************!*\ !*** ./node_modules/c lazy ^\.\/.*$ namespace object ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./1": [ 0, 0 ], "./1.js": [ 0, 0 ], "./2": [ 1, 1 ], "./2.js": [ 1, 1 ] }; function webpackAsyncContext(req) { if(!__webpack_require__.o(map, req)) { return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } var ids = map[req], id = ids[0]; return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__.t(id, 7); }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 4; module.exports = webpackAsyncContext; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 275 bytes 0 [emitted] 1.output.js 284 bytes 1 [emitted] 3.output.js 270 bytes 3 [emitted] output.js 9.72 KiB 2 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 13 bytes <{2}> [rendered] > ./1 [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./1 > ./1.js [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./1.js 1 module chunk {1} 1.output.js 13 bytes <{2}> [rendered] > ./2 [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./2 > ./2.js [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./2.js 1 module chunk {2} output.js (main) 414 bytes >{0}< >{1}< >{3}< [entry] [rendered] > ./example.js main [2] ./example.js 243 bytes {2} [built] [no exports] single entry ./example.js main [4] ./node_modules/c lazy ^\.\/.*$ namespace object 160 bytes {2} [built] import() context lazy c [2] ./example.js 8:8-27 + 1 hidden module chunk {3} 3.output.js 11 bytes <{2}> [rendered] > b [2] ./example.js 3:0-11 1 module ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 76 bytes 0 [emitted] 1.output.js 77 bytes 1 [emitted] 3.output.js 78 bytes 3 [emitted] output.js 2.53 KiB 2 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 13 bytes <{2}> [rendered] > ./1 [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./1 > ./1.js [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./1.js 1 module chunk {1} 1.output.js 13 bytes <{2}> [rendered] > ./2 [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./2 > ./2.js [4] ./node_modules/c lazy ^\.\/.*$ namespace object ./2.js 1 module chunk {2} output.js (main) 414 bytes >{0}< >{1}< >{3}< [entry] [rendered] > ./example.js main [2] ./example.js 243 bytes {2} [built] [no exports] single entry ./example.js main [4] ./node_modules/c lazy ^\.\/.*$ namespace object 160 bytes {2} [built] import() context lazy c [2] ./example.js 8:8-27 + 1 hidden module chunk {3} 3.output.js 11 bytes <{2}> [rendered] > b [2] ./example.js 3:0-11 1 module ``` webpack-4.30.0/examples/code-splitting-harmony/build.js000066400000000000000000000000331345416772700231010ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/code-splitting-harmony/example.js000066400000000000000000000003631345416772700234430ustar00rootroot00000000000000import a from "a"; import("b").then(function(b) { console.log("b loaded", b); }) function loadC(name) { return import("c/" + name); } Promise.all([loadC("1"), loadC("2")]).then(function(arr) { console.log("c/1 and c/2 loaded", arr); }); webpack-4.30.0/examples/code-splitting-harmony/node_modules/000077500000000000000000000000001345416772700241255ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-harmony/node_modules/a.js000066400000000000000000000000131345416772700246750ustar00rootroot00000000000000// module awebpack-4.30.0/examples/code-splitting-harmony/node_modules/b.js000066400000000000000000000000131345416772700246760ustar00rootroot00000000000000// module bwebpack-4.30.0/examples/code-splitting-harmony/node_modules/c/000077500000000000000000000000001345416772700243475ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-harmony/node_modules/c/1.js000066400000000000000000000000151345416772700250410ustar00rootroot00000000000000// module c/1webpack-4.30.0/examples/code-splitting-harmony/node_modules/c/2.js000066400000000000000000000000151345416772700250420ustar00rootroot00000000000000// module c/2webpack-4.30.0/examples/code-splitting-harmony/template.md000066400000000000000000000014001345416772700236000ustar00rootroot00000000000000This example show how to use Code Splitting with the ES6 module syntax. The standard `import` is sync. `import(module: string) -> Promise` can be used to load modules on demand. This acts as split point for webpack and creates a chunk. Providing dynamic expressions to `import` is possible. The same limits as with dynamic expressions in `require` calls apply here. Each possible module creates an additional chunk. In this example `import("c/" + name)` creates two additional chunks (one for each file in `node_modules/c/`). This is called "async context". # example.js ```javascript _{{example.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitting-harmony/webpack.config.js000066400000000000000000000002251345416772700246650ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/code-splitting-native-import-context-filter/000077500000000000000000000000001345416772700255365ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-native-import-context-filter/README.md000066400000000000000000000364601345416772700270260ustar00rootroot00000000000000# example.js This example illustrates how to filter the ContextModule results of `import()` statements. only `.js` files that don't end in `.noimport.js` within the `templates` folder will be bundled. ```javascript async function getTemplate(templateName) { try { let template = await import( /* webpackInclude: /\.js$/ */ /* webpackExclude: /\.noimport\.js$/ */ `./templates/${templateName}` ); console.log(template); } catch(err) { console.error(err); return new Error(err); } } getTemplate("foo"); getTemplate("bar"); getTemplate("baz"); getTemplate("foo.noimport"); getTemplate("bar.noimport"); getTemplate("baz.noimport"); ``` # templates/ - foo.js - foo.noimport.js - baz.js - foo.noimport.js - bar.js - foo.noimport.js All templates are of this pattern: ```javascript var foo = "foo"; export default foo; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */, /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { async function getTemplate(templateName) { try { let template = await __webpack_require__(4)(`./${templateName}`); console.log(template); } catch(err) { console.error(err); return new Error(err); } } getTemplate("foo"); getTemplate("bar"); getTemplate("baz"); getTemplate("foo.noimport"); getTemplate("bar.noimport"); getTemplate("baz.noimport"); /***/ }), /* 4 */ /*!******************************************************************************************!*\ !*** ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ***! \******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./bar": [ 0, 0 ], "./bar.js": [ 0, 0 ], "./baz": [ 1, 1 ], "./baz.js": [ 1, 1 ], "./foo": [ 2, 2 ], "./foo.js": [ 2, 2 ] }; function webpackAsyncContext(req) { if(!__webpack_require__.o(map, req)) { return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } var ids = map[req], id = ids[0]; return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__(id); }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 4; module.exports = webpackAsyncContext; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 433 bytes 0 [emitted] 1.output.js 442 bytes 1 [emitted] 2.output.js 436 bytes 2 [emitted] output.js 9.45 KiB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 38 bytes <{3}> [rendered] > ./bar [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar > ./bar.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar.js [0] ./templates/bar.js 38 bytes {0} [optional] [built] [exports: default] context element ./bar [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar context element ./bar.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar.js chunk {1} 1.output.js 38 bytes <{3}> [rendered] > ./baz [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz > ./baz.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz.js [1] ./templates/baz.js 38 bytes {1} [optional] [built] [exports: default] context element ./baz [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz context element ./baz.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz.js chunk {2} 2.output.js 38 bytes <{3}> [rendered] > ./foo [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo > ./foo.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo.js [2] ./templates/foo.js 38 bytes {2} [optional] [built] [exports: default] context element ./foo [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo context element ./foo.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo.js chunk {3} output.js (main) 597 bytes >{0}< >{1}< >{2}< [entry] [rendered] > ./example.js main [3] ./example.js 437 bytes {3} [built] single entry ./example.js main [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object 160 bytes {3} [optional] [built] import() context lazy ./templates [3] ./example.js 3:23-7:3 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 113 bytes 0 [emitted] 1.output.js 114 bytes 1 [emitted] 2.output.js 115 bytes 2 [emitted] output.js 2.52 KiB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 38 bytes <{3}> [rendered] > ./bar [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar > ./bar.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar.js [0] ./templates/bar.js 38 bytes {0} [optional] [built] [exports: default] context element ./bar [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar context element ./bar.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./bar.js chunk {1} 1.output.js 38 bytes <{3}> [rendered] > ./baz [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz > ./baz.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz.js [1] ./templates/baz.js 38 bytes {1} [optional] [built] [exports: default] context element ./baz [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz context element ./baz.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./baz.js chunk {2} 2.output.js 38 bytes <{3}> [rendered] > ./foo [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo > ./foo.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo.js [2] ./templates/foo.js 38 bytes {2} [optional] [built] [exports: default] context element ./foo [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo context element ./foo.js [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object ./foo.js chunk {3} output.js (main) 597 bytes >{0}< >{1}< >{2}< [entry] [rendered] > ./example.js main [3] ./example.js 437 bytes {3} [built] single entry ./example.js main [4] ./templates lazy ^\.\/.*$ include: \.js$ exclude: \.noimport\.js$ namespace object 160 bytes {3} [optional] [built] import() context lazy ./templates [3] ./example.js 3:23-7:3 ``` webpack-4.30.0/examples/code-splitting-native-import-context-filter/build.js000066400000000000000000000000331345416772700271670ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/code-splitting-native-import-context-filter/example.js000066400000000000000000000006651345416772700275360ustar00rootroot00000000000000async function getTemplate(templateName) { try { let template = await import( /* webpackInclude: /\.js$/ */ /* webpackExclude: /\.noimport\.js$/ */ `./templates/${templateName}` ); console.log(template); } catch(err) { console.error(err); return new Error(err); } } getTemplate("foo"); getTemplate("bar"); getTemplate("baz"); getTemplate("foo.noimport"); getTemplate("bar.noimport"); getTemplate("baz.noimport"); webpack-4.30.0/examples/code-splitting-native-import-context-filter/template.md000066400000000000000000000010711345416772700276720ustar00rootroot00000000000000# example.js This example illustrates how to filter the ContextModule results of `import()` statements. only `.js` files that don't end in `.noimport.js` within the `templates` folder will be bundled. ```javascript _{{example.js}}_ ``` # templates/ - foo.js - foo.noimport.js - baz.js - foo.noimport.js - bar.js - foo.noimport.js All templates are of this pattern: ```javascript _{{templates/foo.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitting-native-import-context-filter/templates/000077500000000000000000000000001345416772700275345ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-native-import-context-filter/templates/bar.js000066400000000000000000000000461345416772700306360ustar00rootroot00000000000000var bar = "bar"; export default bar; webpack-4.30.0/examples/code-splitting-native-import-context-filter/templates/bar.noimport.js000066400000000000000000000000461345416772700325040ustar00rootroot00000000000000var bar = "bar"; export default bar; webpack-4.30.0/examples/code-splitting-native-import-context-filter/templates/baz.js000066400000000000000000000000461345416772700306460ustar00rootroot00000000000000var baz = "baz"; export default baz; webpack-4.30.0/examples/code-splitting-native-import-context-filter/templates/baz.noimport.js000066400000000000000000000000461345416772700325140ustar00rootroot00000000000000var baz = "baz"; export default baz; webpack-4.30.0/examples/code-splitting-native-import-context-filter/templates/foo.js000066400000000000000000000000461345416772700306550ustar00rootroot00000000000000var foo = "foo"; export default foo; webpack-4.30.0/examples/code-splitting-native-import-context-filter/templates/foo.noimport.js000066400000000000000000000000461345416772700325230ustar00rootroot00000000000000var foo = "foo"; export default foo; webpack-4.30.0/examples/code-splitting-native-import-context-filter/webpack.config.js000066400000000000000000000002251345416772700307530ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/code-splitting-native-import-context/000077500000000000000000000000001345416772700242535ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-native-import-context/README.md000066400000000000000000000335741345416772700255460ustar00rootroot00000000000000# example.js This example illustrates how to leverage the `import()` syntax to create ContextModules which are separated into separate chunks for each module in the `./templates` folder. ```javascript async function getTemplate(templateName) { try { let template = await import(`./templates/${templateName}`); console.log(template); } catch(err) { console.error("template error"); return new Error(err); } } getTemplate("foo"); getTemplate("bar"); getTemplate("baz"); ``` # templates/ - foo.js - baz.js - bar.js All templates are of this pattern: ```javascript var foo = "foo"; export default foo; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */, /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { async function getTemplate(templateName) { try { let template = await __webpack_require__(4)(`./${templateName}`); console.log(template); } catch(err) { console.error("template error"); return new Error(err); } } getTemplate("foo"); getTemplate("bar"); getTemplate("baz"); /***/ }), /* 4 */ /*!**************************************************!*\ !*** ./templates lazy ^\.\/.*$ namespace object ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./bar": [ 0, 0 ], "./bar.js": [ 0, 0 ], "./baz": [ 1, 1 ], "./baz.js": [ 1, 1 ], "./foo": [ 2, 2 ], "./foo.js": [ 2, 2 ] }; function webpackAsyncContext(req) { if(!__webpack_require__.o(map, req)) { return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } var ids = map[req], id = ids[0]; return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__(id); }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 4; module.exports = webpackAsyncContext; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 433 bytes 0 [emitted] 1.output.js 442 bytes 1 [emitted] 2.output.js 436 bytes 2 [emitted] output.js 9.26 KiB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 38 bytes <{3}> [rendered] > ./bar [4] ./templates lazy ^\.\/.*$ namespace object ./bar > ./bar.js [4] ./templates lazy ^\.\/.*$ namespace object ./bar.js [0] ./templates/bar.js 38 bytes {0} [optional] [built] [exports: default] context element ./bar [4] ./templates lazy ^\.\/.*$ namespace object ./bar context element ./bar.js [4] ./templates lazy ^\.\/.*$ namespace object ./bar.js chunk {1} 1.output.js 38 bytes <{3}> [rendered] > ./baz [4] ./templates lazy ^\.\/.*$ namespace object ./baz > ./baz.js [4] ./templates lazy ^\.\/.*$ namespace object ./baz.js [1] ./templates/baz.js 38 bytes {1} [optional] [built] [exports: default] context element ./baz [4] ./templates lazy ^\.\/.*$ namespace object ./baz context element ./baz.js [4] ./templates lazy ^\.\/.*$ namespace object ./baz.js chunk {2} 2.output.js 38 bytes <{3}> [rendered] > ./foo [4] ./templates lazy ^\.\/.*$ namespace object ./foo > ./foo.js [4] ./templates lazy ^\.\/.*$ namespace object ./foo.js [2] ./templates/foo.js 38 bytes {2} [optional] [built] [exports: default] context element ./foo [4] ./templates lazy ^\.\/.*$ namespace object ./foo context element ./foo.js [4] ./templates lazy ^\.\/.*$ namespace object ./foo.js chunk {3} output.js (main) 441 bytes >{0}< >{1}< >{2}< [entry] [rendered] > ./example.js main [3] ./example.js 281 bytes {3} [built] single entry ./example.js main [4] ./templates lazy ^\.\/.*$ namespace object 160 bytes {3} [optional] [built] import() context lazy ./templates [3] ./example.js 3:23-60 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 113 bytes 0 [emitted] 1.output.js 114 bytes 1 [emitted] 2.output.js 115 bytes 2 [emitted] output.js 2.49 KiB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 38 bytes <{3}> [rendered] > ./bar [4] ./templates lazy ^\.\/.*$ namespace object ./bar > ./bar.js [4] ./templates lazy ^\.\/.*$ namespace object ./bar.js [0] ./templates/bar.js 38 bytes {0} [optional] [built] [exports: default] context element ./bar [4] ./templates lazy ^\.\/.*$ namespace object ./bar context element ./bar.js [4] ./templates lazy ^\.\/.*$ namespace object ./bar.js chunk {1} 1.output.js 38 bytes <{3}> [rendered] > ./baz [4] ./templates lazy ^\.\/.*$ namespace object ./baz > ./baz.js [4] ./templates lazy ^\.\/.*$ namespace object ./baz.js [1] ./templates/baz.js 38 bytes {1} [optional] [built] [exports: default] context element ./baz [4] ./templates lazy ^\.\/.*$ namespace object ./baz context element ./baz.js [4] ./templates lazy ^\.\/.*$ namespace object ./baz.js chunk {2} 2.output.js 38 bytes <{3}> [rendered] > ./foo [4] ./templates lazy ^\.\/.*$ namespace object ./foo > ./foo.js [4] ./templates lazy ^\.\/.*$ namespace object ./foo.js [2] ./templates/foo.js 38 bytes {2} [optional] [built] [exports: default] context element ./foo [4] ./templates lazy ^\.\/.*$ namespace object ./foo context element ./foo.js [4] ./templates lazy ^\.\/.*$ namespace object ./foo.js chunk {3} output.js (main) 441 bytes >{0}< >{1}< >{2}< [entry] [rendered] > ./example.js main [3] ./example.js 281 bytes {3} [built] single entry ./example.js main [4] ./templates lazy ^\.\/.*$ namespace object 160 bytes {3} [optional] [built] import() context lazy ./templates [3] ./example.js 3:23-60 ``` webpack-4.30.0/examples/code-splitting-native-import-context/build.js000066400000000000000000000000331345416772700257040ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/code-splitting-native-import-context/example.js000066400000000000000000000004311345416772700262420ustar00rootroot00000000000000async function getTemplate(templateName) { try { let template = await import(`./templates/${templateName}`); console.log(template); } catch(err) { console.error("template error"); return new Error(err); } } getTemplate("foo"); getTemplate("bar"); getTemplate("baz"); webpack-4.30.0/examples/code-splitting-native-import-context/template.md000066400000000000000000000007651345416772700264200ustar00rootroot00000000000000# example.js This example illustrates how to leverage the `import()` syntax to create ContextModules which are separated into separate chunks for each module in the `./templates` folder. ```javascript _{{example.js}}_ ``` # templates/ - foo.js - baz.js - bar.js All templates are of this pattern: ```javascript _{{templates/foo.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitting-native-import-context/templates/000077500000000000000000000000001345416772700262515ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-native-import-context/templates/bar.js000066400000000000000000000000461345416772700273530ustar00rootroot00000000000000var bar = "bar"; export default bar; webpack-4.30.0/examples/code-splitting-native-import-context/templates/baz.js000066400000000000000000000000461345416772700273630ustar00rootroot00000000000000var baz = "baz"; export default baz; webpack-4.30.0/examples/code-splitting-native-import-context/templates/foo.js000066400000000000000000000000461345416772700273720ustar00rootroot00000000000000var foo = "foo"; export default foo; webpack-4.30.0/examples/code-splitting-native-import-context/webpack.config.js000066400000000000000000000002251345416772700274700ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/code-splitting-specify-chunk-name/000077500000000000000000000000001345416772700234615ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-specify-chunk-name/README.md000066400000000000000000000341401345416772700247420ustar00rootroot00000000000000# example.js This example illustrates how to specify chunk name in `require.ensure()` and `import()` to separated modules into separate chunks manually. ```javascript import("./templates/foo" /* webpackChunkName: "chunk-foo" */ ).then(function(foo) { console.log('foo:', foo); }) require.ensure([], function(require) { var foo = require("./templates/foo"); console.log('foo:', foo); }, "chunk-foo1"); var createContextVar = "r"; import("./templates/ba" + createContextVar /* webpackChunkName: "chunk-bar-baz" */ ).then(function(bar) { console.log('bar:', bar); }) ``` # templates/ - foo.js - baz.js - bar.js All templates are of this pattern: ```javascript var foo = "foo"; export default foo; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */, /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__.e(/*! import() | chunk-foo */ 2).then(__webpack_require__.bind(null, /*! ./templates/foo */ 0)).then(function(foo) { console.log('foo:', foo); }) __webpack_require__.e(/*! require.ensure | chunk-foo1 */ 2).then((function(require) { var foo = __webpack_require__(/*! ./templates/foo */ 0); console.log('foo:', foo); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); var createContextVar = "r"; __webpack_require__(4)("./ba" + createContextVar).then(function(bar) { console.log('bar:', bar); }) /***/ }), /* 4 */ /*!****************************************************!*\ !*** ./templates lazy ^\.\/ba.*$ namespace object ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./bar": [ 1, 0 ], "./bar.js": [ 1, 0 ], "./baz": [ 2, 1 ], "./baz.js": [ 2, 1 ] }; function webpackAsyncContext(req) { if(!__webpack_require__.o(map, req)) { return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } var ids = map[req], id = ids[0]; return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__(id); }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 4; module.exports = webpackAsyncContext; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 442 bytes 0 [emitted] chunk-bar-baz0 1.output.js 436 bytes 1 [emitted] chunk-bar-baz2 2.output.js 433 bytes 2 [emitted] chunk-foo output.js 9.46 KiB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (chunk-bar-baz0) 38 bytes <{3}> [rendered] > ./bar [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar > ./bar.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar.js [1] ./templates/bar.js 38 bytes {0} [optional] [built] [exports: default] context element ./bar [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar context element ./bar.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar.js chunk {1} 1.output.js (chunk-bar-baz2) 38 bytes <{3}> [rendered] > ./baz [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz > ./baz.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz.js [2] ./templates/baz.js 38 bytes {1} [optional] [built] [exports: default] context element ./baz [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz context element ./baz.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz.js chunk {2} 2.output.js (chunk-foo) 38 bytes <{3}> [rendered] > ./templates/foo [3] ./example.js 1:0-62 > [3] ./example.js 5:0-8:16 [0] ./templates/foo.js 38 bytes {2} [built] [exports: default] import() ./templates/foo [3] ./example.js 1:0-62 cjs require ./templates/foo [3] ./example.js 6:11-37 chunk {3} output.js (main) 565 bytes >{0}< >{1}< >{2}< [entry] [rendered] > ./example.js main [3] ./example.js 405 bytes {3} [built] single entry ./example.js main [4] ./templates lazy ^\.\/ba.*$ namespace object 160 bytes {3} [built] import() context lazy ./templates [3] ./example.js 11:0-84 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 114 bytes 0 [emitted] chunk-bar-baz0 1.output.js 115 bytes 1 [emitted] chunk-bar-baz2 2.output.js 113 bytes 2 [emitted] chunk-foo output.js 2.51 KiB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (chunk-bar-baz0) 38 bytes <{3}> [rendered] > ./bar [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar > ./bar.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar.js [1] ./templates/bar.js 38 bytes {0} [optional] [built] [exports: default] context element ./bar [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar context element ./bar.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./bar.js chunk {1} 1.output.js (chunk-bar-baz2) 38 bytes <{3}> [rendered] > ./baz [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz > ./baz.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz.js [2] ./templates/baz.js 38 bytes {1} [optional] [built] [exports: default] context element ./baz [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz context element ./baz.js [4] ./templates lazy ^\.\/ba.*$ namespace object ./baz.js chunk {2} 2.output.js (chunk-foo) 38 bytes <{3}> [rendered] > ./templates/foo [3] ./example.js 1:0-62 > [3] ./example.js 5:0-8:16 [0] ./templates/foo.js 38 bytes {2} [built] [exports: default] import() ./templates/foo [3] ./example.js 1:0-62 cjs require ./templates/foo [3] ./example.js 6:11-37 chunk {3} output.js (main) 565 bytes >{0}< >{1}< >{2}< [entry] [rendered] > ./example.js main [3] ./example.js 405 bytes {3} [built] single entry ./example.js main [4] ./templates lazy ^\.\/ba.*$ namespace object 160 bytes {3} [built] import() context lazy ./templates [3] ./example.js 11:0-84 ``` webpack-4.30.0/examples/code-splitting-specify-chunk-name/build.js000066400000000000000000000000341345416772700251130ustar00rootroot00000000000000require("../build-common"); webpack-4.30.0/examples/code-splitting-specify-chunk-name/example.js000066400000000000000000000006251345416772700254550ustar00rootroot00000000000000import("./templates/foo" /* webpackChunkName: "chunk-foo" */ ).then(function(foo) { console.log('foo:', foo); }) require.ensure([], function(require) { var foo = require("./templates/foo"); console.log('foo:', foo); }, "chunk-foo1"); var createContextVar = "r"; import("./templates/ba" + createContextVar /* webpackChunkName: "chunk-bar-baz" */ ).then(function(bar) { console.log('bar:', bar); }) webpack-4.30.0/examples/code-splitting-specify-chunk-name/template.md000066400000000000000000000007231345416772700256200ustar00rootroot00000000000000# example.js This example illustrates how to specify chunk name in `require.ensure()` and `import()` to separated modules into separate chunks manually. ```javascript _{{example.js}}_ ``` # templates/ - foo.js - baz.js - bar.js All templates are of this pattern: ```javascript _{{templates/foo.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitting-specify-chunk-name/templates/000077500000000000000000000000001345416772700254575ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting-specify-chunk-name/templates/bar.js000066400000000000000000000000461345416772700265610ustar00rootroot00000000000000var bar = "bar"; export default bar; webpack-4.30.0/examples/code-splitting-specify-chunk-name/templates/baz.js000066400000000000000000000000461345416772700265710ustar00rootroot00000000000000var baz = "baz"; export default baz; webpack-4.30.0/examples/code-splitting-specify-chunk-name/templates/foo.js000066400000000000000000000000461345416772700266000ustar00rootroot00000000000000var foo = "foo"; export default foo; webpack-4.30.0/examples/code-splitting-specify-chunk-name/webpack.config.js000066400000000000000000000002251345416772700266760ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/code-splitting/000077500000000000000000000000001345416772700177755ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting/README.md000066400000000000000000000272471345416772700212700ustar00rootroot00000000000000This example illustrates a very simple case of Code Splitting with `require.ensure`. - `a` and `b` are required normally via CommonJS - `c` is depended through the `require.ensure` array. - This means: make it available, but don't execute it - webpack will load it on demand - `b` and `d` are required via CommonJs in the `require.ensure` callback - webpack detects that these are in the on-demand-callback and - will load them on demand - webpacks optimizer can optimize `b` away - as it is already available through the parent chunks You can see that webpack outputs two files/chunks: - `output.js` is the entry chunk and contains - the module system - chunk loading logic - the entry point `example.js` - module `a` - module `b` - `1.output.js` is an additional chunk (on demand loaded) and contains - module `c` - module `d` You can see that chunks are loaded via JSONP. The additional chunks are pretty small and minimize well. # example.js ```javascript var a = require("a"); var b = require("b"); require.ensure(["c"], function(require) { require("b").xyz(); var d = require("d"); }); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!***************************!*\ !*** ./node_modules/b.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module b /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var a = __webpack_require__(/*! a */ 2); var b = __webpack_require__(/*! b */ 0); __webpack_require__.e(/*! require.ensure */ 1).then((function(require) { __webpack_require__(/*! b */ 0).xyz(); var d = __webpack_require__(/*! d */ 4); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }), /* 2 */ /*!***************************!*\ !*** ./node_modules/a.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module a /***/ }) /******/ ]); ``` # dist/1.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */, /* 1 */, /* 2 */, /* 3 */ /*!***************************!*\ !*** ./node_modules/c.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module c /***/ }), /* 4 */ /*!***************************!*\ !*** ./node_modules/d.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module d /***/ }) ]]); ``` Minimized ```javascript (window.webpackJsonp=window.webpackJsonp||[]).push([[1],[,,,function(n,o){},function(n,o){}]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 490 bytes 1 [emitted] output.js 8.69 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 161 bytes >{1}< [entry] [rendered] > ./example.js main [1] ./example.js 139 bytes {0} [built] single entry ./example.js main + 2 hidden modules chunk {1} 1.output.js 22 bytes <{0}> [rendered] > [1] ./example.js 3:0-6:2 2 modules ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 95 bytes 1 [emitted] output.js 2.05 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 161 bytes >{1}< [entry] [rendered] > ./example.js main [1] ./example.js 139 bytes {0} [built] single entry ./example.js main + 2 hidden modules chunk {1} 1.output.js 22 bytes <{0}> [rendered] > [1] ./example.js 3:0-6:2 2 modules ``` webpack-4.30.0/examples/code-splitting/build.js000066400000000000000000000000331345416772700214260ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/code-splitting/example.js000066400000000000000000000002131345416772700217620ustar00rootroot00000000000000var a = require("a"); var b = require("b"); require.ensure(["c"], function(require) { require("b").xyz(); var d = require("d"); });webpack-4.30.0/examples/code-splitting/node_modules/000077500000000000000000000000001345416772700224525ustar00rootroot00000000000000webpack-4.30.0/examples/code-splitting/node_modules/a.js000066400000000000000000000000131345416772700232220ustar00rootroot00000000000000// module awebpack-4.30.0/examples/code-splitting/node_modules/b.js000066400000000000000000000000131345416772700232230ustar00rootroot00000000000000// module bwebpack-4.30.0/examples/code-splitting/node_modules/c.js000066400000000000000000000000131345416772700232240ustar00rootroot00000000000000// module cwebpack-4.30.0/examples/code-splitting/node_modules/d.js000066400000000000000000000000131345416772700232250ustar00rootroot00000000000000// module dwebpack-4.30.0/examples/code-splitting/template.md000066400000000000000000000024221345416772700221320ustar00rootroot00000000000000This example illustrates a very simple case of Code Splitting with `require.ensure`. - `a` and `b` are required normally via CommonJS - `c` is depended through the `require.ensure` array. - This means: make it available, but don't execute it - webpack will load it on demand - `b` and `d` are required via CommonJs in the `require.ensure` callback - webpack detects that these are in the on-demand-callback and - will load them on demand - webpacks optimizer can optimize `b` away - as it is already available through the parent chunks You can see that webpack outputs two files/chunks: - `output.js` is the entry chunk and contains - the module system - chunk loading logic - the entry point `example.js` - module `a` - module `b` - `1.output.js` is an additional chunk (on demand loaded) and contains - module `c` - module `d` You can see that chunks are loaded via JSONP. The additional chunks are pretty small and minimize well. # example.js ```javascript _{{example.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/1.output.js ```javascript _{{dist/1.output.js}}_ ``` Minimized ```javascript _{{production:dist/1.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/code-splitting/webpack.config.js000066400000000000000000000002251345416772700232120ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/coffee-script/000077500000000000000000000000001345416772700176015ustar00rootroot00000000000000webpack-4.30.0/examples/coffee-script/README.md000066400000000000000000000136771345416772700210760ustar00rootroot00000000000000# example.js ```javascript console.log(require("./cup1")); ``` # cup1.coffee ```coffee-script module.exports = cool: "stuff" answer: 42 external: require "./cup2.coffee" again: require "./cup2" ``` # cup2.coffee ```coffee-script console.log "yeah coffee-script" module.exports = 42 ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { console.log(__webpack_require__(/*! ./cup1 */ 1)); /***/ }), /* 1 */ /*!*********************!*\ !*** ./cup1.coffee ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { cool: "stuff", answer: 42, external: __webpack_require__(/*! ./cup2.coffee */ 2), again: __webpack_require__(/*! ./cup2 */ 2) }; /***/ }), /* 2 */ /*!*********************!*\ !*** ./cup2.coffee ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports) { console.log("yeah coffee-script"); module.exports = 42; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 4.31 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 206 bytes [entry] [rendered] > ./example.js main [0] ./example.js 31 bytes {0} [built] single entry ./example.js main [1] ./cup1.coffee 118 bytes {0} [built] cjs require ./cup1 [0] ./example.js 1:12-29 [2] ./cup2.coffee 57 bytes {0} [built] cjs require ./cup2.coffee [1] ./cup1.coffee 4:12-36 cjs require ./cup2 [1] ./cup1.coffee 5:9-26 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.07 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 206 bytes [entry] [rendered] > ./example.js main [0] ./cup2.coffee 57 bytes {0} [built] cjs require ./cup2.coffee [2] ./cup1.coffee 4:12-36 cjs require ./cup2 [2] ./cup1.coffee 5:9-26 [1] ./example.js 31 bytes {0} [built] single entry ./example.js main [2] ./cup1.coffee 118 bytes {0} [built] cjs require ./cup1 [1] ./example.js 1:12-29 ``` webpack-4.30.0/examples/coffee-script/build.js000066400000000000000000000000331345416772700212320ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/coffee-script/cup1.coffee000066400000000000000000000001471345416772700216240ustar00rootroot00000000000000module.exports = cool: "stuff" answer: 42 external: require "./cup2.coffee" again: require "./cup2"webpack-4.30.0/examples/coffee-script/cup2.coffee000066400000000000000000000000661345416772700216250ustar00rootroot00000000000000console.log "yeah coffee-script" module.exports = 42 webpack-4.30.0/examples/coffee-script/example.js000066400000000000000000000000371345416772700215720ustar00rootroot00000000000000console.log(require("./cup1"));webpack-4.30.0/examples/coffee-script/template.md000066400000000000000000000004741345416772700217430ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # cup1.coffee ```coffee-script _{{cup1.coffee}}_ ``` # cup2.coffee ```coffee-script _{{cup2.coffee}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/coffee-script/webpack.config.js000066400000000000000000000003431345416772700230170ustar00rootroot00000000000000module.exports = { // mode: "development || "production", module: { rules: [ { test: /\.coffee$/, loader: "coffee-loader" } ] }, resolve: { extensions: [".web.coffee", ".web.js", ".coffee", ".js"] } }; webpack-4.30.0/examples/common-chunk-and-vendor-chunk/000077500000000000000000000000001345416772700226075ustar00rootroot00000000000000webpack-4.30.0/examples/common-chunk-and-vendor-chunk/README.md000066400000000000000000000670201345416772700240730ustar00rootroot00000000000000This example shows how to create an explicit vendor chunk as well as a common chunk for code shared among entry points. In this example, we have 3 entry points: `pageA`, `pageB`, and `pageC`. Those entry points share some of the same utility modules, but not others. This configuration will pull out any modules common to at least 2 bundles and place it in the `common` bundle instead, all while keeping the specified vendor libraries in their own bundle by themselves. To better understand, here are the entry points and which utility modules they depend on: - `pageA` - `utility1` - `utility2` - `pageB` - `utility2` - `utility3` - `pageC` - `utility2` - `utility3` Given this configuration, webpack will produce the following bundles: - `vendor` - webpack runtime - `vendor1` - `vendor2` - `common` - `utility2` - `utility3` - `pageA` - `pageA` - `utility1` - `pageB` - `pageB` - `pageC` - `pageC` With this bundle configuration, you would load your third party libraries, then your common application code, then your page-specific application code. # webpack.config.js ```javascript var path = require("path"); module.exports = { // mode: "development" || "production", entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, optimization: { splitChunks: { cacheGroups: { commons: { chunks: "initial", minChunks: 2, maxInitialRequests: 5, // The default limit is too small to showcase the effect minSize: 0 // This is example is too small to create commons chunks }, vendor: { test: /node_modules/, chunks: "initial", name: "vendor", priority: 10, enforce: true } } } }, output: { path: path.join(__dirname, "dist"), filename: "[name].js" } }; ``` # dist/vendor.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],{ /***/ 1: /*!*********************************!*\ !*** ./node_modules/vendor1.js ***! \*********************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "vendor1"; /***/ }), /***/ 5: /*!*********************************!*\ !*** ./node_modules/vendor2.js ***! \*********************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "vendor2"; /***/ }) }]); ``` # dist/commons~pageA~pageB~pageC.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[2],{ /***/ 3: /*!*********************!*\ !*** ./utility2.js ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "utility2"; /***/ }) }]); ``` # dist/commons~pageB~pageC.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[4],{ /***/ 6: /*!*********************!*\ !*** ./utility3.js ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "utility3"; /***/ }) }]); ``` # dist/pageA.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ // add entry modules from loaded chunk to deferred list /******/ deferredModules.push.apply(deferredModules, executeModules || []); /******/ /******/ // run deferred modules when all chunks ready /******/ return checkDeferredModules(); /******/ }; /******/ function checkDeferredModules() { /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ } /******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ var deferredModules = []; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // add entry module to deferred list /******/ deferredModules.push([0,1,2]); /******/ // run deferred modules when ready /******/ return checkDeferredModules(); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var vendor1 = __webpack_require__(/*! vendor1 */ 1); var utility1 = __webpack_require__(/*! ./utility1 */ 2); var utility2 = __webpack_require__(/*! ./utility2 */ 3); module.exports = "pageA"; /***/ }), /* 1 */, /* 2 */ /*!*********************!*\ !*** ./utility1.js ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "utility1"; /***/ }) /******/ ]); ``` # dist/pageB.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ // add entry modules from loaded chunk to deferred list /******/ deferredModules.push.apply(deferredModules, executeModules || []); /******/ /******/ // run deferred modules when all chunks ready /******/ return checkDeferredModules(); /******/ }; /******/ function checkDeferredModules() { /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ } /******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ var deferredModules = []; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // add entry module to deferred list /******/ deferredModules.push([4,1,2,4]); /******/ // run deferred modules when ready /******/ return checkDeferredModules(); /******/ }) /************************************************************************/ /******/ ({ /***/ 4: /*!******************!*\ !*** ./pageB.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var vendor2 = __webpack_require__(/*! vendor2 */ 5); var utility2 = __webpack_require__(/*! ./utility2 */ 3); var utility3 = __webpack_require__(/*! ./utility3 */ 6); module.exports = "pageB"; /***/ }) /******/ }); ``` # dist/pageC.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ // add entry modules from loaded chunk to deferred list /******/ deferredModules.push.apply(deferredModules, executeModules || []); /******/ /******/ // run deferred modules when all chunks ready /******/ return checkDeferredModules(); /******/ }; /******/ function checkDeferredModules() { /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ } /******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 5: 0 /******/ }; /******/ /******/ var deferredModules = []; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // add entry module to deferred list /******/ deferredModules.push([7,2,4]); /******/ // run deferred modules when ready /******/ return checkDeferredModules(); /******/ }) /************************************************************************/ /******/ ({ /***/ 7: /*!******************!*\ !*** ./pageC.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var utility2 = __webpack_require__(/*! ./utility2 */ 3); var utility3 = __webpack_require__(/*! ./utility3 */ 6); module.exports = "pageC"; /***/ }) /******/ }); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names commons~pageA~pageB~pageC.js 269 bytes 2 [emitted] commons~pageA~pageB~pageC commons~pageB~pageC.js 269 bytes 4 [emitted] commons~pageB~pageC pageA.js 6.7 KiB 0 [emitted] pageA pageB.js 6.5 KiB 3 [emitted] pageB pageC.js 6.45 KiB 5 [emitted] pageC vendor.js 536 bytes 1 [emitted] vendor Entrypoint pageA = vendor.js commons~pageA~pageB~pageC.js pageA.js Entrypoint pageB = vendor.js commons~pageA~pageB~pageC.js commons~pageB~pageC.js pageB.js Entrypoint pageC = commons~pageA~pageB~pageC.js commons~pageB~pageC.js pageC.js chunk {0} pageA.js (pageA) 165 bytes ={1}= ={2}= [entry] [rendered] > ./pageA pageA [0] ./pageA.js 137 bytes {0} [built] single entry ./pageA pageA [2] ./utility1.js 28 bytes {0} [built] cjs require ./utility1 [0] ./pageA.js 2:15-36 chunk {1} vendor.js (vendor) 54 bytes ={0}= ={2}= ={3}= ={4}= [initial] [rendered] split chunk (cache group: vendor) (name: vendor) > ./pageA pageA > ./pageB pageB 2 modules chunk {2} commons~pageA~pageB~pageC.js (commons~pageA~pageB~pageC) 28 bytes ={0}= ={1}= ={3}= ={4}= ={5}= [initial] [rendered] split chunk (cache group: commons) (name: commons~pageA~pageB~pageC) > ./pageA pageA > ./pageB pageB > ./pageC pageC [3] ./utility2.js 28 bytes {2} [built] cjs require ./utility2 [0] ./pageA.js 3:15-36 cjs require ./utility2 [4] ./pageB.js 2:15-36 cjs require ./utility2 [7] ./pageC.js 1:15-36 chunk {3} pageB.js (pageB) 137 bytes ={1}= ={2}= ={4}= [entry] [rendered] > ./pageB pageB [4] ./pageB.js 137 bytes {3} [built] single entry ./pageB pageB chunk {4} commons~pageB~pageC.js (commons~pageB~pageC) 28 bytes ={1}= ={2}= ={3}= ={5}= [initial] [rendered] split chunk (cache group: commons) (name: commons~pageB~pageC) > ./pageB pageB > ./pageC pageC [6] ./utility3.js 28 bytes {4} [built] cjs require ./utility3 [4] ./pageB.js 3:15-36 cjs require ./utility3 [7] ./pageC.js 2:15-36 chunk {5} pageC.js (pageC) 102 bytes ={2}= ={4}= [entry] [rendered] > ./pageC pageC [7] ./pageC.js 102 bytes {5} [built] single entry ./pageC pageC ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names commons~pageA~pageB~pageC.js 96 bytes 0 [emitted] commons~pageA~pageB~pageC commons~pageB~pageC.js 97 bytes 1 [emitted] commons~pageB~pageC pageA.js 1.52 KiB 3 [emitted] pageA pageB.js 1.49 KiB 4 [emitted] pageB pageC.js 1.48 KiB 5 [emitted] pageC vendor.js 134 bytes 2 [emitted] vendor Entrypoint pageA = vendor.js commons~pageA~pageB~pageC.js pageA.js Entrypoint pageB = vendor.js commons~pageA~pageB~pageC.js commons~pageB~pageC.js pageB.js Entrypoint pageC = commons~pageA~pageB~pageC.js commons~pageB~pageC.js pageC.js chunk {0} commons~pageA~pageB~pageC.js (commons~pageA~pageB~pageC) 28 bytes ={1}= ={2}= ={3}= ={4}= ={5}= [initial] [rendered] split chunk (cache group: commons) (name: commons~pageA~pageB~pageC) > ./pageA pageA > ./pageB pageB > ./pageC pageC [0] ./utility2.js 28 bytes {0} [built] cjs require ./utility2 [2] ./pageA.js 3:15-36 cjs require ./utility2 [5] ./pageB.js 2:15-36 cjs require ./utility2 [7] ./pageC.js 1:15-36 chunk {1} commons~pageB~pageC.js (commons~pageB~pageC) 28 bytes ={0}= ={2}= ={4}= ={5}= [initial] [rendered] split chunk (cache group: commons) (name: commons~pageB~pageC) > ./pageB pageB > ./pageC pageC [1] ./utility3.js 28 bytes {1} [built] cjs require ./utility3 [5] ./pageB.js 3:15-36 cjs require ./utility3 [7] ./pageC.js 2:15-36 chunk {2} vendor.js (vendor) 54 bytes ={0}= ={1}= ={3}= ={4}= [initial] [rendered] split chunk (cache group: vendor) (name: vendor) > ./pageA pageA > ./pageB pageB 2 modules chunk {3} pageA.js (pageA) 165 bytes ={0}= ={2}= [entry] [rendered] > ./pageA pageA [2] ./pageA.js 137 bytes {3} [built] single entry ./pageA pageA [4] ./utility1.js 28 bytes {3} [built] cjs require ./utility1 [2] ./pageA.js 2:15-36 chunk {4} pageB.js (pageB) 137 bytes ={0}= ={1}= ={2}= [entry] [rendered] > ./pageB pageB [5] ./pageB.js 137 bytes {4} [built] single entry ./pageB pageB chunk {5} pageC.js (pageC) 102 bytes ={0}= ={1}= [entry] [rendered] > ./pageC pageC [7] ./pageC.js 102 bytes {5} [built] single entry ./pageC pageC ``` webpack-4.30.0/examples/common-chunk-and-vendor-chunk/build.js000066400000000000000000000000721345416772700242430ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/common-chunk-and-vendor-chunk/node_modules/000077500000000000000000000000001345416772700252645ustar00rootroot00000000000000webpack-4.30.0/examples/common-chunk-and-vendor-chunk/node_modules/vendor1.js000066400000000000000000000000331345416772700271740ustar00rootroot00000000000000module.exports = "vendor1";webpack-4.30.0/examples/common-chunk-and-vendor-chunk/node_modules/vendor2.js000066400000000000000000000000331345416772700271750ustar00rootroot00000000000000module.exports = "vendor2";webpack-4.30.0/examples/common-chunk-and-vendor-chunk/pageA.js000066400000000000000000000002111345416772700241540ustar00rootroot00000000000000var vendor1 = require('vendor1'); var utility1 = require('./utility1'); var utility2 = require('./utility2'); module.exports = "pageA"; webpack-4.30.0/examples/common-chunk-and-vendor-chunk/pageB.js000066400000000000000000000002111345416772700241550ustar00rootroot00000000000000var vendor2 = require('vendor2'); var utility2 = require('./utility2'); var utility3 = require('./utility3'); module.exports = "pageB"; webpack-4.30.0/examples/common-chunk-and-vendor-chunk/pageC.js000066400000000000000000000001461345416772700241650ustar00rootroot00000000000000var utility2 = require('./utility2'); var utility3 = require('./utility3'); module.exports = "pageC";webpack-4.30.0/examples/common-chunk-and-vendor-chunk/template.md000066400000000000000000000031711345416772700247460ustar00rootroot00000000000000This example shows how to create an explicit vendor chunk as well as a common chunk for code shared among entry points. In this example, we have 3 entry points: `pageA`, `pageB`, and `pageC`. Those entry points share some of the same utility modules, but not others. This configuration will pull out any modules common to at least 2 bundles and place it in the `common` bundle instead, all while keeping the specified vendor libraries in their own bundle by themselves. To better understand, here are the entry points and which utility modules they depend on: - `pageA` - `utility1` - `utility2` - `pageB` - `utility2` - `utility3` - `pageC` - `utility2` - `utility3` Given this configuration, webpack will produce the following bundles: - `vendor` - webpack runtime - `vendor1` - `vendor2` - `common` - `utility2` - `utility3` - `pageA` - `pageA` - `utility1` - `pageB` - `pageB` - `pageC` - `pageC` With this bundle configuration, you would load your third party libraries, then your common application code, then your page-specific application code. # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/vendor.js ```javascript _{{dist/vendor.js}}_ ``` # dist/commons~pageA~pageB~pageC.js ```javascript _{{dist/commons~pageA~pageB~pageC.js}}_ ``` # dist/commons~pageB~pageC.js ```javascript _{{dist/commons~pageB~pageC.js}}_ ``` # dist/pageA.js ```javascript _{{dist/pageA.js}}_ ``` # dist/pageB.js ```javascript _{{dist/pageB.js}}_ ``` # dist/pageC.js ```javascript _{{dist/pageC.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/common-chunk-and-vendor-chunk/utility1.js000066400000000000000000000000341345416772700247260ustar00rootroot00000000000000module.exports = "utility1";webpack-4.30.0/examples/common-chunk-and-vendor-chunk/utility2.js000066400000000000000000000000341345416772700247270ustar00rootroot00000000000000module.exports = "utility2";webpack-4.30.0/examples/common-chunk-and-vendor-chunk/utility3.js000066400000000000000000000000341345416772700247300ustar00rootroot00000000000000module.exports = "utility3";webpack-4.30.0/examples/common-chunk-and-vendor-chunk/webpack.config.js000066400000000000000000000012231345416772700260230ustar00rootroot00000000000000var path = require("path"); module.exports = { // mode: "development" || "production", entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, optimization: { splitChunks: { cacheGroups: { commons: { chunks: "initial", minChunks: 2, maxInitialRequests: 5, // The default limit is too small to showcase the effect minSize: 0 // This is example is too small to create commons chunks }, vendor: { test: /node_modules/, chunks: "initial", name: "vendor", priority: 10, enforce: true } } } }, output: { path: path.join(__dirname, "dist"), filename: "[name].js" } }; webpack-4.30.0/examples/common-chunk-grandchildren/000077500000000000000000000000001345416772700222505ustar00rootroot00000000000000webpack-4.30.0/examples/common-chunk-grandchildren/README.md000066400000000000000000000372551345416772700235430ustar00rootroot00000000000000This example illustrates how common modules from deep ancestors of an entry point can be split into a separate common chunk - `pageA` and `pageB` are dynamically required - `pageC` and `pageA` both require the `reusableComponent` - `pageB` dynamically requires `PageC` You can see that webpack outputs five files/chunks: - `output.js` is the entry chunk and contains - the module system - chunk loading logic - the entry point `example.js` - `0.output.js` is an additional chunk - module `reusableComponent` - `1.output.js` is an additional chunk - module `pageB` - `2.output.js` is an additional chunk - module `pageA` - `3.output.js` is an additional chunk - module `pageC` # example.js ```javascript var main = function() { console.log("Main class"); require.ensure([], () => { const page = require("./pageA"); page(); }); require.ensure([], () => { const page = require("./pageB"); page(); }); }; main(); ``` # pageA.js ```javascript var reusableComponent = require("./reusableComponent"); module.exports = function() { console.log("Page A"); reusableComponent(); }; ``` # pageB.js ```javascript module.exports = function() { console.log("Page B"); require.ensure([], ()=>{ const page = require("./pageC"); page(); }); }; ``` # pageC.js ```javascript var reusableComponent = require("./reusableComponent"); module.exports = function() { console.log("Page C"); reusableComponent(); }; ``` # reusableComponent.js ```javascript module.exports = function() { console.log("reusable Component"); }; ``` # webpack.config.js ```javascript "use strict"; const path = require("path"); module.exports = { // mode: "development || "production", entry: { main: ["./example.js"] }, optimization: { splitChunks: { minSize: 0 // This example is too small, in practice you can use the defaults }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) }, output: { path: path.resolve(__dirname, "dist"), filename: "output.js" } }; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!**************************!*\ !*** multi ./example.js ***! \**************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./example.js */1); /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var main = function() { console.log("Main class"); Promise.all(/*! require.ensure */[__webpack_require__.e(0), __webpack_require__.e(2)]).then((() => { const page = __webpack_require__(/*! ./pageA */ 2); page(); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); __webpack_require__.e(/*! require.ensure */ 3).then((() => { const page = __webpack_require__(/*! ./pageB */ 3); page(); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); }; main(); /***/ }) /******/ ]); ``` # dist/0.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{ /***/ 4: /*!******************************!*\ !*** ./reusableComponent.js ***! \******************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { console.log("reusable Component"); }; /***/ }) }]); ``` # dist/2.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[2],{ /***/ 2: /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var reusableComponent = __webpack_require__(/*! ./reusableComponent */ 4); module.exports = function() { console.log("Page A"); reusableComponent(); }; /***/ }) }]); ``` # dist/3.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[3],{ /***/ 3: /*!******************!*\ !*** ./pageB.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = function() { console.log("Page B"); Promise.all(/*! require.ensure */[__webpack_require__.e(0), __webpack_require__.e(4)]).then((()=>{ const page = __webpack_require__(/*! ./pageC */ 5); page(); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); }; /***/ }) }]); ``` # dist/4.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[4],{ /***/ 5: /*!******************!*\ !*** ./pageC.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var reusableComponent = __webpack_require__(/*! ./reusableComponent */ 4); module.exports = function() { console.log("Page C"); reusableComponent(); }; /***/ }) }]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 337 bytes 0 [emitted] 2.output.js 408 bytes 2 [emitted] 3.output.js 542 bytes 3 [emitted] 4.output.js 408 bytes 4 [emitted] output.js 8.74 KiB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 69 bytes <{1}> <{3}> ={2}= ={4}= [rendered] split chunk (cache group: default) > [1] ./example.js 3:1-6:3 > [3] ./pageB.js 3:1-6:3 [4] ./reusableComponent.js 69 bytes {0} [built] cjs require ./reusableComponent [2] ./pageA.js 1:24-54 cjs require ./reusableComponent [5] ./pageC.js 1:24-54 chunk {1} output.js (main) 248 bytes >{0}< >{2}< >{3}< [entry] [rendered] > main [0] multi ./example.js 28 bytes {1} [built] multi entry [1] ./example.js 220 bytes {1} [built] single entry ./example.js [0] multi ./example.js main[0] chunk {2} 2.output.js 136 bytes <{1}> ={0}= [rendered] > [1] ./example.js 3:1-6:3 [2] ./pageA.js 136 bytes {2} [built] cjs require ./pageA [1] ./example.js 4:15-33 chunk {3} 3.output.js 133 bytes <{1}> >{0}< >{4}< [rendered] > [1] ./example.js 7:1-10:3 [3] ./pageB.js 133 bytes {3} [built] cjs require ./pageB [1] ./example.js 8:15-33 chunk {4} 4.output.js 136 bytes <{3}> ={0}= [rendered] > [3] ./pageB.js 3:1-6:3 [5] ./pageC.js 136 bytes {4} [built] cjs require ./pageC [3] ./pageB.js 4:15-33 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 133 bytes 0 [emitted] 2.output.js 138 bytes 2 [emitted] 3.output.js 198 bytes 3 [emitted] 4.output.js 138 bytes 4 [emitted] output.js 2.13 KiB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 69 bytes <{1}> <{3}> ={2}= ={4}= [rendered] split chunk (cache group: default) > [1] ./example.js 3:1-6:3 > [3] ./pageB.js 3:1-6:3 [4] ./reusableComponent.js 69 bytes {0} [built] cjs require ./reusableComponent [2] ./pageA.js 1:24-54 cjs require ./reusableComponent [5] ./pageC.js 1:24-54 chunk {1} output.js (main) 248 bytes >{0}< >{2}< >{3}< [entry] [rendered] > main [0] multi ./example.js 28 bytes {1} [built] multi entry [1] ./example.js 220 bytes {1} [built] single entry ./example.js [0] multi ./example.js main[0] chunk {2} 2.output.js 136 bytes <{1}> ={0}= [rendered] > [1] ./example.js 3:1-6:3 [2] ./pageA.js 136 bytes {2} [built] cjs require ./pageA [1] ./example.js 4:15-33 chunk {3} 3.output.js 133 bytes <{1}> >{0}< >{4}< [rendered] > [1] ./example.js 7:1-10:3 [3] ./pageB.js 133 bytes {3} [built] cjs require ./pageB [1] ./example.js 8:15-33 chunk {4} 4.output.js 136 bytes <{3}> ={0}= [rendered] > [3] ./pageB.js 3:1-6:3 [5] ./pageC.js 136 bytes {4} [built] cjs require ./pageC [3] ./pageB.js 4:15-33 ``` webpack-4.30.0/examples/common-chunk-grandchildren/build.js000066400000000000000000000000721345416772700237040ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/common-chunk-grandchildren/example.js000066400000000000000000000003341345416772700242410ustar00rootroot00000000000000var main = function() { console.log("Main class"); require.ensure([], () => { const page = require("./pageA"); page(); }); require.ensure([], () => { const page = require("./pageB"); page(); }); }; main(); webpack-4.30.0/examples/common-chunk-grandchildren/pageA.js000066400000000000000000000002101345416772700236140ustar00rootroot00000000000000var reusableComponent = require("./reusableComponent"); module.exports = function() { console.log("Page A"); reusableComponent(); }; webpack-4.30.0/examples/common-chunk-grandchildren/pageB.js000066400000000000000000000002051345416772700236210ustar00rootroot00000000000000module.exports = function() { console.log("Page B"); require.ensure([], ()=>{ const page = require("./pageC"); page(); }); }; webpack-4.30.0/examples/common-chunk-grandchildren/pageC.js000066400000000000000000000002101345416772700236160ustar00rootroot00000000000000var reusableComponent = require("./reusableComponent"); module.exports = function() { console.log("Page C"); reusableComponent(); }; webpack-4.30.0/examples/common-chunk-grandchildren/reusableComponent.js000066400000000000000000000001051345416772700262670ustar00rootroot00000000000000module.exports = function() { console.log("reusable Component"); }; webpack-4.30.0/examples/common-chunk-grandchildren/template.md000066400000000000000000000026141345416772700244100ustar00rootroot00000000000000This example illustrates how common modules from deep ancestors of an entry point can be split into a separate common chunk - `pageA` and `pageB` are dynamically required - `pageC` and `pageA` both require the `reusableComponent` - `pageB` dynamically requires `PageC` You can see that webpack outputs five files/chunks: - `output.js` is the entry chunk and contains - the module system - chunk loading logic - the entry point `example.js` - `0.output.js` is an additional chunk - module `reusableComponent` - `1.output.js` is an additional chunk - module `pageB` - `2.output.js` is an additional chunk - module `pageA` - `3.output.js` is an additional chunk - module `pageC` # example.js ```javascript _{{example.js}}_ ``` # pageA.js ```javascript _{{pageA.js}}_ ``` # pageB.js ```javascript _{{pageB.js}}_ ``` # pageC.js ```javascript _{{pageC.js}}_ ``` # reusableComponent.js ```javascript _{{reusableComponent.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/0.output.js ```javascript _{{dist/0.output.js}}_ ``` # dist/2.output.js ```javascript _{{dist/2.output.js}}_ ``` # dist/3.output.js ```javascript _{{dist/3.output.js}}_ ``` # dist/4.output.js ```javascript _{{dist/4.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/common-chunk-grandchildren/webpack.config.js000066400000000000000000000007101345416772700254640ustar00rootroot00000000000000"use strict"; const path = require("path"); module.exports = { // mode: "development || "production", entry: { main: ["./example.js"] }, optimization: { splitChunks: { minSize: 0 // This example is too small, in practice you can use the defaults }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) }, output: { path: path.resolve(__dirname, "dist"), filename: "output.js" } }; webpack-4.30.0/examples/commonjs/000077500000000000000000000000001345416772700166755ustar00rootroot00000000000000webpack-4.30.0/examples/commonjs/README.md000066400000000000000000000150521345416772700201570ustar00rootroot00000000000000This very simple example shows usage of CommonJS. The three files `example.js`, `increment.js` and `math.js` form a dependency chain. They use `require(dependency)` to declare dependencies. You can see the output file that webpack creates by bundling them together in one file. Keep in mind that webpack adds comments to make reading this file easier. These comments are removed when minimizing the file. You can also see the info messages webpack prints to console (for both normal and minimized build). # example.js ```javascript const inc = require('./increment').increment; const a = 1; inc(a); // 2 ``` # increment.js ```javascript const add = require('./math').add; exports.increment = function(val) { return add(val, 1); }; ``` # math.js ```javascript exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; }; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { const inc = __webpack_require__(/*! ./increment */ 1).increment; const a = 1; inc(a); // 2 /***/ }), /* 1 */ /*!**********************!*\ !*** ./increment.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { const add = __webpack_require__(/*! ./math */ 2).add; exports.increment = function(val) { return add(val, 1); }; /***/ }), /* 2 */ /*!*****************!*\ !*** ./math.js ***! \*****************/ /*! no static exports found */ /***/ (function(module, exports) { exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; }; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 4.4 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 326 bytes [entry] [rendered] > ./example.js main [0] ./example.js 72 bytes {0} [built] single entry ./example.js main [1] ./increment.js 98 bytes {0} [built] cjs require ./increment [0] ./example.js 1:12-34 [2] ./math.js 156 bytes {0} [built] cjs require ./math [1] ./increment.js 1:12-29 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.1 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 326 bytes [entry] [rendered] > ./example.js main [0] ./example.js 72 bytes {0} [built] single entry ./example.js main [1] ./increment.js 98 bytes {0} [built] cjs require ./increment [0] ./example.js 1:12-34 [2] ./math.js 156 bytes {0} [built] cjs require ./math [1] ./increment.js 1:12-29 ``` webpack-4.30.0/examples/commonjs/build.js000066400000000000000000000000331345416772700203260ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/commonjs/example.js000066400000000000000000000001101345416772700206560ustar00rootroot00000000000000const inc = require('./increment').increment; const a = 1; inc(a); // 2 webpack-4.30.0/examples/commonjs/increment.js000066400000000000000000000001421345416772700212140ustar00rootroot00000000000000const add = require('./math').add; exports.increment = function(val) { return add(val, 1); }; webpack-4.30.0/examples/commonjs/math.js000066400000000000000000000002341345416772700201630ustar00rootroot00000000000000exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; };webpack-4.30.0/examples/commonjs/template.md000066400000000000000000000014551345416772700210370ustar00rootroot00000000000000This very simple example shows usage of CommonJS. The three files `example.js`, `increment.js` and `math.js` form a dependency chain. They use `require(dependency)` to declare dependencies. You can see the output file that webpack creates by bundling them together in one file. Keep in mind that webpack adds comments to make reading this file easier. These comments are removed when minimizing the file. You can also see the info messages webpack prints to console (for both normal and minimized build). # example.js ```javascript _{{example.js}}_ ``` # increment.js ```javascript _{{increment.js}}_ ``` # math.js ```javascript _{{math.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/dll-app-and-vendor/000077500000000000000000000000001345416772700204345ustar00rootroot00000000000000webpack-4.30.0/examples/dll-app-and-vendor/0-vendor/000077500000000000000000000000001345416772700220665ustar00rootroot00000000000000webpack-4.30.0/examples/dll-app-and-vendor/0-vendor/README.md000066400000000000000000000145331345416772700233530ustar00rootroot00000000000000This is the vendor build part. It's built separately from the app part. The vendors dll is only built when the array of vendors has changed and not during the normal development cycle. The DllPlugin in combination with the `output.library` option exposes the internal require function as global variable in the target environment. A manifest is created which includes mappings from module names to internal ids. ### webpack.config.js ```javascript var path = require("path"); var webpack = require("../../../"); module.exports = { // mode: "development || "production", context: __dirname, entry: ["example-vendor"], output: { filename: "vendor.js", // best use [hash] here too path: path.resolve(__dirname, "dist"), library: "vendor_lib_[hash]" }, plugins: [ new webpack.DllPlugin({ name: "vendor_lib_[hash]", path: path.resolve(__dirname, "dist/vendor-manifest.json") }) ] }; ``` # example-vendor ```javascript export function square(n) { return n * n; } ``` # dist/vendor.js ```javascript var vendor_lib_a132d30959ef28c3f004 = ```
/******/ (function(modules) { /* webpackBootstrap */ }) ``` js /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!****************!*\ !*** dll main ***! \****************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__; /***/ }), /* 1 */ /*!*****************************************!*\ !*** ../node_modules/example-vendor.js ***! \*****************************************/ /*! exports provided: square */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "square", function() { return square; }); function square(n) { return n * n; } /***/ }) /******/ ]); ``` # dist/vendor-manifest.json ```javascript {"name":"vendor_lib_a132d30959ef28c3f004","content":{"../node_modules/example-vendor.js":{"id":1,"buildMeta":{"exportsType":"namespace","providedExports":["square"]}}}} ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names vendor.js 4.28 KiB 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 57 bytes [entry] [rendered] > main [0] dll main 12 bytes {0} [built] dll entry DllPlugin + 1 hidden module ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names vendor.js 1.06 KiB 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 57 bytes [entry] [rendered] > main [0] dll main 12 bytes {0} [built] dll entry DllPlugin + 1 hidden module ``` webpack-4.30.0/examples/dll-app-and-vendor/0-vendor/build.js000066400000000000000000000000751345416772700235250ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../../build-common"); webpack-4.30.0/examples/dll-app-and-vendor/0-vendor/template.md000066400000000000000000000014331345416772700242240ustar00rootroot00000000000000This is the vendor build part. It's built separately from the app part. The vendors dll is only built when the array of vendors has changed and not during the normal development cycle. The DllPlugin in combination with the `output.library` option exposes the internal require function as global variable in the target environment. A manifest is created which includes mappings from module names to internal ids. ### webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # example-vendor ```javascript _{{../node_modules/example-vendor.js}}_ ``` # dist/vendor.js ```javascript _{{dist/vendor.js}}_ ``` # dist/vendor-manifest.json ```javascript _{{dist/vendor-manifest.json}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/dll-app-and-vendor/0-vendor/webpack.config.js000066400000000000000000000007061345416772700253070ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../"); module.exports = { // mode: "development || "production", context: __dirname, entry: ["example-vendor"], output: { filename: "vendor.js", // best use [hash] here too path: path.resolve(__dirname, "dist"), library: "vendor_lib_[hash]" }, plugins: [ new webpack.DllPlugin({ name: "vendor_lib_[hash]", path: path.resolve(__dirname, "dist/vendor-manifest.json") }) ] }; webpack-4.30.0/examples/dll-app-and-vendor/1-app/000077500000000000000000000000001345416772700213525ustar00rootroot00000000000000webpack-4.30.0/examples/dll-app-and-vendor/1-app/README.md000066400000000000000000000201701345416772700226310ustar00rootroot00000000000000This is the app part. The previously built vendor dll is used. The DllReferencePlugin reads the content of the dll from the manifest file and excludes all vendor modules from the compilation. Instead references to these modules will be loaded from the vendor dll via a global variable (`vendor_lib_xxxx`). # webpack.config.js ```javascript var path = require("path"); var webpack = require("../../../"); module.exports = { // mode: "development" || "production", context: __dirname, entry: "./example-app", output: { filename: "app.js", path: path.resolve(__dirname, "dist") }, plugins: [ new webpack.DllReferencePlugin({ context: ".", manifest: require("../0-vendor/dist/vendor-manifest.json") // eslint-disable-line }) ] }; ``` # example-app.js ```javascript import { square } from "example-vendor"; console.log(square(7)); console.log(new square(7)); ``` # example.html ```html ``` # dist/app.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!************************!*\ !*** ./example-app.js ***! \************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var example_vendor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! example-vendor */ 1); console.log(Object(example_vendor__WEBPACK_IMPORTED_MODULE_0__["square"])(7)); console.log(new example_vendor__WEBPACK_IMPORTED_MODULE_0__["square"](7)); /***/ }), /* 1 */ /*!******************************************************************************************************!*\ !*** delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_a132d30959ef28c3f004 ***! \******************************************************************************************************/ /*! exports provided: square */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference vendor_lib_a132d30959ef28c3f004 */ 2))(1); /***/ }), /* 2 */ /*!**************************************************!*\ !*** external "vendor_lib_a132d30959ef28c3f004" ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = vendor_lib_a132d30959ef28c3f004; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names app.js 4.86 KiB 0 [emitted] main Entrypoint main = app.js chunk {0} app.js (main) 178 bytes [entry] [rendered] > ./example-app main [0] ./example-app.js 94 bytes {0} [built] [no exports] single entry ./example-app main [1] delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_a132d30959ef28c3f004 42 bytes {0} [built] [exports: square] harmony side effect evaluation example-vendor [0] ./example-app.js 1:0-40 harmony import specifier example-vendor [0] ./example-app.js 3:12-18 harmony import specifier example-vendor [0] ./example-app.js 4:16-22 [2] external "vendor_lib_a132d30959ef28c3f004" 42 bytes {0} [built] delegated source dll-reference vendor_lib_a132d30959ef28c3f004 [1] delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_a132d30959ef28c3f004 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names app.js 1.09 KiB 0 [emitted] main Entrypoint main = app.js chunk {0} app.js (main) 178 bytes [entry] [rendered] > ./example-app main [0] delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_a132d30959ef28c3f004 42 bytes {0} [built] [exports: square] harmony side effect evaluation example-vendor [1] ./example-app.js 1:0-40 harmony import specifier example-vendor [1] ./example-app.js 3:12-18 harmony import specifier example-vendor [1] ./example-app.js 4:16-22 [1] ./example-app.js 94 bytes {0} [built] [no exports] single entry ./example-app main [2] external "vendor_lib_a132d30959ef28c3f004" 42 bytes {0} [built] delegated source dll-reference vendor_lib_a132d30959ef28c3f004 [0] delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_a132d30959ef28c3f004 ``` webpack-4.30.0/examples/dll-app-and-vendor/1-app/build.js000066400000000000000000000000751345416772700230110ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../../build-common"); webpack-4.30.0/examples/dll-app-and-vendor/1-app/example-app.js000066400000000000000000000001361345416772700241210ustar00rootroot00000000000000import { square } from "example-vendor"; console.log(square(7)); console.log(new square(7)); webpack-4.30.0/examples/dll-app-and-vendor/1-app/example.html000066400000000000000000000002461345416772700236750ustar00rootroot00000000000000 webpack-4.30.0/examples/dll-app-and-vendor/1-app/template.md000066400000000000000000000013531345416772700235110ustar00rootroot00000000000000This is the app part. The previously built vendor dll is used. The DllReferencePlugin reads the content of the dll from the manifest file and excludes all vendor modules from the compilation. Instead references to these modules will be loaded from the vendor dll via a global variable (`vendor_lib_xxxx`). # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # example-app.js ```javascript _{{example-app.js}}_ ``` # example.html ```html _{{example.html}}_ ``` # dist/app.js ```javascript _{{dist/app.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/dll-app-and-vendor/1-app/webpack.config.js000066400000000000000000000006301345416772700245670ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../"); module.exports = { // mode: "development" || "production", context: __dirname, entry: "./example-app", output: { filename: "app.js", path: path.resolve(__dirname, "dist") }, plugins: [ new webpack.DllReferencePlugin({ context: ".", manifest: require("../0-vendor/dist/vendor-manifest.json") // eslint-disable-line }) ] }; webpack-4.30.0/examples/dll-app-and-vendor/README.md000066400000000000000000000006221345416772700217130ustar00rootroot00000000000000This example shows how to use the DllPlugin to separate vendor and app build. This can boost the speed of the app build because vendors are no longer included, but built separately. See [vendor part](0-vendor) and [app part](1-app). [DllPlugin documentation](https://webpack.js.org/plugins/dll-plugin) > Based on this gist: https://gist.github.com/Eoksni/83d1f1559e0ec00d0e89c33a6d763049 by Eoksni webpack-4.30.0/examples/dll-app-and-vendor/node_modules/000077500000000000000000000000001345416772700231115ustar00rootroot00000000000000webpack-4.30.0/examples/dll-app-and-vendor/node_modules/example-vendor.js000066400000000000000000000000551345416772700263750ustar00rootroot00000000000000export function square(n) { return n * n; } webpack-4.30.0/examples/dll-entry-only/000077500000000000000000000000001345416772700177415ustar00rootroot00000000000000webpack-4.30.0/examples/dll-entry-only/README.md000066400000000000000000000237041345416772700212260ustar00rootroot00000000000000# Dll scope hoisting [DllPlugin documentation](https://webpack.js.org/plugins/dll-plugin) This example demonstrates the usage of `entryOnly` option in combination with module concatenation / scope hoisting. By default `DllPlugin` exposes all the modules referenced in the bundle as separate entries. The manifest includes the individual modules available for use by `DllReferencePlugin`. Since all the modules are being accounted for, this prevents advanced optimizations such as tree shaking. The `entryOnly` flag tells `DllPlugin` to only expose the modules which are configured as entry points; this affects both the manifest and the resulting bundle. Since some of the modules are no longer included in the "public contract" of the Dll, they can be optimized by merging (concatenating) multiple modules together or removing unused code. This allows to take advantage of tree shaking (scope hoisting and dead code removal) optimizations. In this example only `example.js` module is exposed, since it's the entry point. Modules `a.js` and `b.js` are concatenated into `example.js`. Module `cjs.js` is left as is, since it's in CommonJS format. The manifest includes `example.js` as the only exposed module and lists the exports as `["a","b","c"]` from the corresponding modules `a.js`, `b.js` and `cjs.js`. None of the other modules are exposed. Also see [tree shaking](https://github.com/webpack/webpack/tree/master/examples/harmony-unused) and [scope hoisting example](https://github.com/webpack/webpack/tree/master/examples/scope-hoisting). # example.js ```javascript export { a, b } from "./a"; export { c } from "./cjs"; ``` # webpack.config.js ```javascript var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development" || "production", entry: { dll: ["./example"] }, output: { path: path.join(__dirname, "dist"), filename: "[name].js", library: "[name]_[hash]" }, optimization: { concatenateModules: true // this is enabled by default in production mode }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "dist", "[name]-manifest.json"), name: "[name]_[hash]", entryOnly: true }) ] }; ``` # dist/dll.js ```javascript var dll_3eea518f6d09aac41ec7 = ```
/******/ (function(modules) { /* webpackBootstrap */ }) ``` js /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!***************!*\ !*** dll dll ***! \***************/ /*! no static exports found */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__; /***/ }), /* 1 */ /*!****************!*\ !*** ./cjs.js ***! \****************/ /*! no static exports found */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports) { // module cjs (commonjs) exports.c = "c"; /***/ }), /* 2 */ /*!********************************!*\ !*** ./example.js + 2 modules ***! \********************************/ /*! exports provided: a, b, c */ /*! ModuleConcatenation bailout: Cannot concat with ./cjs.js (<- Module is not an ECMAScript module) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // CONCATENATED MODULE: ./b.js // module b function b() { return "b"; } // CONCATENATED MODULE: ./a.js // module a var a = "a"; // EXTERNAL MODULE: ./cjs.js var cjs = __webpack_require__(1); // CONCATENATED MODULE: ./example.js /* concated harmony reexport a */__webpack_require__.d(__webpack_exports__, "a", function() { return a; }); /* concated harmony reexport b */__webpack_require__.d(__webpack_exports__, "b", function() { return b; }); /* concated harmony reexport c */__webpack_require__.d(__webpack_exports__, "c", function() { return cjs["c"]; }); /***/ }) /******/ ]); ``` # dist/dll-manifest.json ```javascript {"name":"dll_3eea518f6d09aac41ec7","content":{"./example.js":{"id":2,"buildMeta":{"exportsType":"namespace","providedExports":["a","b","c"]}}}} ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names dll.js 5.03 KiB 0 [emitted] dll Entrypoint dll = dll.js chunk {0} dll.js (dll) 216 bytes [entry] [rendered] > dll [0] dll dll 12 bytes {0} [built] dll entry [1] ./cjs.js 42 bytes {0} [built] harmony side effect evaluation ./cjs [2] ./example.js + 2 modules 2:0-26 harmony export imported specifier ./cjs [2] ./example.js + 2 modules 2:0-26 [2] ./example.js + 2 modules 162 bytes {0} [built] [exports: a, b, c] single entry ./example [0] dll dll dll[0] | ./example.js 55 bytes [built] | [exports: a, b, c] | single entry ./example [0] dll dll dll[0] | ./a.js 53 bytes [built] | [exports: a, b] | harmony side effect evaluation ./a ./example.js 1:0-27 | harmony export imported specifier ./a ./example.js 1:0-27 | harmony export imported specifier ./a ./example.js 1:0-27 | ./b.js 49 bytes [built] | [exports: b] | harmony side effect evaluation ./b ./a.js 3:0-20 | harmony export imported specifier ./b ./a.js 3:0-20 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names dll.js 1.15 KiB 0 [emitted] dll Entrypoint dll = dll.js chunk {0} dll.js (dll) 216 bytes [entry] [rendered] > dll [0] ./cjs.js 42 bytes {0} [built] [only some exports used: c] harmony side effect evaluation ./cjs [2] ./example.js + 2 modules 2:0-26 harmony export imported specifier ./cjs [2] ./example.js + 2 modules 2:0-26 [1] dll dll 12 bytes {0} [built] dll entry [2] ./example.js + 2 modules 162 bytes {0} [built] [exports: a, b, c] single entry ./example [1] dll dll dll[0] | ./example.js 55 bytes [built] | [exports: a, b, c] | single entry ./example [1] dll dll dll[0] | ./a.js 53 bytes [built] | [exports: a, b] | [all exports used] | harmony side effect evaluation ./a ./example.js 1:0-27 | harmony export imported specifier ./a ./example.js 1:0-27 | harmony export imported specifier ./a ./example.js 1:0-27 | ./b.js 49 bytes [built] | [exports: b] | [all exports used] | harmony side effect evaluation ./b ./a.js 3:0-20 | harmony export imported specifier ./b ./a.js 3:0-20 ``` webpack-4.30.0/examples/dll-entry-only/a.js000066400000000000000000000000651345416772700205200ustar00rootroot00000000000000// module a export var a = "a"; export * from "./b"; webpack-4.30.0/examples/dll-entry-only/b.js000066400000000000000000000000611345416772700205150ustar00rootroot00000000000000// module b export function b() { return "b"; } webpack-4.30.0/examples/dll-entry-only/build.js000066400000000000000000000000721345416772700213750ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/dll-entry-only/cjs.js000066400000000000000000000000521345416772700210530ustar00rootroot00000000000000// module cjs (commonjs) exports.c = "c"; webpack-4.30.0/examples/dll-entry-only/example.js000066400000000000000000000000671345416772700217350ustar00rootroot00000000000000export { a, b } from "./a"; export { c } from "./cjs"; webpack-4.30.0/examples/dll-entry-only/template.md000066400000000000000000000035441345416772700221040ustar00rootroot00000000000000# Dll scope hoisting [DllPlugin documentation](https://webpack.js.org/plugins/dll-plugin) This example demonstrates the usage of `entryOnly` option in combination with module concatenation / scope hoisting. By default `DllPlugin` exposes all the modules referenced in the bundle as separate entries. The manifest includes the individual modules available for use by `DllReferencePlugin`. Since all the modules are being accounted for, this prevents advanced optimizations such as tree shaking. The `entryOnly` flag tells `DllPlugin` to only expose the modules which are configured as entry points; this affects both the manifest and the resulting bundle. Since some of the modules are no longer included in the "public contract" of the Dll, they can be optimized by merging (concatenating) multiple modules together or removing unused code. This allows to take advantage of tree shaking (scope hoisting and dead code removal) optimizations. In this example only `example.js` module is exposed, since it's the entry point. Modules `a.js` and `b.js` are concatenated into `example.js`. Module `cjs.js` is left as is, since it's in CommonJS format. The manifest includes `example.js` as the only exposed module and lists the exports as `["a","b","c"]` from the corresponding modules `a.js`, `b.js` and `cjs.js`. None of the other modules are exposed. Also see [tree shaking](https://github.com/webpack/webpack/tree/master/examples/harmony-unused) and [scope hoisting example](https://github.com/webpack/webpack/tree/master/examples/scope-hoisting). # example.js ```javascript _{{example.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/dll.js ```javascript _{{dist/dll.js}}_ ``` # dist/dll-manifest.json ```javascript _{{dist/dll-manifest.json}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/dll-entry-only/webpack.config.js000066400000000000000000000010041345416772700231520ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development" || "production", entry: { dll: ["./example"] }, output: { path: path.join(__dirname, "dist"), filename: "[name].js", library: "[name]_[hash]" }, optimization: { concatenateModules: true // this is enabled by default in production mode }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "dist", "[name]-manifest.json"), name: "[name]_[hash]", entryOnly: true }) ] }; webpack-4.30.0/examples/dll-user/000077500000000000000000000000001345416772700165775ustar00rootroot00000000000000webpack-4.30.0/examples/dll-user/README.md000066400000000000000000000307401345416772700200620ustar00rootroot00000000000000# DllUser [DllPlugin documentation](https://webpack.js.org/plugins/dll-plugin) This is the _user_ bundle, which uses the manifest from [dll-reference example](https://github.com/webpack/webpack/tree/master/examples/dll) # webpack.config.js ```javascript var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development || "production", plugins: [ new webpack.DllReferencePlugin({ context: path.join(__dirname, "..", "dll"), manifest: require("../dll/dist/alpha-manifest.json") // eslint-disable-line }), new webpack.DllReferencePlugin({ scope: "beta", manifest: require("../dll/dist/beta-manifest.json"), // eslint-disable-line extensions: [".js", ".jsx"] }) ] }; ``` # example.js ```javascript console.log(require("../dll/alpha")); console.log(require("../dll/a")); console.log(require("beta/beta")); console.log(require("beta/b")); console.log(require("beta/c")); console.log(require("module")); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { console.log(__webpack_require__(/*! ../dll/alpha */ 1)); console.log(__webpack_require__(/*! ../dll/a */ 3)); console.log(__webpack_require__(/*! beta/beta */ 4)); console.log(__webpack_require__(/*! beta/b */ 6)); console.log(__webpack_require__(/*! beta/c */ 7)); console.log(__webpack_require__(/*! module */ 8)); /***/ }), /* 1 */ /*!**************************************************************************!*\ !*** delegated ./alpha.js from dll-reference alpha_d61ee01b5c383d26e2c0 ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference alpha_d61ee01b5c383d26e2c0 */ 2))(1); /***/ }), /* 2 */ /*!*********************************************!*\ !*** external "alpha_d61ee01b5c383d26e2c0" ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = alpha_d61ee01b5c383d26e2c0; /***/ }), /* 3 */ /*!**********************************************************************!*\ !*** delegated ./a.js from dll-reference alpha_d61ee01b5c383d26e2c0 ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference alpha_d61ee01b5c383d26e2c0 */ 2))(2); /***/ }), /* 4 */ /*!************************************************************************!*\ !*** delegated ./beta.js from dll-reference beta_d61ee01b5c383d26e2c0 ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference beta_d61ee01b5c383d26e2c0 */ 5))(5); /***/ }), /* 5 */ /*!********************************************!*\ !*** external "beta_d61ee01b5c383d26e2c0" ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = beta_d61ee01b5c383d26e2c0; /***/ }), /* 6 */ /*!*********************************************************************!*\ !*** delegated ./b.js from dll-reference beta_d61ee01b5c383d26e2c0 ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference beta_d61ee01b5c383d26e2c0 */ 5))(6); /***/ }), /* 7 */ /*!**********************************************************************!*\ !*** delegated ./c.jsx from dll-reference beta_d61ee01b5c383d26e2c0 ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference beta_d61ee01b5c383d26e2c0 */ 5))(7); /***/ }), /* 8 */ /*!*****************************************************************************************!*\ !*** delegated ../node_modules/module.js from dll-reference alpha_d61ee01b5c383d26e2c0 ***! \*****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference alpha_d61ee01b5c383d26e2c0 */ 2))(3); /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 7.14 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 541 bytes [entry] [rendered] > ./example.js main [0] ./example.js 205 bytes {0} [built] single entry ./example.js main [1] delegated ./alpha.js from dll-reference alpha_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require ../dll/alpha [0] ./example.js 1:12-35 [2] external "alpha_d61ee01b5c383d26e2c0" 42 bytes {0} [built] delegated source dll-reference alpha_d61ee01b5c383d26e2c0 [1] delegated ./alpha.js from dll-reference alpha_d61ee01b5c383d26e2c0 delegated source dll-reference alpha_d61ee01b5c383d26e2c0 [3] delegated ./a.js from dll-reference alpha_d61ee01b5c383d26e2c0 delegated source dll-reference alpha_d61ee01b5c383d26e2c0 [8] delegated ../node_modules/module.js from dll-reference alpha_d61ee01b5c383d26e2c0 [3] delegated ./a.js from dll-reference alpha_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require ../dll/a [0] ./example.js 2:12-31 [4] delegated ./beta.js from dll-reference beta_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require beta/beta [0] ./example.js 4:12-32 [5] external "beta_d61ee01b5c383d26e2c0" 42 bytes {0} [built] delegated source dll-reference beta_d61ee01b5c383d26e2c0 [4] delegated ./beta.js from dll-reference beta_d61ee01b5c383d26e2c0 delegated source dll-reference beta_d61ee01b5c383d26e2c0 [6] delegated ./b.js from dll-reference beta_d61ee01b5c383d26e2c0 delegated source dll-reference beta_d61ee01b5c383d26e2c0 [7] delegated ./c.jsx from dll-reference beta_d61ee01b5c383d26e2c0 [6] delegated ./b.js from dll-reference beta_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require beta/b [0] ./example.js 5:12-29 [7] delegated ./c.jsx from dll-reference beta_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require beta/c [0] ./example.js 6:12-29 [8] delegated ../node_modules/module.js from dll-reference alpha_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require module [0] ./example.js 8:12-29 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.33 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 541 bytes [entry] [rendered] > ./example.js main [0] external "alpha_d61ee01b5c383d26e2c0" 42 bytes {0} [built] delegated source dll-reference alpha_d61ee01b5c383d26e2c0 [3] delegated ./alpha.js from dll-reference alpha_d61ee01b5c383d26e2c0 delegated source dll-reference alpha_d61ee01b5c383d26e2c0 [4] delegated ./a.js from dll-reference alpha_d61ee01b5c383d26e2c0 delegated source dll-reference alpha_d61ee01b5c383d26e2c0 [8] delegated ../node_modules/module.js from dll-reference alpha_d61ee01b5c383d26e2c0 [1] external "beta_d61ee01b5c383d26e2c0" 42 bytes {0} [built] delegated source dll-reference beta_d61ee01b5c383d26e2c0 [5] delegated ./beta.js from dll-reference beta_d61ee01b5c383d26e2c0 delegated source dll-reference beta_d61ee01b5c383d26e2c0 [6] delegated ./b.js from dll-reference beta_d61ee01b5c383d26e2c0 delegated source dll-reference beta_d61ee01b5c383d26e2c0 [7] delegated ./c.jsx from dll-reference beta_d61ee01b5c383d26e2c0 [2] ./example.js 205 bytes {0} [built] single entry ./example.js main [3] delegated ./alpha.js from dll-reference alpha_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require ../dll/alpha [2] ./example.js 1:12-35 [4] delegated ./a.js from dll-reference alpha_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require ../dll/a [2] ./example.js 2:12-31 [5] delegated ./beta.js from dll-reference beta_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require beta/beta [2] ./example.js 4:12-32 [6] delegated ./b.js from dll-reference beta_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require beta/b [2] ./example.js 5:12-29 [7] delegated ./c.jsx from dll-reference beta_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require beta/c [2] ./example.js 6:12-29 [8] delegated ../node_modules/module.js from dll-reference alpha_d61ee01b5c383d26e2c0 42 bytes {0} [built] cjs require module [2] ./example.js 8:12-29 ``` webpack-4.30.0/examples/dll-user/build.js000066400000000000000000000000331345416772700202300ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/dll-user/example.html000066400000000000000000000003521345416772700211200ustar00rootroot00000000000000 webpack-4.30.0/examples/dll-user/example.js000066400000000000000000000003151345416772700205670ustar00rootroot00000000000000console.log(require("../dll/alpha")); console.log(require("../dll/a")); console.log(require("beta/beta")); console.log(require("beta/b")); console.log(require("beta/c")); console.log(require("module")); webpack-4.30.0/examples/dll-user/template.md000066400000000000000000000007551345416772700207430ustar00rootroot00000000000000# DllUser [DllPlugin documentation](https://webpack.js.org/plugins/dll-plugin) This is the _user_ bundle, which uses the manifest from [dll-reference example](https://github.com/webpack/webpack/tree/master/examples/dll) # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # example.js ```javascript _{{example.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/dll-user/webpack.config.js000066400000000000000000000007311345416772700220160ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development || "production", plugins: [ new webpack.DllReferencePlugin({ context: path.join(__dirname, "..", "dll"), manifest: require("../dll/dist/alpha-manifest.json") // eslint-disable-line }), new webpack.DllReferencePlugin({ scope: "beta", manifest: require("../dll/dist/beta-manifest.json"), // eslint-disable-line extensions: [".js", ".jsx"] }) ] }; webpack-4.30.0/examples/dll/000077500000000000000000000000001345416772700156235ustar00rootroot00000000000000webpack-4.30.0/examples/dll/README.md000066400000000000000000000174061345416772700171120ustar00rootroot00000000000000# DllReference [DllPlugin documentation](https://webpack.js.org/plugins/dll-plugin) This is the _reference_ bundle (with the manifests) for [dll user example](https://github.com/webpack/webpack/tree/master/examples/dll-user) # webpack.config.js ```javascript var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development || "production", resolve: { extensions: [".js", ".jsx"] }, entry: { alpha: ["./alpha", "./a", "module"], beta: ["./beta", "./b", "./c"] }, output: { path: path.join(__dirname, "dist"), filename: "MyDll.[name].js", library: "[name]_[hash]" }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "dist", "[name]-manifest.json"), name: "[name]_[hash]" }) ] }; ``` # dist/MyDll.alpha.js ```javascript var alpha_d61ee01b5c383d26e2c0 = ```
/******/ (function(modules) { /* webpackBootstrap */ }) ``` js /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!*****************!*\ !*** dll alpha ***! \*****************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__; /***/ }), /* 1 */ /*!******************!*\ !*** ./alpha.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "alpha"; /***/ }), /* 2 */ /*!**************!*\ !*** ./a.js ***! \**************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "a"; /***/ }), /* 3 */ /*!*********************************!*\ !*** ../node_modules/module.js ***! \*********************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "module"; /***/ }) /******/ ]); ``` # dist/alpha-manifest.json ```javascript {"name":"alpha_d61ee01b5c383d26e2c0","content":{"./alpha.js":{"id":1,"buildMeta":{"providedExports":true}},"./a.js":{"id":2,"buildMeta":{"providedExports":true}},"../node_modules/module.js":{"id":3,"buildMeta":{"providedExports":true}}}} ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names MyDll.alpha.js 4.42 KiB 0 [emitted] alpha MyDll.beta.js 4.4 KiB 1 [emitted] beta Entrypoint alpha = MyDll.alpha.js Entrypoint beta = MyDll.beta.js chunk {0} MyDll.alpha.js (alpha) 84 bytes [entry] [rendered] > alpha [0] dll alpha 12 bytes {0} [built] dll entry DllPlugin [1] ./alpha.js 25 bytes {0} [built] single entry ./alpha [0] dll alpha alpha[0] DllPlugin [2] ./a.js 21 bytes {0} [built] single entry ./a [0] dll alpha alpha[1] DllPlugin + 1 hidden module chunk {1} MyDll.beta.js (beta) 80 bytes [entry] [rendered] > beta [4] dll beta 12 bytes {1} [built] dll entry DllPlugin [5] ./beta.js 24 bytes {1} [built] single entry ./beta [4] dll beta beta[0] DllPlugin [6] ./b.js 21 bytes {1} [built] single entry ./b [4] dll beta beta[1] DllPlugin [7] ./c.jsx 23 bytes {1} [built] single entry ./c [4] dll beta beta[2] DllPlugin ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names MyDll.alpha.js 1.06 KiB 0 [emitted] alpha MyDll.beta.js 1.05 KiB 1 [emitted] beta Entrypoint alpha = MyDll.alpha.js Entrypoint beta = MyDll.beta.js chunk {0} MyDll.alpha.js (alpha) 84 bytes [entry] [rendered] > alpha [0] dll alpha 12 bytes {0} [built] dll entry DllPlugin [1] ./alpha.js 25 bytes {0} [built] single entry ./alpha [0] dll alpha alpha[0] DllPlugin [2] ./a.js 21 bytes {0} [built] single entry ./a [0] dll alpha alpha[1] DllPlugin + 1 hidden module chunk {1} MyDll.beta.js (beta) 80 bytes [entry] [rendered] > beta [4] dll beta 12 bytes {1} [built] dll entry DllPlugin [5] ./beta.js 24 bytes {1} [built] single entry ./beta [4] dll beta beta[0] DllPlugin [6] ./b.js 21 bytes {1} [built] single entry ./b [4] dll beta beta[1] DllPlugin [7] ./c.jsx 23 bytes {1} [built] single entry ./c [4] dll beta beta[2] DllPlugin ``` webpack-4.30.0/examples/dll/a.js000066400000000000000000000000251345416772700163760ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/examples/dll/alpha.js000066400000000000000000000000311345416772700172400ustar00rootroot00000000000000module.exports = "alpha";webpack-4.30.0/examples/dll/b.js000066400000000000000000000000251345416772700163770ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/examples/dll/beta.js000066400000000000000000000000301345416772700170650ustar00rootroot00000000000000module.exports = "beta";webpack-4.30.0/examples/dll/build.js000066400000000000000000000000711345416772700172560ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-4.30.0/examples/dll/c.jsx000066400000000000000000000000271345416772700165720ustar00rootroot00000000000000module.exports = "jsx";webpack-4.30.0/examples/dll/template.md000066400000000000000000000010301345416772700177520ustar00rootroot00000000000000# DllReference [DllPlugin documentation](https://webpack.js.org/plugins/dll-plugin) This is the _reference_ bundle (with the manifests) for [dll user example](https://github.com/webpack/webpack/tree/master/examples/dll-user) # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/MyDll.alpha.js ```javascript _{{dist/MyDll.alpha.js}}_ ``` # dist/alpha-manifest.json ```javascript _{{dist/alpha-manifest.json}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/dll/webpack.config.js000066400000000000000000000007641345416772700210500ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development || "production", resolve: { extensions: [".js", ".jsx"] }, entry: { alpha: ["./alpha", "./a", "module"], beta: ["./beta", "./b", "./c"] }, output: { path: path.join(__dirname, "dist"), filename: "MyDll.[name].js", library: "[name]_[hash]" }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "dist", "[name]-manifest.json"), name: "[name]_[hash]" }) ] }; webpack-4.30.0/examples/examples.js000066400000000000000000000011541345416772700172250ustar00rootroot00000000000000"use strict"; const fs = require("fs"); const path = require("path"); function findInFolder(folder, depth) { if(fs.existsSync(path.join(folder, "template.md"))) { return [folder]; } else if(depth > 0) { const files = fs.readdirSync(folder); const results = []; for(const file of files) { const innerPath = path.join(folder, file); if(fs.statSync(innerPath).isDirectory()) { const innerResult = findInFolder(innerPath, depth - 1); for(const item of innerResult) results.push(item); } } return results; } else { return []; } } module.exports = findInFolder(__dirname, 2).sort(); webpack-4.30.0/examples/explicit-vendor-chunk/000077500000000000000000000000001345416772700212725ustar00rootroot00000000000000webpack-4.30.0/examples/explicit-vendor-chunk/README.md000066400000000000000000000351541345416772700225610ustar00rootroot00000000000000# webpack.config.js ```javascript var path = require("path"); var webpack = require("../../"); module.exports = [ { name: "vendor", // mode: "development || "production", entry: ["./vendor", "./vendor2"], output: { path: path.resolve(__dirname, "dist"), filename: "vendor.js", library: "vendor_[hash]" }, plugins: [ new webpack.DllPlugin({ name: "vendor_[hash]", path: path.resolve(__dirname, "dist/manifest.json") }) ] }, { name: "app", // mode: "development || "production", dependencies: ["vendor"], entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "dist"), filename: "[name].js" }, plugins: [ new webpack.DllReferencePlugin({ manifest: path.resolve(__dirname, "dist/manifest.json") }) ] } ]; ``` # dist/vendor.js ```javascript var vendor_d9f5eab93a0e9010218f = ```
/******/ (function(modules) { /* webpackBootstrap */ }) ``` js /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!****************!*\ !*** dll main ***! \****************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__; /***/ }), /* 1 */ /*!*******************!*\ !*** ./vendor.js ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "Vendor"; /***/ }), /* 2 */ /*!********************!*\ !*** ./vendor2.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "Vendor2"; /***/ }) /******/ ]); ``` # dist/pageA.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { console.log(__webpack_require__(/*! ./vendor */ 1)); module.exports = "pageA"; /***/ }), /* 1 */ /*!****************************************************************************!*\ !*** delegated ./vendor.js from dll-reference vendor_d9f5eab93a0e9010218f ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(/*! dll-reference vendor_d9f5eab93a0e9010218f */ 2))(1); /***/ }), /* 2 */ /*!**********************************************!*\ !*** external "vendor_d9f5eab93a0e9010218f" ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = vendor_d9f5eab93a0e9010218f; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Child vendor: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names vendor.js 4.2 KiB 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 65 bytes [entry] [rendered] > main [0] dll main 12 bytes {0} [built] dll entry DllPlugin [1] ./vendor.js 26 bytes {0} [built] single entry ./vendor [0] dll main main[0] DllPlugin [2] ./vendor2.js 27 bytes {0} [built] single entry ./vendor2 [0] dll main main[1] DllPlugin Child app: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names pageA.js 4.49 KiB 0 [emitted] pageA pageB.js 4.51 KiB 1 [emitted] pageB pageC.js 3.71 KiB 2 [emitted] pageC Entrypoint pageA = pageA.js Entrypoint pageB = pageB.js Entrypoint pageC = pageC.js chunk {0} pageA.js (pageA) 143 bytes [entry] [rendered] > ./pageA pageA [0] ./pageA.js 59 bytes {0} [built] single entry ./pageA pageA [1] delegated ./vendor.js from dll-reference vendor_d9f5eab93a0e9010218f 42 bytes {0} [built] cjs require ./vendor [0] ./pageA.js 1:12-31 [2] external "vendor_d9f5eab93a0e9010218f" 42 bytes {0} {1} [built] delegated source dll-reference vendor_d9f5eab93a0e9010218f [1] delegated ./vendor.js from dll-reference vendor_d9f5eab93a0e9010218f delegated source dll-reference vendor_d9f5eab93a0e9010218f [4] delegated ./vendor2.js from dll-reference vendor_d9f5eab93a0e9010218f chunk {1} pageB.js (pageB) 144 bytes [entry] [rendered] > ./pageB pageB [2] external "vendor_d9f5eab93a0e9010218f" 42 bytes {0} {1} [built] delegated source dll-reference vendor_d9f5eab93a0e9010218f [1] delegated ./vendor.js from dll-reference vendor_d9f5eab93a0e9010218f delegated source dll-reference vendor_d9f5eab93a0e9010218f [4] delegated ./vendor2.js from dll-reference vendor_d9f5eab93a0e9010218f [3] ./pageB.js 60 bytes {1} [built] single entry ./pageB pageB [4] delegated ./vendor2.js from dll-reference vendor_d9f5eab93a0e9010218f 42 bytes {1} [built] cjs require ./vendor2 [3] ./pageB.js 1:12-32 chunk {2} pageC.js (pageC) 25 bytes [entry] [rendered] > ./pageC pageC [5] ./pageC.js 25 bytes {2} [built] single entry ./pageC pageC ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Child vendor: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names vendor.js 1.03 KiB 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 65 bytes [entry] [rendered] > main [0] dll main 12 bytes {0} [built] dll entry DllPlugin [1] ./vendor.js 26 bytes {0} [built] single entry ./vendor [0] dll main main[0] DllPlugin [2] ./vendor2.js 27 bytes {0} [built] single entry ./vendor2 [0] dll main main[1] DllPlugin Child app: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names pageA.js 1.04 KiB 0 [emitted] pageA pageB.js 1.04 KiB 1 [emitted] pageB pageC.js 954 bytes 2 [emitted] pageC Entrypoint pageA = pageA.js Entrypoint pageB = pageB.js Entrypoint pageC = pageC.js chunk {0} pageA.js (pageA) 143 bytes [entry] [rendered] > ./pageA pageA [0] external "vendor_eacfb43e8e821a56978d" 42 bytes {0} {1} [built] delegated source dll-reference vendor_eacfb43e8e821a56978d [2] delegated ./vendor.js from dll-reference vendor_eacfb43e8e821a56978d delegated source dll-reference vendor_eacfb43e8e821a56978d [4] delegated ./vendor2.js from dll-reference vendor_eacfb43e8e821a56978d [1] ./pageA.js 59 bytes {0} [built] single entry ./pageA pageA [2] delegated ./vendor.js from dll-reference vendor_eacfb43e8e821a56978d 42 bytes {0} [built] cjs require ./vendor [1] ./pageA.js 1:12-31 chunk {1} pageB.js (pageB) 144 bytes [entry] [rendered] > ./pageB pageB [0] external "vendor_eacfb43e8e821a56978d" 42 bytes {0} {1} [built] delegated source dll-reference vendor_eacfb43e8e821a56978d [2] delegated ./vendor.js from dll-reference vendor_eacfb43e8e821a56978d delegated source dll-reference vendor_eacfb43e8e821a56978d [4] delegated ./vendor2.js from dll-reference vendor_eacfb43e8e821a56978d [3] ./pageB.js 60 bytes {1} [built] single entry ./pageB pageB [4] delegated ./vendor2.js from dll-reference vendor_eacfb43e8e821a56978d 42 bytes {1} [built] cjs require ./vendor2 [3] ./pageB.js 1:12-32 chunk {2} pageC.js (pageC) 25 bytes [entry] [rendered] > ./pageC pageC [5] ./pageC.js 25 bytes {2} [built] single entry ./pageC pageC ``` webpack-4.30.0/examples/explicit-vendor-chunk/build.js000066400000000000000000000000721345416772700227260ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/explicit-vendor-chunk/pageA.html000066400000000000000000000002331345416772700231730ustar00rootroot00000000000000 webpack-4.30.0/examples/explicit-vendor-chunk/pageA.js000066400000000000000000000000731345416772700226450ustar00rootroot00000000000000console.log(require("./vendor")); module.exports = "pageA";webpack-4.30.0/examples/explicit-vendor-chunk/pageB.js000066400000000000000000000000741345416772700226470ustar00rootroot00000000000000console.log(require("./vendor2")); module.exports = "pageB";webpack-4.30.0/examples/explicit-vendor-chunk/pageC.js000066400000000000000000000000311345416772700226410ustar00rootroot00000000000000module.exports = "pageC";webpack-4.30.0/examples/explicit-vendor-chunk/template.md000066400000000000000000000004241345416772700234270ustar00rootroot00000000000000# webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/vendor.js ```javascript _{{dist/vendor.js}}_ ``` # dist/pageA.js ```javascript _{{dist/pageA.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/explicit-vendor-chunk/vendor.js000066400000000000000000000000321345416772700231200ustar00rootroot00000000000000module.exports = "Vendor";webpack-4.30.0/examples/explicit-vendor-chunk/vendor2.js000066400000000000000000000000331345416772700232030ustar00rootroot00000000000000module.exports = "Vendor2";webpack-4.30.0/examples/explicit-vendor-chunk/webpack.config.js000066400000000000000000000014401345416772700245070ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = [ { name: "vendor", // mode: "development || "production", entry: ["./vendor", "./vendor2"], output: { path: path.resolve(__dirname, "dist"), filename: "vendor.js", library: "vendor_[hash]" }, plugins: [ new webpack.DllPlugin({ name: "vendor_[hash]", path: path.resolve(__dirname, "dist/manifest.json") }) ] }, { name: "app", // mode: "development || "production", dependencies: ["vendor"], entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "dist"), filename: "[name].js" }, plugins: [ new webpack.DllReferencePlugin({ manifest: path.resolve(__dirname, "dist/manifest.json") }) ] } ]; webpack-4.30.0/examples/externals/000077500000000000000000000000001345416772700170555ustar00rootroot00000000000000webpack-4.30.0/examples/externals/README.md000066400000000000000000000202251345416772700203350ustar00rootroot00000000000000This example demonstrates how to build a library with webpack that has dependencies to other libraries which should not be included in the compiled version. We use the `libraryTarget: "umd"` option to build a UMD module that is consumable in CommonJs, AMD and with script tags. We don't specify the `library` option so the library is exported to the root namespace. We use the `externals` option to define dependencies that should be resolved in the target environment. In the simple case we just need to specify a string (`"add"`). Then it's resolved as `"add"` module in CommonJs and AMD, and as global `add` when used with script tag. In the complex case we specify different values for each environment: | environment | config value | resolved as | | ------------------ | ------------------------ | ---------------------------- | | CommonJs (strict) | `["./math", "subtract"]` | `require("./math").subtract` | | CommonJs (node.js) | `"./subtract"` | `require("./subtract")` | | AMD | `"subtract"` | `define(["subtract"], ...)` | | script tag | `"subtract"` | `this.subtract` | # example.js ```javascript var add = require("add"); var subtract = require("subtract"); exports.exampleValue = subtract(add(42, 2), 2); ``` # webpack.config.js ```javascript module.exports = { // mode: "development || "production", output: { libraryTarget: "umd" }, externals: [ "add", { subtract: { root: "subtract", commonjs2: "./subtract", commonjs: ["./math", "subtract"], amd: "subtract" } } ] }; ``` # dist/output.js ```javascript (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("add"), require("./subtract")); else if(typeof define === 'function' && define.amd) define(["add", "subtract"], factory); else { var a = typeof exports === 'object' ? factory(require("add"), require("./math")["subtract"]) : factory(root["add"], root["subtract"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(window, function(__WEBPACK_EXTERNAL_MODULE__1__, __WEBPACK_EXTERNAL_MODULE__2__) { ```
return /******/ (function(modules) { /* webpackBootstrap */ }) ``` js return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var add = __webpack_require__(/*! add */ 1); var subtract = __webpack_require__(/*! subtract */ 2); exports.exampleValue = subtract(add(42, 2), 2); /***/ }), /* 1 */ /*!**********************!*\ !*** external "add" ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__1__; /***/ }), /* 2 */ /*!***************************************************************************************************************!*\ !*** external {"root":"subtract","commonjs2":"./subtract","commonjs":["./math","subtract"],"amd":"subtract"} ***! \***************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__2__; /***/ }) /******/ ]); }); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 5.13 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 194 bytes [entry] [rendered] > ./example.js main [0] ./example.js 110 bytes {0} [built] single entry ./example.js main [1] external "add" 42 bytes {0} [built] cjs require add [0] ./example.js 1:10-24 [2] external {"root":"subtract","commonjs2":"./subtract","commonjs":["./math","subtract"],"amd":"subtract"} 42 bytes {0} [built] cjs require subtract [0] ./example.js 2:15-34 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.4 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 194 bytes [entry] [rendered] > ./example.js main [0] ./example.js 110 bytes {0} [built] single entry ./example.js main [1] external "add" 42 bytes {0} [built] cjs require add [0] ./example.js 1:10-24 [2] external {"root":"subtract","commonjs2":"./subtract","commonjs":["./math","subtract"],"amd":"subtract"} 42 bytes {0} [built] cjs require subtract [0] ./example.js 2:15-34 ``` webpack-4.30.0/examples/externals/build.js000066400000000000000000000000331345416772700205060ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/externals/example.js000066400000000000000000000001561345416772700210500ustar00rootroot00000000000000var add = require("add"); var subtract = require("subtract"); exports.exampleValue = subtract(add(42, 2), 2);webpack-4.30.0/examples/externals/template.md000066400000000000000000000026761345416772700212250ustar00rootroot00000000000000This example demonstrates how to build a library with webpack that has dependencies to other libraries which should not be included in the compiled version. We use the `libraryTarget: "umd"` option to build a UMD module that is consumable in CommonJs, AMD and with script tags. We don't specify the `library` option so the library is exported to the root namespace. We use the `externals` option to define dependencies that should be resolved in the target environment. In the simple case we just need to specify a string (`"add"`). Then it's resolved as `"add"` module in CommonJs and AMD, and as global `add` when used with script tag. In the complex case we specify different values for each environment: | environment | config value | resolved as | | ------------------ | ------------------------ | ---------------------------- | | CommonJs (strict) | `["./math", "subtract"]` | `require("./math").subtract` | | CommonJs (node.js) | `"./subtract"` | `require("./subtract")` | | AMD | `"subtract"` | `define(["subtract"], ...)` | | script tag | `"subtract"` | `this.subtract` | # example.js ```javascript _{{example.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/externals/webpack.config.js000066400000000000000000000004071345416772700222740ustar00rootroot00000000000000module.exports = { // mode: "development || "production", output: { libraryTarget: "umd" }, externals: [ "add", { subtract: { root: "subtract", commonjs2: "./subtract", commonjs: ["./math", "subtract"], amd: "subtract" } } ] }; webpack-4.30.0/examples/extra-async-chunk-advanced/000077500000000000000000000000001345416772700221575ustar00rootroot00000000000000webpack-4.30.0/examples/extra-async-chunk-advanced/README.md000066400000000000000000000362041345416772700234430ustar00rootroot00000000000000# example.js ```javascript require(["./a", "./b", "./c"], function(a, b, c) {}); require.ensure(["./a"], function(require) { require("./b"); require("./d"); }); require.ensure(["./a", "./e"], function(require) { require("./a"); require.ensure(["./b"], function(require) { require("./f"); }); require.ensure(["./b"], function(require) { require("./g"); }); }); ``` # webpack.config.js ```javascript module.exports = { // mode: "development || "production", optimization: { splitChunks: { minSize: 0 // This example is too small }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 2: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
```javascript /******/ ({ /***/ 2: /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { Promise.all(/*! AMD require */[__webpack_require__.e(0), __webpack_require__.e(1), __webpack_require__.e(3)]).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(/*! ./a */ 0), __webpack_require__(/*! ./b */ 1), __webpack_require__(/*! ./c */ 3)]; (function(a, b, c) {}).apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);}).catch(__webpack_require__.oe); Promise.all(/*! require.ensure */[__webpack_require__.e(0), __webpack_require__.e(1), __webpack_require__.e(4)]).then((function(require) { __webpack_require__(/*! ./b */ 1); __webpack_require__(/*! ./d */ 4); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); Promise.all(/*! require.ensure */[__webpack_require__.e(1), __webpack_require__.e(5)]).then((function(require) { __webpack_require__(/*! ./a */ 0); Promise.all(/*! require.ensure */[__webpack_require__.e(0), __webpack_require__.e(6)]).then((function(require) { __webpack_require__(/*! ./f */ 6); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); Promise.all(/*! require.ensure */[__webpack_require__.e(0), __webpack_require__.e(7)]).then((function(require) { __webpack_require__(/*! ./g */ 7); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }) /******/ }); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 247 bytes 0 [emitted] 1.output.js 238 bytes 1 [emitted] 3.output.js 241 bytes 3 [emitted] 4.output.js 241 bytes 4 [emitted] 5.output.js 241 bytes 5 [emitted] 6.output.js 241 bytes 6 [emitted] 7.output.js 241 bytes 7 [emitted] output.js 9.28 KiB 2 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 21 bytes <{1}> <{2}> <{5}> ={1}= ={3}= ={4}= ={6}= ={7}= [rendered] split chunk (cache group: default) > [2] ./example.js 10:1-12:3 > [2] ./example.js 13:1-15:3 > ./a ./b ./c [2] ./example.js 1:0-52 > [2] ./example.js 3:0-6:2 [1] ./b.js 21 bytes {0} [built] amd require ./b [2] ./example.js 1:0-52 cjs require ./b [2] ./example.js 4:1-15 require.ensure item ./b [2] ./example.js 10:1-12:3 require.ensure item ./b [2] ./example.js 13:1-15:3 chunk {1} 1.output.js 21 bytes <{2}> ={0}= ={3}= ={4}= ={5}= >{0}< >{6}< >{7}< [rendered] split chunk (cache group: default) > ./a ./b ./c [2] ./example.js 1:0-52 > [2] ./example.js 3:0-6:2 > [2] ./example.js 8:0-16:2 [0] ./a.js 21 bytes {1} [built] amd require ./a [2] ./example.js 1:0-52 require.ensure item ./a [2] ./example.js 3:0-6:2 require.ensure item ./a [2] ./example.js 8:0-16:2 cjs require ./a [2] ./example.js 9:1-15 chunk {2} output.js (main) 346 bytes >{0}< >{1}< >{3}< >{4}< >{5}< [entry] [rendered] > ./example.js main [2] ./example.js 346 bytes {2} [built] single entry ./example.js main chunk {3} 3.output.js 21 bytes <{2}> ={0}= ={1}= [rendered] > ./a ./b ./c [2] ./example.js 1:0-52 [3] ./c.js 21 bytes {3} [built] amd require ./c [2] ./example.js 1:0-52 chunk {4} 4.output.js 21 bytes <{2}> ={0}= ={1}= [rendered] > [2] ./example.js 3:0-6:2 [4] ./d.js 21 bytes {4} [built] cjs require ./d [2] ./example.js 5:1-15 chunk {5} 5.output.js 21 bytes <{2}> ={1}= >{0}< >{6}< >{7}< [rendered] > [2] ./example.js 8:0-16:2 [5] ./e.js 21 bytes {5} [built] require.ensure item ./e [2] ./example.js 8:0-16:2 chunk {6} 6.output.js 21 bytes <{1}> <{5}> ={0}= [rendered] > [2] ./example.js 10:1-12:3 [6] ./f.js 21 bytes {6} [built] cjs require ./f [2] ./example.js 11:2-16 chunk {7} 7.output.js 21 bytes <{1}> <{5}> ={0}= [rendered] > [2] ./example.js 13:1-15:3 [7] ./g.js 21 bytes {7} [built] cjs require ./g [2] ./example.js 14:2-16 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 90 bytes 0 [emitted] 1.output.js 89 bytes 1 [emitted] 3.output.js 91 bytes 3 [emitted] 4.output.js 91 bytes 4 [emitted] 5.output.js 91 bytes 5 [emitted] 6.output.js 91 bytes 6 [emitted] 7.output.js 91 bytes 7 [emitted] output.js 2.39 KiB 2 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 21 bytes <{1}> <{2}> <{5}> ={1}= ={3}= ={4}= ={6}= ={7}= [rendered] split chunk (cache group: default) > [2] ./example.js 10:1-12:3 > [2] ./example.js 13:1-15:3 > ./a ./b ./c [2] ./example.js 1:0-52 > [2] ./example.js 3:0-6:2 [1] ./b.js 21 bytes {0} [built] amd require ./b [2] ./example.js 1:0-52 cjs require ./b [2] ./example.js 4:1-15 require.ensure item ./b [2] ./example.js 10:1-12:3 require.ensure item ./b [2] ./example.js 13:1-15:3 chunk {1} 1.output.js 21 bytes <{2}> ={0}= ={3}= ={4}= ={5}= >{0}< >{6}< >{7}< [rendered] split chunk (cache group: default) > ./a ./b ./c [2] ./example.js 1:0-52 > [2] ./example.js 3:0-6:2 > [2] ./example.js 8:0-16:2 [0] ./a.js 21 bytes {1} [built] amd require ./a [2] ./example.js 1:0-52 require.ensure item ./a [2] ./example.js 3:0-6:2 require.ensure item ./a [2] ./example.js 8:0-16:2 cjs require ./a [2] ./example.js 9:1-15 chunk {2} output.js (main) 346 bytes >{0}< >{1}< >{3}< >{4}< >{5}< [entry] [rendered] > ./example.js main [2] ./example.js 346 bytes {2} [built] single entry ./example.js main chunk {3} 3.output.js 21 bytes <{2}> ={0}= ={1}= [rendered] > ./a ./b ./c [2] ./example.js 1:0-52 [3] ./c.js 21 bytes {3} [built] amd require ./c [2] ./example.js 1:0-52 chunk {4} 4.output.js 21 bytes <{2}> ={0}= ={1}= [rendered] > [2] ./example.js 3:0-6:2 [4] ./d.js 21 bytes {4} [built] cjs require ./d [2] ./example.js 5:1-15 chunk {5} 5.output.js 21 bytes <{2}> ={1}= >{0}< >{6}< >{7}< [rendered] > [2] ./example.js 8:0-16:2 [5] ./e.js 21 bytes {5} [built] require.ensure item ./e [2] ./example.js 8:0-16:2 chunk {6} 6.output.js 21 bytes <{1}> <{5}> ={0}= [rendered] > [2] ./example.js 10:1-12:3 [6] ./f.js 21 bytes {6} [built] cjs require ./f [2] ./example.js 11:2-16 chunk {7} 7.output.js 21 bytes <{1}> <{5}> ={0}= [rendered] > [2] ./example.js 13:1-15:3 [7] ./g.js 21 bytes {7} [built] cjs require ./g [2] ./example.js 14:2-16 ``` webpack-4.30.0/examples/extra-async-chunk-advanced/a.js000066400000000000000000000000251345416772700227320ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/examples/extra-async-chunk-advanced/b.js000066400000000000000000000000251345416772700227330ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/examples/extra-async-chunk-advanced/build.js000066400000000000000000000000331345416772700236100ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/extra-async-chunk-advanced/c.js000066400000000000000000000000251345416772700227340ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/examples/extra-async-chunk-advanced/d.js000066400000000000000000000000251345416772700227350ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/examples/extra-async-chunk-advanced/e.js000066400000000000000000000000251345416772700227360ustar00rootroot00000000000000module.exports = "e";webpack-4.30.0/examples/extra-async-chunk-advanced/example.js000066400000000000000000000005321345416772700241500ustar00rootroot00000000000000require(["./a", "./b", "./c"], function(a, b, c) {}); require.ensure(["./a"], function(require) { require("./b"); require("./d"); }); require.ensure(["./a", "./e"], function(require) { require("./a"); require.ensure(["./b"], function(require) { require("./f"); }); require.ensure(["./b"], function(require) { require("./g"); }); }); webpack-4.30.0/examples/extra-async-chunk-advanced/f.js000066400000000000000000000000251345416772700227370ustar00rootroot00000000000000module.exports = "f";webpack-4.30.0/examples/extra-async-chunk-advanced/g.js000066400000000000000000000000251345416772700227400ustar00rootroot00000000000000module.exports = "g";webpack-4.30.0/examples/extra-async-chunk-advanced/template.md000066400000000000000000000004161345416772700243150ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/extra-async-chunk-advanced/webpack.config.js000066400000000000000000000003761345416772700254030ustar00rootroot00000000000000module.exports = { // mode: "development || "production", optimization: { splitChunks: { minSize: 0 // This example is too small }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/extra-async-chunk/000077500000000000000000000000001345416772700204145ustar00rootroot00000000000000webpack-4.30.0/examples/extra-async-chunk/README.md000066400000000000000000000322211345416772700216730ustar00rootroot00000000000000This example shows automatically created async commons chunks. The example entry references two chunks: - entry chunk - async require -> chunk X - async require -> chunk Y - chunk X - module `a` - module `b` - module `c` - chunk Y - module `a` - module `b` - module `d` These chunks share modules `a` and `b`. The optimization extract these into chunk Z: Note: Actually the optimization compare size of chunk Z to some minimum value, but this is disabled from this example. In practice there is no configuration needed for this. - entry chunk - async require -> chunk X & Z - async require -> chunk Y & Z - chunk X - module `c` - chunk Y - module `d` - chunk Z - module `a` - module `b` Pretty useful for a router in a SPA. # example.js ```javascript // a chunks with a, b, c require(["./a", "./b", "./c"]); // a chunk with a, b, d require.ensure(["./a"], function(require) { require("./b"); require("./d"); }); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
```javascript /******/ ({ /***/ 2: /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // a chunks with a, b, c Promise.all(/*! AMD require */[__webpack_require__.e(0), __webpack_require__.e(2)]).then(function() {[__webpack_require__(/*! ./a */ 0), __webpack_require__(/*! ./b */ 1), __webpack_require__(/*! ./c */ 3)];}).catch(__webpack_require__.oe); // a chunk with a, b, d Promise.all(/*! require.ensure */[__webpack_require__.e(0), __webpack_require__.e(3)]).then((function(require) { __webpack_require__(/*! ./b */ 1); __webpack_require__(/*! ./d */ 4); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }) /******/ }); ``` # dist/0.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],[ /* 0 */ /*!**************!*\ !*** ./a.js ***! \**************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "a"; /***/ }), /* 1 */ /*!**************!*\ !*** ./b.js ***! \**************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "b"; /***/ }) ]]); ``` # dist/2.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[2],{ /***/ 3: /*!**************!*\ !*** ./c.js ***! \**************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "c"; /***/ }) }]); ``` # dist/3.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[3],{ /***/ 4: /*!**************!*\ !*** ./d.js ***! \**************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "d"; /***/ }) }]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 405 bytes 0 [emitted] 2.output.js 241 bytes 2 [emitted] 3.output.js 241 bytes 3 [emitted] output.js 8.54 KiB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 42 bytes <{1}> ={2}= ={3}= [rendered] split chunk (cache group: default) > ./a ./b ./c [2] ./example.js 2:0-30 > [2] ./example.js 5:0-8:2 [0] ./a.js 21 bytes {0} [built] amd require ./a [2] ./example.js 2:0-30 require.ensure item ./a [2] ./example.js 5:0-8:2 [1] ./b.js 21 bytes {0} [built] amd require ./b [2] ./example.js 2:0-30 cjs require ./b [2] ./example.js 6:1-15 chunk {1} output.js (main) 164 bytes >{0}< >{2}< >{3}< [entry] [rendered] > ./example.js main [2] ./example.js 164 bytes {1} [built] single entry ./example.js main chunk {2} 2.output.js 21 bytes <{1}> ={0}= [rendered] > ./a ./b ./c [2] ./example.js 2:0-30 [3] ./c.js 21 bytes {2} [built] amd require ./c [2] ./example.js 2:0-30 chunk {3} 3.output.js 21 bytes <{1}> ={0}= [rendered] > [2] ./example.js 5:0-8:2 [4] ./d.js 21 bytes {3} [built] cjs require ./d [2] ./example.js 7:1-15 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0.output.js 118 bytes 0 [emitted] 2.output.js 91 bytes 2 [emitted] 3.output.js 91 bytes 3 [emitted] output.js 2.1 KiB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 42 bytes <{1}> ={2}= ={3}= [rendered] split chunk (cache group: default) > ./a ./b ./c [2] ./example.js 2:0-30 > [2] ./example.js 5:0-8:2 [0] ./a.js 21 bytes {0} [built] amd require ./a [2] ./example.js 2:0-30 require.ensure item ./a [2] ./example.js 5:0-8:2 [1] ./b.js 21 bytes {0} [built] amd require ./b [2] ./example.js 2:0-30 cjs require ./b [2] ./example.js 6:1-15 chunk {1} output.js (main) 164 bytes >{0}< >{2}< >{3}< [entry] [rendered] > ./example.js main [2] ./example.js 164 bytes {1} [built] single entry ./example.js main chunk {2} 2.output.js 21 bytes <{1}> ={0}= [rendered] > ./a ./b ./c [2] ./example.js 2:0-30 [3] ./c.js 21 bytes {2} [built] amd require ./c [2] ./example.js 2:0-30 chunk {3} 3.output.js 21 bytes <{1}> ={0}= [rendered] > [2] ./example.js 5:0-8:2 [4] ./d.js 21 bytes {3} [built] cjs require ./d [2] ./example.js 7:1-15 ``` webpack-4.30.0/examples/extra-async-chunk/a.js000066400000000000000000000000251345416772700211670ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/examples/extra-async-chunk/b.js000066400000000000000000000000251345416772700211700ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/examples/extra-async-chunk/build.js000066400000000000000000000000331345416772700220450ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/extra-async-chunk/c.js000066400000000000000000000000251345416772700211710ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/examples/extra-async-chunk/d.js000066400000000000000000000000251345416772700211720ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/examples/extra-async-chunk/example.js000066400000000000000000000002441345416772700224050ustar00rootroot00000000000000// a chunks with a, b, c require(["./a", "./b", "./c"]); // a chunk with a, b, d require.ensure(["./a"], function(require) { require("./b"); require("./d"); }); webpack-4.30.0/examples/extra-async-chunk/template.md000066400000000000000000000021771345416772700225600ustar00rootroot00000000000000This example shows automatically created async commons chunks. The example entry references two chunks: - entry chunk - async require -> chunk X - async require -> chunk Y - chunk X - module `a` - module `b` - module `c` - chunk Y - module `a` - module `b` - module `d` These chunks share modules `a` and `b`. The optimization extract these into chunk Z: Note: Actually the optimization compare size of chunk Z to some minimum value, but this is disabled from this example. In practice there is no configuration needed for this. - entry chunk - async require -> chunk X & Z - async require -> chunk Y & Z - chunk X - module `c` - chunk Y - module `d` - chunk Z - module `a` - module `b` Pretty useful for a router in a SPA. # example.js ```javascript _{{example.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/0.output.js ```javascript _{{dist/0.output.js}}_ ``` # dist/2.output.js ```javascript _{{dist/2.output.js}}_ ``` # dist/3.output.js ```javascript _{{dist/3.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/extra-async-chunk/webpack.config.js000066400000000000000000000003761345416772700236400ustar00rootroot00000000000000module.exports = { // mode: "development || "production", optimization: { splitChunks: { minSize: 0 // This example is too small }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/harmony-interop/000077500000000000000000000000001345416772700202035ustar00rootroot00000000000000webpack-4.30.0/examples/harmony-interop/README.md000066400000000000000000000265101345416772700214660ustar00rootroot00000000000000# example.js ```javascript // harmony module // import from CommonJs module import fs from "./fs"; import { readFile } from "./fs"; import * as fs2 from "./fs"; fs.readFile("file"); readFile("file"); fs2.readFile("file"); // import from harmony module import { readFile as readFile2 } from "./reexport-commonjs"; readFile2("file"); // import a CommonJs module for sideeffects import "./example2"; ``` # fs.js ```javascript // an example CommonJs module // content is omitted for brevity exports.readFile = function() {}; // using module.exports would be equivalent, // webpack doesn't care which syntax is used // AMD modules are also possible and equivalent to CommonJs modules ``` # reexport-commonjs.js ```javascript // reexport a CommonJs module export * from "./fs"; // Note that the default export doesn't reexport via export * // (this is not interop-specific, it applies for every export *) // Note: reexporting a CommonJs module is a special case, // because in this module we have no information about exports ``` # example2.js ```javascript // CommonJs module // require a harmony module var module = require("./harmony"); var defaultExport = module.default; var namedExport = module.named; ``` # harmony.js ```javascript // just some exports export default "default"; export var named = "named"; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fs */ 1); /* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_fs__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _reexport_commonjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./reexport-commonjs */ 2); /* harmony import */ var _example2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./example2 */ 3); /* harmony import */ var _example2__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_example2__WEBPACK_IMPORTED_MODULE_2__); // harmony module // import from CommonJs module _fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFile("file"); Object(_fs__WEBPACK_IMPORTED_MODULE_0__["readFile"])("file"); _fs__WEBPACK_IMPORTED_MODULE_0__["readFile"]("file"); // import from harmony module Object(_reexport_commonjs__WEBPACK_IMPORTED_MODULE_1__["readFile"])("file"); // import a CommonJs module for sideeffects /***/ }), /* 1 */ /*!***************!*\ !*** ./fs.js ***! \***************/ /*! no static exports found */ /***/ (function(module, exports) { // an example CommonJs module // content is omitted for brevity exports.readFile = function() {}; // using module.exports would be equivalent, // webpack doesn't care which syntax is used // AMD modules are also possible and equivalent to CommonJs modules /***/ }), /* 2 */ /*!******************************!*\ !*** ./reexport-commonjs.js ***! \******************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fs */ 1); /* harmony import */ var _fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_fs__WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _fs__WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _fs__WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); // reexport a CommonJs module // Note that the default export doesn't reexport via export * // (this is not interop-specific, it applies for every export *) // Note: reexporting a CommonJs module is a special case, // because in this module we have no information about exports /***/ }), /* 3 */ /*!*********************!*\ !*** ./example2.js ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // CommonJs module // require a harmony module var module = __webpack_require__(/*! ./harmony */ 4); var defaultExport = module.default; var namedExport = module.named; /***/ }), /* 4 */ /*!********************!*\ !*** ./harmony.js ***! \********************/ /*! exports provided: default, named */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "named", function() { return named; }); // just some exports /* harmony default export */ __webpack_exports__["default"] = ("default"); var named = "named"; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 7.05 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 1.13 KiB [entry] [rendered] > ./example.js main [0] ./example.js 373 bytes {0} [built] [no exports] single entry ./example.js main [1] ./fs.js 257 bytes {0} [built] harmony side effect evaluation ./fs [0] ./example.js 4:0-22 harmony side effect evaluation ./fs [0] ./example.js 5:0-32 harmony side effect evaluation ./fs [0] ./example.js 6:0-28 harmony import specifier ./fs [0] ./example.js 7:0-2 harmony import specifier ./fs [0] ./example.js 8:0-8 harmony import specifier ./fs [0] ./example.js 9:0-12 harmony side effect evaluation ./fs [2] ./reexport-commonjs.js 2:0-21 harmony export imported specifier ./fs [2] ./reexport-commonjs.js 2:0-21 [2] ./reexport-commonjs.js 301 bytes {0} [built] harmony side effect evaluation ./reexport-commonjs [0] ./example.js 12:0-60 harmony import specifier ./reexport-commonjs [0] ./example.js 13:0-9 [3] ./example2.js 152 bytes {0} [built] harmony side effect evaluation ./example2 [0] ./example.js 16:0-20 [4] ./harmony.js 75 bytes {0} [built] [exports: default, named] cjs require ./harmony [3] ./example2.js 4:13-33 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.35 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 1.13 KiB [entry] [rendered] > ./example.js main [0] ./fs.js 257 bytes {0} [built] [only some exports used: default, readFile] harmony side effect evaluation ./fs [1] ./reexport-commonjs.js 2:0-21 harmony export imported specifier ./fs [1] ./reexport-commonjs.js 2:0-21 harmony side effect evaluation ./fs [2] ./example.js 4:0-22 harmony side effect evaluation ./fs [2] ./example.js 5:0-32 harmony side effect evaluation ./fs [2] ./example.js 6:0-28 harmony import specifier ./fs [2] ./example.js 7:0-2 harmony import specifier ./fs [2] ./example.js 8:0-8 harmony import specifier ./fs [2] ./example.js 9:0-12 [1] ./reexport-commonjs.js 301 bytes {0} [built] [only some exports used: readFile] harmony side effect evaluation ./reexport-commonjs [2] ./example.js 12:0-60 harmony import specifier ./reexport-commonjs [2] ./example.js 13:0-9 [2] ./example.js 373 bytes {0} [built] [no exports] single entry ./example.js main [3] ./example2.js 152 bytes {0} [built] [no exports used] harmony side effect evaluation ./example2 [2] ./example.js 16:0-20 [4] ./harmony.js 75 bytes {0} [built] [exports: default, named] cjs require ./harmony [3] ./example2.js 4:13-33 ``` webpack-4.30.0/examples/harmony-interop/build.js000066400000000000000000000000331345416772700216340ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/harmony-interop/example.js000066400000000000000000000005651345416772700222020ustar00rootroot00000000000000// harmony module // import from CommonJs module import fs from "./fs"; import { readFile } from "./fs"; import * as fs2 from "./fs"; fs.readFile("file"); readFile("file"); fs2.readFile("file"); // import from harmony module import { readFile as readFile2 } from "./reexport-commonjs"; readFile2("file"); // import a CommonJs module for sideeffects import "./example2"; webpack-4.30.0/examples/harmony-interop/example2.js000066400000000000000000000002301345416772700222510ustar00rootroot00000000000000// CommonJs module // require a harmony module var module = require("./harmony"); var defaultExport = module.default; var namedExport = module.named; webpack-4.30.0/examples/harmony-interop/fs.js000066400000000000000000000004011345416772700211440ustar00rootroot00000000000000// an example CommonJs module // content is omitted for brevity exports.readFile = function() {}; // using module.exports would be equivalent, // webpack doesn't care which syntax is used // AMD modules are also possible and equivalent to CommonJs modules webpack-4.30.0/examples/harmony-interop/harmony.js000066400000000000000000000001131345416772700222110ustar00rootroot00000000000000// just some exports export default "default"; export var named = "named"; webpack-4.30.0/examples/harmony-interop/reexport-commonjs.js000066400000000000000000000004551345416772700242400ustar00rootroot00000000000000// reexport a CommonJs module export * from "./fs"; // Note that the default export doesn't reexport via export * // (this is not interop-specific, it applies for every export *) // Note: reexporting a CommonJs module is a special case, // because in this module we have no information about exports webpack-4.30.0/examples/harmony-interop/template.md000066400000000000000000000006421345416772700223420ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # fs.js ```javascript _{{fs.js}}_ ``` # reexport-commonjs.js ```javascript _{{reexport-commonjs.js}}_ ``` # example2.js ```javascript _{{example2.js}}_ ``` # harmony.js ```javascript _{{harmony.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/harmony-library/000077500000000000000000000000001345416772700201675ustar00rootroot00000000000000webpack-4.30.0/examples/harmony-library/README.md000066400000000000000000000134741345416772700214570ustar00rootroot00000000000000# webpack.config.js ```javascript var path = require("path"); module.exports = { // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "MyLibrary.umd.js", library: "MyLibrary", libraryTarget: "umd" } }; ``` # dist/MyLibrary.umd.js ```javascript (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["MyLibrary"] = factory(); else root["MyLibrary"] = factory(); })(window, function() { ```
return /******/ (function(modules) { /* webpackBootstrap */ }) ``` js return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! exports provided: value, increment, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "value", function() { return value; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "increment", function() { return increment; }); var value = 0; function increment() { value++; } /* harmony default export */ __webpack_exports__["default"] = ("MyLibrary"); /***/ }) /******/ ]); }); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names MyLibrary.umd.js 4.52 KiB 0 [emitted] main Entrypoint main = MyLibrary.umd.js chunk {0} MyLibrary.umd.js (main) 92 bytes [entry] [rendered] > ./example main [0] ./example.js 92 bytes {0} [built] [exports: value, increment, default] single entry ./example main ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names MyLibrary.umd.js 1.28 KiB 0 [emitted] main Entrypoint main = MyLibrary.umd.js chunk {0} MyLibrary.umd.js (main) 92 bytes [entry] [rendered] > ./example main [0] ./example.js 92 bytes {0} [built] [exports: value, increment, default] single entry ./example main ``` webpack-4.30.0/examples/harmony-library/build.js000066400000000000000000000000711345416772700216220ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-4.30.0/examples/harmony-library/example.js000066400000000000000000000001341345416772700221560ustar00rootroot00000000000000export var value = 0; export function increment() { value++; } export default "MyLibrary"; webpack-4.30.0/examples/harmony-library/template.md000066400000000000000000000003521345416772700223240ustar00rootroot00000000000000# webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/MyLibrary.umd.js ```javascript _{{dist/MyLibrary.umd.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/harmony-library/webpack.config.js000066400000000000000000000003621345416772700234060ustar00rootroot00000000000000var path = require("path"); module.exports = { // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "MyLibrary.umd.js", library: "MyLibrary", libraryTarget: "umd" } }; webpack-4.30.0/examples/harmony-unused/000077500000000000000000000000001345416772700200265ustar00rootroot00000000000000webpack-4.30.0/examples/harmony-unused/README.md000066400000000000000000000313551345416772700213140ustar00rootroot00000000000000This example demonstrates how webpack tracks the using of ES6 imports and exports. Only used exports are emitted to the resulting bundle. The minimizing step then removes the declarations because they are unused. Excluding unused exports from bundles is known as "[tree-shaking](http://www.2ality.com/2015/12/webpack-tree-shaking.html)". In this example, only `add` and `multiply` in `./math.js` are used by the app. `list` is unused and is not included in the minimized bundle (Look for `Array.from` in the minimized bundle). In addition to that, `library.js` simulates an entry point to a big library. `library.js` re-exports multiple identifiers from submodules. Often big parts of that is unused, like `abc.js`. Note how the usage information flows from `example.js` through `library.js` into `abc.js` and all declarations in `abc.js` are not included in the minimized bundle (Look for `console.log("a")` in the minimized bundle). # example.js ```javascript import { add } from './math'; import * as library from "./library"; add(1, 2); library.reexportedMultiply(1, 2); ``` # math.js ```javascript export function add() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; } export function multiply() { var product = 1, i = 0, args = arguments, l = args.length; while (i < l) { product *= args[i++]; } return product; } export function list() { return Array.from(arguments); } ``` # library.js ```javascript export { a, b, c } from "./abc"; export { add as reexportedAdd, multiply as reexportedMultiply } from "./math"; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./math */ 1); /* harmony import */ var _library__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./library */ 2); Object(_math__WEBPACK_IMPORTED_MODULE_0__["add"])(1, 2); _library__WEBPACK_IMPORTED_MODULE_1__["reexportedMultiply"](1, 2); /***/ }), /* 1 */ /*!*****************!*\ !*** ./math.js ***! \*****************/ /*! exports provided: add, multiply, list */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "add", function() { return add; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multiply", function() { return multiply; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "list", function() { return list; }); function add() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; } function multiply() { var product = 1, i = 0, args = arguments, l = args.length; while (i < l) { product *= args[i++]; } return product; } function list() { return Array.from(arguments); } /***/ }), /* 2 */ /*!********************!*\ !*** ./library.js ***! \********************/ /*! exports provided: a, b, c, reexportedAdd, reexportedMultiply */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _abc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abc */ 3); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _abc__WEBPACK_IMPORTED_MODULE_0__["a"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "b", function() { return _abc__WEBPACK_IMPORTED_MODULE_0__["b"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "c", function() { return _abc__WEBPACK_IMPORTED_MODULE_0__["c"]; }); /* harmony import */ var _math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./math */ 1); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reexportedAdd", function() { return _math__WEBPACK_IMPORTED_MODULE_1__["add"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "reexportedMultiply", function() { return _math__WEBPACK_IMPORTED_MODULE_1__["multiply"]; }); /***/ }), /* 3 */ /*!****************!*\ !*** ./abc.js ***! \****************/ /*! exports provided: a, b, c */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return a; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return b; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return c; }); function a() { console.log("a"); } function b() { console.log("b"); } function c() { console.log("c"); } /***/ }) /******/ ]); ``` # dist/output.js ```javascript !function(t){var e={};function n(r){if(e[r])return e[r].exports;var u=e[r]={i:r,l:!1,exports:{}};return t[r].call(u.exports,u,u.exports,n),u.l=!0,u.exports}n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var u in t)n.d(r,u,function(e){return t[e]}.bind(null,u));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="dist/",n(n.s=3)}([function(t,e,n){"use strict";function r(){for(var t=0,e=0,n=arguments,r=n.length;e ./example.js main [0] ./example.js 114 bytes {0} [built] [no exports] single entry ./example.js main [1] ./math.js 347 bytes {0} [built] [exports: add, multiply, list] harmony side effect evaluation ./math [0] ./example.js 1:0-29 harmony import specifier ./math [0] ./example.js 4:0-3 harmony side effect evaluation ./math [2] ./library.js 2:0-78 harmony export imported specifier ./math [2] ./library.js 2:0-78 harmony export imported specifier ./math [2] ./library.js 2:0-78 [2] ./library.js 111 bytes {0} [built] [exports: a, b, c, reexportedAdd, reexportedMultiply] harmony side effect evaluation ./library [0] ./example.js 2:0-37 harmony import specifier ./library [0] ./example.js 5:0-26 [3] ./abc.js 126 bytes {0} [built] [exports: a, b, c] harmony side effect evaluation ./abc [2] ./library.js 1:0-32 harmony export imported specifier ./abc [2] ./library.js 1:0-32 harmony export imported specifier ./abc [2] ./library.js 1:0-32 harmony export imported specifier ./abc [2] ./library.js 1:0-32 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.32 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 698 bytes [entry] [rendered] > ./example.js main [0] ./math.js 347 bytes {0} [built] [exports: add, multiply, list] [only some exports used: add, multiply] harmony side effect evaluation ./math [2] ./library.js 2:0-78 harmony export imported specifier ./math [2] ./library.js 2:0-78 harmony export imported specifier ./math [2] ./library.js 2:0-78 harmony side effect evaluation ./math [3] ./example.js 1:0-29 harmony import specifier ./math [3] ./example.js 4:0-3 [1] ./abc.js 126 bytes {0} [built] [exports: a, b, c] [no exports used] harmony side effect evaluation ./abc [2] ./library.js 1:0-32 harmony export imported specifier ./abc [2] ./library.js 1:0-32 harmony export imported specifier ./abc [2] ./library.js 1:0-32 harmony export imported specifier ./abc [2] ./library.js 1:0-32 [2] ./library.js 111 bytes {0} [built] [exports: a, b, c, reexportedAdd, reexportedMultiply] [only some exports used: reexportedMultiply] harmony side effect evaluation ./library [3] ./example.js 2:0-37 harmony import specifier ./library [3] ./example.js 5:0-26 [3] ./example.js 114 bytes {0} [built] [no exports] single entry ./example.js main ``` webpack-4.30.0/examples/harmony-unused/abc.js000066400000000000000000000001761345416772700211150ustar00rootroot00000000000000export function a() { console.log("a"); } export function b() { console.log("b"); } export function c() { console.log("c"); } webpack-4.30.0/examples/harmony-unused/build.js000066400000000000000000000000331345416772700214570ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/harmony-unused/example.js000066400000000000000000000001621345416772700220160ustar00rootroot00000000000000import { add } from './math'; import * as library from "./library"; add(1, 2); library.reexportedMultiply(1, 2); webpack-4.30.0/examples/harmony-unused/library.js000066400000000000000000000001571345416772700220330ustar00rootroot00000000000000export { a, b, c } from "./abc"; export { add as reexportedAdd, multiply as reexportedMultiply } from "./math";webpack-4.30.0/examples/harmony-unused/math.js000066400000000000000000000005331345416772700213160ustar00rootroot00000000000000export function add() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; } export function multiply() { var product = 1, i = 0, args = arguments, l = args.length; while (i < l) { product *= args[i++]; } return product; } export function list() { return Array.from(arguments); } webpack-4.30.0/examples/harmony-unused/template.md000066400000000000000000000024341345416772700221660ustar00rootroot00000000000000This example demonstrates how webpack tracks the using of ES6 imports and exports. Only used exports are emitted to the resulting bundle. The minimizing step then removes the declarations because they are unused. Excluding unused exports from bundles is known as "[tree-shaking](http://www.2ality.com/2015/12/webpack-tree-shaking.html)". In this example, only `add` and `multiply` in `./math.js` are used by the app. `list` is unused and is not included in the minimized bundle (Look for `Array.from` in the minimized bundle). In addition to that, `library.js` simulates an entry point to a big library. `library.js` re-exports multiple identifiers from submodules. Often big parts of that is unused, like `abc.js`. Note how the usage information flows from `example.js` through `library.js` into `abc.js` and all declarations in `abc.js` are not included in the minimized bundle (Look for `console.log("a")` in the minimized bundle). # example.js ```javascript _{{example.js}}_ ``` # math.js ```javascript _{{math.js}}_ ``` # library.js ```javascript _{{library.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/output.js ```javascript _{{production:dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/harmony-unused/webpack.config.js000066400000000000000000000001561345416772700232460ustar00rootroot00000000000000module.exports = { // mode: "development || "production", optimization: { concatenateModules: false } }; webpack-4.30.0/examples/harmony/000077500000000000000000000000001345416772700165255ustar00rootroot00000000000000webpack-4.30.0/examples/harmony/README.md000066400000000000000000000303071345416772700200070ustar00rootroot00000000000000# example.js ```javascript import { increment as inc } from './increment'; var a = 1; inc(a); // 2 // async loading import("./async-loaded").then(function(asyncLoaded) { console.log(asyncLoaded); }); ``` # increment.js ```javascript import { add } from './math'; export function increment(val) { return add(val, 1); }; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!**********************!*\ !*** ./increment.js ***! \**********************/ /*! exports provided: increment */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "increment", function() { return increment; }); /* harmony import */ var _math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./math */ 1); function increment(val) { return Object(_math__WEBPACK_IMPORTED_MODULE_0__["add"])(val, 1); }; /***/ }), /* 1 */ /*!*****************!*\ !*** ./math.js ***! \*****************/ /*! exports provided: add */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "add", function() { return add; }); function add() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; } /***/ }), /* 2 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _increment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./increment */ 0); var a = 1; Object(_increment__WEBPACK_IMPORTED_MODULE_0__["increment"])(a); // 2 // async loading __webpack_require__.e(/*! import() */ 1).then(__webpack_require__.bind(null, /*! ./async-loaded */ 3)).then(function(asyncLoaded) { console.log(asyncLoaded); }); /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 478 bytes 1 [emitted] output.js 9.48 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 400 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./increment.js 90 bytes {0} [built] [exports: increment] harmony side effect evaluation ./increment [2] ./example.js 1:0-47 harmony import specifier ./increment [2] ./example.js 3:0-3 [1] ./math.js 135 bytes {0} [built] [exports: add] harmony side effect evaluation ./math [0] ./increment.js 1:0-29 harmony import specifier ./math [0] ./increment.js 3:11-14 [2] ./example.js 175 bytes {0} [built] [no exports] single entry ./example.js main chunk {1} 1.output.js 24 bytes <{0}> [rendered] > ./async-loaded [2] ./example.js 6:0-24 [3] ./async-loaded.js 24 bytes {1} [built] [exports: answer] import() ./async-loaded [2] ./example.js 6:0-24 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 144 bytes 1 [emitted] output.js 2.1 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 400 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./example.js + 2 modules 400 bytes {0} [built] [no exports] single entry ./example.js main | ./example.js 175 bytes [built] | [no exports] | single entry ./example.js main | ./increment.js 90 bytes [built] | [exports: increment] | [all exports used] | harmony side effect evaluation ./increment ./example.js 1:0-47 | harmony import specifier ./increment ./example.js 3:0-3 | ./math.js 135 bytes [built] | [exports: add] | [all exports used] | harmony side effect evaluation ./math ./increment.js 1:0-29 | harmony import specifier ./math ./increment.js 3:11-14 chunk {1} 1.output.js 24 bytes <{0}> [rendered] > ./async-loaded [] 6:0-24 [1] ./async-loaded.js 24 bytes {1} [built] [exports: answer] import() ./async-loaded ./example.js 6:0-24 ``` webpack-4.30.0/examples/harmony/async-loaded.js000066400000000000000000000000301345416772700214170ustar00rootroot00000000000000export var answer = 42; webpack-4.30.0/examples/harmony/build.js000066400000000000000000000000331345416772700201560ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/harmony/example.js000066400000000000000000000002571345416772700205220ustar00rootroot00000000000000import { increment as inc } from './increment'; var a = 1; inc(a); // 2 // async loading import("./async-loaded").then(function(asyncLoaded) { console.log(asyncLoaded); }); webpack-4.30.0/examples/harmony/increment.js000066400000000000000000000001321345416772700210430ustar00rootroot00000000000000import { add } from './math'; export function increment(val) { return add(val, 1); }; webpack-4.30.0/examples/harmony/math.js000066400000000000000000000002071345416772700200130ustar00rootroot00000000000000export function add() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; } webpack-4.30.0/examples/harmony/template.md000066400000000000000000000004041345416772700206600ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # increment.js ```javascript _{{increment.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/harmony/webpack.config.js000066400000000000000000000002251345416772700217420ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/http2-aggressive-splitting/000077500000000000000000000000001345416772700222615ustar00rootroot00000000000000webpack-4.30.0/examples/http2-aggressive-splitting/README.md000066400000000000000000000131641345416772700235450ustar00rootroot00000000000000This example demonstrates the AggressiveSplittingPlugin for splitting the bundle into multiple smaller chunks to improve caching. This works best with a HTTP2 web server, otherwise there is an overhead for the increased number of requests. AggressiveSplittingPlugin splits every chunk until it reaches the specified `maxSize`. In this example it tries to create chunks with <50kB raw code, which typically minimizes to ~10kB. It groups modules together by folder structure, because modules in the same folder are likely to have similar repetitive text, making them gzip efficiently together. They are also likely to change together. AggressiveSplittingPlugin records its splitting in the webpack records. When it is next run, it tries to use the last recorded splitting. Since changes to application code between one run and the next are usually in only a few modules (or just one), re-using the old splittings (and chunks, which are probably still in the client's cache), is highly advantageous. Only chunks which are bigger than the specified `minSize` are stored into the records. This ensures that these chunks fill up as your application grows, instead of creating many records of small chunks for every change. If a module changes, its chunks are declared to be invalid, and are put back into the module pool. New chunks are created from all modules in the pool. There is a tradeoff here: The caching improves with smaller `maxSize`, as chunks change less often and can be reused more often after an update. The compression improves with bigger `maxSize`, as gzip works better for bigger files. It's more likely to find duplicate strings, etc. The backward compatibility (non HTTP2 client) improves with bigger `maxSize`, as the number of requests decreases. ```js var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development || "production", cache: true, // better performance for the AggressiveSplittingPlugin entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "[chunkhash].js", chunkFilename: "[chunkhash].js" }, plugins: [ new webpack.optimize.AggressiveSplittingPlugin({ minSize: 30000, maxSize: 50000 }), new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }) ], recordsOutputPath: path.join(__dirname, "dist", "records.json") }; ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 050bae6698d8aaba4919.js 6.91 KiB 1 [emitted] 0880c00cc5a4aa58c8f1.js 755 bytes 3 [emitted] 251da330b2eb8da40210.js 18 KiB 0 [emitted] main f03d13da014f1d9733df.js 106 KiB 2 [emitted] Entrypoint main = 251da330b2eb8da40210.js chunk {0} 251da330b2eb8da40210.js (main) 8.96 KiB >{1}< >{2}< >{3}< [entry] [rendered] > ./example main [0] ./example.js 42 bytes {0} [built] + 3 hidden modules chunk {1} 050bae6698d8aaba4919.js 6.41 KiB <{0}> ={2}= ={3}= [rendered] > react-dom [0] ./example.js 2:0-22 3 modules chunk {2} f03d13da014f1d9733df.js 106 KiB <{0}> ={1}= ={3}= [rendered] split chunk (cache group: vendors) > react-dom [0] ./example.js 2:0-22 1 module chunk {3} 0880c00cc5a4aa58c8f1.js 472 bytes <{0}> ={1}= ={2}= [rendered] [recorded] aggressive splitted > react-dom [0] ./example.js 2:0-22 [8] (webpack)/buildin/global.js 472 bytes {3} [built] ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 3e7f320bdbeae27d9ceb.js 5.08 KiB 1 [emitted] 4bf06c4116a056b43cf1.js 103 KiB 3 [emitted] e2f3160a2b31dabb3444.js 207 bytes 2 [emitted] f0d9bbf43c76640c63b2.js 9.64 KiB 0 [emitted] main Entrypoint main = f0d9bbf43c76640c63b2.js chunk {0} f0d9bbf43c76640c63b2.js (main) 8.96 KiB >{1}< >{2}< >{3}< [entry] [rendered] > ./example main [2] ./example.js 42 bytes {0} [built] + 3 hidden modules chunk {1} 3e7f320bdbeae27d9ceb.js 6.41 KiB <{0}> ={2}= ={3}= [rendered] > react-dom [2] ./example.js 2:0-22 3 modules chunk {2} e2f3160a2b31dabb3444.js 472 bytes <{0}> ={1}= ={3}= [rendered] [recorded] aggressive splitted > react-dom [2] ./example.js 2:0-22 [8] (webpack)/buildin/global.js 472 bytes {2} [built] chunk {3} 4bf06c4116a056b43cf1.js 106 KiB <{0}> ={1}= ={2}= [rendered] split chunk (cache group: vendors) > react-dom [2] ./example.js 2:0-22 1 module ``` ## Records ``` { "modules": { "byIdentifier": { "example.js": 0, "../../node_modules/react/index.js": 1, "../../node_modules/react/cjs/react.production.min.js": 2, "../../node_modules/object-assign/index.js": 3, "../../node_modules/react-dom/index.js": 4, "../../node_modules/react-dom/cjs/react-dom.production.min.js": 5, "../../node_modules/scheduler/index.js": 6, "../../node_modules/scheduler/cjs/scheduler.production.min.js": 7, "../../buildin/global.js": 8 }, "usedIds": { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8 } }, "chunks": { "byName": { "main": 0 }, "bySource": { "2 example.js react-dom": 1, "0 example.js react-dom": 2, "1 example.js react-dom": 3 }, "usedIds": [ 0, 1, 2, 3 ] }, "aggressiveSplits": [ { "modules": [ "../../buildin/global.js", "../../node_modules/react-dom/cjs/react-dom.production.min.js" ], "size": 108540, "hash": "0880c00cc5a4aa58c8f164d5b18e50e0", "id": 3 } ] } ``` webpack-4.30.0/examples/http2-aggressive-splitting/build.js000066400000000000000000000001231345416772700237120ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; global.NO_REASONS = true; require("../build-common");webpack-4.30.0/examples/http2-aggressive-splitting/example.js000066400000000000000000000000521345416772700242470ustar00rootroot00000000000000require("react"); require(["react-dom"]); webpack-4.30.0/examples/http2-aggressive-splitting/template.md000066400000000000000000000036401345416772700244210ustar00rootroot00000000000000This example demonstrates the AggressiveSplittingPlugin for splitting the bundle into multiple smaller chunks to improve caching. This works best with a HTTP2 web server, otherwise there is an overhead for the increased number of requests. AggressiveSplittingPlugin splits every chunk until it reaches the specified `maxSize`. In this example it tries to create chunks with <50kB raw code, which typically minimizes to ~10kB. It groups modules together by folder structure, because modules in the same folder are likely to have similar repetitive text, making them gzip efficiently together. They are also likely to change together. AggressiveSplittingPlugin records its splitting in the webpack records. When it is next run, it tries to use the last recorded splitting. Since changes to application code between one run and the next are usually in only a few modules (or just one), re-using the old splittings (and chunks, which are probably still in the client's cache), is highly advantageous. Only chunks which are bigger than the specified `minSize` are stored into the records. This ensures that these chunks fill up as your application grows, instead of creating many records of small chunks for every change. If a module changes, its chunks are declared to be invalid, and are put back into the module pool. New chunks are created from all modules in the pool. There is a tradeoff here: The caching improves with smaller `maxSize`, as chunks change less often and can be reused more often after an update. The compression improves with bigger `maxSize`, as gzip works better for bigger files. It's more likely to find duplicate strings, etc. The backward compatibility (non HTTP2 client) improves with bigger `maxSize`, as the number of requests decreases. ```js _{{webpack.config.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` ## Records ``` _{{dist/records.json}}_ ``` webpack-4.30.0/examples/http2-aggressive-splitting/webpack.config.js000066400000000000000000000011241345416772700254750ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { // mode: "development || "production", cache: true, // better performance for the AggressiveSplittingPlugin entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "[chunkhash].js", chunkFilename: "[chunkhash].js" }, plugins: [ new webpack.optimize.AggressiveSplittingPlugin({ minSize: 30000, maxSize: 50000 }), new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }) ], recordsOutputPath: path.join(__dirname, "dist", "records.json") }; webpack-4.30.0/examples/hybrid-routing/000077500000000000000000000000001345416772700200165ustar00rootroot00000000000000webpack-4.30.0/examples/hybrid-routing/README.md000066400000000000000000000464471345416772700213140ustar00rootroot00000000000000# webpack.config.js ```javascript var path = require("path"); module.exports = { // mode: "development || "production", entry: { // The entry points for the pages // They also contains router pageA: ["./aEntry", "./router"], pageB: ["./bEntry", "./router"] }, output: { path: path.join(__dirname, "dist"), publicPath: "js/", filename: "[name].bundle.js", chunkFilename: "[name].chunk.js" }, optimization: { // Extract common modules from initial chunks too // This is optional, but good for performance. splitChunks: { chunks: "all", minSize: 0 // This example is too small }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; ``` # aEntry.js ```javascript // Just show the page "a" var render = require("./render"); render(require("./aPage")); ``` `bEntry.js` is similar. You may want to use a loader to generate this file. # aPage.js ```javascript module.exports = function() { return "This is page A."; }; ``` `bEntry.js` is similar. # router.js ```javascript var render = require("./render"); // Event when another page should be opened // Maybe hook click on links, hashchange or popstate window.onLinkToPage = function onLinkToPage(name) { // name is "a" or "b" // require the page with a dynamic require // It's important that this require only matches the pages // elsewise there is blood in the bundle. Here this is done with a // specific file prefix. It's also possible to use a directory, // overwriting the RegExp with the ContextReplacementPlugin, or // using the require.context method. // This line may throw a exception on runtime if the page wasn't found. import(/* webpackChunkName: "[request]" */`./${name}Page`).then(page => {; render(page.default); }); } ``` # pageA.html ```html ``` # dist/pageA~pageB.chunk.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[2],[ /* 0 */ /*!*******************!*\ !*** ./render.js ***! \*******************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function(page) { console.log(page()); }; /***/ }), /* 1 */, /* 2 */ /*!*******************!*\ !*** ./router.js ***! \*******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var render = __webpack_require__(/*! ./render */ 0); // Event when another page should be opened // Maybe hook click on links, hashchange or popstate window.onLinkToPage = function onLinkToPage(name) { // name is "a" or "b" // require the page with a dynamic require // It's important that this require only matches the pages // elsewise there is blood in the bundle. Here this is done with a // specific file prefix. It's also possible to use a directory, // overwriting the RegExp with the ContextReplacementPlugin, or // using the require.context method. // This line may throw a exception on runtime if the page wasn't found. __webpack_require__(6)(`./${name}Page`).then(page => {; render(page.default); }); } /***/ }), /* 3 */, /* 4 */, /* 5 */, /* 6 */ /*!********************************************!*\ !*** . lazy ^\.\/.*Page$ namespace object ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./aPage": [ 1, 0 ], "./bPage": [ 3, 1 ] }; function webpackAsyncContext(req) { if(!__webpack_require__.o(map, req)) { return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } var ids = map[req], id = ids[0]; return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__.t(id, 7); }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 6; module.exports = webpackAsyncContext; /***/ }) ]]); ``` # dist/pageA.bundle.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ // add entry modules from loaded chunk to deferred list /******/ deferredModules.push.apply(deferredModules, executeModules || []); /******/ /******/ // run deferred modules when all chunks ready /******/ return checkDeferredModules(); /******/ }; /******/ function checkDeferredModules() { /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ } /******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ var deferredModules = []; /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + ({"1":"bPage"}[chunkId]||chunkId) + ".chunk.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // add entry module to deferred list /******/ deferredModules.push([4,2,0]); /******/ // run deferred modules when ready /******/ return checkDeferredModules(); /******/ }) /************************************************************************/ ```
```javascript /******/ ({ /***/ 4: /*!*******************************!*\ !*** multi ./aEntry ./router ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./aEntry */5); module.exports = __webpack_require__(/*! ./router */2); /***/ }), /***/ 5: /*!*******************!*\ !*** ./aEntry.js ***! \*******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Just show the page "a" var render = __webpack_require__(/*! ./render */ 0); render(__webpack_require__(/*! ./aPage */ 1)); /***/ }) /******/ }); ``` # dist/aPage.chunk.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],[ /* 0 */, /* 1 */ /*!******************!*\ !*** ./aPage.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This is page A."; }; /***/ }) ]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names aPage.chunk.js 297 bytes 0 [emitted] aPage bPage.chunk.js 291 bytes 1 [emitted] bPage pageA.bundle.js 9.42 KiB 3 [emitted] pageA pageA~pageB.chunk.js 2.04 KiB 2 [emitted] pageA~pageB pageB.bundle.js 9.42 KiB 4 [emitted] pageB Entrypoint pageA = pageA~pageB.chunk.js aPage.chunk.js pageA.bundle.js Entrypoint pageB = pageA~pageB.chunk.js bPage.chunk.js pageB.bundle.js chunk {0} aPage.chunk.js (aPage) 59 bytes <{1}> <{2}> <{4}> ={2}= ={3}= >{1}< [initial] [rendered] reused as split chunk (cache group: default) > ./aPage [6] . lazy ^\.\/.*Page$ namespace object ./aPage > ./aPage [6] . lazy ^\.\/.*Page$ namespace object ./aPage > pageA [1] ./aPage.js 59 bytes {0} [built] cjs require ./aPage [5] ./aEntry.js 3:7-25 context element ./aPage [6] . lazy ^\.\/.*Page$ namespace object ./aPage chunk {1} bPage.chunk.js (bPage) 59 bytes <{0}> <{2}> <{3}> ={2}= ={4}= >{0}< [initial] [rendered] reused as split chunk (cache group: default) > ./bPage [6] . lazy ^\.\/.*Page$ namespace object ./bPage > ./bPage [6] . lazy ^\.\/.*Page$ namespace object ./bPage > pageB [3] ./bPage.js 59 bytes {1} [built] context element ./bPage [6] . lazy ^\.\/.*Page$ namespace object ./bPage cjs require ./bPage [8] ./bEntry.js 3:7-25 chunk {2} pageA~pageB.chunk.js (pageA~pageB) 950 bytes ={0}= ={1}= ={3}= ={4}= >{0}< >{1}< [initial] [rendered] split chunk (cache group: default) (name: pageA~pageB) > pageA > pageB [0] ./render.js 58 bytes {2} [built] cjs require ./render [2] ./router.js 1:13-32 cjs require ./render [5] ./aEntry.js 2:13-32 cjs require ./render [8] ./bEntry.js 2:13-32 [2] ./router.js 732 bytes {2} [built] single entry ./router [4] multi ./aEntry ./router pageA[1] single entry ./router [7] multi ./bEntry ./router pageB[1] [6] . lazy ^\.\/.*Page$ namespace object 160 bytes {2} [built] import() context lazy . [2] ./router.js 15:1-59 chunk {3} pageA.bundle.js (pageA) 127 bytes ={0}= ={2}= >{1}< [entry] [rendered] > pageA [4] multi ./aEntry ./router 40 bytes {3} [built] multi entry [5] ./aEntry.js 87 bytes {3} [built] single entry ./aEntry [4] multi ./aEntry ./router pageA[0] chunk {4} pageB.bundle.js (pageB) 127 bytes ={1}= ={2}= >{0}< [entry] [rendered] > pageB [7] multi ./bEntry ./router 40 bytes {4} [built] multi entry [8] ./bEntry.js 87 bytes {4} [built] single entry ./bEntry [7] multi ./bEntry ./router pageB[0] ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names aPage.chunk.js 122 bytes 0 [emitted] aPage bPage.chunk.js 123 bytes 1 [emitted] bPage pageA.bundle.js 2.22 KiB 3 [emitted] pageA pageA~pageB.chunk.js 559 bytes 2 [emitted] pageA~pageB pageB.bundle.js 2.22 KiB 4 [emitted] pageB Entrypoint pageA = pageA~pageB.chunk.js aPage.chunk.js pageA.bundle.js Entrypoint pageB = pageA~pageB.chunk.js bPage.chunk.js pageB.bundle.js chunk {0} aPage.chunk.js (aPage) 59 bytes <{1}> <{2}> <{4}> ={2}= ={3}= >{1}< [initial] [rendered] reused as split chunk (cache group: default) > ./aPage [6] . lazy ^\.\/.*Page$ namespace object ./aPage > ./aPage [6] . lazy ^\.\/.*Page$ namespace object ./aPage > pageA [1] ./aPage.js 59 bytes {0} [built] cjs require ./aPage [5] ./aEntry.js 3:7-25 context element ./aPage [6] . lazy ^\.\/.*Page$ namespace object ./aPage chunk {1} bPage.chunk.js (bPage) 59 bytes <{0}> <{2}> <{3}> ={2}= ={4}= >{0}< [initial] [rendered] reused as split chunk (cache group: default) > ./bPage [6] . lazy ^\.\/.*Page$ namespace object ./bPage > ./bPage [6] . lazy ^\.\/.*Page$ namespace object ./bPage > pageB [3] ./bPage.js 59 bytes {1} [built] context element ./bPage [6] . lazy ^\.\/.*Page$ namespace object ./bPage cjs require ./bPage [8] ./bEntry.js 3:7-25 chunk {2} pageA~pageB.chunk.js (pageA~pageB) 950 bytes ={0}= ={1}= ={3}= ={4}= >{0}< >{1}< [initial] [rendered] split chunk (cache group: default) (name: pageA~pageB) > pageA > pageB [0] ./render.js 58 bytes {2} [built] cjs require ./render [2] ./router.js 1:13-32 cjs require ./render [5] ./aEntry.js 2:13-32 cjs require ./render [8] ./bEntry.js 2:13-32 [2] ./router.js 732 bytes {2} [built] single entry ./router [4] multi ./aEntry ./router pageA[1] single entry ./router [7] multi ./bEntry ./router pageB[1] [6] . lazy ^\.\/.*Page$ namespace object 160 bytes {2} [built] import() context lazy . [2] ./router.js 15:1-59 chunk {3} pageA.bundle.js (pageA) 127 bytes ={0}= ={2}= >{1}< [entry] [rendered] > pageA [4] multi ./aEntry ./router 40 bytes {3} [built] multi entry [5] ./aEntry.js 87 bytes {3} [built] single entry ./aEntry [4] multi ./aEntry ./router pageA[0] chunk {4} pageB.bundle.js (pageB) 127 bytes ={1}= ={2}= >{0}< [entry] [rendered] > pageB [7] multi ./bEntry ./router 40 bytes {4} [built] multi entry [8] ./bEntry.js 87 bytes {4} [built] single entry ./bEntry [7] multi ./bEntry ./router pageB[0] ``` webpack-4.30.0/examples/hybrid-routing/aEntry.js000066400000000000000000000001271345416772700216160ustar00rootroot00000000000000// Just show the page "a" var render = require("./render"); render(require("./aPage"));webpack-4.30.0/examples/hybrid-routing/aPage.js000066400000000000000000000000731345416772700213710ustar00rootroot00000000000000module.exports = function() { return "This is page A."; };webpack-4.30.0/examples/hybrid-routing/bEntry.js000066400000000000000000000001271345416772700216170ustar00rootroot00000000000000// Just show the page "b" var render = require("./render"); render(require("./bPage"));webpack-4.30.0/examples/hybrid-routing/bPage.js000066400000000000000000000000731345416772700213720ustar00rootroot00000000000000module.exports = function() { return "This is page B."; };webpack-4.30.0/examples/hybrid-routing/build.js000066400000000000000000000000721345416772700214520ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/hybrid-routing/pageA.html000066400000000000000000000004021345416772700217150ustar00rootroot00000000000000 webpack-4.30.0/examples/hybrid-routing/pageB.html000066400000000000000000000004021345416772700217160ustar00rootroot00000000000000 webpack-4.30.0/examples/hybrid-routing/render.js000066400000000000000000000000721345416772700216320ustar00rootroot00000000000000module.exports = function(page) { console.log(page()); };webpack-4.30.0/examples/hybrid-routing/router.js000066400000000000000000000013341345416772700216750ustar00rootroot00000000000000var render = require("./render"); // Event when another page should be opened // Maybe hook click on links, hashchange or popstate window.onLinkToPage = function onLinkToPage(name) { // name is "a" or "b" // require the page with a dynamic require // It's important that this require only matches the pages // elsewise there is blood in the bundle. Here this is done with a // specific file prefix. It's also possible to use a directory, // overwriting the RegExp with the ContextReplacementPlugin, or // using the require.context method. // This line may throw a exception on runtime if the page wasn't found. import(/* webpackChunkName: "[request]" */`./${name}Page`).then(page => {; render(page.default); }); } webpack-4.30.0/examples/hybrid-routing/template.md000066400000000000000000000012341345416772700221530ustar00rootroot00000000000000# webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # aEntry.js ```javascript _{{aEntry.js}}_ ``` `bEntry.js` is similar. You may want to use a loader to generate this file. # aPage.js ```javascript _{{aPage.js}}_ ``` `bEntry.js` is similar. # router.js ```javascript _{{router.js}}_ ``` # pageA.html ```html _{{pageA.html}}_ ``` # dist/pageA~pageB.chunk.js ```javascript _{{dist/pageA~pageB.chunk.js}}_ ``` # dist/pageA.bundle.js ```javascript _{{dist/pageA.bundle.js}}_ ``` # dist/aPage.chunk.js ```javascript _{{dist/aPage.chunk.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/hybrid-routing/webpack.config.js000066400000000000000000000012641345416772700232370ustar00rootroot00000000000000var path = require("path"); module.exports = { // mode: "development || "production", entry: { // The entry points for the pages // They also contains router pageA: ["./aEntry", "./router"], pageB: ["./bEntry", "./router"] }, output: { path: path.join(__dirname, "dist"), publicPath: "js/", filename: "[name].bundle.js", chunkFilename: "[name].chunk.js" }, optimization: { // Extract common modules from initial chunks too // This is optional, but good for performance. splitChunks: { chunks: "all", minSize: 0 // This example is too small }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/i18n/000077500000000000000000000000001345416772700156275ustar00rootroot00000000000000webpack-4.30.0/examples/i18n/README.md000066400000000000000000000247501345416772700171160ustar00rootroot00000000000000This example uses the I18nPlugin in combination with the multi-compiler feature. The `webpack.config.js` exports an array of all config combinations that should be compiled. In this example two different parameters for the I18nPlugin are used. The I18nPlugin replaces every occurrence of the i18n function `__(...)` with a const string. i. e. `__("Hello World")` with `"Hello World"` resp. `"Hallo Welt"`. # example.js ```javascript console.log(__("Hello World")); console.log(__("Missing Text")); ``` # webpack.config.js ```javascript var path = require("path"); var I18nPlugin = require("i18n-webpack-plugin"); var languages = { en: null, de: require("./de.json") }; module.exports = Object.keys(languages).map(function(language) { return { name: language, // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: language + ".output.js" }, plugins: [new I18nPlugin(languages[language])] }; }); ``` # de.json ```javascript { "Hello World": "Hallo Welt" } ``` # dist/de.output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { console.log("Hallo Welt"); console.log("Missing Text"); /***/ }) /******/ ]); ``` # dist/en.output.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { console.log("Hello World"); console.log("Missing Text"); /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Child en: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names en.output.js 3.76 KiB 0 [emitted] main Entrypoint main = en.output.js chunk {0} en.output.js (main) 64 bytes [entry] [rendered] > ./example main [0] ./example.js 64 bytes {0} [built] single entry ./example main Child de: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names de.output.js 3.76 KiB 0 [emitted] main Entrypoint main = de.output.js chunk {0} de.output.js (main) 64 bytes [entry] [rendered] > ./example main [0] ./example.js 64 bytes {0} [built] [1 warning] single entry ./example main WARNING in ./example.js Missing localization: Missing Text ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Child en: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names en.output.js 991 bytes 0 [emitted] main Entrypoint main = en.output.js chunk {0} en.output.js (main) 64 bytes [entry] [rendered] > ./example main [0] ./example.js 64 bytes {0} [built] single entry ./example main Child de: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names de.output.js 990 bytes 0 [emitted] main Entrypoint main = de.output.js chunk {0} de.output.js (main) 64 bytes [entry] [rendered] > ./example main [0] ./example.js 64 bytes {0} [built] [1 warning] single entry ./example main WARNING in ./example.js Missing localization: Missing Text ``` webpack-4.30.0/examples/i18n/build.js000066400000000000000000000000711345416772700172620ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-4.30.0/examples/i18n/de.json000066400000000000000000000000401345416772700171040ustar00rootroot00000000000000{ "Hello World": "Hallo Welt" }webpack-4.30.0/examples/i18n/example.js000066400000000000000000000001001345416772700176070ustar00rootroot00000000000000console.log(__("Hello World")); console.log(__("Missing Text"));webpack-4.30.0/examples/i18n/template.md000066400000000000000000000014311345416772700177630ustar00rootroot00000000000000This example uses the I18nPlugin in combination with the multi-compiler feature. The `webpack.config.js` exports an array of all config combinations that should be compiled. In this example two different parameters for the I18nPlugin are used. The I18nPlugin replaces every occurrence of the i18n function `__(...)` with a const string. i. e. `__("Hello World")` with `"Hello World"` resp. `"Hallo Welt"`. # example.js ```javascript _{{example.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # de.json ```javascript _{{de.json}}_ ``` # dist/de.output.js ```javascript _{{dist/de.output.js}}_ ``` # dist/en.output.js ```javascript _{{dist/en.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/i18n/webpack.config.js000066400000000000000000000006711345416772700210510ustar00rootroot00000000000000var path = require("path"); var I18nPlugin = require("i18n-webpack-plugin"); var languages = { en: null, de: require("./de.json") }; module.exports = Object.keys(languages).map(function(language) { return { name: language, // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: language + ".output.js" }, plugins: [new I18nPlugin(languages[language])] }; }); webpack-4.30.0/examples/loader/000077500000000000000000000000001345416772700163165ustar00rootroot00000000000000webpack-4.30.0/examples/loader/README.md000066400000000000000000000227321345416772700176030ustar00rootroot00000000000000# example.js ```javascript // use our loader console.dir(require("./loader!./file")); // use buildin css loader console.dir(require("./test.css")); // default by extension console.dir(require("!css-loader!./test.css")); // manual ``` # file.js ```javascript exports.foo = "bar"; ``` # loader.js ```javascript module.exports = function(content) { return "exports.answer = 42;\n" + content; } ``` # test.css ```css .some-class { color: hotpink; } ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // use our loader console.dir(__webpack_require__(/*! ./loader!./file */ 1)); // use buildin css loader console.dir(__webpack_require__(/*! ./test.css */ 2)); // default by extension console.dir(__webpack_require__(/*! css-loader!./test.css */ 2)); // manual /***/ }), /* 1 */ /*!*****************************!*\ !*** ./loader.js!./file.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports) { exports.answer = 42; exports.foo = "bar"; /***/ }), /* 2 */ /*!****************************************************************!*\ !*** (webpack)/node_modules/css-loader/dist/cjs.js!./test.css ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! ../../node_modules/css-loader/dist/runtime/api.js */ 3)(false); // Module exports.push([module.i, ".some-class {\n\tcolor: hotpink;\n}\n", ""]); /***/ }), /* 3 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/css-loader/dist/runtime/api.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function (useSourceMap) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item, useSourceMap); if (item[2]) { return '@media ' + item[2] + '{' + content + '}'; } else { return content; } }).join(''); }; // import a list of modules into the list list.i = function (modules, mediaQuery) { if (typeof modules === 'string') { modules = [[null, modules, '']]; } var alreadyImportedModules = {}; for (var i = 0; i < this.length; i++) { var id = this[i][0]; if (id != null) { alreadyImportedModules[id] = true; } } for (i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if (item[0] == null || !alreadyImportedModules[item[0]]) { if (mediaQuery && !item[2]) { item[2] = mediaQuery; } else if (mediaQuery) { item[2] = '(' + item[2] + ') and (' + mediaQuery + ')'; } list.push(item); } } }; return list; }; function cssWithMappingToString(item, useSourceMap) { var content = item[1] || ''; var cssMapping = item[3]; if (!cssMapping) { return content; } if (useSourceMap && typeof btoa === 'function') { var sourceMapping = toComment(cssMapping); var sourceURLs = cssMapping.sources.map(function (source) { return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */'; }); return [content].concat(sourceURLs).concat([sourceMapping]).join('\n'); } return [content].join('\n'); } // Adapted from convert-source-map (MIT) function toComment(sourceMap) { // eslint-disable-next-line no-undef var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))); var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; return '/*# ' + data + ' */'; } /***/ }) /******/ ]); ``` # Console output Prints in node.js (`enhanced-require example.js`) and in browser: ``` { answer: 42, foo: 'bar' } { foobar: 1234 } { foobar: 1234 } ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 7.34 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 2.76 KiB [entry] [rendered] > ./example.js main [0] ./example.js 204 bytes {0} [built] single entry ./example.js main [1] ./loader.js!./file.js 41 bytes {0} [built] cjs require ./loader!./file [0] ./example.js 2:12-38 [2] (webpack)/node_modules/css-loader/dist/cjs.js!./test.css 179 bytes {0} [built] cjs require ./test.css [0] ./example.js 5:12-33 cjs require !css-loader!./test.css [0] ./example.js 6:12-45 + 1 hidden module ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.88 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 2.76 KiB [entry] [rendered] > ./example.js main [0] (webpack)/node_modules/css-loader/dist/cjs.js!./test.css 179 bytes {0} [built] cjs require ./test.css [1] ./example.js 5:12-33 cjs require !css-loader!./test.css [1] ./example.js 6:12-45 [1] ./example.js 204 bytes {0} [built] single entry ./example.js main [2] ./loader.js!./file.js 41 bytes {0} [built] cjs require ./loader!./file [1] ./example.js 2:12-38 + 1 hidden module ``` webpack-4.30.0/examples/loader/build.js000066400000000000000000000000331345416772700177470ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/loader/example.js000066400000000000000000000003141345416772700203050ustar00rootroot00000000000000// use our loader console.dir(require("./loader!./file")); // use buildin css loader console.dir(require("./test.css")); // default by extension console.dir(require("!css-loader!./test.css")); // manual webpack-4.30.0/examples/loader/file.js000066400000000000000000000000241345416772700175670ustar00rootroot00000000000000exports.foo = "bar";webpack-4.30.0/examples/loader/loader.js000066400000000000000000000001221345416772700201150ustar00rootroot00000000000000module.exports = function(content) { return "exports.answer = 42;\n" + content; }webpack-4.30.0/examples/loader/template.md000066400000000000000000000007541345416772700204610ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # file.js ```javascript _{{file.js}}_ ``` # loader.js ```javascript _{{loader.js}}_ ``` # test.css ```css _{{test.css}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Console output Prints in node.js (`enhanced-require example.js`) and in browser: ``` { answer: 42, foo: 'bar' } { foobar: 1234 } { foobar: 1234 } ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/loader/test.css000066400000000000000000000000411345416772700200020ustar00rootroot00000000000000.some-class { color: hotpink; } webpack-4.30.0/examples/loader/webpack.config.js000066400000000000000000000002221345416772700215300ustar00rootroot00000000000000module.exports = { // mode: "development || "production", module: { rules: [ { test: /\.css$/, loader: "css-loader" } ] } }; webpack-4.30.0/examples/many-pages/000077500000000000000000000000001345416772700171115ustar00rootroot00000000000000webpack-4.30.0/examples/many-pages/README.md000066400000000000000000000165111345416772700203740ustar00rootroot00000000000000# Info This example illustrates webpack's algorithm for automatic deduplication using `optimization.splitChunks`. This example application contains 7 pages, each of them importing 1-3 modules from the `node_modules` folder (vendor libs) and 0-3 modules from the `stuff` folder (application modules). In reallity an application is probably more complex, but the same mechanisms apply. The following configuration is used: - `optimization.splitChunks.chunks: "all"` - This opt-in into automatic splitting of initial chunks which is off by default - `optimization.splitChunks.maxInitial/AsyncRequests: 20` - This opt-in into a HTTP2 optimized splitting mode by increasing the allowed amount of requests. Browser only supports 6 requests in parallel for HTTP1.1. # Interpreting the result - `pageA.js` the normal output files for the entrypoint `pageA` - `vendors~pageD~pageE~pageF~pageG.js` vendor libs shared by these pages extracted into a separate output file when larger then the threshold in size - `vendors~pageA.js` vendors only used by a single page but larger than the threshold in size - `pageA~pageD~pageF.js` application modules shared by these pages and larger than the threshold in size The threshold is here 40 bytes, but by default (in a real application) 30kb. Some modules are intentially duplicated, i. e. `./stuff/s4.js` is shared by `pageA` and `pageC`, but it's the only shared module so no separate output file is created because it would be smaller than the threshold. A separate request (which comes with an overhead and worsen gzipping) is not worth the extra bytes. Note: decreasing `maxInitial/AsyncRequest` will increase duplication further to reduce the number of requests. Duplication doesn't affect initial page load, it only affects download size of navigations to other pages of the application. ## webpack.config.js ``` module.exports = { // mode: "development || "production", entry: { pageA: "./pages/a", pageB: "./pages/b", pageC: "./pages/c", pageD: "./pages/d", pageE: "./pages/e", pageF: "./pages/f", pageG: "./pages/g" }, optimization: { splitChunks: { chunks: "all", maxInitialRequests: 20, // for HTTP2 maxAsyncRequests: 20, // for HTTP2 minSize: 40 // for example only: chosen to match 2 modules // omit minSize in real use case to use the default of 30kb } } }; ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names pageA.js 1.55 KiB 4 [emitted] pageA pageA~pageD~pageF.js 156 bytes 1 [emitted] pageA~pageD~pageF pageB.js 1.65 KiB 5 [emitted] pageB pageC.js 1.65 KiB 6 [emitted] pageC pageD.js 1.55 KiB 7 [emitted] pageD pageE.js 1.54 KiB 8 [emitted] pageE pageF.js 1.55 KiB 9 [emitted] pageF pageG.js 1.53 KiB 10 [emitted] pageG vendors~pageA.js 122 bytes 11 [emitted] vendors~pageA vendors~pageA~pageB~pageC.js 178 bytes 2 [emitted] vendors~pageA~pageB~pageC vendors~pageB.js 122 bytes 12 [emitted] vendors~pageB vendors~pageC.js 122 bytes 13 [emitted] vendors~pageC vendors~pageD~pageE~pageF.js 180 bytes 3 [emitted] vendors~pageD~pageE~pageF vendors~pageD~pageE~pageF~pageG.js 119 bytes 0 [emitted] vendors~pageD~pageE~pageF~pageG Entrypoint pageA = vendors~pageA~pageB~pageC.js vendors~pageA.js pageA~pageD~pageF.js pageA.js Entrypoint pageB = vendors~pageA~pageB~pageC.js vendors~pageB.js pageB.js Entrypoint pageC = vendors~pageA~pageB~pageC.js vendors~pageC.js pageC.js Entrypoint pageD = vendors~pageD~pageE~pageF~pageG.js vendors~pageD~pageE~pageF.js pageA~pageD~pageF.js pageD.js Entrypoint pageE = vendors~pageD~pageE~pageF~pageG.js vendors~pageD~pageE~pageF.js pageE.js Entrypoint pageF = vendors~pageD~pageE~pageF~pageG.js vendors~pageD~pageE~pageF.js pageA~pageD~pageF.js pageF.js Entrypoint pageG = vendors~pageD~pageE~pageF~pageG.js pageG.js chunk {0} vendors~pageD~pageE~pageF~pageG.js (vendors~pageD~pageE~pageF~pageG) 43 bytes ={1}= ={3}= ={7}= ={8}= ={9}= ={10}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~pageD~pageE~pageF~pageG) > ./pages/d pageD > ./pages/e pageE > ./pages/f pageF > ./pages/g pageG 1 module chunk {1} pageA~pageD~pageF.js (pageA~pageD~pageF) 62 bytes ={0}= ={2}= ={3}= ={4}= ={7}= ={9}= ={11}= [initial] [rendered] split chunk (cache group: default) (name: pageA~pageD~pageF) > ./pages/a pageA > ./pages/d pageD > ./pages/f pageF [4] ./stuff/s2.js 31 bytes {1} [built] [5] ./stuff/s3.js 31 bytes {1} [built] chunk {2} vendors~pageA~pageB~pageC.js (vendors~pageA~pageB~pageC) 86 bytes ={1}= ={4}= ={5}= ={6}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~pageA~pageB~pageC) > ./pages/a pageA > ./pages/b pageB > ./pages/c pageC 2 modules chunk {3} vendors~pageD~pageE~pageF.js (vendors~pageD~pageE~pageF) 86 bytes ={0}= ={1}= ={7}= ={8}= ={9}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~pageD~pageE~pageF) > ./pages/d pageD > ./pages/e pageE > ./pages/f pageF 2 modules chunk {4} pageA.js (pageA) 137 bytes ={1}= ={2}= ={11}= [entry] [rendered] > ./pages/a pageA [6] ./stuff/s4.js 31 bytes {4} {6} [built] [10] ./pages/a.js 106 bytes {4} [built] chunk {5} pageB.js (pageB) 199 bytes ={2}= ={12}= [entry] [rendered] > ./pages/b pageB [0] ./stuff/s1.js 31 bytes {5} {7} {9} {10} [built] [7] ./stuff/s7.js 31 bytes {5} {8} [built] [12] ./pages/b.js 106 bytes {5} [built] [14] ./stuff/s8.js 31 bytes {5} [built] chunk {6} pageC.js (pageC) 199 bytes ={2}= ={13}= [entry] [rendered] > ./pages/c pageC [6] ./stuff/s4.js 31 bytes {4} {6} [built] [15] ./pages/c.js 106 bytes {6} [built] [17] ./stuff/s5.js 31 bytes {6} [built] [18] ./stuff/s6.js 31 bytes {6} [built] chunk {7} pageD.js (pageD) 137 bytes ={0}= ={1}= ={3}= [entry] [rendered] > ./pages/d pageD [0] ./stuff/s1.js 31 bytes {5} {7} {9} {10} [built] [19] ./pages/d.js 106 bytes {7} [built] chunk {8} pageE.js (pageE) 93 bytes ={0}= ={3}= [entry] [rendered] > ./pages/e pageE [7] ./stuff/s7.js 31 bytes {5} {8} [built] [20] ./pages/e.js 62 bytes {8} [built] chunk {9} pageF.js (pageF) 137 bytes ={0}= ={1}= ={3}= [entry] [rendered] > ./pages/f pageF [0] ./stuff/s1.js 31 bytes {5} {7} {9} {10} [built] [21] ./pages/f.js 106 bytes {9} [built] chunk {10} pageG.js (pageG) 67 bytes ={0}= [entry] [rendered] > ./pages/g pageG [0] ./stuff/s1.js 31 bytes {5} {7} {9} {10} [built] [22] ./pages/g.js 36 bytes {10} [built] chunk {11} vendors~pageA.js (vendors~pageA) 43 bytes ={1}= ={2}= ={4}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~pageA) > ./pages/a pageA 1 module chunk {12} vendors~pageB.js (vendors~pageB) 43 bytes ={2}= ={5}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~pageB) > ./pages/b pageB 1 module chunk {13} vendors~pageC.js (vendors~pageC) 43 bytes ={2}= ={6}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~pageC) > ./pages/c pageC 1 module ``` webpack-4.30.0/examples/many-pages/build.js000066400000000000000000000001231345416772700205420ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; global.NO_REASONS = true; require("../build-common");webpack-4.30.0/examples/many-pages/node_modules/000077500000000000000000000000001345416772700215665ustar00rootroot00000000000000webpack-4.30.0/examples/many-pages/node_modules/m1.js000066400000000000000000000000531345416772700224370ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/node_modules/m2.js000066400000000000000000000000531345416772700224400ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/node_modules/m3.js000066400000000000000000000000531345416772700224410ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/node_modules/m4.js000066400000000000000000000000531345416772700224420ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/node_modules/m5.js000066400000000000000000000000531345416772700224430ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/node_modules/m6.js000066400000000000000000000000531345416772700224440ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/node_modules/m7.js000066400000000000000000000000531345416772700224450ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/node_modules/m8.js000066400000000000000000000000531345416772700224460ustar00rootroot00000000000000console.log("a module installed from npm");webpack-4.30.0/examples/many-pages/pages/000077500000000000000000000000001345416772700202105ustar00rootroot00000000000000webpack-4.30.0/examples/many-pages/pages/a.js000066400000000000000000000001521345416772700207640ustar00rootroot00000000000000import "m1"; import "m2"; import "m3"; import "../stuff/s2"; import "../stuff/s3"; import "../stuff/s4"; webpack-4.30.0/examples/many-pages/pages/b.js000066400000000000000000000001521345416772700207650ustar00rootroot00000000000000import "m1"; import "m2"; import "m4"; import "../stuff/s1"; import "../stuff/s7"; import "../stuff/s8"; webpack-4.30.0/examples/many-pages/pages/c.js000066400000000000000000000001521345416772700207660ustar00rootroot00000000000000import "m1"; import "m2"; import "m5"; import "../stuff/s4"; import "../stuff/s5"; import "../stuff/s6"; webpack-4.30.0/examples/many-pages/pages/d.js000066400000000000000000000001521345416772700207670ustar00rootroot00000000000000import "m6"; import "m7"; import "m8"; import "../stuff/s1"; import "../stuff/s2"; import "../stuff/s3"; webpack-4.30.0/examples/many-pages/pages/e.js000066400000000000000000000000761345416772700207750ustar00rootroot00000000000000import "m6"; import "m7"; import "m8"; import "../stuff/s7"; webpack-4.30.0/examples/many-pages/pages/f.js000066400000000000000000000001521345416772700207710ustar00rootroot00000000000000import "m6"; import "m7"; import "m8"; import "../stuff/s1"; import "../stuff/s2"; import "../stuff/s3"; webpack-4.30.0/examples/many-pages/pages/g.js000066400000000000000000000000441345416772700207720ustar00rootroot00000000000000import "m6"; import "../stuff/s1"; webpack-4.30.0/examples/many-pages/stuff/000077500000000000000000000000001345416772700202405ustar00rootroot00000000000000webpack-4.30.0/examples/many-pages/stuff/s1.js000066400000000000000000000000371345416772700211210ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/stuff/s2.js000066400000000000000000000000371345416772700211220ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/stuff/s3.js000066400000000000000000000000371345416772700211230ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/stuff/s4.js000066400000000000000000000000371345416772700211240ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/stuff/s5.js000066400000000000000000000000371345416772700211250ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/stuff/s6.js000066400000000000000000000000371345416772700211260ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/stuff/s7.js000066400000000000000000000000371345416772700211270ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/stuff/s8.js000066400000000000000000000000371345416772700211300ustar00rootroot00000000000000console.log("some own module");webpack-4.30.0/examples/many-pages/template.md000066400000000000000000000036301345416772700212500ustar00rootroot00000000000000# Info This example illustrates webpack's algorithm for automatic deduplication using `optimization.splitChunks`. This example application contains 7 pages, each of them importing 1-3 modules from the `node_modules` folder (vendor libs) and 0-3 modules from the `stuff` folder (application modules). In reallity an application is probably more complex, but the same mechanisms apply. The following configuration is used: - `optimization.splitChunks.chunks: "all"` - This opt-in into automatic splitting of initial chunks which is off by default - `optimization.splitChunks.maxInitial/AsyncRequests: 20` - This opt-in into a HTTP2 optimized splitting mode by increasing the allowed amount of requests. Browser only supports 6 requests in parallel for HTTP1.1. # Interpreting the result - `pageA.js` the normal output files for the entrypoint `pageA` - `vendors~pageD~pageE~pageF~pageG.js` vendor libs shared by these pages extracted into a separate output file when larger then the threshold in size - `vendors~pageA.js` vendors only used by a single page but larger than the threshold in size - `pageA~pageD~pageF.js` application modules shared by these pages and larger than the threshold in size The threshold is here 40 bytes, but by default (in a real application) 30kb. Some modules are intentially duplicated, i. e. `./stuff/s4.js` is shared by `pageA` and `pageC`, but it's the only shared module so no separate output file is created because it would be smaller than the threshold. A separate request (which comes with an overhead and worsen gzipping) is not worth the extra bytes. Note: decreasing `maxInitial/AsyncRequest` will increase duplication further to reduce the number of requests. Duplication doesn't affect initial page load, it only affects download size of navigations to other pages of the application. ## webpack.config.js ``` _{{webpack.config.js}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/many-pages/webpack.config.js000066400000000000000000000007531345416772700223340ustar00rootroot00000000000000module.exports = { // mode: "development || "production", entry: { pageA: "./pages/a", pageB: "./pages/b", pageC: "./pages/c", pageD: "./pages/d", pageE: "./pages/e", pageF: "./pages/f", pageG: "./pages/g" }, optimization: { splitChunks: { chunks: "all", maxInitialRequests: 20, // for HTTP2 maxAsyncRequests: 20, // for HTTP2 minSize: 40 // for example only: chosen to match 2 modules // omit minSize in real use case to use the default of 30kb } } }; webpack-4.30.0/examples/mixed/000077500000000000000000000000001345416772700161565ustar00rootroot00000000000000webpack-4.30.0/examples/mixed/README.md000066400000000000000000000450601345416772700174420ustar00rootroot00000000000000This example shows how you can mix different module styles in webpack. Here CommonJs, AMD and Harmony Modules (ES6 Modules) are used. In addition to that there are different types of dynamic requires (`"../require.context/templates/"+amd1+".js"` and `Math.random() < 0.5 ? "./commonjs" : "./amd"`). You see that everything is working nicely together. # example.js ```javascript // CommonJs-style requires var commonjs1 = require("./commonjs"); var amd1 = require("./amd"); var harmony1 = require("./harmony"); // AMD-style requires (with all webpack features) require([ "./commonjs", "./amd", "../require.context/templates/"+amd1+".js", Math.random() < 0.5 ? "./commonjs" : "./amd"], function(commonjs2, amd2, template, randModule) { // Do something with it... } ); ``` # amd.js ```javascript // AMD Module Format define( "app/amd", // anonym is also supported ["./commonjs", "./harmony"], function(commonjs1, harmony1) { // but you can use CommonJs-style requires: var commonjs2 = require("./commonjs"); var harmony2 = require("./harmony"); // Do something... return 456; } ); ``` # commonjs.js ```javascript // CommonJs Module Format module.exports = 123; // but you can use amd style requires require( ["./amd", "./harmony"], function(amd1, harmony) { var amd2 = require("./amd"); var harmony2 = require("./harmony"); } ); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!*********************!*\ !*** ./commonjs.js ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // CommonJs Module Format module.exports = 123; // but you can use amd style requires Promise.resolve(/*! AMD require */).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(/*! ./amd */ 1), __webpack_require__(/*! ./harmony */ 2)]; (function(amd1, harmony) { var amd2 = __webpack_require__(/*! ./amd */ 1); var harmony2 = __webpack_require__(/*! ./harmony */ 2); }).apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);}).catch(__webpack_require__.oe); /***/ }), /* 1 */ /*!****************!*\ !*** ./amd.js ***! \****************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// AMD Module Format !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ./commonjs */ 0), __webpack_require__(/*! ./harmony */ 2)], __WEBPACK_AMD_DEFINE_RESULT__ = (function(commonjs1, harmony1) { // but you can use CommonJs-style requires: var commonjs2 = __webpack_require__(/*! ./commonjs */ 0); var harmony2 = __webpack_require__(/*! ./harmony */ 2); // Do something... return 456; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }), /* 2 */ /*!********************!*\ !*** ./harmony.js ***! \********************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _commonjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./commonjs */ 0); /* harmony import */ var _commonjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_commonjs__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _amd__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./amd */ 1); /* harmony import */ var _amd__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_amd__WEBPACK_IMPORTED_MODULE_1__); // ES6 Modules /* harmony default export */ __webpack_exports__["default"] = (456); /***/ }), /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // CommonJs-style requires var commonjs1 = __webpack_require__(/*! ./commonjs */ 0); var amd1 = __webpack_require__(/*! ./amd */ 1); var harmony1 = __webpack_require__(/*! ./harmony */ 2); // AMD-style requires (with all webpack features) __webpack_require__.e(/*! AMD require */ 1).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [ __webpack_require__(/*! ./commonjs */ 0), __webpack_require__(/*! ./amd */ 1), __webpack_require__(4)("./"+amd1+".js"), Math.random() < 0.5 ? __webpack_require__(/*! ./commonjs */ 0) : __webpack_require__(/*! ./amd */ 1)]; (function(commonjs2, amd2, template, randModule) { // Do something with it... }).apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);}).catch(__webpack_require__.oe); /***/ }) /******/ ]); ``` # dist/1.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */, /* 1 */, /* 2 */, /* 3 */, /* 4 */ /*!******************************************************!*\ !*** ../require.context/templates sync ^\.\/.*\.js$ ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./a.js": 5, "./b.js": 6, "./c.js": 7 }; function webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } function webpackContextResolve(req) { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 4; /***/ }), /* 5 */ /*!*****************************************!*\ !*** ../require.context/templates/a.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 6 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 7 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 1.82 KiB 1 [emitted] output.js 11 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 1010 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./commonjs.js 223 bytes {0} [built] amd require ./commonjs [1] ./amd.js 2:0-12:1 cjs require ./commonjs [1] ./amd.js 7:18-39 harmony side effect evaluation ./commonjs [2] ./harmony.js 2:0-34 cjs require ./commonjs [3] ./example.js 2:16-37 amd require ./commonjs [3] ./example.js 7:0-14:1 amd require ./commonjs [3] ./example.js 7:0-14:1 [1] ./amd.js 298 bytes {0} [built] amd require ./amd [0] ./commonjs.js 5:0-11:1 cjs require ./amd [0] ./commonjs.js 8:13-29 harmony side effect evaluation ./amd [2] ./harmony.js 3:0-24 cjs require ./amd [3] ./example.js 3:11-27 amd require ./amd [3] ./example.js 7:0-14:1 amd require ./amd [3] ./example.js 7:0-14:1 [2] ./harmony.js 96 bytes {0} [built] [exports: default] amd require ./harmony [0] ./commonjs.js 5:0-11:1 cjs require ./harmony [0] ./commonjs.js 9:17-37 amd require ./harmony [1] ./amd.js 2:0-12:1 cjs require ./harmony [1] ./amd.js 8:17-37 cjs require ./harmony [3] ./example.js 4:15-35 [3] ./example.js 396 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js 433 bytes <{0}> [rendered] > [3] ./example.js 7:0-14:1 [4] ../require.context/templates sync ^\.\/.*\.js$ 193 bytes {1} [built] amd require context ../require.context/templates [3] ./example.js 7:0-14:1 [5] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a.js [4] ../require.context/templates sync ^\.\/.*\.js$ ./a.js [6] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b.js [4] ../require.context/templates sync ^\.\/.*\.js$ ./b.js [7] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c.js [4] ../require.context/templates sync ^\.\/.*\.js$ ./c.js ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 600 bytes 1 [emitted] output.js 2.41 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 1010 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./commonjs.js 223 bytes {0} [built] amd require ./commonjs [1] ./amd.js 2:0-12:1 cjs require ./commonjs [1] ./amd.js 7:18-39 harmony side effect evaluation ./commonjs [2] ./harmony.js 2:0-34 cjs require ./commonjs [3] ./example.js 2:16-37 amd require ./commonjs [3] ./example.js 7:0-14:1 amd require ./commonjs [3] ./example.js 7:0-14:1 [1] ./amd.js 298 bytes {0} [built] amd require ./amd [0] ./commonjs.js 5:0-11:1 cjs require ./amd [0] ./commonjs.js 8:13-29 harmony side effect evaluation ./amd [2] ./harmony.js 3:0-24 cjs require ./amd [3] ./example.js 3:11-27 amd require ./amd [3] ./example.js 7:0-14:1 amd require ./amd [3] ./example.js 7:0-14:1 [2] ./harmony.js 96 bytes {0} [built] [exports: default] amd require ./harmony [0] ./commonjs.js 5:0-11:1 cjs require ./harmony [0] ./commonjs.js 9:17-37 amd require ./harmony [1] ./amd.js 2:0-12:1 cjs require ./harmony [1] ./amd.js 8:17-37 cjs require ./harmony [3] ./example.js 4:15-35 [3] ./example.js 396 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js 433 bytes <{0}> [rendered] > [3] ./example.js 7:0-14:1 [4] ../require.context/templates sync ^\.\/.*\.js$ 193 bytes {1} [built] amd require context ../require.context/templates [3] ./example.js 7:0-14:1 [5] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a.js [4] ../require.context/templates sync ^\.\/.*\.js$ ./a.js [6] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b.js [4] ../require.context/templates sync ^\.\/.*\.js$ ./b.js [7] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c.js [4] ../require.context/templates sync ^\.\/.*\.js$ ./c.js ``` webpack-4.30.0/examples/mixed/amd.js000066400000000000000000000004521345416772700172560ustar00rootroot00000000000000// AMD Module Format define( "app/amd", // anonym is also supported ["./commonjs", "./harmony"], function(commonjs1, harmony1) { // but you can use CommonJs-style requires: var commonjs2 = require("./commonjs"); var harmony2 = require("./harmony"); // Do something... return 456; } );webpack-4.30.0/examples/mixed/build.js000066400000000000000000000000331345416772700176070ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/mixed/commonjs.js000066400000000000000000000003371345416772700203440ustar00rootroot00000000000000// CommonJs Module Format module.exports = 123; // but you can use amd style requires require( ["./amd", "./harmony"], function(amd1, harmony) { var amd2 = require("./amd"); var harmony2 = require("./harmony"); } );webpack-4.30.0/examples/mixed/example.js000066400000000000000000000006141345416772700201500ustar00rootroot00000000000000// CommonJs-style requires var commonjs1 = require("./commonjs"); var amd1 = require("./amd"); var harmony1 = require("./harmony"); // AMD-style requires (with all webpack features) require([ "./commonjs", "./amd", "../require.context/templates/"+amd1+".js", Math.random() < 0.5 ? "./commonjs" : "./amd"], function(commonjs2, amd2, template, randModule) { // Do something with it... } ); webpack-4.30.0/examples/mixed/harmony.js000066400000000000000000000001401345416772700201640ustar00rootroot00000000000000// ES6 Modules import commonjs from "./commonjs"; import amd from "./amd"; export default 456; webpack-4.30.0/examples/mixed/template.md000066400000000000000000000013131345416772700203110ustar00rootroot00000000000000This example shows how you can mix different module styles in webpack. Here CommonJs, AMD and Harmony Modules (ES6 Modules) are used. In addition to that there are different types of dynamic requires (`"../require.context/templates/"+amd1+".js"` and `Math.random() < 0.5 ? "./commonjs" : "./amd"`). You see that everything is working nicely together. # example.js ```javascript _{{example.js}}_ ``` # amd.js ```javascript _{{amd.js}}_ ``` # commonjs.js ```javascript _{{commonjs.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/1.output.js ```javascript _{{dist/1.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/mixed/webpack.config.js000066400000000000000000000002251345416772700213730ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/multi-compiler/000077500000000000000000000000001345416772700200125ustar00rootroot00000000000000webpack-4.30.0/examples/multi-compiler/README.md000066400000000000000000000247321345416772700213010ustar00rootroot00000000000000# example.js ```javascript if(ENV === "mobile") { require("./mobile-stuff"); } console.log("Running " + ENV + " build"); ``` # webpack.config.js ```javascript var path = require("path"); var webpack = require("../../"); module.exports = [ { name: "mobile", // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "mobile.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("mobile") }) ] }, { name: "desktop", // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "desktop.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("desktop") }) ] } ]; ``` # dist/desktop.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { if(false) {} console.log("Running " + "desktop" + " build"); /***/ }) /******/ ]); ``` # dist/mobile.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { if(true) { __webpack_require__(/*! ./mobile-stuff */ 1); } console.log("Running " + "mobile" + " build"); /***/ }), /* 1 */ /*!*************************!*\ !*** ./mobile-stuff.js ***! \*************************/ /*! no static exports found */ /***/ (function(module, exports) { // mobile only stuff /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Child mobile: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names mobile.js 4 KiB 0 [emitted] main Entrypoint main = mobile.js chunk {0} mobile.js (main) 114 bytes [entry] [rendered] > ./example main [0] ./example.js 94 bytes {0} [built] single entry ./example main [1] ./mobile-stuff.js 20 bytes {0} [built] cjs require ./mobile-stuff [0] ./example.js 2:1-26 Child desktop: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names desktop.js 3.76 KiB 0 [emitted] main Entrypoint main = desktop.js chunk {0} desktop.js (main) 94 bytes [entry] [rendered] > ./example main [0] ./example.js 94 bytes {0} [built] single entry ./example main ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Child mobile: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names mobile.js 993 bytes 0 [emitted] main Entrypoint main = mobile.js chunk {0} mobile.js (main) 114 bytes [entry] [rendered] > ./example main [0] ./example.js 94 bytes {0} [built] single entry ./example main [1] ./mobile-stuff.js 20 bytes {0} [built] cjs require ./mobile-stuff [0] ./example.js 2:1-26 Child desktop: Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names desktop.js 973 bytes 0 [emitted] main Entrypoint main = desktop.js chunk {0} desktop.js (main) 94 bytes [entry] [rendered] > ./example main [0] ./example.js 94 bytes {0} [built] single entry ./example main ``` webpack-4.30.0/examples/multi-compiler/build.js000066400000000000000000000000711345416772700214450ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-4.30.0/examples/multi-compiler/example.js000066400000000000000000000001361345416772700220030ustar00rootroot00000000000000if(ENV === "mobile") { require("./mobile-stuff"); } console.log("Running " + ENV + " build");webpack-4.30.0/examples/multi-compiler/mobile-stuff.js000066400000000000000000000000241345416772700227400ustar00rootroot00000000000000// mobile only stuffwebpack-4.30.0/examples/multi-compiler/template.md000066400000000000000000000005121345416772700221450ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/desktop.js ```javascript _{{dist/desktop.js}}_ ``` # dist/mobile.js ```javascript _{{dist/mobile.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/multi-compiler/webpack.config.js000066400000000000000000000011261345416772700232300ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = [ { name: "mobile", // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "mobile.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("mobile") }) ] }, { name: "desktop", // mode: "development || "production", entry: "./example", output: { path: path.join(__dirname, "dist"), filename: "desktop.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("desktop") }) ] } ]; webpack-4.30.0/examples/multi-part-library/000077500000000000000000000000001345416772700206105ustar00rootroot00000000000000webpack-4.30.0/examples/multi-part-library/README.md000066400000000000000000000266471345416772700221060ustar00rootroot00000000000000This example demonstrates how to build a complex library with webpack. The library consist of multiple parts that are usable on its own and together. When using this library with script tags it exports itself to the namespace `MyLibrary` and each part to a property in this namespace (`MyLibrary.alpha` and `MyLibrary.beta`). When consuming the library with CommonsJs or AMD it just export each part. We are using multiple entry points (`entry` option) to build every part of the library as separate output file. The `output.filename` option contains `[name]` to give each output file a different name. We are using the `libraryTarget` option to generate a UMD ([Universal Module Definition](https://github.com/umdjs/umd)) module that is consumable in CommonsJs, AMD and with script tags. The `library` option defines the namespace. We are using `[name]` in the `library` option to give every entry a different namespace. You can see that webpack automatically wraps your module so that it is consumable in every environment. All you need is this simple config. Note: You can also use the `library` and `libraryTarget` options without multiple entry points. Then you don't need `[name]`. Note: When your library has dependencies that should not be included in the compiled version, you can use the `externals` option. See [externals example](https://github.com/webpack/webpack/tree/master/examples/externals). # webpack.config.js ```javascript var path = require("path"); module.exports = { // mode: "development || "production", entry: { alpha: "./alpha", beta: "./beta" }, output: { path: path.join(__dirname, "dist"), filename: "MyLibrary.[name].js", library: ["MyLibrary", "[name]"], libraryTarget: "umd" } }; ``` # dist/MyLibrary.alpha.js ```javascript (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["alpha"] = factory(); else root["MyLibrary"] = root["MyLibrary"] || {}, root["MyLibrary"]["alpha"] = factory(); })(window, function() { ```
return /******/ (function(modules) { /* webpackBootstrap */ }) ``` js return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!******************!*\ !*** ./alpha.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "alpha"; /***/ }) /******/ ]); }); ``` # dist/MyLibrary.beta.js ```javascript (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["beta"] = factory(); else root["MyLibrary"] = root["MyLibrary"] || {}, root["MyLibrary"]["beta"] = factory(); })(window, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */, /* 1 */ /*!*****************!*\ !*** ./beta.js ***! \*****************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "beta"; /***/ }) /******/ ]); }); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names MyLibrary.alpha.js 4.12 KiB 0 [emitted] alpha MyLibrary.beta.js 4.12 KiB 1 [emitted] beta Entrypoint alpha = MyLibrary.alpha.js Entrypoint beta = MyLibrary.beta.js chunk {0} MyLibrary.alpha.js (alpha) 25 bytes [entry] [rendered] > ./alpha alpha [0] ./alpha.js 25 bytes {0} [built] single entry ./alpha alpha chunk {1} MyLibrary.beta.js (beta) 24 bytes [entry] [rendered] > ./beta beta [1] ./beta.js 24 bytes {1} [built] single entry ./beta beta ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names MyLibrary.alpha.js 1.19 KiB 0 [emitted] alpha MyLibrary.beta.js 1.19 KiB 1 [emitted] beta Entrypoint alpha = MyLibrary.alpha.js Entrypoint beta = MyLibrary.beta.js chunk {0} MyLibrary.alpha.js (alpha) 25 bytes [entry] [rendered] > ./alpha alpha [0] ./alpha.js 25 bytes {0} [built] single entry ./alpha alpha chunk {1} MyLibrary.beta.js (beta) 24 bytes [entry] [rendered] > ./beta beta [1] ./beta.js 24 bytes {1} [built] single entry ./beta beta ``` webpack-4.30.0/examples/multi-part-library/alpha.js000066400000000000000000000000311345416772700222250ustar00rootroot00000000000000module.exports = "alpha";webpack-4.30.0/examples/multi-part-library/beta.js000066400000000000000000000000301345416772700220520ustar00rootroot00000000000000module.exports = "beta";webpack-4.30.0/examples/multi-part-library/build.js000066400000000000000000000000711345416772700222430ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-4.30.0/examples/multi-part-library/template.md000066400000000000000000000033011345416772700227420ustar00rootroot00000000000000This example demonstrates how to build a complex library with webpack. The library consist of multiple parts that are usable on its own and together. When using this library with script tags it exports itself to the namespace `MyLibrary` and each part to a property in this namespace (`MyLibrary.alpha` and `MyLibrary.beta`). When consuming the library with CommonsJs or AMD it just export each part. We are using multiple entry points (`entry` option) to build every part of the library as separate output file. The `output.filename` option contains `[name]` to give each output file a different name. We are using the `libraryTarget` option to generate a UMD ([Universal Module Definition](https://github.com/umdjs/umd)) module that is consumable in CommonsJs, AMD and with script tags. The `library` option defines the namespace. We are using `[name]` in the `library` option to give every entry a different namespace. You can see that webpack automatically wraps your module so that it is consumable in every environment. All you need is this simple config. Note: You can also use the `library` and `libraryTarget` options without multiple entry points. Then you don't need `[name]`. Note: When your library has dependencies that should not be included in the compiled version, you can use the `externals` option. See [externals example](https://github.com/webpack/webpack/tree/master/examples/externals). # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/MyLibrary.alpha.js ```javascript _{{dist/MyLibrary.alpha.js}}_ ``` # dist/MyLibrary.beta.js ```javascript _{{dist/MyLibrary.beta.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/multi-part-library/webpack.config.js000066400000000000000000000004371345416772700240320ustar00rootroot00000000000000var path = require("path"); module.exports = { // mode: "development || "production", entry: { alpha: "./alpha", beta: "./beta" }, output: { path: path.join(__dirname, "dist"), filename: "MyLibrary.[name].js", library: ["MyLibrary", "[name]"], libraryTarget: "umd" } }; webpack-4.30.0/examples/multiple-entry-points/000077500000000000000000000000001345416772700213545ustar00rootroot00000000000000webpack-4.30.0/examples/multiple-entry-points/README.md000066400000000000000000000604131345416772700226370ustar00rootroot00000000000000This example shows how to use multiple entry points with a commons chunk. In this example you have two (HTML) pages `pageA` and `pageB`. You want to create individual bundles for each page. In addition to this you want to create a shared bundle that contains all modules used in both pages (assuming there are many/big modules in common). The pages also use Code Splitting to load a less used part of the features on demand. You can see how to define multiple entry points via the `entry` option. You can use You can see the output files: - `commons.js` contains: - module `common.js` which is used in both pages - `pageA.js` contains: (`pageB.js` is similar) - the module system - chunk loading logic - the entry point `pageA.js` - it would contain any other module that is only used by `pageA` - `0.chunk.js` is an additional chunk which is used by both pages. It contains: - module `shared.js` You can also see the info that is printed to console. It shows among others: - the generated files - the chunks with file, name and id - see lines starting with `chunk` - the modules that are in the chunks - the reasons why the modules are included - the reasons why a chunk is created - see lines starting with `>` # pageA.js ```javascript var common = require("./common"); require(["./shared"], function(shared) { shared("This is page A"); }); ``` # pageB.js ```javascript var common = require("./common"); require.ensure(["./shared"], function(require) { var shared = require("./shared"); shared("This is page B"); }); ``` # webpack.config.js ```javascript module.exports = { // mode: "development || "production", entry: { pageA: "./pageA", pageB: "./pageB" }, optimization: { splitChunks: { cacheGroups: { commons: { name: "commons", chunks: "initial", minChunks: 2, minSize: 0 } } }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; ``` # pageA.html ```html ``` # dist/commons.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],[ /* 0 */ /*!*******************!*\ !*** ./common.js ***! \*******************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "Common"; /***/ }) ]]); ``` # dist/pageA.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ // add entry modules from loaded chunk to deferred list /******/ deferredModules.push.apply(deferredModules, executeModules || []); /******/ /******/ // run deferred modules when all chunks ready /******/ return checkDeferredModules(); /******/ }; /******/ function checkDeferredModules() { /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ } /******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 2: 0 /******/ }; /******/ /******/ var deferredModules = []; /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // add entry module to deferred list /******/ deferredModules.push([2,0]); /******/ // run deferred modules when ready /******/ return checkDeferredModules(); /******/ }) /************************************************************************/ ```
```javascript /******/ ({ /***/ 2: /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var common = __webpack_require__(/*! ./common */ 0); __webpack_require__.e(/*! AMD require */ 1).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(/*! ./shared */ 1)]; (function(shared) { shared("This is page A"); }).apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);}).catch(__webpack_require__.oe); /***/ }) /******/ }); ``` # dist/pageB.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ // add entry modules from loaded chunk to deferred list /******/ deferredModules.push.apply(deferredModules, executeModules || []); /******/ /******/ // run deferred modules when all chunks ready /******/ return checkDeferredModules(); /******/ }; /******/ function checkDeferredModules() { /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ } /******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ var deferredModules = []; /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // add entry module to deferred list /******/ deferredModules.push([3,0]); /******/ // run deferred modules when ready /******/ return checkDeferredModules(); /******/ }) /************************************************************************/ /******/ ({ /***/ 3: /*!******************!*\ !*** ./pageB.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var common = __webpack_require__(/*! ./common */ 0); __webpack_require__.e(/*! require.ensure */ 1).then((function(require) { var shared = __webpack_require__(/*! ./shared */ 1); shared("This is page B"); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }) /******/ }); ``` # dist/1.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */, /* 1 */ /*!*******************!*\ !*** ./shared.js ***! \*******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var common = __webpack_require__(/*! ./common */ 0); module.exports = function(msg) { console.log(msg); }; /***/ }) ]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.js 369 bytes 1 [emitted] commons.js 258 bytes 0 [emitted] commons pageA.js 9.28 KiB 2 [emitted] pageA pageB.js 9.24 KiB 3 [emitted] pageB Entrypoint pageA = commons.js pageA.js Entrypoint pageB = commons.js pageB.js chunk {0} commons.js (commons) 26 bytes ={2}= ={3}= >{1}< [initial] [rendered] split chunk (cache group: commons) (name: commons) > ./pageA pageA > ./pageB pageB [0] ./common.js 26 bytes {0} [built] cjs require ./common [1] ./shared.js 1:13-32 cjs require ./common [2] ./pageA.js 1:13-32 cjs require ./common [3] ./pageB.js 1:13-32 chunk {1} 1.js 88 bytes <{0}> <{2}> <{3}> [rendered] > ./shared [2] ./pageA.js 2:0-4:2 > [3] ./pageB.js 2:0-5:2 [1] ./shared.js 88 bytes {1} [built] amd require ./shared [2] ./pageA.js 2:0-4:2 require.ensure item ./shared [3] ./pageB.js 2:0-5:2 cjs require ./shared [3] ./pageB.js 3:14-33 chunk {2} pageA.js (pageA) 105 bytes ={0}= >{1}< [entry] [rendered] > ./pageA pageA [2] ./pageA.js 105 bytes {2} [built] single entry ./pageA pageA chunk {3} pageB.js (pageB) 148 bytes ={0}= >{1}< [entry] [rendered] > ./pageB pageB [3] ./pageB.js 148 bytes {3} [built] single entry ./pageB pageB ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.js 121 bytes 1 [emitted] commons.js 94 bytes 0 [emitted] commons pageA.js 2.26 KiB 2 [emitted] pageA pageB.js 2.23 KiB 3 [emitted] pageB Entrypoint pageA = commons.js pageA.js Entrypoint pageB = commons.js pageB.js chunk {0} commons.js (commons) 26 bytes ={2}= ={3}= >{1}< [initial] [rendered] split chunk (cache group: commons) (name: commons) > ./pageA pageA > ./pageB pageB [0] ./common.js 26 bytes {0} [built] cjs require ./common [1] ./shared.js 1:13-32 cjs require ./common [2] ./pageA.js 1:13-32 cjs require ./common [3] ./pageB.js 1:13-32 chunk {1} 1.js 88 bytes <{0}> <{2}> <{3}> [rendered] > ./shared [2] ./pageA.js 2:0-4:2 > [3] ./pageB.js 2:0-5:2 [1] ./shared.js 88 bytes {1} [built] amd require ./shared [2] ./pageA.js 2:0-4:2 require.ensure item ./shared [3] ./pageB.js 2:0-5:2 cjs require ./shared [3] ./pageB.js 3:14-33 chunk {2} pageA.js (pageA) 105 bytes ={0}= >{1}< [entry] [rendered] > ./pageA pageA [2] ./pageA.js 105 bytes {2} [built] single entry ./pageA pageA chunk {3} pageB.js (pageB) 148 bytes ={0}= >{1}< [entry] [rendered] > ./pageB pageB [3] ./pageB.js 148 bytes {3} [built] single entry ./pageB pageB ``` webpack-4.30.0/examples/multiple-entry-points/build.js000066400000000000000000000000721345416772700230100ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/multiple-entry-points/common.js000066400000000000000000000000321345416772700231750ustar00rootroot00000000000000module.exports = "Common";webpack-4.30.0/examples/multiple-entry-points/pageA.html000066400000000000000000000002431345416772700232560ustar00rootroot00000000000000 webpack-4.30.0/examples/multiple-entry-points/pageA.js000066400000000000000000000001511345416772700227240ustar00rootroot00000000000000var common = require("./common"); require(["./shared"], function(shared) { shared("This is page A"); });webpack-4.30.0/examples/multiple-entry-points/pageAB.html000066400000000000000000000003401345416772700233560ustar00rootroot00000000000000 webpack-4.30.0/examples/multiple-entry-points/pageB.js000066400000000000000000000002241345416772700227260ustar00rootroot00000000000000var common = require("./common"); require.ensure(["./shared"], function(require) { var shared = require("./shared"); shared("This is page B"); });webpack-4.30.0/examples/multiple-entry-points/shared.js000066400000000000000000000001301345416772700231520ustar00rootroot00000000000000var common = require("./common"); module.exports = function(msg) { console.log(msg); };webpack-4.30.0/examples/multiple-entry-points/template.md000066400000000000000000000033331345416772700235130ustar00rootroot00000000000000This example shows how to use multiple entry points with a commons chunk. In this example you have two (HTML) pages `pageA` and `pageB`. You want to create individual bundles for each page. In addition to this you want to create a shared bundle that contains all modules used in both pages (assuming there are many/big modules in common). The pages also use Code Splitting to load a less used part of the features on demand. You can see how to define multiple entry points via the `entry` option. You can use You can see the output files: - `commons.js` contains: - module `common.js` which is used in both pages - `pageA.js` contains: (`pageB.js` is similar) - the module system - chunk loading logic - the entry point `pageA.js` - it would contain any other module that is only used by `pageA` - `0.chunk.js` is an additional chunk which is used by both pages. It contains: - module `shared.js` You can also see the info that is printed to console. It shows among others: - the generated files - the chunks with file, name and id - see lines starting with `chunk` - the modules that are in the chunks - the reasons why the modules are included - the reasons why a chunk is created - see lines starting with `>` # pageA.js ```javascript _{{pageA.js}}_ ``` # pageB.js ```javascript _{{pageB.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # pageA.html ```html _{{pageA.html}}_ ``` # dist/commons.js ```javascript _{{dist/commons.js}}_ ``` # dist/pageA.js ```javascript _{{dist/pageA.js}}_ ``` # dist/pageB.js ```javascript _{{dist/pageB.js}}_ ``` # dist/1.js ```javascript _{{dist/1.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/multiple-entry-points/webpack.config.js000066400000000000000000000006051345416772700245730ustar00rootroot00000000000000module.exports = { // mode: "development || "production", entry: { pageA: "./pageA", pageB: "./pageB" }, optimization: { splitChunks: { cacheGroups: { commons: { name: "commons", chunks: "initial", minChunks: 2, minSize: 0 } } }, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/named-chunks/000077500000000000000000000000001345416772700174255ustar00rootroot00000000000000webpack-4.30.0/examples/named-chunks/README.md000066400000000000000000000306271345416772700207140ustar00rootroot00000000000000# example.js ```javascript var a = require("a"); require.ensure(["b"], function(require) { // a named chunk var c = require("c"); }, "my own chunk"); require.ensure(["b"], function(require) { // another chunk with the same name var d = require("d"); }, "my own chunk"); require.ensure([], function(require) { // the same again }, "my own chunk"); require.ensure(["b"], function(require) { // chunk without name var d = require("d"); }); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var a = __webpack_require__(/*! a */ 3); __webpack_require__.e(/*! require.ensure | my own chunk */ 1).then((function(require) { // a named chunk var c = __webpack_require__(/*! c */ 4); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); __webpack_require__.e(/*! require.ensure | my own chunk */ 1).then((function(require) { // another chunk with the same name var d = __webpack_require__(/*! d */ 1); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); __webpack_require__.e(/*! require.ensure | my own chunk */ 1).then((function(require) { // the same again }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); __webpack_require__.e(/*! require.ensure */ 2).then((function(require) { // chunk without name var d = __webpack_require__(/*! d */ 1); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }), /* 3 */ /*!***************************!*\ !*** ./node_modules/a.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module a /***/ }) /******/ ]); ``` # dist/1.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!***************************!*\ !*** ./node_modules/b.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module b /***/ }), /* 1 */ /*!***************************!*\ !*** ./node_modules/d.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module d /***/ }), /* 2 */, /* 3 */, /* 4 */ /*!***************************!*\ !*** ./node_modules/c.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module c /***/ }) ]]); ``` # dist/2.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[2],[ /* 0 */ /*!***************************!*\ !*** ./node_modules/b.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module b /***/ }), /* 1 */ /*!***************************!*\ !*** ./node_modules/d.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports) { // module d /***/ }) ]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 677 bytes 1 [emitted] my own chunk 2.output.js 463 bytes 2 [emitted] output.js 9.07 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 432 bytes >{1}< >{2}< [entry] [rendered] > ./example.js main [2] ./example.js 421 bytes {0} [built] single entry ./example.js main + 1 hidden module chunk {1} 1.output.js (my own chunk) 33 bytes <{0}> [rendered] > [2] ./example.js 13:0-15:18 > [2] ./example.js 3:0-6:18 > [2] ./example.js 8:0-11:18 3 modules chunk {2} 2.output.js 22 bytes <{0}> [rendered] > [2] ./example.js 17:0-20:2 2 modules ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 112 bytes 1, 2 [emitted] my own chunk 2.output.js 92 bytes 2 [emitted] output.js 2.19 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 432 bytes >{1}< >{2}< [entry] [rendered] > ./example.js main [2] ./example.js 421 bytes {0} [built] single entry ./example.js main + 1 hidden module chunk {1} 1.output.js (my own chunk) 33 bytes <{0}> [rendered] > [2] ./example.js 13:0-15:18 > [2] ./example.js 3:0-6:18 > [2] ./example.js 8:0-11:18 3 modules chunk {2} 2.output.js 22 bytes <{0}> [rendered] > [2] ./example.js 17:0-20:2 2 modules ``` webpack-4.30.0/examples/named-chunks/build.js000066400000000000000000000000331345416772700210560ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/named-chunks/example.js000066400000000000000000000006451345416772700214230ustar00rootroot00000000000000var a = require("a"); require.ensure(["b"], function(require) { // a named chunk var c = require("c"); }, "my own chunk"); require.ensure(["b"], function(require) { // another chunk with the same name var d = require("d"); }, "my own chunk"); require.ensure([], function(require) { // the same again }, "my own chunk"); require.ensure(["b"], function(require) { // chunk without name var d = require("d"); }); webpack-4.30.0/examples/named-chunks/node_modules/000077500000000000000000000000001345416772700221025ustar00rootroot00000000000000webpack-4.30.0/examples/named-chunks/node_modules/a.js000066400000000000000000000000131345416772700226520ustar00rootroot00000000000000// module awebpack-4.30.0/examples/named-chunks/node_modules/b.js000066400000000000000000000000131345416772700226530ustar00rootroot00000000000000// module bwebpack-4.30.0/examples/named-chunks/node_modules/c.js000066400000000000000000000000131345416772700226540ustar00rootroot00000000000000// module cwebpack-4.30.0/examples/named-chunks/node_modules/d.js000066400000000000000000000000131345416772700226550ustar00rootroot00000000000000// module dwebpack-4.30.0/examples/named-chunks/template.md000066400000000000000000000005121345416772700215600ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/1.output.js ```javascript _{{dist/1.output.js}}_ ``` # dist/2.output.js ```javascript _{{dist/2.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/named-chunks/webpack.config.js000066400000000000000000000002251345416772700226420ustar00rootroot00000000000000module.exports = { optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/node_modules/000077500000000000000000000000001345416772700175255ustar00rootroot00000000000000webpack-4.30.0/examples/node_modules/module.js000066400000000000000000000000321345416772700213430ustar00rootroot00000000000000module.exports = "module";webpack-4.30.0/examples/require.context/000077500000000000000000000000001345416772700202075ustar00rootroot00000000000000webpack-4.30.0/examples/require.context/README.md000066400000000000000000000177531345416772700215030ustar00rootroot00000000000000# example.js ``` javascript function getTemplate(templateName) { return require("./templates/"+templateName); } console.log(getTemplate("a")); console.log(getTemplate("b")); ``` # templates/ * a.js * b.js * c.js All templates are of this pattern: ``` javascript module.exports = function() { return "This text was generated by template X"; } ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { function getTemplate(templateName) { return __webpack_require__(1)("./"+templateName); } console.log(getTemplate("a")); console.log(getTemplate("b")); /***/ }), /* 1 */ /*!*********************************!*\ !*** ./templates sync ^\.\/.*$ ***! \*********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./a": 2, "./a.js": 2, "./b": 3, "./b.js": 3, "./c": 4, "./c.js": 4 }; function webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } function webpackContextResolve(req) { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 1; /***/ }), /* 2 */ /*!************************!*\ !*** ./templates/a.js ***! \************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 3 */ /*!************************!*\ !*** ./templates/b.js ***! \************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 4 */ /*!************************!*\ !*** ./templates/c.js ***! \************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 5.39 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 603 bytes [entry] [rendered] > ./example.js main [0] ./example.js 146 bytes {0} [built] single entry ./example.js main [1] ./templates sync ^\.\/.*$ 217 bytes {0} [built] cjs require context ./templates [0] ./example.js 2:8-44 [2] ./templates/a.js 80 bytes {0} [optional] [built] context element ./a [1] ./templates sync ^\.\/.*$ ./a context element ./a.js [1] ./templates sync ^\.\/.*$ ./a.js [3] ./templates/b.js 80 bytes {0} [optional] [built] context element ./b [1] ./templates sync ^\.\/.*$ ./b context element ./b.js [1] ./templates sync ^\.\/.*$ ./b.js [4] ./templates/c.js 80 bytes {0} [optional] [built] context element ./c [1] ./templates sync ^\.\/.*$ ./c context element ./c.js [1] ./templates sync ^\.\/.*$ ./c.js ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.53 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 603 bytes [entry] [rendered] > ./example.js main [0] ./templates/a.js 80 bytes {0} [optional] [built] context element ./a [4] ./templates sync ^\.\/.*$ ./a context element ./a.js [4] ./templates sync ^\.\/.*$ ./a.js [1] ./templates/b.js 80 bytes {0} [optional] [built] context element ./b [4] ./templates sync ^\.\/.*$ ./b context element ./b.js [4] ./templates sync ^\.\/.*$ ./b.js [2] ./templates/c.js 80 bytes {0} [optional] [built] context element ./c [4] ./templates sync ^\.\/.*$ ./c context element ./c.js [4] ./templates sync ^\.\/.*$ ./c.js [3] ./example.js 146 bytes {0} [built] single entry ./example.js main [4] ./templates sync ^\.\/.*$ 217 bytes {0} [built] cjs require context ./templates [3] ./example.js 2:8-44 ``` # Code Splitting See [this example combined with code splitting](../code-splitted-require.context) webpack-4.30.0/examples/require.context/build.js000066400000000000000000000000331345416772700216400ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/require.context/example.js000066400000000000000000000002221345416772700221740ustar00rootroot00000000000000function getTemplate(templateName) { return require("./templates/"+templateName); } console.log(getTemplate("a")); console.log(getTemplate("b"));webpack-4.30.0/examples/require.context/template.md000066400000000000000000000007421345416772700223470ustar00rootroot00000000000000# example.js ``` javascript _{{example.js}}_ ``` # templates/ * a.js * b.js * c.js All templates are of this pattern: ``` javascript module.exports = function() { return "This text was generated by template X"; } ``` # dist/output.js ``` javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` # Code Splitting See [this example combined with code splitting](../code-splitted-require.context) webpack-4.30.0/examples/require.context/templates/000077500000000000000000000000001345416772700222055ustar00rootroot00000000000000webpack-4.30.0/examples/require.context/templates/a.js000066400000000000000000000001201345416772700227540ustar00rootroot00000000000000module.exports = function() { return "This text was generated by template A"; }webpack-4.30.0/examples/require.context/templates/b.js000066400000000000000000000001201345416772700227550ustar00rootroot00000000000000module.exports = function() { return "This text was generated by template B"; }webpack-4.30.0/examples/require.context/templates/c.js000066400000000000000000000001201345416772700227560ustar00rootroot00000000000000module.exports = function() { return "This text was generated by template C"; }webpack-4.30.0/examples/require.resolve/000077500000000000000000000000001345416772700202025ustar00rootroot00000000000000webpack-4.30.0/examples/require.resolve/README.md000066400000000000000000000134701345416772700214660ustar00rootroot00000000000000# example.js ``` javascript var a = require("./a"); // get module id var aId = require.resolve("./a.js"); // clear module in require.cache delete require.cache[aId]; // require module again, it should be reexecuted var a2 = require("./a"); // verify it if(a == a2) throw new Error("Cache clear failed :("); ``` # a.js ``` javascript module.exports = Math.random(); ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var a = __webpack_require__(/*! ./a */ 1); // get module id var aId = /*require.resolve*/(/*! ./a.js */ 1); // clear module in require.cache delete __webpack_require__.c[aId]; // require module again, it should be reexecuted var a2 = __webpack_require__(/*! ./a */ 1); // verify it if(a == a2) throw new Error("Cache clear failed :("); /***/ }), /* 1 */ /*!**************!*\ !*** ./a.js ***! \**************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = Math.random(); /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 4.21 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 313 bytes [entry] [rendered] > ./example.js main [0] ./example.js 282 bytes {0} [built] single entry ./example.js main [1] ./a.js 31 bytes {0} [built] cjs require ./a [0] ./example.js 1:8-22 require.resolve ./a.js [0] ./example.js 4:10-35 cjs require ./a [0] ./example.js 10:9-23 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 1.03 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 313 bytes [entry] [rendered] > ./example.js main [0] ./a.js 31 bytes {0} [built] cjs require ./a [1] ./example.js 1:8-22 require.resolve ./a.js [1] ./example.js 4:10-35 cjs require ./a [1] ./example.js 10:9-23 [1] ./example.js 282 bytes {0} [built] single entry ./example.js main ``` webpack-4.30.0/examples/require.resolve/a.js000066400000000000000000000000371345416772700207600ustar00rootroot00000000000000module.exports = Math.random();webpack-4.30.0/examples/require.resolve/build.js000066400000000000000000000000331345416772700216330ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/require.resolve/example.js000066400000000000000000000004321345416772700221720ustar00rootroot00000000000000var a = require("./a"); // get module id var aId = require.resolve("./a.js"); // clear module in require.cache delete require.cache[aId]; // require module again, it should be reexecuted var a2 = require("./a"); // verify it if(a == a2) throw new Error("Cache clear failed :(");webpack-4.30.0/examples/require.resolve/template.md000066400000000000000000000003701345416772700223370ustar00rootroot00000000000000# example.js ``` javascript _{{example.js}}_ ``` # a.js ``` javascript _{{a.js}}_ ``` # dist/output.js ``` javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/scope-hoisting/000077500000000000000000000000001345416772700200035ustar00rootroot00000000000000webpack-4.30.0/examples/scope-hoisting/README.md000066400000000000000000000417021345416772700212660ustar00rootroot00000000000000This example demonstrates Scope Hoisting in combination with Code Splitting. This is the dependency graph for the example: (solid lines express sync imports, dashed lines async imports) ![](graph.png) All modules except `cjs` are EcmaScript modules. `cjs` is a CommonJs module. The interesting thing here is that putting all modules in single scope won't work, because of multiple reasons: - Modules `lazy`, `c`, `d` and `cjs` need to be in a separate chunk - Module `shared` is accessed by two chunks (different scopes) - Module `cjs` is a CommonJs module ![](graph2.png) webpack therefore uses a approach called **"Partial Scope Hoisting"** or "Module concatenation", which chooses the largest possible subsets of ES modules which can be scope hoisted and combines them with the default webpack primitives. ![](graph3.png) While module concatenation identifiers in modules are renamed to avoid conflicts and internal imports are simplified. External imports and exports from the root module use the existing ESM constructs. # example.js ```javascript import { a, x, y } from "a"; import * as b from "b"; import("./lazy").then(function(lazy) { console.log(a, b.a(), x, y, lazy.c, lazy.d.a, lazy.x, lazy.y); }); ``` # lazy.js ```javascript export * from "c"; import * as d from "d"; export { d }; ``` # a.js ```javascript // module a export var a = "a"; export * from "shared"; ``` # b.js ```javascript // module b export function a() { return "b"; }; ``` # c.js ```javascript // module c import { c as e } from "cjs"; export var c = String.fromCharCode(e.charCodeAt(0) - 2); export { x, y } from "shared"; ``` # d.js ```javascript // module d export var a = "d"; ``` # cjs.js ```javascript // module cjs (commonjs) exports.c = "e"; ``` # shared.js ```javascript // shared module export var x = "x"; export * from "shared2"; ``` # shared2.js ```javascript // shared2 module export var y = "y"; ``` # webpack.config.js ```javascript module.exports = { // mode: "development" || "production", optimization: { usedExports: true, concatenateModules: true, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************************************!*\ !*** ./node_modules/shared.js + 1 modules ***! \********************************************/ /*! exports provided: x, y */ /*! exports used: x, y */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // CONCATENATED MODULE: ./node_modules/shared2.js // shared2 module var y = "y"; // CONCATENATED MODULE: ./node_modules/shared.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return x; }); /* concated harmony reexport y */__webpack_require__.d(__webpack_exports__, "b", function() { return y; }); // shared module var x = "x"; /***/ }), /* 1 */ /*!********************************!*\ !*** ./example.js + 2 modules ***! \********************************/ /*! no exports provided */ /*! all exports used */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/shared.js because of ./node_modules/c.js */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: ./node_modules/shared.js + 1 modules var shared = __webpack_require__(0); // CONCATENATED MODULE: ./node_modules/a.js // module a var a = "a"; // CONCATENATED MODULE: ./node_modules/b.js // module b function b_a() { return "b"; }; // CONCATENATED MODULE: ./example.js __webpack_require__.e(/*! import() */ 1).then(__webpack_require__.bind(null, /*! ./lazy */ 3)).then(function(lazy) { console.log(a, b_a(), shared["a" /* x */], shared["b" /* y */], lazy.c, lazy.d.a, lazy.x, lazy.y); }); /***/ }) /******/ ]); ``` # dist/1.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */, /* 1 */, /* 2 */ /*!*****************************!*\ !*** ./node_modules/cjs.js ***! \*****************************/ /*! no static exports found */ /*! exports used: c */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports) { // module cjs (commonjs) exports.c = "e"; /***/ }), /* 3 */ /*!*****************************!*\ !*** ./lazy.js + 2 modules ***! \*****************************/ /*! exports provided: d, c, x, y */ /*! all exports used */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/cjs.js (<- Module is not an ECMAScript module) */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/shared.js */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); var d_namespaceObject = {}; __webpack_require__.r(d_namespaceObject); __webpack_require__.d(d_namespaceObject, "a", function() { return a; }); // EXTERNAL MODULE: ./node_modules/cjs.js var cjs = __webpack_require__(2); // EXTERNAL MODULE: ./node_modules/shared.js + 1 modules var shared = __webpack_require__(0); // CONCATENATED MODULE: ./node_modules/c.js // module c var c = String.fromCharCode(cjs["c"].charCodeAt(0) - 2); // CONCATENATED MODULE: ./node_modules/d.js // module d var a = "d"; // CONCATENATED MODULE: ./lazy.js /* concated harmony reexport c */__webpack_require__.d(__webpack_exports__, "c", function() { return c; }); /* concated harmony reexport x */__webpack_require__.d(__webpack_exports__, "x", function() { return shared["a" /* x */]; }); /* concated harmony reexport y */__webpack_require__.d(__webpack_exports__, "y", function() { return shared["b" /* y */]; }); /* concated harmony reexport d */__webpack_require__.d(__webpack_exports__, "d", function() { return d_namespaceObject; }); /***/ }) ]]); ``` Minimized ```javascript (window.webpackJsonp=window.webpackJsonp||[]).push([[1],[,,function(n,r){r.c="e"},function(n,r,t){"use strict";t.r(r);var c={};t.r(c),t.d(c,"a",function(){return e});var o=t(2),u=t(0),d=String.fromCharCode(o.c.charCodeAt(0)-2),e="d";t.d(r,"c",function(){return d}),t.d(r,"x",function(){return u.a}),t.d(r,"y",function(){return u.b}),t.d(r,"d",function(){return c})}]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 1.9 KiB 1 [emitted] output.js 9.41 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 372 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./node_modules/shared.js + 1 modules 100 bytes {0} [built] [exports: x, y] [all exports used] harmony side effect evaluation shared [1] ./example.js + 2 modules 3:0-23 harmony export imported specifier shared [1] ./example.js + 2 modules 3:0-23 harmony side effect evaluation shared [3] ./lazy.js + 2 modules 6:0-30 harmony export imported specifier shared [3] ./lazy.js + 2 modules 6:0-30 harmony export imported specifier shared [3] ./lazy.js + 2 modules 6:0-30 | 2 modules [1] ./example.js + 2 modules 272 bytes {0} [built] [no exports] single entry ./example.js main | ./example.js 161 bytes [built] | [no exports] | single entry ./example.js main | + 2 hidden modules chunk {1} 1.output.js 273 bytes <{0}> [rendered] > ./lazy [] 4:0-16 [3] ./lazy.js + 2 modules 231 bytes {1} [built] [exports: d, c, x, y] import() ./lazy ./example.js 4:0-16 | ./lazy.js 57 bytes [built] | [exports: d, c, x, y] | import() ./lazy ./example.js 4:0-16 | + 2 hidden modules + 1 hidden module ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 369 bytes 1 [emitted] output.js 2.17 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 372 bytes >{1}< [entry] [rendered] > ./example.js main [0] ./node_modules/shared.js + 1 modules 100 bytes {0} [built] [exports: x, y] [all exports used] harmony side effect evaluation shared [1] ./example.js + 2 modules 3:0-23 harmony export imported specifier shared [1] ./example.js + 2 modules 3:0-23 harmony side effect evaluation shared [3] ./lazy.js + 2 modules 6:0-30 harmony export imported specifier shared [3] ./lazy.js + 2 modules 6:0-30 harmony export imported specifier shared [3] ./lazy.js + 2 modules 6:0-30 | 2 modules [1] ./example.js + 2 modules 272 bytes {0} [built] [no exports] single entry ./example.js main | ./example.js 161 bytes [built] | [no exports] | single entry ./example.js main | + 2 hidden modules chunk {1} 1.output.js 273 bytes <{0}> [rendered] > ./lazy [] 4:0-16 [3] ./lazy.js + 2 modules 231 bytes {1} [built] [exports: d, c, x, y] import() ./lazy ./example.js 4:0-16 | ./lazy.js 57 bytes [built] | [exports: d, c, x, y] | import() ./lazy ./example.js 4:0-16 | + 2 hidden modules + 1 hidden module ``` webpack-4.30.0/examples/scope-hoisting/build.js000066400000000000000000000000331345416772700214340ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/scope-hoisting/example.js000066400000000000000000000002411345416772700217710ustar00rootroot00000000000000import { a, x, y } from "a"; import * as b from "b"; import("./lazy").then(function(lazy) { console.log(a, b.a(), x, y, lazy.c, lazy.d.a, lazy.x, lazy.y); }); webpack-4.30.0/examples/scope-hoisting/graph.png000066400000000000000000000401021345416772700216070ustar00rootroot00000000000000PNG  IHDR5RAu)tEXtcopyleftGenerated by http://plantuml.com094zTXtplantumlxeOO@E`FbfێeMK~z-$*̛\m5}{eB²sοvgRū5nK3NQ=6YLmR@HQ8{RB8pOxIDATx \Uyeke ELWR7 IXXeB@ b 55o96M ,<3̙YԨPdSFɦFM%5J65Jo*[RW*"+{{\\O-UdM[\';;ݒ iѩe;~[4amIcm9s)]b^QvGDbbQxJzvlEghkl_;P}YW Jb_=(` NcdmrEv[OuM6kAYױX Rzȟ^*(G}[e5O^ZQg Y߀;fI2Lk2 ]+7j2mDEEn-]~@(کV"#=vvڵ ɣGC6o15pvvc:thצM WW'ҳgw|{oed'}>[^ͮcwz.XzO$t`M_&ԏQ"c$h @ʓ'u^z֭O'yyH$q&dw-ie`eE|eP{d BY8㇢ ƍK@$}ka6UX(2^ bIl/y"3FFf3Ҙ~^8 ]7(')D h%K~-ho℄SNUUU1mk{Wqj%#?,)`"7tޅ,2wqq8#)TUNϳxR9VU%oRS:i*p%vfh(-'mb9DKC+n؂P1߹sYYAدPn{ Jiii8^=mm}#ǩ'lA_h9ۀI#A*=ٕjXv ЫRw]AÇYbQCA#ȀIH ('\  i-lyAE6֭Xa׮ߛ7av]d5ErTA;H$bT67gK B'.S%g74hndh iUk M ;88X& 1N :nIN,v M [5ҐKΣ ¨( _٬k;ΆUNvCAw/㊺} +9Ғ];坆` ƑF{n伿YH(S& #ݯ4_ȆjGk!#wUwِKyke*nfm=G^^k>_(94ya], 6wta ѵX@ A va ن@߿((D+4l1׆uI q/b޶eD<5]^|{rMߢ u˃]HlkL {~DUlQ^Q2cmX,H&wf=W|xhpbb/dB 4{o)d#@￞0zX8^5Aurs chȰ=mZ* Xk\¬IPّ: $P%ɡ#=|>s(`a:7|NT14^zAC:d8^-khUWo |7\wǸ}G=k5H4[3m |]S% ]6 5=nkmhj-Gޘ(]0s` FՒ:X<\Ptq޽c8ʭlKJ5% 78D$\&kK1 KG`A~}2n@2MR5u? 2 c46ZVGtô:֌|HCpGaM#Z;̗>CC RM8$-l"Ueu?'C5\͚?Jޤ6zWwln0Z3*tT!"@=x7lM~heɹAh=*r$N~h &0 GPki 'S4q9h f3?R1IɄo[ޓ;jsȄŢs ~S>_`MT!y|?[OېbYәP*3E#]оu)nű2}bٽMq8:ng!yE? ?].ZZ:i}℅?qZUߞ8]tZbώW݋Re{'V'O_zA{RX t9;U4f^I'+p |`ϡΡ]ǐD=:ӌ+ /:/:xfgˆg,,T~u".D@d2F9ɋ}6-ӯC*~w.f((ElA0f_s0Ox-qc•^zN캈Y. %7փvyA# jp3V%N4@E+EcHM$\Hfa)٪P܀PSd}#3f>cM|…Uq9ShVQ+]D:,??2ӗҋd7D9;>fIa DK\Xc;Ů F`xq5؈q+j7G,2e=e;0P1,J̘8nD_,}ʥ$k WIv_~M3[}ƒk7m.g#Vu*:#vU݈q WA)ڲ4/뽵^+ sv4s`ޒ*ndknd!aX?t>k5tYC!f%[퓨%cOyDuSlmYMFjEJdžjېƨIh P6O '~T5 in#u}hَ4\M;k4v9,9gVl L1wd7=aCB(O>/&ômd*ftf8| 1x l$lBN Vk914Q|;IbdujJak)iQ]6~t6kg6FidcHjm^];٨mȎg9Lsnjk\Et}gLҜ0^$5+jVý- k:-m*:"\/.ה_nȠF6۠Rh.>6QI&+eVթHyJ66VO9C6sB!0Ƒ( *. i1-! 䐵}KXHym>}\h!gf>S>rr5.]):hQHdSY Rjwd#h[av/E]APZ=I;Ӭn0NmC zSz?I/o4FM#*-G!~ mVʂ:5OǷ6cz54jz <~ ':JvPNiqfCoZwd`yY(D[~!᧡kkov,0^N_ ?*0T #b?gT*MZK>lFV0 Nv68<1e^ >ѽRVHN5qҰ' koCEdo[[ ]Y e{63|Ⱥ?tC' [?-XC'a~b_V `ą:fY%#]O+LvMFAcD㕚YDlO6aÜ 8mE ,gL^G/|`ZE#iS#=lt*PwdCXG,i34xš@4^S3váFN6tmI WMR ZZ,nuO7tG6696R2) ^yuXhDrDPy1I$o ȺMֺ#;s:ٿƳP$NDoGGD$ua|#xvßZz60Lq0'*CN>}~ g^᜘t **'C8䑟"HN^+8o(F*:C.{9ک0\=[ƺlzy8+ju`!k+}ppSO^-LkӸӳAp>K Csn^pU3gew‡f#oȖz-j 8>gs>{%\OT_4lf?c327y`qrSɮy\X/zyd9,v6]gd=yGk8::NV~gm=p) ϟb@Σ)"<몜FW[EϢ*6;ݩ׹$9m xHҴ4t.ZJ8h",#G~x@+ws#曯)'Q#:5"Vˊ&1VS_l *йA6i#8SSطiiP(BϨ̧!H%ͫțPr|Sr6]>VQ',0&ʝ\8&ڨAv Ḑ"WWhXV%g+|StvɮJvMҹ!nl3p ҳ`@=yu& jSyͫȫKvo¹O1,U~ހ'dР~}|fs=;=[$^>Mr&Zg`gwSu`{!log\狋хזdIrΧ;[&Cdl%[0{8CR̝Po4M'bFwy@hyh?[P婢Tv{? %] 2~Y\ D!F޹W49?vg(8?v}ld%$BmyU"oL/cz^ACmNq$s0u ?ְ2qN%X "88X}CKm/퇾Ȓ3I"O޶y{V/s (ٺ&G~pF3VOQyD6 mR& M@] kJ. 5b]^l!)(62t{\YMˋmdCjK;12 -dTJ!n["::?.QCYwL )'= W^QC6yɃsvaMOk'\5aM iV_ԾA05%/d_a g)<%d3[dXrpkJ6O6$o`CF~ kJ6_Ȇ۬y֑'\ 5JdBW߂{ BX{(FH6vCCaJgwyQlp\ǩʍsv筇l Kmd?}/)نD6r~Ad;n6ddlJ{Wcsv7klC"aMYqz7 <md?=Sl֑'\4JdՓnأfˋMɮ.%s D{B e2*%۰?דȀ&bmS |:|ZiNBUT^de-ur+]WJօݫ''rfَ>jϰ],Y n?y*]~PefdcwL+|t'K47ThW9 W854 Ѐ,i'VIlsᳰduW.]6VH6dt-Hȋȑ:NϪ4 踑Nu9P9\{cÂ`k 3T1>&Ƀ ]}k1C' 7%||qIRP^A~v{YY7Op@x`PbLs˽َ7&_>k(u_xQiV5LPדڛEv411%wW)=xG BeY}RF+}yO233 nձh״T+INd/nez*PDF'Sk]~K~ُnމnwJU5&軶a- mv܄ >ˣ;Ya/ \SQQP-Sč駟d#:thצM>0;YBB [{x;1'& g?OtޥU'vvmu{y>WWU>=}}]UlH%HӾ*..&pbzOKY! &3B׳gwAa7T Č%]Lj℄SN!FMT ԓӝTa_7?zٳ'Xs@3:y2ɓ5k'?:u[m|~S&]K2|Pekw.26-%ͷEoR躡^cb4媪(Pu(M[RiZZ4ɾUTþ(: (Ț55ʃۇfwNϳ?)/f9Ò-G:' >5Տ*-dWFg3{F7T捬"wIr^JXCQ?"p%I':5OE)CCw@f(' ~Ҥ1Mj ?A%}+wME6qB팊o*Synlz X588X&!hV,̞=A ޽Q y +^ Vl6&*mChn:AAADZE-PìPB6z|sC"=@ lfX H999JWu6bᇊQ$99RE]vPEA]HP"FQ+%e6DvrX1X$;Dr")J$97"8 t !6,W]CաPN~ffg7:)|00tv쬬z'$ooFn Usb3ya?+U숈mg/]Ɇ]˔ϟ3sԝz| _msn5H <ԽlBɆ]Fߝ0^ ,O2C^k(lOM, mѕD >oDx=ϛvɆ8Web e+~~xɷ ÈD"$*+~avxǑiVשct.A@v:5tRa۶y#f7ݗ;e Fϑ+>S2M<<͚6gg `qhYWjNNL [.# N}dzVO UZDI5Hwa>cHKnmd59hN@LUr=E:30q2_@R5IQ$[X|&܋[ADӜ "X3Pbv YL!3 }I~׺Ө4;'Y:ڻ1J }2+cex\I[k'*l6ęim -.h5f:U-k8rprta|+7 : 5~ďp(psz&+#+ھ#ґ}ְPԁYFpXyQq!aR9FnF.- }ܾ*1]7y#!I$r*0  -2虝;J1ԈhAz-1 0MXůOwFzeT qTD $$$0۽e]-y AIѽ> !fIlXXF4lnFX#4o`!;{9~.z{\+ke*|n•٫֟]߾~VvoS>2r$ɋGaPg 3i)0,ApnDPH7'`Ռ?qP»Y !9DhtHsnoOHV@|g¹D? 8qcT*me #/\+O?~\}+C2lSJ'\#dN.F$C+]i|X{UddGdqB\yxJ(]cR=!=>(뾂Lakdh87 ʹ m[!D$>#2 3C67$ ^Ȏr˹ 3PȬEfB3pn:8޺yD!D$>/Uk캈YPNr9tI}IFwe.$7 md@+*kS QNr9 daP[\I7juGr3M5Bm+@ o }٤zXR3iPdSFɦFɦdSdSQ)(ԨQQdSdSQ)(ٔljlj(ԨQQ)(ٔljlJ65J65jlj((ٔljlJ65J6%%5J65J6%%MMɦFɦdSdSFɦFɦdSdSQ)(ٔljlj((ٔljlJ65J6%Z# %d+|K}]XQ/թy$ٿUV}/Dc^UZO UgGd I&d_OʔV5&& 4Fh%Q3`a}LÞ}h Q3x/&J RCk'.c&Axi >5DɆ.` 6Ê7f$d?yG~Q#XCHȆ,F놚ڍ{WQ~-NC8d_Ɠ7 (TvS `DVX~@\1cfsczOk?,^GGN2os.q'oxwZԴB68{Rh| /OgZr1>~]Cò.6sJznd^ś'9 Wd.Fbz[˺Zpa`w(f詊(tl*! @` XkgeG^Hߣ#__O` 2ÈG&v_bpieS7dĒIs@ϟ:qyEp%U/7 /t40o@VQ9uJv=RO!K33B/J94yΫA9q;Yg݅8ZYߒaJ#- ;e XďOt)[e5fZ|tݏ)lVZzЂh 1&.';{~D[Cʄt/2l7i]bݿz|]oߝ:=)y#n3Tlf 4'2,993rYQͨl @Z^8zQ)8kLc-nnv!5Ғݻ'.3qvcIҁi[tM蠊l'jFe䍔F `"`yE }'g+˯%)KsH~W@7g-Y0{Q8ٹ M4+4-M- `ȳνA79cb}¸?q\u7n?젿.E9a+=>cvKcΖn%4-c/Oi_, ., *0㢩%]oO@R8!YK?&UIKE.9>2̘gl1 ׊!Y{ҌoY,8 y2ݢM7@ "$ץ.j``>y_=eJ7ۅkwۉ"% {@O5cد&iJJY.P,S \Xc {~ho,4ISK9 hQ`!ck,J1=bfJK9 hQ`!ck,J1=bfJ֭. XcaUbcj! m5 +5c 5J65jlj-5BIENDB`webpack-4.30.0/examples/scope-hoisting/graph.svg000066400000000000000000000151721345416772700216330ustar00rootroot00000000000000exampleabsharedshared2lazycdcjswebpack-4.30.0/examples/scope-hoisting/graph2.png000066400000000000000000000472201345416772700217010ustar00rootroot00000000000000PNG  IHDR.}58M)tEXtcopyleftGenerated by http://plantuml.com09jzTXtplantumlxmQO0ߛ.vލW$ ~(/ׯΝ;ksbb7x>>!I,E8+Q"رc-:u"sS2/נB b5 ?f+EZp(ũ)ïhт$+@5[lkNp:l*:oEB(imS'6ȓ=~(b'88;ϟ [ž:oEB(>f&8uk׮ŋt@"߬Yy߾}QsbH(EHJJ端 /yԿĨ#b]LHmҤJ(*eH$|Ĉ"HB("HB("H($"H($" H(" HB(" HB(" HB(" HB(" HB(" HB(U))[^մ۵"l= IE][,K=:}ϼt'/ys'i] ]b^eTl /=Z|Y\" 噇l k.i[p:p .C+&`;y`^{6OZ4/rOGEyEڂ%'WGd{Nj3wt@`/HK7Cl8 ӝț75""PBCg&X=5F=3&e QW#-ZvY7˳A ze EBѨ(eپLLΞԓVḛ2BTEBH("*"k%fH`ӗ ۟FʂW^ǥ"QD,ww=s塰f# ~p&}<"hXʛ;X,@z"ө7F߻H" D,'c;R p:֩ݩq{= Eӣ.QXŒњȶӁkwOly͛75P$ btpмB͚HШ>r i$ ExfS4eK57߄:_K͚>{8|a^׮BC _`c݃.ӠAz:;z5i-no;ujs挂YP\|Y[| e+I浨ˁ4Q7wNj3XvmcQKj?wD"WO=~3p5{0R*I@o>CFc؏_buE|S"m␕_C EBQ())C@ʤ}T\Ͽq# @ѣƍ ]oKK҂#o"i\A ҄FBP3ײ`hn $[΋!!?s'%%? dӼdzսTYRMɆ@=D-KJJ-))y&H( +jV…Se˦ ?s*3/Isd ѣp"h\1Vr߉򖚺y"> :IZ]4~dDԫbX.1 zPoj2pP23{s$~ 0;; x,l͛Xڹs[PD YXWHnd!:61!!!aaaqqqQ EBѨ(B؎mSnuYn]6"f6򿉈XԩSw[7ha"Hn̨\$ Di#;IkWidH$-BP4\SXIy_MoMt^7%$ yEӏAåum >}ţVqqH7Cd@rEB(B sOuʛ/ $8~ /JJ)D!bf;0Ӥ݄ N|0܆U?JTsI Eӣ?{ʒ&̎z/L6~~eڔ)Qķ}gI#! @Mi hza|r|r9!t4TCȜaXX>%k!H(Ee޽;..[>Irpd<[~ ~oe_h?nP2Gx G!H@\&.L33H ҡC`Nz颣ulvs?8k`yPa¬B ; y4+2^T鏫X]EH0qi@\&.LI͛=fr'¾<1}רWzd*>tOs?ZgQőqYs (!}&i*1Zuט՛8 aҘ3,~'\2Ȧ˱.GSu[ߒ1E"P.1I| ]8~)'Ěg7mQys17V2&~2dO^ yAy~.lgsO{`QMFlDQQ`|p!:CH(F2,dEZ"ɘl"+O#Sp7Ht4 6{IugIg..]/ AÃEC(6 Q!$ EӠ $!= de,VCL8=tХkf/]-K",HiՁJQ9>NS3BP(0³Pg EBє(VfDTvY N&-ϜOQ*gNtep:kN H( EMDD('DxQ -'!"lgtep:=>+Hb (V%"@%BA8!n#K$I#IEĽGQIsr1&U(~hBP48g6e}+@ rp'ik"(\^b^nT1o͘L=$>}I!+wb턚G$̵zAz.DC,,W<:hfBQ@(ʚo\ݾU)GPHw 1& Ŵ4˾}j N6C(YԐbQ(zdw):i^(^MqEzUP<@C,EImo56˖VEvU tkE8yyEDiS2\fT&&Qȑ#[&%@CFzX9+L_DM*%Nud(C&Ak*--L| wc9: ʢFP޽{===7n\^0Dᠨܛ6oۻЊYYY%%%"RFn6RwJ`&b[*vVܴipS^|o`o?- Ǝ5)ãG*78S{3ݾmqK|f wK734k׮_tzE;;;Pb7k֬J᭧'FQ5N5nVCiJJ ,W_c5 ~pP#b]LHmҤIFFnƍO8QM@K(Ţ | ;[ؿ_~AHX8 kW]:0TfIBTie;&IEN2\fM0C& EaiޕkzY[g)J\BTʹvW F1T]S9,V.P4~j4χ'FBQ @5dbcLPGZX9O;\lEf[#cR֮z\P4c*Kz|2&= pm@csupM' oy. Ak(9jԇauզ2F(E6,2Ce (Y~1*42HwFբn ]YWDz(7lQ!j E\/Ũ E8w\nPe5TDhSPT cZbK=H BUV4Bs{WKVPcr\>'j ;zAbSܣr‡I7N0Yd?C{}jP[k}PZ[P?ԗk};zGLI }!k`YPq+v|Y8V+P,jg/~2mESʾOmE.mGK7C?pJ8մ|Dv~8`(\T.}4eUy$c򃡆e^ŖTeCKdY2Pk=;C(ם-'U %;MmhS&}x/UٻDo eC' v<^s(,3x;s788`2qJl#{_$- PEڏ7wF\#UXLspxR>.N(V+\-+ZPP?hIpfwy[dIĮ]qļ4\j`ֈG|\s!z/{%l G䎟35;@6]>=:܂4aǗȧQ/D*lEogõ/V. ~26Uh(>}xH|TFܿ*p^8jEokϙ%̔YpRW4hG$GF$lSt]=Ygڄ=劃|W{lG$w[ Ó<χ?kN`L‹ʚ:If~wF(8` Є]-ۇ&?>^y?lwrm|V G۬_QJ79\SXs׮_gXAgO*//7kbP^y#EX(2<==СC%%%FS_|[+~/H{w컃ԪEڑC!+N 4kbӗP'(<1bݻsssB0x*Kм:6 gjUxӢxruX@ v+%K5BDbnpƲ5WRֈ1 m%ے*I?{zuE"N4&ּ&DL˶]PĶo8ICɩKQ<~s~7ߒV7(jՠ;VIjo$A!Fhpk7ΠB$Gh@7Tc/XVzBcdÆȴvv[ێ-b\.GL"\{j66o2rpj{f]fx5-+A0N#pLtlԤ(rą}\sHYCjT(>yիԩ[]$` v}Bg-4tK^kvy~&̫H|\„^Q+jԇ>P!߿v/5<~K R܎EGZ-"֩\Q?20HCn\ sQN}wdڵ[|8޾Bs7U=.{P۶}wf?tV=NcZHR#Xу:=[8|Xʺm>Z}MH$zuV{n^uϺu:ujxW껚%.r&j+"G:ƵE |ՠ+Jݦ "MϽCD3U v_7 rÌv^Mթ fƫkuP9PԧF;&[ MR1ڦ6Zmg¤k Kx_{~ǎu'QJun#'ԯbT?O1џ~)\ yTQrw0ɟ4^GY_Niir=aK4Z[PӚ̈!42J+Sqrj>3#IodP1 fGʛ[aj[[/5i*r{\q8m>U6_1~w.mx7XX&Xdb̿{IДoG~èoƽه-Fnpk!1Ab3}7CQg */'2se,~͍\qf)fFqJں0P]\pSEڴቱq^rPܵadRq$!Rs0 _4 A\~Y xx܀ICukG" 6TRwx[~)Am&lpk JEI~\߀S ׬,ts-9S}ܟ.dh%]{,\zgpXlbW`hnOtdxt3[~"LVI$]FZ($߁}=Vӏ5Piڂ"O#ʔ$^ޓVYIF\td(ńTf&,4ZcmpSTڕt=!-/yees:6R}\\Oxr*kK**srih(2 [\_&Z.dȏGGy& 6y5%id\ׂ(4tz}n2(ZTOlY{Oh,kOo*As@(ǦQ>$ uQv+f&YyQMSw)ð nE ڠ͊W̓gZ5%W|k҈5hTpkf\D=XjC7ƽqX`Uxg`{Dϰ/P>tEX6j@$(ڏ|ᢠԤʂOyM.Ah(D4hP$#|Ό f _>ꭾ[ه΁hp7w)*otO("P"$%Sߡ{xB>EU}Rk}j᳣*߭N7)D9t?񓼥7nBřOI^~6w)(Oe2ݾ=\L( S룳F! EBTz2BQ(޻rMִ %M>Z2ŋEQ|­0\P4#w<_WL}>ti:}襳LTT]; QtE"P8oayxC} Eb\,BQ(m.Z#<~uysX+P<Ѭ-Euh9\\qcԒAp٠C Àwz9$ͰZyxlBjkxmAZyO6|ڂ"RZ2μP0jQP7㍢3P|RfmX μPR 84)P,ۙevj^{ @U#)6c͢ף VIm/T&.H(VǟG( GqzFn~]B,f(}ju֮_ҡv""^ ΌP4T5=;Z 0Zb^ ΌP,ԕEmlc;APk)O,qf"\ o-$w-ڋ/EBWkEP{Q(]-ox5`ں:1g hzQy*$h4]?trg+c Kp|Tg/)9B_YoWG/!.4Jp˯#u!s!l/!؁UvnGe; xb6  8xH9;0aǥ*قmF.i6 k7BѠe+G"&tj}ta{}E [yaxcUjȬ |f+>7%4)6c?2bm4M%/Vi?TO*Y"ccz-xWG/EgPۧ/Ɛ$F UbVcRwy6H& o2}13 J@9DVXQ2ɿ>!c/HuwWu)o@ajRal5c(ryFBЊq6ŷ}/(0au2l"ys'h9_6׼Q,Ud&w UܯoޭS@` 9mbk3?s9-s! pOXa=}?|ώNËsKKKo޼iZR#Hw::ݱcD=c4yXWu8hư8rp!r^[߬aE]hӪ(JJ~޿_Vlܸ!3gWvvo(&iiA75DR|0.M݂IzH+f-4^B)Jr+E%'oW- VDFF"҃oAeYwh_Vb\0Uc4~+DA^TDj{ :h*GUt Q/ +!(fyS *ҤZ"pLk6Xe]hf^QÇk|݊3b׮~Rs<\U*^1>$vYWD9̫H|ZRRb*~+ƽiAQy-//:bίDu P\Ѫ84 :o Aj"jɶctKH$ꗕ?20HCnN(xKh2 &j 6=ŶmݼُE;-}gfVNፙOְۆH$褶Xԧ +&AuQ߃ma$O=q-]RPAU[8|.fv_1݁>q޾ r?>|ڷoV6lElc.bG A8(>GkWis}E}I+y+;txճ쾢mP,WD-EŘTni߹5:C8|6ѯJ7inmM6꒎3$ulk KYo4*f 7GP,sRwM*tcPmԳK%1џ~ܔk.~Zu )?aKD-ۆ3WRwwv&/d ~dѣGu&N{>̌7yH#2_'w33bF( *ѵ%PqMȣ yɌlh;9ݤ+628]"|E%秺W]t0F9Hv|Ř)ߎX-~e%LG7SIೇOqd 4|\8d1ZYBş<zI|oЯşL.C#CQg */'2se,~[nw?pǙڶ#f". ~Aqcm|[Z*~G~Q ڨ?l7u ΐ9 E4%ቱqi1zkӗAHC>45 ':MZ7_liU_gЯnYKB}4ˆf/jE>TQ֮\t}Vo^-( [.|Cyő*1҃_3bN]5ᛟ>%k90N>!T3!ʜ~Wp: c#>`D+և/ {]^]LK[Xmo:-a1,^{]Fvqu+u_94ok[LF|{xߥ 2ǧ rֺK eWƏo&A2UY6Jr${nT!AE Ɣ \1 N.W巐+kHB.eRTQQEWZoM'Ǿ鈘 ;M͹Jޏo&U@ E0 af}㷈P:,_1#6ʋjHEK (עQY1?7iWUXm K",/['^(0U%*GyL΄ެcZ!؁Â$&(*_r^%D*IISvb &@1E=~4 nL;sP*;0_AƮPT,nu$ߤA)]p*paV叕cޏ7F3?_jZZ& JԪ{Q0̪2{' EAU(2\yaUcX"hN(j"c.+pEșy,bWԨp.DA"H(' J EBĊ+ߊ# EBP$ 'O^跙# E+"EP$Ms!P$ EBP$<5bG(&Vմ>H("H("(<^fG(&Vܝ2+G("H(O/.kڏ# E+LP$ EBP$z EBP$ EBрףD H(Xq.\JvSRFՐۧ/"hb@kG  EA(.q/)9D H(Xq^V?H(^q BP$ EBP$ EBQP+r1H(&V=P$ EBP$ EBPlYBGO! EBP$ gr><)˟$ E+A(V+7AQ[BP$ %ǗKU9:PccWyxslESUPnEM=j8c7O_"kQg6Eo pvVc^@-QOt'9g.;>Tq P Q^;Z Vf8:>PxheBL;yJSwuk5"ӁkovY^I ٺh%wC}p6eM`/iR3b3@ q~ܭz: uD[4)[l)հ:Lslgh~(>TYiظמ/^x\ʟooe_/TN[U0ƽfcG+?73bb կ1ϭ(wuj=A)6ޱ{h50{zI&g 4`U9Ncb^g1|xFI&7xn\4jh΢w?0wcii͛7߿O( {W$w|7-{7Mfkjr=/pzHփq>u{f9SOX<"<,ʄ_uMm`2ʑV#[_q-;ZçE;y>39u{|}rKCCnr7LJJBXRR! b4˖j'd ׫WS6RRE;ӳիOKvyxaqv[7:u^d$$}f^={yogm6jݺ~Ua~ٝXw* Ms*u[B\թOeCFv?H$Hv}СRqEQ%Gws5ݶm ~AAԨQμaNN8?qǾq_fy{{ƍLv׮66qL_j?wDUl XXFlN(^`km\Mrj E5eǎu c]UPN}*р8hsPXXX\\\zz:.bQQt:V픗U1Ŀ?J 7nG[ sD҂ӷW矻,\8E[YjMm$f*eU(Sʆl aa*#)BP(^MGW"n!pzQQKyOAv^>U >)o2ϕOa/_R#\>7PT5WeD-2,++ 5C( +b;|XfͷmѭX1(vn/'U>W cs-2Vtp݃:ȼbҵFbhԣXEk""d  +&wԭ Awn誼PDp:vT*z^=XHL")2WE"Q PԮU5A^l {.m۾yT;wn[[;Ʈ` vwm56@jx;v>r+.?{{PmNRթrj;R)hzj8}8:~}~5(fgo  Elݯdž>$G50p6&M?Փ#/uv 9sCYmWQ*WLoM[}q߀PjGrtF@Sc\+4UZFjb&f.Q`P)h\=KҘ[65f^X0cvl\;ΒI?H#3&946/`Y -X k"\O#ZAIDx-T<{xx3b֩-R|t=å32#!xe J͊{_lN׶ 8d)kxH2KX'C4aG|2JR0ỏ+͈ ~wܚ?󇧁(6~R|8{BdALͼffOu4-K֣b7RtXM+>4D$elyQN%re,x[pԹcX-ݴOG~+1p ސ9b <[t s"W!GƙPDQx(+q/MTMV}\ .]\W|hBaȴ {DAP#tm"?:xv]>;0SW_I@|ad{.s=8  d9!+!ݜPdu팈 }[`!:کҤp4xE[li kg;%3C M ꀄB=La}K׆M'2%먨Β>##]}Ǥ ro?f%6\\Ė7=`qws3'L:yGQw<[@=f:8Jx*o! ~ E":,"gNDϢW33rLi,I6P]<%d!+ ' f~RKNۃEׅ} mɑ=>j7T9 }|>]åc9Jg-ΊgWfApyš+ 4ĩwx9K#Wll>P%yfτPT)6de,a=е+stb3C&^N:0|RgyUCxr >px6)B- DS[P4,de,aQ$ M:?7Șj/1! A:bB$T2_tP(FQDy!AEemCHFuMEL'Q!hLBP$!!IHHT2C3մIENDB`webpack-4.30.0/examples/scope-hoisting/graph2.svg000066400000000000000000000167521345416772700217220ustar00rootroot00000000000000Chunk AChunk Bexampleabsharedshared2lazycdcjswebpack-4.30.0/examples/scope-hoisting/graph3.png000066400000000000000000000605011345416772700216770ustar00rootroot00000000000000PNG  IHDRί)tEXtcopyleftGenerated by http://plantuml.com09yzTXtplantumlxmAo@&`ֶ1ج0ma!bM{W6^vg{%;*%K7)BwwL@p ӬH<Դ9+W{(T`bԮ65+^ZJt-,ka/usdlS=3۶`D_MhoMh2O)097L 58=pn{,8Mb<(J +`Jk%ЇCg,Bi+”y\*ԏ9Q5f" V]iF_A޻۷N(d|Q]J|?hJ-5uG(6d+&QYDO$\v_NIDATx |W7bkնZ,~e6H6EU[E+K*~T2\L$$H„A5nqiԽ}:$\3y?g}=yΩ(U(((("(**(((("("(*(((("("(*((((Kk׮]|(F̴>}:%P>rHuԉUT "(AΝ;NꥭA4yDvbㆢ 3qvv>{lihҤ v܊yۯ\'(ʔ*>i۶--[ϻ*H&a~]vazm"LdooڵkKRJÆ  nt 1 D,T*CźujxԵ,˱~Ȑ!DET9 ("***"("(*"("(**"("(**"("**("(**"("***"("(*"("( Uŵk." >ea**ʱP>:uDTQD죎*Pdee/DETU*///R UQeeT=~߿aÆUTZjڵl-3T* X\:??*+?e2ӧO>|m۶nݺZfxxxFU9CTQD)UF p1__Zjjٲ%:iSJJk"aݾ"p֜CBB4O{nⴭ[} ohȑ"*nXŏB,+ +[űZ%*"?.BU:NKTQQUD,Vvm=ÇK*N@TQQ5k֜:uJD2 8q*5j$s1cƈM)))"TԬ8߾}&VJ{i5kv ,b\\DE9.ZlYF '''t͛71cfhhС lj Á@Fc[; `xX^=\BR醔*rd"QEQDQETQDUEGU"UDETQDEUDQEUDQEQDETQDQETUQETUETQDETUDQEUQEQDETQDQETUQEUQETUDETUDEUQEUDQETQDkw/9u0Zӭ؊O*"̥G7n9qQĒCDWjkӠR=fęq~\(J_=Zf1&-M>nk$DV밵q>{7|~3N^z&pe~ȚIȵPlŔ`>v>4i*La|~1 ѤXlCch8hH QEQDozPxJ~+S?%EeV^!/g]/M;=3 24.#]x)A(Eӹ] I)kƑLzNOn90{dZ_ o(@Ս7@@woڹn-6μ  j/); _?ܙ?:cͼxSiӝ_2-?߼MTQDUE@ uf}t|ӁEUC!#B!K# C*;FUaz䇬y|/ˮ!5!nRpszkڭ[ԎJLWRQݣ-+1%??POZUQep8t;E5 LI+",}kBڞ \7Q iʔԣm[ϔ ޽.$zyu^j*{pN 4+WZo8Iװغuӧ֯+DU$?] ;|2]RI+",}؆ݓx_ :x0/'>m(1dgo<~<0gOГ'ɓWMn2lOLZx[ :r$h$?%ѓVDETY}܀JEv֪i*m3 &4)O_}\G±"(ʎ*P\i[g,/i۶̙c@Eբ!&9ZbpBBBr9)~HUv*MZ!ھ}{tDN{kzF-o#V/M{wLT.jB9[ZOyn?v )/::=+PD}JU~~~NNNZZb"^ WՐO͙yx}e .χ5I[1r| T ^6wbثY??(ʞP%hu֭^ӎX)x7XǛ_^7-8?k|Nʿh\W3A>sI͞L DHĂ5LP?TxJr\UB#wu~K£t9PfTP]vU&!SY x[U%puW $)U(k1ԥ]Uɱ1rwwN9:uDTL_~0Uj9'y4*LIT@WS7}CJ.ʾPeU*iЀB!7|A z#VZ?DUCp3۔Azyy)JXQNNNAAQe +0TϱFETٲRRRkժUJU+xlUHaÆ ~%@ ),,,66VRUэۊrfuU2GCg}t7ŋX|-[ufkO>]j۶mk/*͐*ȸZkp*$~΋s͠* B"B^3gJÍݻwoݺud}&+!Puh2LFCe oT]\>PD>|X7ãYbz-QU=1/y܈*@qUϫ6G`*n+K藳*<&;&NNNy7QXhՋO]P5rss"/onq ȭg#6U&A7to]Ռ3ثW/\xRy+8dU|h|oۺuQ4 QUQßh*#OzikaǏ7U ČٳgIǏ#iCPtWWZ*8XCܴm˖kΟ?f LiX&*8)J4*[_ҿc ;j'vDAݺuK*JPanݺ%JRZF#`$*9>M);ֺZo)tpU՞A~uRlc@ʔo*QETU Kt.?_ZSe¦ZX]5hu.<*s KzVUL *x.٣癊z6U]e7 o_QETU+eZu+PDUAqHTWUQUAPu)AeNuQEUUY#g{ⲩ*[@f#"^;.6U]e Ӛ ډ*2F7sO93imPjg"Ͱ7*2FD?*۩ XRag_UDQeR=ǖ]JPHuMU زҋDQET'FVs5Glר~<~PW*2@ZImBu+PDݣ* w*"+viDET9"45߹[}d@@U9;_sIcz rQΆƧuֆϠ*[AՁ M=MqBWvUeǦ*jk2;-TWK]3QET[Z]4g'*7d|}d*zxrEDl{AUv=MqY+ cT_fkY(^Q|$fkY*{E#k-v9VWUQe24zъUUJ(RS(k׮]Dt:]L8>M);:_Rzf}L,,S*[,/DVsVuUnxyݧSQN*裴ITm?_ ThyYŐ*)).+]Uao!DU Y/,,$%b몊ٗ>ZDU KT"srr *sLӔ)*T 6Ǐ7lذJ*UV]MCR֫W)^z˖-'Nx5sRXXXll,OT-wL="*N=-$r?e2ӧO>|m۶nݺݣgut|_|ػ!U7qDXŰY)QUNըQ~i;;v NMZ=6V/fsX7xΚsHHiwq֭[kL8{T]M=`iU*o&8ă[(4i$''gϞ1y&''=z\~f 8s;=ʕ+Q500޹s*v:t(Qe:6sÁ *tz]-߽IFՌ)_1 ~RG[`eMܰ >|a&JۊgΜ< $5j$UV/s,|+ʄ4o*LӧO 9RT] ءQܰLX-e& xCGT7X}܀uva@,hu|̬QW YQĀâc СCg!تX|A4<3 vZ>ooo^zJ*1 )\.Шys,ܱMx]~gJҪ=3QETUjaT٬"xv1 zX{iʦTHDQU2,6>>3ϒ* 4eU藨" C+Q2s-ˑQR*NK *Tp*HcXuhe T*JݸUԭ,ꇍq( 7D D*!K]ET=+*ιߝSHFQuh2~fXl/J*J{aqψ*7|+e{\R35'ʔ#U@?A[ҺfrQeCzDák_ء363Z5fzNT)y*K0;]8hZ9!,Mq-o>d?J9\AUFU'I/}ݸ}pb+Ibd5WQǼ ɶw ;COf(BJz{,>Oy[_c"?'R2J|*QUՊø 'ƀDEQ<%J8dw5eafn>6yga!Q]U?y+J(.*w=-P^ΑȪN,GDP(OYkt.1 ^Q 1om' :r;tGj#yۚx\D:77ߪ6"lP򈨲7Ƈ ,tjl{CB\D"S CTiΩ !YH LdyrDT OhscGx.Y$2~V /CBplwѵ=skԪ 2F ďb¼cjU&i?ϲ ˏf.ƤEtnm<Q Qe%:+zDһ~o !Q5;IYλjԓ+"n架fDM80u{|w:0QW5ޣҰ󪃚S=KE|w%E.&̟ \ytƬ=F'RTVG1 e{-332 TvG7860CڳD)&/*}oy̸C/gzx}LquoHv~d*{0`OvUӭרOi;mJTĥg H?GA;wڹWUK~)nӓPŧG3O,_9}nzQ帨B%iEI!kv #ȝ\*Iw/;8ޯaZB@Ҋ*[[K ^^]WZJ=:\Spp^%A+Vnݺe Nl+HOȶ'4ʼUNbsXQe {PxCԜ9:yG'O>|x_;T8aՠsrr Tĉ1K7֤֯kUJpLF;k z&7ݷ2R1>װ0ߚ)<ʮ[ś73W^i#ca7sO,ճԪUC"Y CBBpTĉğ [Uԑ#/7of-3DУ(6$TS,0i.ϟ`>2.dշ::v52J\We>}P Ȩ)6nE\aa9rW#Ŵ L2,66ф); 7(/\\Z޾[] 6yx}hT8y:ʚ^M:޶m[̜9}T:$|2*44TTT* ZVGTYU&-ݥ6Z O {+W@սKpޟY U]J{A.U:oᬣdF#W' *2_eW6L'nt@vrޖ::&\wajȧ5\+[ Uw DW :<(Zn6E[ʈ_ CU|+H"ZDخA_*'uUc9_ 5b? N_GYg՜?ghy_Yu&ouQ!s|CŬ`d1 ǓbMYc[* z˯_?Ij3y>l~#o2p)g9$F| 9% J|̗ 'ͶUVjDã^F?wA¥Q7~p5Q/JwsP鏪Q B?Y8/6]FD註Sժ/ԭbu횵w>UV;OƬ.gŴ(qJ&ii7|(yW\~CO[4?=Ddljyo~g]Eb`rW4sKoy&XQe O[)AWkGޥ]QrB&q*H ߳s׶ޣ3tzp 6DUqٛٹ/ ()g'bMOnOK>Bp*VGTYCfbH,b%6*#k@,)`= LnH2N-^7;[PL6kl"n]^Kp-҅PaƓPhsce0 :R)@2CFi Wa*i>t4u]xKï.*9X)BrMaM9QU~?=j2y"Wl`e6U8~<~̱ETML6Fp77k.7nL'EKq;6z6"lUv$;ͬ[/OI_2s]Fw썜SFUi=Cۻ͜:#T]Iޗ>+̧6*K\xRgmXlh|oч|* в߹0uD treG <! aUlBbrk QeP5d*CT}gYSΓ1?!,VԞψ*/7}<Q + w*9$_]M=S6DE$CTw/T.#췶t Ӡ!WB SJ6*K+X CT)Ѷg:VDƸ ٟ,Qe&EVs5n RrDT=(@ƀD]iϙ=zUgEt rXT[mkDQUN>4iCTtC'WD]-Qe@o.c@L]M= VOm*hvtA 7SCK -CT9 U*aUf:yb+_;vP!̡܀u{[ʎ^FUVSB ƀDne]nt(sD*55[*W ?]*o6ƙ7rN6m-BU DRZVM0;&{OenEEtk+N9c'M*UQ諩zمc帨j/Z۷-ܶm[ntRaɡLݷlقPcƌAjf-E؆-f'WDurTըQg~i;;vLrjZl;>NV/f۽+RPPog9$$DW8m֭qZ=}@i&lUqZX:"ι:VD)oĉb&M4ٳgGP2u넹8Gׯ_uf*ik^NNNW\GecOMT]M=`/O, YNJ2ׯ/~AAVo}.|a&JۊgΜ Z {mۖMT0 $Xmm<6'LO9r! v vJkTrT .&JۊxqPRw:Bc5#MʦP8˿;6?'(4TA+dt4m߶Ufn0_0:fxʁP%bڵkQot?>#,m8mBB2eM7+ ZؚcETRǚ5kN:%"AL M8Ql5йx1cĦd2[=iVo߾]U$KV߻w/N۬Y'n[Z{.kI''lUnʬ=:UV62//-[aqrrRJg̘!:t(,$[5[ln5佖Ii4VDM `xX^=\BR;? lUŵ\[X=z<7UTK *keߞA~6-=Qe+՘=J U.#8^z]mDZ"lH0M8W-Qhsw+ "P!߮HCUTt.nܶbڔcETِ`[$gE jvz&f}pbVb+_2ݻ 3Aፘ=l&*Rn Ӆ1QU]̵b/L%fi~?w@<| :B؆.O5 =` QeVt>rgF/l$+ϬdD}* qA+J O⛾[AT94AJ7>[UI 2Wo~^Ҋi /M0IӠu-Q8BH}7rNX`@@΅'irr=颅:$U62XdXb^TPDcJOYaN0hqP7 s<<@&o6vsK‘6}HTٖT*ӈ*A\737`]B ӫXK@- *Ѷ6Y1 Qe[Bqa¥”7{#Q8[ ߕFV﨨^7'Ⱥ:/}|3tt.6"1UNT9P*ĖW{om{*B$:DzR<>:S?zؿ0rPT=+jUaD> :'Hn9uAQ<tC"vb/*[`+vf_M=5h268XQU~ %jm*C*}kEATYMO?s\VjIFYCs 3.% U٣mm<0=Gl*??Rwhzt}ys7]~M8;\}TC>=0܀'/>MWRZS~l:z)<4ijTaMJ']s  U˛Lnz {_υ{7m*0бpHȳ =zx!_dzh;qμqd]3}YET_(KYTNZ.rQG`:Twc37'kp7IaITK]Id[B] ~t;Tlg~ lI( tMTx9OYK؏j)%F@ _H~aX9{^#LsI.ßG> K⩴ f{meqS~d sQ)yObtXlΜ؆Ee$QeǤ6 K{~v[ T ]FQuf|0bU;xRh=_[[w֭[ȵ2u7RB0C_#9"1ٛcD*U4f(s($mgRwUӚ>QU?UT {tC @~KI)|k~pφ3Q&gxRDQ|/!9`D nyi&4}_Ӡ8eCfpZZZNNN~~~aaeh'.CaײF[95(DUyX[޸aI*؆"߿Na*c𨗳f;L.n۳p,C#P3*!r' JdD$~MolZZD+?&OB@#+G?rL>{uPٸOPPhH0''e>*w_݉7vtް'^/͚~G1`{N۷w5x7=AOQ'>tȀo\\ZfSs6msHۨѫz:q6M Z:1/N}RDTiJt;ۺu9||AA҈tAKWDG3 7L>7DCW3D{7ZW(g SKIÞwjժ!rt_yyE RSVmU6ɾ NO #ktnHpDUqIǝGn&%ſ:f-޸qcXX")&@H uCM?2,66anNJ2RWSF_IcU@8M5@X>n+I ڤ QX4y' ݁n2})PT*U*vsJk7DCh"CcETќR,]Bhф2Qնm3Zu$򛎖W,YU"jѫ2WFT D>o9P%ŀ 7CBxE;.'KQTIM !Cp/ʸP]WYplHGPuUUzQ|d;\jo"aUkEe}zqA(C9 dieY׮[o5+ U;w~2*j8yFF59 Nju0h\Y\6"N*7.$~7эz+ o d23^!Qe=t3ht_twoGz^^]zq iٲ1\W0Oo*h7~ Iz2Q^Vb+:QV H*-4Z6o7!]GcѮJPvUۛhWU:ȝxnMJ|L<:l՟@k?*VQ/,1e wrQ,6,,%NUTڬJdu Nd2u]Ƌdk FXή_7ODN_GW*IG՜*rrV[UPʤE|ծ|(L)>z v*Yӳ<"Zx) z˯_?IjA{VYמ`yQ}ŋs,%qy&503E?%8%T(*Q6JN.7V|$yh8.OU/vRY6pQ%ops.!klw=D|~8BQM3E NB| hWDUiZv}~c@/YPʩ"Y@Igd)O[u/_~N=D%L ba]Jx ԯ%gJr8e@T&@薨tǣ2d#qeM;ϧ Y))@ ?u`KOԥK3t9ҟ`m?Y-FIC>e^xqr/&x6e}EsuRϴ %Lk@T<`??_J@qE}GEX4\vSL8s(l[[UU:BzLr-չ oDNI(QsnaNF,_iXu$RBS{W/ M?QeGrý,X:x|XA9*_ﵳϘuasF-}x}/Fmo!$>G͓*^@ IΔz& A($V zQu. o\6* ;[ba<(8xъgZ!WIA* M?Qe\0A,,x! lvmښnw1O͙>e z*l=4k/S&}D|AƊf(VēTiڽ*L}[UvIbMM)8ScJND0E<$rH͔K_UD5pE8D=#ö6Yp jvs}SMZprŦaD- t.<)7`k%fnl^'X󅫤 Qe^09uxuF -]~o[yf;7-7`ƩKt16Jb1 dgh$i_e=43ODmɂ!|d5WQt{}DLϝ9 `>"2s̥YCTLO?,8f:BI` !rӣۙ7O,_|p]]JF~ %ArLYTRB^&%L0exT6o5sMjL9Ubњn Pԉ~ϴUnzCTCIj'Ng=ۺl=Bā1fG$;Z0 Π *-=7w>Ȳw8y{*[2}Duuoڵ,-㩴\w`VLOuA ʴ-x|"IIjB]C@RZ'ՐO\myF?D "nTz"mJ"z)\ג)nܞA]'뽩/]5 -ιORo=_kLWXҊ-x |[Νzx] k7nۻ sfK' UBW"6^'4}iET=/]FScrzuLJZ~@j=?I~6׏.;o&Jhbx BaaaYYY&"AQu|L1z+AիVRu |6yfX\|x_:߼!W91rr~ӦPGD_hQu\gh״GV^C ٯ;Z-ݺu9L|AA҈PUiMGg%֮ NKKÝc刨{4k+mRXZbDMZ|`_UV ӧMnn,-awҦ %j޳g5UN$;!Q]- Y\G^iMcq ٌo6n(@8V(NH%C0+)rle ytUIk>}W*i&{b]˭\҈:}'bUG+DiVTbք/BCCJJBJR,]hф2Qնm3Zu$"2M8/{{@B/? t{U(lt4+*ѫYTI1 <_RA몒xd)Ӂ*9R64T!jY\][Q2cwUkm? tU!+WXӊJR˂Lr*;FxW@ @^&5{}Z VPs gdYZ(5Ձ0pJTŧaÇO6( ~-J~YOr4+*p QET=oWUߚtwoGz^^]zq iٲ1\W0O='&h7~ B$]ztlݺ/VHl0i&BeD7|ji6o7!2xcҬx-}?!<FXZOEUgOUFJ^ZWR:ĈK*7ݿ|MlY(*6?+kOr2u8Q%qν0/o3,8 b:Qd9p\>5_)?dMsME(ex d27l6}zVU"ww#eYUd5PeKTUpTʊ4wC`>mGQŢUOe*} EW=jp y *XJXeLZm[yZԮC0%ngkW{?J.)&Z8=(۴T&C}^ D+_MaZOufG+#f>؜9q<Ϧ`Ť%gJ :Srרa$[]W)Dr2Q;ZӋr eZhQ0kG_͏6{v [w`W=L *=ɓ5(J(P9R6*fFYHR'RJV ^LѯtMOZr9i/_olρjŊ`ɇ%ꤰMRQ۱of6EXBѕ,D(N CQAbނY#'9#r!5eLIί)~D gye! o^x"NN|wh[  8߮8v١Ys񤝃>="EY=PlRW]'P؄CV@ 截2k"B6m=uS"^im/{ƴ?bd$OJr&qQeDH+g^YR[؆C&ΐ "ϧa$kO5Yjh:&K]ԭ4[ VPSC?갮=5$ [%B9 OPB#U4V+ڄQKPPEcMXUtCUHWFQEcMXUU\6*1[iQQEUQETUDETQDETUQEUQEQDETQDQEUQEUETQDETUQEUQEQDETQDETQQEUQETQDETQDEYU U⨂&̅* 6d//髯2P]e.Ti#bqrEQ@GP],*š9TEYUEQDEQDEQQEQETQUnR<]@fIENDB`webpack-4.30.0/examples/scope-hoisting/graph3.svg000066400000000000000000000210171345416772700217110ustar00rootroot00000000000000Chunk AScope 1Scope 2Chunk BScope 3exampleabsharedshared2cjslazycdwebpack-4.30.0/examples/scope-hoisting/lazy.js000066400000000000000000000000711345416772700213160ustar00rootroot00000000000000export * from "c"; import * as d from "d"; export { d }; webpack-4.30.0/examples/scope-hoisting/node_modules/000077500000000000000000000000001345416772700224605ustar00rootroot00000000000000webpack-4.30.0/examples/scope-hoisting/node_modules/a.js000066400000000000000000000000701345416772700232330ustar00rootroot00000000000000// module a export var a = "a"; export * from "shared"; webpack-4.30.0/examples/scope-hoisting/node_modules/b.js000066400000000000000000000000621345416772700232350ustar00rootroot00000000000000// module b export function a() { return "b"; }; webpack-4.30.0/examples/scope-hoisting/node_modules/c.js000066400000000000000000000002041345416772700232340ustar00rootroot00000000000000// module c import { c as e } from "cjs"; export var c = String.fromCharCode(e.charCodeAt(0) - 2); export { x, y } from "shared"; webpack-4.30.0/examples/scope-hoisting/node_modules/cjs.js000066400000000000000000000000521345416772700235720ustar00rootroot00000000000000// module cjs (commonjs) exports.c = "e"; webpack-4.30.0/examples/scope-hoisting/node_modules/d.js000066400000000000000000000000401345416772700232330ustar00rootroot00000000000000// module d export var a = "d"; webpack-4.30.0/examples/scope-hoisting/node_modules/shared.js000066400000000000000000000000761345416772700242670ustar00rootroot00000000000000// shared module export var x = "x"; export * from "shared2"; webpack-4.30.0/examples/scope-hoisting/node_modules/shared2.js000066400000000000000000000000461345416772700243460ustar00rootroot00000000000000// shared2 module export var y = "y"; webpack-4.30.0/examples/scope-hoisting/template.md000066400000000000000000000035031345416772700221410ustar00rootroot00000000000000This example demonstrates Scope Hoisting in combination with Code Splitting. This is the dependency graph for the example: (solid lines express sync imports, dashed lines async imports) ![](graph.png) All modules except `cjs` are EcmaScript modules. `cjs` is a CommonJs module. The interesting thing here is that putting all modules in single scope won't work, because of multiple reasons: - Modules `lazy`, `c`, `d` and `cjs` need to be in a separate chunk - Module `shared` is accessed by two chunks (different scopes) - Module `cjs` is a CommonJs module ![](graph2.png) webpack therefore uses a approach called **"Partial Scope Hoisting"** or "Module concatenation", which chooses the largest possible subsets of ES modules which can be scope hoisted and combines them with the default webpack primitives. ![](graph3.png) While module concatenation identifiers in modules are renamed to avoid conflicts and internal imports are simplified. External imports and exports from the root module use the existing ESM constructs. # example.js ```javascript _{{example.js}}_ ``` # lazy.js ```javascript _{{lazy.js}}_ ``` # a.js ```javascript _{{node_modules/a.js}}_ ``` # b.js ```javascript _{{node_modules/b.js}}_ ``` # c.js ```javascript _{{node_modules/c.js}}_ ``` # d.js ```javascript _{{node_modules/d.js}}_ ``` # cjs.js ```javascript _{{node_modules/cjs.js}}_ ``` # shared.js ```javascript _{{node_modules/shared.js}}_ ``` # shared2.js ```javascript _{{node_modules/shared2.js}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/1.output.js ```javascript _{{dist/1.output.js}}_ ``` Minimized ```javascript _{{production:dist/1.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/scope-hoisting/webpack.config.js000066400000000000000000000003571345416772700232260ustar00rootroot00000000000000module.exports = { // mode: "development" || "production", optimization: { usedExports: true, concatenateModules: true, occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/side-effects/000077500000000000000000000000001345416772700174115ustar00rootroot00000000000000webpack-4.30.0/examples/side-effects/README.md000066400000000000000000000246431345416772700207010ustar00rootroot00000000000000This example shows how the `sideEffects` flag for library authors works. The example contains a large library, `big-module`. `big-module` contains multiple child modules: `a`, `b` and `c`. The exports from the child modules are re-exported in the entry module (`index.js`) of the library. A consumer uses **some** of the exports, importing them from the library via `import { a, b } from "big-module"`. According to the EcmaScript spec, all child modules _must_ be evaluated because they could contain side effects. The `"sideEffects": false` flag in `big-module`'s `package.json` indicates that the package's modules have no side effects (on evaluation) and only expose exports. This allows tools like webpack to optimize re-exports. In the case `import { a, b } from "big-module-with-flag"` is rewritten to `import { a } from "big-module-with-flag/a"; import { b } from "big-module-with-flag/b"`. The example contains two variants of `big-module`. `big-module` has no `sideEffects` flag and `big-module-with-flag` has the `sideEffects` flag. The example client imports `a` and `b` from each of the variants. After being built by webpack, the output bundle contains `index.js` `a.js` `b.js` `c.js` from `big-module`, but only `a.js` and `b.js` from `big-module-with-flag`. Advantages: - Smaller bundles - Faster bootup # example.js ```javascript import { a as a1, b as b1 } from "big-module"; import { a as a2, b as b2 } from "big-module-with-flag"; console.log( a1, b1, a2, b2 ); ``` # node_modules/big-module/package.json ```javascript { "name": "big-module" } ``` # node_modules/big-module-with-flag/package.json ```javascript { "name": "big-module-with-flag", "sideEffects": false } ``` # node_modules/big-module(-with-flag)/index.js ```javascript export { a } from "./a"; export { b } from "./b"; export { c } from "./c"; ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var big_module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! big-module */ 3); /* harmony import */ var big_module_with_flag__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! big-module-with-flag */ 7); /* harmony import */ var big_module_with_flag__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! big-module-with-flag */ 8); console.log( big_module__WEBPACK_IMPORTED_MODULE_0__["a"], big_module__WEBPACK_IMPORTED_MODULE_0__["b"], big_module_with_flag__WEBPACK_IMPORTED_MODULE_1__["a"], big_module_with_flag__WEBPACK_IMPORTED_MODULE_2__["b"] ); /***/ }), /* 1 */, /* 2 */, /* 3 */ /*!******************************************!*\ !*** ./node_modules/big-module/index.js ***! \******************************************/ /*! exports provided: a, b, c */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _a__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./a */ 4); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _a__WEBPACK_IMPORTED_MODULE_0__["a"]; }); /* harmony import */ var _b__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./b */ 5); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "b", function() { return _b__WEBPACK_IMPORTED_MODULE_1__["b"]; }); /* harmony import */ var _c__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./c */ 6); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "c", function() { return _c__WEBPACK_IMPORTED_MODULE_2__["c"]; }); /***/ }), /* 4 */ /*!**************************************!*\ !*** ./node_modules/big-module/a.js ***! \**************************************/ /*! exports provided: a */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return a; }); const a = "a"; /***/ }), /* 5 */ /*!**************************************!*\ !*** ./node_modules/big-module/b.js ***! \**************************************/ /*! exports provided: b */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return b; }); const b = "b"; /***/ }), /* 6 */ /*!**************************************!*\ !*** ./node_modules/big-module/c.js ***! \**************************************/ /*! exports provided: c */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return c; }); const c = "c"; /***/ }), /* 7 */ /*!************************************************!*\ !*** ./node_modules/big-module-with-flag/a.js ***! \************************************************/ /*! exports provided: a */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return a; }); const a = "a"; /***/ }), /* 8 */ /*!************************************************!*\ !*** ./node_modules/big-module-with-flag/b.js ***! \************************************************/ /*! exports provided: b */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return b; }); const b = "b"; /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 7.51 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 325 bytes [entry] [rendered] > ./example.js main [0] ./example.js 140 bytes {0} [built] [no exports] single entry ./example.js main + 6 hidden modules ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names output.js 985 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 325 bytes [entry] [rendered] > ./example.js main [0] ./example.js + 6 modules 325 bytes {0} [built] [no exports] single entry ./example.js main | ./example.js 140 bytes [built] | [no exports] | single entry ./example.js main | + 6 hidden modules ``` webpack-4.30.0/examples/side-effects/build.js000066400000000000000000000000331345416772700210420ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/side-effects/example.js000066400000000000000000000002141345416772700213770ustar00rootroot00000000000000import { a as a1, b as b1 } from "big-module"; import { a as a2, b as b2 } from "big-module-with-flag"; console.log( a1, b1, a2, b2 ); webpack-4.30.0/examples/side-effects/node_modules/000077500000000000000000000000001345416772700220665ustar00rootroot00000000000000webpack-4.30.0/examples/side-effects/node_modules/big-module-with-flag/000077500000000000000000000000001345416772700257725ustar00rootroot00000000000000webpack-4.30.0/examples/side-effects/node_modules/big-module-with-flag/a.js000066400000000000000000000000261345416772700265460ustar00rootroot00000000000000export const a = "a"; webpack-4.30.0/examples/side-effects/node_modules/big-module-with-flag/b.js000066400000000000000000000000261345416772700265470ustar00rootroot00000000000000export const b = "b"; webpack-4.30.0/examples/side-effects/node_modules/big-module-with-flag/c.js000066400000000000000000000000261345416772700265500ustar00rootroot00000000000000export const c = "c"; webpack-4.30.0/examples/side-effects/node_modules/big-module-with-flag/index.js000066400000000000000000000001131345416772700274320ustar00rootroot00000000000000export { a } from "./a"; export { b } from "./b"; export { c } from "./c"; webpack-4.30.0/examples/side-effects/node_modules/big-module-with-flag/package.json000066400000000000000000000000751345416772700302620ustar00rootroot00000000000000{ "name": "big-module-with-flag", "sideEffects": false } webpack-4.30.0/examples/side-effects/node_modules/big-module/000077500000000000000000000000001345416772700241125ustar00rootroot00000000000000webpack-4.30.0/examples/side-effects/node_modules/big-module/a.js000066400000000000000000000000261345416772700246660ustar00rootroot00000000000000export const a = "a"; webpack-4.30.0/examples/side-effects/node_modules/big-module/b.js000066400000000000000000000000261345416772700246670ustar00rootroot00000000000000export const b = "b"; webpack-4.30.0/examples/side-effects/node_modules/big-module/c.js000066400000000000000000000000261345416772700246700ustar00rootroot00000000000000export const c = "c"; webpack-4.30.0/examples/side-effects/node_modules/big-module/index.js000066400000000000000000000001131345416772700255520ustar00rootroot00000000000000export { a } from "./a"; export { b } from "./b"; export { c } from "./c"; webpack-4.30.0/examples/side-effects/node_modules/big-module/package.json000066400000000000000000000000331345416772700263740ustar00rootroot00000000000000{ "name": "big-module" } webpack-4.30.0/examples/side-effects/template.md000066400000000000000000000035211345416772700215470ustar00rootroot00000000000000This example shows how the `sideEffects` flag for library authors works. The example contains a large library, `big-module`. `big-module` contains multiple child modules: `a`, `b` and `c`. The exports from the child modules are re-exported in the entry module (`index.js`) of the library. A consumer uses **some** of the exports, importing them from the library via `import { a, b } from "big-module"`. According to the EcmaScript spec, all child modules _must_ be evaluated because they could contain side effects. The `"sideEffects": false` flag in `big-module`'s `package.json` indicates that the package's modules have no side effects (on evaluation) and only expose exports. This allows tools like webpack to optimize re-exports. In the case `import { a, b } from "big-module-with-flag"` is rewritten to `import { a } from "big-module-with-flag/a"; import { b } from "big-module-with-flag/b"`. The example contains two variants of `big-module`. `big-module` has no `sideEffects` flag and `big-module-with-flag` has the `sideEffects` flag. The example client imports `a` and `b` from each of the variants. After being built by webpack, the output bundle contains `index.js` `a.js` `b.js` `c.js` from `big-module`, but only `a.js` and `b.js` from `big-module-with-flag`. Advantages: - Smaller bundles - Faster bootup # example.js ```javascript _{{example.js}}_ ``` # node_modules/big-module/package.json ```javascript _{{node_modules/big-module/package.json}}_ ``` # node_modules/big-module-with-flag/package.json ```javascript _{{node_modules/big-module-with-flag/package.json}}_ ``` # node_modules/big-module(-with-flag)/index.js ```javascript _{{node_modules/big-module-with-flag/index.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/side-effects/webpack.config.js000066400000000000000000000000761345416772700226320ustar00rootroot00000000000000module.exports = { optimization: { sideEffects: true } }; webpack-4.30.0/examples/source-map/000077500000000000000000000000001345416772700171235ustar00rootroot00000000000000webpack-4.30.0/examples/source-map/README.md000066400000000000000000000516671345416772700204210ustar00rootroot00000000000000This example demonstrates various types of source-maps. # example.coffee ```coffeescript # Taken from http://coffeescript.org/ # Objects: math = root: Math.sqrt square: square cube: (x) -> x * square x # Splats: race = (winner, runners...) -> print winner, runners ``` # webpack.config.js ```javascript var path = require("path"); module.exports = [ "cheap-eval-source-map", "cheap-module-eval-source-map", "cheap-module-source-map", "cheap-source-map", "eval", "eval-source-map", "hidden-source-map", "inline-source-map", "nosources-source-map", "source-map" ].map(devtool => ({ mode: "development", entry: { bundle: "coffee-loader!./example.coffee" }, output: { path: path.join(__dirname, "dist"), filename: `./[name]-${devtool}.js` }, devtool, optimization: { runtimeChunk: true } })); ``` # Generated source-maps ## source-map.js and source-map.js.map ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // Taken from http://coffeescript.org/ // Objects: var math, race; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; // Splats: race = function(winner, ...runners) { return print(winner, runners); }; /***/ }) ],[[0,0]]]); //# sourceMappingURL=bundle-source-map.js.map ``` ```javascript {"version":3,"sources":["webpack:///./example.coffee"],"names":[],"mappings":";;;;;;;;AAAA;;;AAAA;;AAGA,OACE;EAAA,MAAQ,IAAI,CAAC,IAAb;EACA,QAAQ,MADR;EAEA,MAAQ,SAAC,CAAD;WAAO,IAAI,OAAO,CAAP;EAAX;AAFR,EAJF;;;AASA,OAAO,SAAC,MAAD,KAAS,OAAT;SACL,MAAM,MAAN,EAAc,OAAd;AADK","file":"./bundle-source-map.js","sourcesContent":["# Taken from http://coffeescript.org/\n\n# Objects:\nmath =\n root: Math.sqrt\n square: square\n cube: (x) -> x * square x\n\n# Splats:\nrace = (winner, runners...) ->\n print winner, runners\n"],"sourceRoot":""} ``` ## hidden-source-map.js and hidden-source-map.js.map ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // Taken from http://coffeescript.org/ // Objects: var math, race; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; // Splats: race = function(winner, ...runners) { return print(winner, runners); }; /***/ }) ],[[0,0]]]); ``` ```javascript {"version":3,"sources":["webpack:///./example.coffee"],"names":[],"mappings":";;;;;;;;AAAA;;;AAAA;;AAGA,OACE;EAAA,MAAQ,IAAI,CAAC,IAAb;EACA,QAAQ,MADR;EAEA,MAAQ,SAAC,CAAD;WAAO,IAAI,OAAO,CAAP;EAAX;AAFR,EAJF;;;AASA,OAAO,SAAC,MAAD,KAAS,OAAT;SACL,MAAM,MAAN,EAAc,OAAd;AADK","file":"./bundle-hidden-source-map.js","sourcesContent":["# Taken from http://coffeescript.org/\n\n# Objects:\nmath =\n root: Math.sqrt\n square: square\n cube: (x) -> x * square x\n\n# Splats:\nrace = (winner, runners...) ->\n print winner, runners\n"],"sourceRoot":""} ``` ## inline-source-map.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // Taken from http://coffeescript.org/ // Objects: var math, race; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; // Splats: race = function(winner, ...runners) { return print(winner, runners); }; /***/ }) ],[[0,0]]]); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9leGFtcGxlLmNvZmZlZSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7OztBQUFBOzs7QUFBQTs7QUFHQSxPQUNFO0VBQUEsTUFBUSxJQUFJLENBQUMsSUFBYjtFQUNBLFFBQVEsTUFEUjtFQUVBLE1BQVEsU0FBQyxDQUFEO1dBQU8sSUFBSSxPQUFPLENBQVA7RUFBWDtBQUZSLEVBSkY7OztBQVNBLE9BQU8sU0FBQyxNQUFELEtBQVMsT0FBVDtTQUNMLE1BQU0sTUFBTixFQUFjLE9BQWQ7QUFESyIsImZpbGUiOiIuL2J1bmRsZS1pbmxpbmUtc291cmNlLW1hcC5qcyIsInNvdXJjZXNDb250ZW50IjpbIiMgVGFrZW4gZnJvbSBodHRwOi8vY29mZmVlc2NyaXB0Lm9yZy9cblxuIyBPYmplY3RzOlxubWF0aCA9XG4gIHJvb3Q6ICAgTWF0aC5zcXJ0XG4gIHNxdWFyZTogc3F1YXJlXG4gIGN1YmU6ICAgKHgpIC0+IHggKiBzcXVhcmUgeFxuXG4jIFNwbGF0czpcbnJhY2UgPSAod2lubmVyLCBydW5uZXJzLi4uKSAtPlxuICBwcmludCB3aW5uZXIsIHJ1bm5lcnNcbiJdLCJzb3VyY2VSb290IjoiIn0= ``` ## nosources-source-map.js.map ```javascript {"version":3,"sources":["webpack:///./example.coffee"],"names":[],"mappings":";;;;;;;;AAAA;;;AAAA;;AAGA,OACE;EAAA,MAAQ,IAAI,CAAC,IAAb;EACA,QAAQ,MADR;EAEA,MAAQ,SAAC,CAAD;WAAO,IAAI,OAAO,CAAP;EAAX;AAFR,EAJF;;;AASA,OAAO,SAAC,MAAD,KAAS,OAAT;SACL,MAAM,MAAN,EAAc,OAAd;AADK","file":"./bundle-nosources-source-map.js","sourceRoot":""} ``` ## eval-source-map.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("// Taken from http://coffeescript.org/\n\n// Objects:\nvar math, race;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\n// Splats:\nrace = function(winner, ...runners) {\n return print(winner, runners);\n};\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9leGFtcGxlLmNvZmZlZT8yNDE2Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7QUFBQTs7QUFHQSxPQUNFO0VBQUEsTUFBUSxJQUFJLENBQUMsSUFBYjtFQUNBLFFBQVEsTUFEUjtFQUVBLE1BQVEsU0FBQyxDQUFEO1dBQU8sSUFBSSxPQUFPLENBQVA7RUFBWDtBQUZSLEVBSkY7OztBQVNBLE9BQU8sU0FBQyxNQUFELEtBQVMsT0FBVDtTQUNMLE1BQU0sTUFBTixFQUFjLE9BQWQ7QUFESyIsImZpbGUiOiIwLmpzIiwic291cmNlc0NvbnRlbnQiOlsiIyBUYWtlbiBmcm9tIGh0dHA6Ly9jb2ZmZWVzY3JpcHQub3JnL1xuXG4jIE9iamVjdHM6XG5tYXRoID1cbiAgcm9vdDogICBNYXRoLnNxcnRcbiAgc3F1YXJlOiBzcXVhcmVcbiAgY3ViZTogICAoeCkgLT4geCAqIHNxdWFyZSB4XG5cbiMgU3BsYXRzOlxucmFjZSA9ICh3aW5uZXIsIHJ1bm5lcnMuLi4pIC0+XG4gIHByaW50IHdpbm5lciwgcnVubmVyc1xuIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///0\n"); /***/ }) ],[[0,0]]]); ``` ## eval.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("// Taken from http://coffeescript.org/\n\n// Objects:\nvar math, race;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\n// Splats:\nrace = function(winner, ...runners) {\n return print(winner, runners);\n};\n\n\n//# sourceURL=webpack:///./example.coffee?(webpack)/node_modules/coffee-loader"); /***/ }) ],[[0,0]]]); ``` ## cheap-eval-source-map.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("// Taken from http://coffeescript.org/\n\n// Objects:\nvar math, race;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\n// Splats:\nrace = function(winner, ...runners) {\n return print(winner, runners);\n};\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL2V4YW1wbGUuY29mZmVlP2MxNzAiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gVGFrZW4gZnJvbSBodHRwOi8vY29mZmVlc2NyaXB0Lm9yZy9cblxuLy8gT2JqZWN0czpcbnZhciBtYXRoLCByYWNlO1xuXG5tYXRoID0ge1xuICByb290OiBNYXRoLnNxcnQsXG4gIHNxdWFyZTogc3F1YXJlLFxuICBjdWJlOiBmdW5jdGlvbih4KSB7XG4gICAgcmV0dXJuIHggKiBzcXVhcmUoeCk7XG4gIH1cbn07XG5cbi8vIFNwbGF0czpcbnJhY2UgPSBmdW5jdGlvbih3aW5uZXIsIC4uLnJ1bm5lcnMpIHtcbiAgcmV0dXJuIHByaW50KHdpbm5lciwgcnVubmVycyk7XG59O1xuIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOyIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///0\n"); /***/ }) ],[[0,0]]]); ``` ## cheap-module-eval-source-map.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("// Taken from http://coffeescript.org/\n\n// Objects:\nvar math, race;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\n// Splats:\nrace = function(winner, ...runners) {\n return print(winner, runners);\n};\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL2V4YW1wbGUuY29mZmVlPzI0MTYiXSwic291cmNlc0NvbnRlbnQiOlsiIyBUYWtlbiBmcm9tIGh0dHA6Ly9jb2ZmZWVzY3JpcHQub3JnL1xuXG4jIE9iamVjdHM6XG5tYXRoID1cbiAgcm9vdDogICBNYXRoLnNxcnRcbiAgc3F1YXJlOiBzcXVhcmVcbiAgY3ViZTogICAoeCkgLT4geCAqIHNxdWFyZSB4XG5cbiMgU3BsYXRzOlxucmFjZSA9ICh3aW5uZXIsIHJ1bm5lcnMuLi4pIC0+XG4gIHByaW50IHdpbm5lciwgcnVubmVyc1xuIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBOztBQURBO0FBQ0E7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUFBO0FBQUE7QUFGQTtBQUNBOztBQUlBO0FBQ0E7QUFEQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///0\n"); /***/ }) ],[[0,0]]]); ``` ## cheap-module-source-map.js.map ```javascript {"version":3,"file":"./bundle-cheap-module-source-map.js","sources":["webpack:///./example.coffee"],"sourcesContent":["# Taken from http://coffeescript.org/\n\n# Objects:\nmath =\n root: Math.sqrt\n square: square\n cube: (x) -> x * square x\n\n# Splats:\nrace = (winner, runners...) ->\n print winner, runners\n"],"mappings":";;;;;;;;AAAA;AACA;;AADA;AACA;AAEA;AACA;AACA;AACA;AAAA;AAAA;AAFA;AACA;;AAIA;AACA;AADA;;;;A","sourceRoot":""} ``` ## cheap-source-map.js.map ```javascript {"version":3,"file":"./bundle-cheap-source-map.js","sources":["webpack:///./example.coffee"],"sourcesContent":["// Taken from http://coffeescript.org/\n\n// Objects:\nvar math, race;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\n// Splats:\nrace = function(winner, ...runners) {\n return print(winner, runners);\n};\n"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;A","sourceRoot":""} ``` # webpack output ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-cheap-eval-source-map.js 1.39 KiB 1 [emitted] bundle ./runtime~bundle-cheap-eval-source-map.js 6.04 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-cheap-eval-source-map.js ./bundle-cheap-eval-source-map.js chunk {0} ./runtime~bundle-cheap-eval-source-map.js (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-cheap-eval-source-map.js (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-cheap-module-eval-source-map.js 1.28 KiB 1 [emitted] bundle ./runtime~bundle-cheap-module-eval-source-map.js 6.04 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-cheap-module-eval-source-map.js ./bundle-cheap-module-eval-source-map.js chunk {0} ./runtime~bundle-cheap-module-eval-source-map.js (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-cheap-module-eval-source-map.js (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-cheap-module-source-map.js 681 bytes 1 [emitted] bundle ./bundle-cheap-module-source-map.js.map 442 bytes 1 [emitted] bundle ./runtime~bundle-cheap-module-source-map.js 6.11 KiB 0 [emitted] runtime~bundle ./runtime~bundle-cheap-module-source-map.js.map 6 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-cheap-module-source-map.js ./runtime~bundle-cheap-module-source-map.js.map ./bundle-cheap-module-source-map.js ./bundle-cheap-module-source-map.js.map chunk {0} ./runtime~bundle-cheap-module-source-map.js, ./runtime~bundle-cheap-module-source-map.js.map (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-cheap-module-source-map.js, ./bundle-cheap-module-source-map.js.map (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-cheap-source-map.js 674 bytes 1 [emitted] bundle ./bundle-cheap-source-map.js.map 515 bytes 1 [emitted] bundle ./runtime~bundle-cheap-source-map.js 6.1 KiB 0 [emitted] runtime~bundle ./runtime~bundle-cheap-source-map.js.map 6 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-cheap-source-map.js ./runtime~bundle-cheap-source-map.js.map ./bundle-cheap-source-map.js ./bundle-cheap-source-map.js.map chunk {0} ./runtime~bundle-cheap-source-map.js, ./runtime~bundle-cheap-source-map.js.map (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-cheap-source-map.js, ./bundle-cheap-source-map.js.map (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-eval.js 730 bytes 1 [emitted] bundle ./runtime~bundle-eval.js 6.04 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-eval.js ./bundle-eval.js chunk {0} ./runtime~bundle-eval.js (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-eval.js (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-eval-source-map.js 1.43 KiB 1 [emitted] bundle ./runtime~bundle-eval-source-map.js 6.04 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-eval-source-map.js ./bundle-eval-source-map.js chunk {0} ./runtime~bundle-eval-source-map.js (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-eval-source-map.js (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-hidden-source-map.js 622 bytes 1 [emitted] bundle ./bundle-hidden-source-map.js.map 545 bytes 1 [emitted] bundle ./runtime~bundle-hidden-source-map.js 6.04 KiB 0 [emitted] runtime~bundle ./runtime~bundle-hidden-source-map.js.map 6.09 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-hidden-source-map.js ./runtime~bundle-hidden-source-map.js.map ./bundle-hidden-source-map.js ./bundle-hidden-source-map.js.map chunk {0} ./runtime~bundle-hidden-source-map.js, ./runtime~bundle-hidden-source-map.js.map (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-hidden-source-map.js, ./bundle-hidden-source-map.js.map (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-inline-source-map.js 1.38 KiB 1 [emitted] bundle ./runtime~bundle-inline-source-map.js 14.2 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-inline-source-map.js ./bundle-inline-source-map.js chunk {0} ./runtime~bundle-inline-source-map.js (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-inline-source-map.js (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-nosources-source-map.js 678 bytes 1 [emitted] bundle ./bundle-nosources-source-map.js.map 325 bytes 1 [emitted] bundle ./runtime~bundle-nosources-source-map.js 6.1 KiB 0 [emitted] runtime~bundle ./runtime~bundle-nosources-source-map.js.map 981 bytes 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-nosources-source-map.js ./runtime~bundle-nosources-source-map.js.map ./bundle-nosources-source-map.js ./bundle-nosources-source-map.js.map chunk {0} ./runtime~bundle-nosources-source-map.js, ./runtime~bundle-nosources-source-map.js.map (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-nosources-source-map.js, ./bundle-nosources-source-map.js.map (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle Child Hash: 0a1b2c3d4e5f6a7b8c9d Asset Size Chunks Chunk Names ./bundle-source-map.js 668 bytes 1 [emitted] bundle ./bundle-source-map.js.map 538 bytes 1 [emitted] bundle ./runtime~bundle-source-map.js 6.09 KiB 0 [emitted] runtime~bundle ./runtime~bundle-source-map.js.map 6.08 KiB 0 [emitted] runtime~bundle Entrypoint bundle = ./runtime~bundle-source-map.js ./runtime~bundle-source-map.js.map ./bundle-source-map.js ./bundle-source-map.js.map chunk {0} ./runtime~bundle-source-map.js, ./runtime~bundle-source-map.js.map (runtime~bundle) 0 bytes ={1}= [entry] [rendered] > coffee-loader!./example.coffee bundle chunk {1} ./bundle-source-map.js, ./bundle-source-map.js.map (bundle) 256 bytes ={0}= [initial] [rendered] > coffee-loader!./example.coffee bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee 256 bytes {1} [built] single entry coffee-loader!./example.coffee bundle ``` webpack-4.30.0/examples/source-map/build.js000066400000000000000000000000721345416772700205570ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/source-map/example.coffee000066400000000000000000000002761345416772700217340ustar00rootroot00000000000000# Taken from http://coffeescript.org/ # Objects: math = root: Math.sqrt square: square cube: (x) -> x * square x # Splats: race = (winner, runners...) -> print winner, runners webpack-4.30.0/examples/source-map/template.md000066400000000000000000000023651345416772700212660ustar00rootroot00000000000000This example demonstrates various types of source-maps. # example.coffee ```coffeescript _{{example.coffee}}_ ``` # webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # Generated source-maps ## source-map.js and source-map.js.map ```javascript _{{dist/bundle-source-map.js}}_ ``` ```javascript _{{dist/bundle-source-map.js.map}}_ ``` ## hidden-source-map.js and hidden-source-map.js.map ```javascript _{{dist/bundle-hidden-source-map.js}}_ ``` ```javascript _{{dist/bundle-hidden-source-map.js.map}}_ ``` ## inline-source-map.js ```javascript _{{dist/bundle-inline-source-map.js}}_ ``` ## nosources-source-map.js.map ```javascript _{{dist/bundle-nosources-source-map.js.map}}_ ``` ## eval-source-map.js ```javascript _{{dist/bundle-eval-source-map.js}}_ ``` ## eval.js ```javascript _{{dist/bundle-eval.js}}_ ``` ## cheap-eval-source-map.js ```javascript _{{dist/bundle-cheap-eval-source-map.js}}_ ``` ## cheap-module-eval-source-map.js ```javascript _{{dist/bundle-cheap-module-eval-source-map.js}}_ ``` ## cheap-module-source-map.js.map ```javascript _{{dist/bundle-cheap-module-source-map.js.map}}_ ``` ## cheap-source-map.js.map ```javascript _{{dist/bundle-cheap-source-map.js.map}}_ ``` # webpack output ``` _{{stdout}}_ ``` webpack-4.30.0/examples/source-map/webpack.config.js000066400000000000000000000010011345416772700223310ustar00rootroot00000000000000var path = require("path"); module.exports = [ "cheap-eval-source-map", "cheap-module-eval-source-map", "cheap-module-source-map", "cheap-source-map", "eval", "eval-source-map", "hidden-source-map", "inline-source-map", "nosources-source-map", "source-map" ].map(devtool => ({ mode: "development", entry: { bundle: "coffee-loader!./example.coffee" }, output: { path: path.join(__dirname, "dist"), filename: `./[name]-${devtool}.js` }, devtool, optimization: { runtimeChunk: true } })); webpack-4.30.0/examples/template-common.js000066400000000000000000000050601345416772700205100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const fs = require("fs"); const path = require("path"); function lessStrict(regExpStr) { regExpStr = regExpStr .replace(/node_modules/g, "(node_modules|~)") .replace(/(\\\/|\\\\)/g, "[\\/\\\\]"); return regExpStr; } const runtimeRegexp = /(```\s*(?:js|javascript)\n)?(.*)(\/\*\*\*\*\*\*\/ \(function\(modules\) \{ \/\/ webpackBootstrap\n(?:.|\n)*?\n\/\*\*\*\*\*\*\/ \}\)\n\/\**\/\n)/; const timeRegexp = /\s*Time: \d+ms/g; const buildAtRegexp = /\s*Built at: .+/mg; const hashRegexp = /Hash: [a-f0-9]+/g; exports.replaceBase = (template) => { const cwd = process.cwd(); let webpack = path.join(__dirname, ".."); let webpackParent = path.join(__dirname, "..", ".."); const cwdRegExpStr = lessStrict(cwd.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); const cwdRegExp = new RegExp(cwdRegExpStr, "g"); const cwdSlashRegExp = new RegExp(cwdRegExpStr + "[\\/\\\\]", "g"); webpack = lessStrict(webpack.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); webpack = new RegExp(webpack, "g"); webpackParent = lessStrict(webpackParent.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); webpackParent = new RegExp(webpackParent, "g"); return template .replace(/\r\n/g, "\n") .replace(/\r/g, "\n") .replace(cwdSlashRegExp, "./") .replace(cwdRegExp, ".") .replace(webpack, "(webpack)") .replace(webpackParent, "(webpack)/~") .replace(timeRegexp, "") .replace(buildAtRegexp, "") .replace(hashRegexp, "Hash: 0a1b2c3d4e5f6a7b8c9d") .replace(/\.chunkhash\./g, ".[chunkhash].") .replace(runtimeRegexp, function(match) { match = runtimeRegexp.exec(match); const prefix = match[1] ? "" : "```\n"; const inner = match[1] ? match[1] : "``` js\n"; return prefix + "
" + match[2] + "/******/ (function(modules) { /* webpackBootstrap */ })\n\n" + inner + match[2] + match[3] + "```\n\n
\n\n" + inner; }); }; exports.needResults = (template, prefix) => { const regExp = prefix ? new RegExp(`_\\{\\{${prefix}:`) : /_\{\{/; return regExp.test(template); }; exports.replaceResults = (template, baseDir, stdout, prefix) => { const regexp = new RegExp("_\\{\\{" + (prefix ? prefix + ":" : "") + "([^:\\}]+)\\}\\}_", "g"); return template.replace(regexp, function(match) { match = match.substr(3 + (prefix ? prefix.length + 1 : 0), match.length - 6 - (prefix ? prefix.length + 1 : 0)); if(match === "stdout") return stdout; return fs.readFileSync(path.join(baseDir, match), "utf-8").replace(/[\r\n]*$/, ""); }); }; webpack-4.30.0/examples/two-explicit-vendor-chunks/000077500000000000000000000000001345416772700222645ustar00rootroot00000000000000webpack-4.30.0/examples/two-explicit-vendor-chunks/README.md000066400000000000000000000427021345416772700235500ustar00rootroot00000000000000# webpack.config.js ```javascript var path = require("path"); module.exports = { // mode: "development || "production", entry: { vendor1: ["./vendor1"], vendor2: ["./vendor2"], pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "dist"), filename: "[name].js" }, optimization: { splitChunks: { cacheGroups: { vendor1: { name: "vendor1", test: "vendor1", enforce: true }, vendor2: { name: "vendor2", test: "vendor2", enforce: true } } } } }; ``` # dist/vendor1.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!***********************!*\ !*** multi ./vendor1 ***! \***********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./vendor1 */1); /***/ }), /* 1 */ /*!********************!*\ !*** ./vendor1.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "Vendor1"; /***/ }) /******/ ]); ``` # dist/vendor2.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ /******/ ([ /* 0 */, /* 1 */ /*!********************!*\ !*** ./vendor1.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "Vendor1"; /***/ }), /* 2 */ /*!***********************!*\ !*** multi ./vendor2 ***! \***********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./vendor2 */3); /***/ }), /* 3 */ /*!********************!*\ !*** ./vendor2.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = "Vendor2"; __webpack_require__(/*! ./vendor1 */ 1); /***/ }) /******/ ]); ``` # dist/pageA.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 4); /******/ }) /************************************************************************/ /******/ ([ /* 0 */, /* 1 */ /*!********************!*\ !*** ./vendor1.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = "Vendor1"; /***/ }), /* 2 */, /* 3 */ /*!********************!*\ !*** ./vendor2.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = "Vendor2"; __webpack_require__(/*! ./vendor1 */ 1); /***/ }), /* 4 */ /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = "pageA"; __webpack_require__(/*! ./vendor1 */ 1); __webpack_require__(/*! ./vendor2 */ 3); /***/ }) /******/ ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names pageA.js 4.26 KiB 2 [emitted] pageA pageB.js 3.71 KiB 3 [emitted] pageB pageC.js 3.71 KiB 4 [emitted] pageC vendor1.js 3.96 KiB 0 [emitted] vendor1 vendor2.js 4.21 KiB 1 [emitted] vendor2 Entrypoint vendor1 = vendor1.js Entrypoint vendor2 = vendor2.js Entrypoint pageA = pageA.js Entrypoint pageB = pageB.js Entrypoint pageC = pageC.js chunk {0} vendor1.js (vendor1) 55 bytes [entry] [rendered] > vendor1 [0] multi ./vendor1 28 bytes {0} [built] multi entry [1] ./vendor1.js 27 bytes {0} {1} {2} [built] single entry ./vendor1 [0] multi ./vendor1 vendor1[0] cjs require ./vendor1 [3] ./vendor2.js 2:0-20 cjs require ./vendor1 [4] ./pageA.js 2:0-20 chunk {1} vendor2.js (vendor2) 105 bytes [entry] [rendered] > vendor2 [1] ./vendor1.js 27 bytes {0} {1} {2} [built] single entry ./vendor1 [0] multi ./vendor1 vendor1[0] cjs require ./vendor1 [3] ./vendor2.js 2:0-20 cjs require ./vendor1 [4] ./pageA.js 2:0-20 [2] multi ./vendor2 28 bytes {1} [built] multi entry [3] ./vendor2.js 50 bytes {1} {2} [built] single entry ./vendor2 [2] multi ./vendor2 vendor2[0] cjs require ./vendor2 [4] ./pageA.js 3:0-20 chunk {2} pageA.js (pageA) 147 bytes [entry] [rendered] > ./pageA pageA [1] ./vendor1.js 27 bytes {0} {1} {2} [built] single entry ./vendor1 [0] multi ./vendor1 vendor1[0] cjs require ./vendor1 [3] ./vendor2.js 2:0-20 cjs require ./vendor1 [4] ./pageA.js 2:0-20 [3] ./vendor2.js 50 bytes {1} {2} [built] single entry ./vendor2 [2] multi ./vendor2 vendor2[0] cjs require ./vendor2 [4] ./pageA.js 3:0-20 [4] ./pageA.js 70 bytes {2} [built] single entry ./pageA pageA chunk {3} pageB.js (pageB) 25 bytes [entry] [rendered] > ./pageB pageB [5] ./pageB.js 25 bytes {3} [built] single entry ./pageB pageB chunk {4} pageC.js (pageC) 25 bytes [entry] [rendered] > ./pageC pageC [6] ./pageC.js 25 bytes {4} [built] single entry ./pageC pageC ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names pageA.js 1.02 KiB 0 [emitted] pageA pageB.js 954 bytes 1 [emitted] pageB pageC.js 954 bytes 2 [emitted] pageC vendor1.js 987 bytes 3 [emitted] vendor1 vendor2.js 1 KiB 4 [emitted] vendor2 Entrypoint vendor1 = vendor1.js Entrypoint vendor2 = vendor2.js Entrypoint pageA = pageA.js Entrypoint pageB = pageB.js Entrypoint pageC = pageC.js chunk {0} pageA.js (pageA) 147 bytes [entry] [rendered] > ./pageA pageA [0] ./vendor1.js 27 bytes {0} {3} {4} [built] cjs require ./vendor1 [1] ./vendor2.js 2:0-20 single entry ./vendor1 [2] multi ./vendor1 vendor1[0] cjs require ./vendor1 [4] ./pageA.js 2:0-20 [1] ./vendor2.js 50 bytes {0} {4} [built] single entry ./vendor2 [3] multi ./vendor2 vendor2[0] cjs require ./vendor2 [4] ./pageA.js 3:0-20 [4] ./pageA.js 70 bytes {0} [built] single entry ./pageA pageA chunk {1} pageB.js (pageB) 25 bytes [entry] [rendered] > ./pageB pageB [5] ./pageB.js 25 bytes {1} [built] single entry ./pageB pageB chunk {2} pageC.js (pageC) 25 bytes [entry] [rendered] > ./pageC pageC [6] ./pageC.js 25 bytes {2} [built] single entry ./pageC pageC chunk {3} vendor1.js (vendor1) 55 bytes [entry] [rendered] > vendor1 [0] ./vendor1.js 27 bytes {0} {3} {4} [built] cjs require ./vendor1 [1] ./vendor2.js 2:0-20 single entry ./vendor1 [2] multi ./vendor1 vendor1[0] cjs require ./vendor1 [4] ./pageA.js 2:0-20 [2] multi ./vendor1 28 bytes {3} [built] multi entry chunk {4} vendor2.js (vendor2) 105 bytes [entry] [rendered] > vendor2 [0] ./vendor1.js 27 bytes {0} {3} {4} [built] cjs require ./vendor1 [1] ./vendor2.js 2:0-20 single entry ./vendor1 [2] multi ./vendor1 vendor1[0] cjs require ./vendor1 [4] ./pageA.js 2:0-20 [1] ./vendor2.js 50 bytes {0} {4} [built] single entry ./vendor2 [3] multi ./vendor2 vendor2[0] cjs require ./vendor2 [4] ./pageA.js 3:0-20 [3] multi ./vendor2 28 bytes {4} [built] multi entry ``` webpack-4.30.0/examples/two-explicit-vendor-chunks/build.js000066400000000000000000000000721345416772700237200ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-4.30.0/examples/two-explicit-vendor-chunks/pageA.html000066400000000000000000000003241345416772700241660ustar00rootroot00000000000000 webpack-4.30.0/examples/two-explicit-vendor-chunks/pageA.js000066400000000000000000000001061345416772700236340ustar00rootroot00000000000000module.exports = "pageA"; require("./vendor1"); require("./vendor2"); webpack-4.30.0/examples/two-explicit-vendor-chunks/pageB.js000066400000000000000000000000311345416772700236320ustar00rootroot00000000000000module.exports = "pageB";webpack-4.30.0/examples/two-explicit-vendor-chunks/pageC.js000066400000000000000000000000311345416772700236330ustar00rootroot00000000000000module.exports = "pageC";webpack-4.30.0/examples/two-explicit-vendor-chunks/template.md000066400000000000000000000005221345416772700244200ustar00rootroot00000000000000# webpack.config.js ```javascript _{{webpack.config.js}}_ ``` # dist/vendor1.js ```javascript _{{dist/vendor1.js}}_ ``` # dist/vendor2.js ```javascript _{{dist/vendor2.js}}_ ``` # dist/pageA.js ```javascript _{{dist/pageA.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/two-explicit-vendor-chunks/vendor1.js000066400000000000000000000000331345416772700241740ustar00rootroot00000000000000module.exports = "Vendor1";webpack-4.30.0/examples/two-explicit-vendor-chunks/vendor2.js000066400000000000000000000000621345416772700241770ustar00rootroot00000000000000module.exports = "Vendor2"; require("./vendor1"); webpack-4.30.0/examples/two-explicit-vendor-chunks/webpack.config.js000066400000000000000000000010151345416772700254770ustar00rootroot00000000000000var path = require("path"); module.exports = { // mode: "development || "production", entry: { vendor1: ["./vendor1"], vendor2: ["./vendor2"], pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "dist"), filename: "[name].js" }, optimization: { splitChunks: { cacheGroups: { vendor1: { name: "vendor1", test: "vendor1", enforce: true }, vendor2: { name: "vendor2", test: "vendor2", enforce: true } } } } }; webpack-4.30.0/examples/wasm-simple/000077500000000000000000000000001345416772700173065ustar00rootroot00000000000000webpack-4.30.0/examples/wasm-simple/README.md000066400000000000000000000521051345416772700205700ustar00rootroot00000000000000This very simple example shows usage of WebAssembly. WebAssembly modules can be imported like other modules. Their download and compilation happens in parallel to the download and evaluation of the javascript chunk. # example.js ```javascript import("./add.wasm").then(addModule => { console.log(addModule.add(22, 2200)); import("./math").then(math => { console.log(math.add(10, 101)); console.log(math.factorial(15)); console.log(math.factorialJavascript(15)); console.log(math.fibonacci(15)); console.log(math.fibonacciJavascript(15)); timed("wasm factorial", () => math.factorial(1500)); timed("js factorial", () => math.factorialJavascript(1500)); timed("wasm fibonacci", () => math.fibonacci(22)); timed("js fibonacci", () => math.fibonacciJavascript(22)); }); }); function timed(name, fn) { if(!console.time || !console.timeEnd) return fn(); // warmup for(var i = 0; i < 10; i++) fn(); console.time(name) for(var i = 0; i < 5000; i++) fn(); console.timeEnd(name) } ``` # math.js ```javascript import { add } from "./add.wasm"; import { factorial } from "./factorial.wasm"; import { fibonacci } from "./fibonacci.wasm"; export { add, factorial, fibonacci }; export function factorialJavascript(i) { if(i < 1) return 1; return i * factorialJavascript(i - 1); } export function fibonacciJavascript(i) { if(i < 2) return 1; return fibonacciJavascript(i - 1) + fibonacciJavascript(i - 2); } ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ /******/ /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]); /******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(data); /******/ /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 0: 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + chunkId + ".output.js" /******/ } /******/ /******/ // object to store loaded and loading wasm modules /******/ var installedWasmModules = {}; /******/ /******/ function promiseResolve() { return Promise.resolve(); } /******/ /******/ var wasmImportObjects = { /******/ 1: function() { /******/ return { /******/ /******/ }; /******/ }, /******/ 3: function() { /******/ return { /******/ /******/ }; /******/ }, /******/ 4: function() { /******/ return { /******/ /******/ }; /******/ }, /******/ 1: function() { /******/ return { /******/ /******/ }; /******/ }, /******/ }; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ /******/ /******/ // JSONP chunk loading for javascript /******/ /******/ var installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[2]); /******/ } else { /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ promises.push(installedChunkData[2] = promise); /******/ /******/ // start chunk loading /******/ var script = document.createElement('script'); /******/ var onScriptComplete; /******/ /******/ script.charset = 'utf-8'; /******/ script.timeout = 120; /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = jsonpScriptSrc(chunkId); /******/ /******/ onScriptComplete = function (event) { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); /******/ var realSrc = event && event.target && event.target.src; /******/ var error = new Error('Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'); /******/ error.type = errorType; /******/ error.request = realSrc; /******/ chunk[1](error); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ var timeout = setTimeout(function(){ /******/ onScriptComplete({ type: 'timeout', target: script }); /******/ }, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ document.head.appendChild(script); /******/ } /******/ } /******/ /******/ // Fetch + compile chunk loading for webassembly /******/ /******/ var wasmModules = {"1":[1,3,4],"2":[1]}[chunkId] || []; /******/ /******/ wasmModules.forEach(function(wasmModuleId) { /******/ var installedWasmModuleData = installedWasmModules[wasmModuleId]; /******/ /******/ // a Promise means "currently loading" or "already loaded". /******/ if(installedWasmModuleData) /******/ promises.push(installedWasmModuleData); /******/ else { /******/ var importObject = wasmImportObjects[wasmModuleId](); /******/ var req = fetch(__webpack_require__.p + "" + {"1":"c50d6212832abfc3ae1e","3":"3580ad47c1ba500584ea","4":"baf012e37fe9b85e815a"}[wasmModuleId] + ".wasm"); /******/ var promise; /******/ if(importObject instanceof Promise && typeof WebAssembly.compileStreaming === 'function') { /******/ promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) { /******/ return WebAssembly.instantiate(items[0], items[1]); /******/ }); /******/ } else if(typeof WebAssembly.instantiateStreaming === 'function') { /******/ promise = WebAssembly.instantiateStreaming(req, importObject); /******/ } else { /******/ var bytesPromise = req.then(function(x) { return x.arrayBuffer(); }); /******/ promise = bytesPromise.then(function(bytes) { /******/ return WebAssembly.instantiate(bytes, importObject); /******/ }); /******/ } /******/ promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) { /******/ return __webpack_require__.w[wasmModuleId] = (res.instance || res).exports; /******/ })); /******/ } /******/ }); /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // object with all WebAssembly.instance exports /******/ __webpack_require__.w = {}; /******/ /******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; /******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); /******/ jsonpArray.push = webpackJsonpCallback; /******/ jsonpArray = jsonpArray.slice(); /******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); /******/ var parentJsonpFunction = oldJsonpFunction; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__.e(/*! import() */ 2).then(__webpack_require__.bind(null, /*! ./add.wasm */ 1)).then(addModule => { console.log(addModule.add(22, 2200)); __webpack_require__.e(/*! import() */ 1).then(__webpack_require__.bind(null, /*! ./math */ 2)).then(math => { console.log(math.add(10, 101)); console.log(math.factorial(15)); console.log(math.factorialJavascript(15)); console.log(math.fibonacci(15)); console.log(math.fibonacciJavascript(15)); timed("wasm factorial", () => math.factorial(1500)); timed("js factorial", () => math.factorialJavascript(1500)); timed("wasm fibonacci", () => math.fibonacci(22)); timed("js fibonacci", () => math.fibonacciJavascript(22)); }); }); function timed(name, fn) { if(!console.time || !console.timeEnd) return fn(); // warmup for(var i = 0; i < 10; i++) fn(); console.time(name) for(var i = 0; i < 5000; i++) fn(); console.timeEnd(name) } /***/ }) /******/ ]); ``` # dist/1.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ /* 0 */, /* 1 */ /*!******************!*\ !*** ./add.wasm ***! \******************/ /*! exports provided: add */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Instantiate WebAssembly module var wasmExports = __webpack_require__.w[module.i]; __webpack_require__.r(exports); // export exports from WebAssembly module for(var name in wasmExports) if(name != "__webpack_init__") exports[name] = wasmExports[name]; // exec imports from WebAssembly module (for esm order) // exec wasm module wasmExports["__webpack_init__"]() /***/ }), /* 2 */ /*!*****************!*\ !*** ./math.js ***! \*****************/ /*! exports provided: add, factorial, fibonacci, factorialJavascript, fibonacciJavascript */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "factorialJavascript", function() { return factorialJavascript; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fibonacciJavascript", function() { return fibonacciJavascript; }); /* harmony import */ var _add_wasm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./add.wasm */ 1); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "add", function() { return _add_wasm__WEBPACK_IMPORTED_MODULE_0__["add"]; }); /* harmony import */ var _factorial_wasm__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./factorial.wasm */ 3); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "factorial", function() { return _factorial_wasm__WEBPACK_IMPORTED_MODULE_1__["factorial"]; }); /* harmony import */ var _fibonacci_wasm__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fibonacci.wasm */ 4); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fibonacci", function() { return _fibonacci_wasm__WEBPACK_IMPORTED_MODULE_2__["fibonacci"]; }); function factorialJavascript(i) { if(i < 1) return 1; return i * factorialJavascript(i - 1); } function fibonacciJavascript(i) { if(i < 2) return 1; return fibonacciJavascript(i - 1) + fibonacciJavascript(i - 2); } /***/ }), /* 3 */ /*!************************!*\ !*** ./factorial.wasm ***! \************************/ /*! exports provided: factorial */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Instantiate WebAssembly module var wasmExports = __webpack_require__.w[module.i]; __webpack_require__.r(exports); // export exports from WebAssembly module for(var name in wasmExports) if(name != "__webpack_init__") exports[name] = wasmExports[name]; // exec imports from WebAssembly module (for esm order) // exec wasm module wasmExports["__webpack_init__"]() /***/ }), /* 4 */ /*!************************!*\ !*** ./fibonacci.wasm ***! \************************/ /*! exports provided: fibonacci */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Instantiate WebAssembly module var wasmExports = __webpack_require__.w[module.i]; __webpack_require__.r(exports); // export exports from WebAssembly module for(var name in wasmExports) if(name != "__webpack_init__") exports[name] = wasmExports[name]; // exec imports from WebAssembly module (for esm order) // exec wasm module wasmExports["__webpack_init__"]() /***/ }) ]]); ``` # dist/2.output.js ```javascript (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[2],[ /* 0 */, /* 1 */ /*!******************!*\ !*** ./add.wasm ***! \******************/ /*! exports provided: add */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Instantiate WebAssembly module var wasmExports = __webpack_require__.w[module.i]; __webpack_require__.r(exports); // export exports from WebAssembly module for(var name in wasmExports) if(name != "__webpack_init__") exports[name] = wasmExports[name]; // exec imports from WebAssembly module (for esm order) // exec wasm module wasmExports["__webpack_init__"]() /***/ }) ]]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.output.js 3.37 KiB 1 [emitted] 2.output.js 636 bytes 2 [emitted] 3580ad47c1ba500584ea.wasm unknown size 1 [emitted] baf012e37fe9b85e815a.wasm unknown size 1 [emitted] c50d6212832abfc3ae1e.wasm unknown size 1, 2 [emitted] output.js 11.2 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 762 bytes >{1}< >{2}< [entry] [rendered] > ./example.js main [0] ./example.js 762 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js, c50d6212832abfc3ae1e.wasm, 3580ad47c1ba500584ea.wasm, baf012e37fe9b85e815a.wasm 570 bytes <{0}> [rendered] > ./math [0] ./example.js 3:1-17 [1] ./add.wasm 41 bytes {1} {2} [built] [exports: add] import() ./add.wasm [0] ./example.js 1:0-20 harmony side effect evaluation ./add.wasm [2] ./math.js 1:0-33 harmony export imported specifier ./add.wasm [2] ./math.js 5:0-37 [2] ./math.js 400 bytes {1} [built] [exports: add, factorial, fibonacci, factorialJavascript, fibonacciJavascript] import() ./math [0] ./example.js 3:1-17 [3] ./factorial.wasm 62 bytes {1} [built] [exports: factorial] harmony side effect evaluation ./factorial.wasm [2] ./math.js 2:0-45 harmony export imported specifier ./factorial.wasm [2] ./math.js 5:0-37 [4] ./fibonacci.wasm 67 bytes {1} [built] [exports: fibonacci] harmony side effect evaluation ./fibonacci.wasm [2] ./math.js 3:0-45 harmony export imported specifier ./fibonacci.wasm [2] ./math.js 5:0-37 chunk {2} 2.output.js, c50d6212832abfc3ae1e.wasm 41 bytes <{0}> [rendered] > ./add.wasm [0] ./example.js 1:0-20 [1] ./add.wasm 41 bytes {1} {2} [built] [exports: add] import() ./add.wasm [0] ./example.js 1:0-20 harmony side effect evaluation ./add.wasm [2] ./math.js 1:0-33 harmony export imported specifier ./add.wasm [2] ./math.js 5:0-37 ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 0a12d714e570b7fd9d8b.wasm unknown size 1, 2 [emitted] 1.output.js 681 bytes 1, 2 [emitted] 2.output.js 184 bytes 2 [emitted] a04390412f9500b1d7ae.wasm unknown size 1, 2 [emitted] a36cec63b02caac8e61a.wasm unknown size 1, 2, 2 [emitted] output.js 3.29 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 762 bytes >{1}< >{2}< [entry] [rendered] > ./example.js main [0] ./example.js 762 bytes {0} [built] single entry ./example.js main chunk {1} 1.output.js, a36cec63b02caac8e61a.wasm, a04390412f9500b1d7ae.wasm, 0a12d714e570b7fd9d8b.wasm 570 bytes <{0}> [rendered] > ./math [0] ./example.js 3:1-17 [1] ./add.wasm 41 bytes {1} {2} [built] [exports: add] import() ./add.wasm [0] ./example.js 1:0-20 harmony side effect evaluation ./add.wasm [2] ./math.js 1:0-33 harmony export imported specifier ./add.wasm [2] ./math.js 5:0-37 [2] ./math.js 400 bytes {1} [built] [exports: add, factorial, fibonacci, factorialJavascript, fibonacciJavascript] import() ./math [0] ./example.js 3:1-17 [3] ./factorial.wasm 62 bytes {1} [built] [exports: factorial] [all exports used] harmony side effect evaluation ./factorial.wasm [2] ./math.js 2:0-45 harmony export imported specifier ./factorial.wasm [2] ./math.js 5:0-37 [4] ./fibonacci.wasm 67 bytes {1} [built] [exports: fibonacci] [all exports used] harmony side effect evaluation ./fibonacci.wasm [2] ./math.js 3:0-45 harmony export imported specifier ./fibonacci.wasm [2] ./math.js 5:0-37 chunk {2} 2.output.js, a36cec63b02caac8e61a.wasm 41 bytes <{0}> [rendered] > ./add.wasm [0] ./example.js 1:0-20 [1] ./add.wasm 41 bytes {1} {2} [built] [exports: add] import() ./add.wasm [0] ./example.js 1:0-20 harmony side effect evaluation ./add.wasm [2] ./math.js 1:0-33 harmony export imported specifier ./add.wasm [2] ./math.js 5:0-37 ``` webpack-4.30.0/examples/wasm-simple/add.wasm000066400000000000000000000000511345416772700207230ustar00rootroot00000000000000asm`add  j webpack-4.30.0/examples/wasm-simple/build.js000066400000000000000000000000331345416772700207370ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/wasm-simple/example.js000066400000000000000000000013721345416772700213020ustar00rootroot00000000000000import("./add.wasm").then(addModule => { console.log(addModule.add(22, 2200)); import("./math").then(math => { console.log(math.add(10, 101)); console.log(math.factorial(15)); console.log(math.factorialJavascript(15)); console.log(math.fibonacci(15)); console.log(math.fibonacciJavascript(15)); timed("wasm factorial", () => math.factorial(1500)); timed("js factorial", () => math.factorialJavascript(1500)); timed("wasm fibonacci", () => math.fibonacci(22)); timed("js fibonacci", () => math.fibonacciJavascript(22)); }); }); function timed(name, fn) { if(!console.time || !console.timeEnd) return fn(); // warmup for(var i = 0; i < 10; i++) fn(); console.time(name) for(var i = 0; i < 5000; i++) fn(); console.timeEnd(name) } webpack-4.30.0/examples/wasm-simple/factorial.wasm000066400000000000000000000000761345416772700221460ustar00rootroot00000000000000asm`  factorial  AHA Akl webpack-4.30.0/examples/wasm-simple/fibonacci.wasm000066400000000000000000000001031345416772700221060ustar00rootroot00000000000000asm`  fibonacci  AHA Ak Akj webpack-4.30.0/examples/wasm-simple/index.html000066400000000000000000000001071345416772700213010ustar00rootroot00000000000000 webpack-4.30.0/examples/wasm-simple/math.js000066400000000000000000000006201345416772700205730ustar00rootroot00000000000000import { add } from "./add.wasm"; import { factorial } from "./factorial.wasm"; import { fibonacci } from "./fibonacci.wasm"; export { add, factorial, fibonacci }; export function factorialJavascript(i) { if(i < 1) return 1; return i * factorialJavascript(i - 1); } export function fibonacciJavascript(i) { if(i < 2) return 1; return fibonacciJavascript(i - 1) + fibonacciJavascript(i - 2); } webpack-4.30.0/examples/wasm-simple/template.md000066400000000000000000000011201345416772700214350ustar00rootroot00000000000000This very simple example shows usage of WebAssembly. WebAssembly modules can be imported like other modules. Their download and compilation happens in parallel to the download and evaluation of the javascript chunk. # example.js ```javascript _{{example.js}}_ ``` # math.js ```javascript _{{math.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/1.output.js ```javascript _{{dist/1.output.js}}_ ``` # dist/2.output.js ```javascript _{{dist/2.output.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/wasm-simple/test.filter.js000066400000000000000000000002241345416772700221050ustar00rootroot00000000000000var supportsWebAssembly = require("../../test/helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/examples/wasm-simple/webpack.config.js000066400000000000000000000005641345416772700225310ustar00rootroot00000000000000module.exports = { // mode: "development || "production", output: { webassemblyModuleFilename: "[modulehash].wasm", publicPath: "js/" }, module: { rules: [ { test: /\.wasm$/, type: "webassembly/experimental" } ] }, optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/web-worker/000077500000000000000000000000001345416772700171345ustar00rootroot00000000000000webpack-4.30.0/examples/web-worker/README.md000066400000000000000000000376561345416772700204340ustar00rootroot00000000000000# example.js ```javascript var Worker = require("worker-loader?name=hash.worker.js!./worker"); var worker = new Worker; worker.postMessage("b"); worker.onmessage = function(event) { var templateB = event.data; // "This text was generated by template B" } ``` # worker.js ```javascript onmessage = function(event) { var template = event.data; require(["../require.context/templates/" + event.data], function(tmpl) { postMessage(tmpl()); }); } ``` # dist/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ```javascript /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
```javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var Worker = __webpack_require__(/*! worker-loader?name=hash.worker.js!./worker */ 1); var worker = new Worker; worker.postMessage("b"); worker.onmessage = function(event) { var templateB = event.data; // "This text was generated by template B" } /***/ }), /* 1 */ /*!****************************************************************************************!*\ !*** (webpack)/node_modules/worker-loader/dist/cjs.js?name=hash.worker.js!./worker.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = function() { return new Worker(__webpack_require__.p + "hash.worker.js"); }; /***/ }) /******/ ]); ``` # dist/[hash].worker.js ```javascript /******/ (function(modules) { // webpackBootstrap /******/ window["webpackChunk"] = function webpackChunkCallback(chunkIds, moreModules) { /******/ for(var moduleId in moreModules) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ while(chunkIds.length) /******/ installedChunks[chunkIds.pop()] = 1; /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded chunks /******/ // "1" means "already loaded" /******/ var installedChunks = { /******/ 0: 1 /******/ }; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId) { /******/ var promises = []; /******/ promises.push(Promise.resolve().then(function() { /******/ // "1" is the signal for "already loaded" /******/ if(!installedChunks[chunkId]) { /******/ importScripts("" + chunkId + ".hash.worker.js"); /******/ } /******/ })); /******/ return Promise.all(promises); /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "dist/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!*******************!*\ !*** ./worker.js ***! \*******************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { onmessage = function(event) { var template = event.data; __webpack_require__.e(/*! AMD require */ 1).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(1)("./" + event.data)]; (function(tmpl) { postMessage(tmpl()); }).apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);}).catch(__webpack_require__.oe); } /***/ }) /******/ ]); ``` # dist/1.[hash].worker.js ```javascript window["webpackChunk"]([1],[ /* 0 */, /* 1 */ /*!**************************************************!*\ !*** ../require.context/templates sync ^\.\/.*$ ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var map = { "./a": 2, "./a.js": 2, "./b": 3, "./b.js": 3, "./c": 4, "./c.js": 4 }; function webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } function webpackContextResolve(req) { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 1; /***/ }), /* 2 */ /*!*****************************************!*\ !*** ../require.context/templates/a.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 3 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 4 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]); ``` # Info ## Unoptimized ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.hash.worker.js 1.77 KiB [emitted] hash.worker.js 4.98 KiB [emitted] output.js 4.42 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 326 bytes [entry] [rendered] > ./example.js main [0] ./example.js 229 bytes {0} [built] single entry ./example.js main [1] (webpack)/node_modules/worker-loader/dist/cjs.js?name=hash.worker.js!./worker.js 97 bytes {0} [not cacheable] [built] cjs require worker-loader?name=hash.worker.js!./worker [0] ./example.js 1:13-66 Child worker: Asset Size Chunks Chunk Names 1.hash.worker.js 1.77 KiB 1 [emitted] hash.worker.js 4.98 KiB 0 [emitted] main Entrypoint main = hash.worker.js chunk {0} hash.worker.js (main) 162 bytes >{1}< [entry] [rendered] > !!./worker.js main [0] ./worker.js 162 bytes {0} [built] single entry !!./worker.js main chunk {1} 1.hash.worker.js 457 bytes <{0}> [rendered] > [0] ./worker.js 3:1-5:3 [1] ../require.context/templates sync ^\.\/.*$ 217 bytes {1} [built] amd require context ../require.context/templates [0] ./worker.js 3:1-5:3 [2] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a [1] ../require.context/templates sync ^\.\/.*$ ./a context element ./a.js [1] ../require.context/templates sync ^\.\/.*$ ./a.js [3] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b [1] ../require.context/templates sync ^\.\/.*$ ./b context element ./b.js [1] ../require.context/templates sync ^\.\/.*$ ./b.js [4] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c [1] ../require.context/templates sync ^\.\/.*$ ./c context element ./c.js [1] ../require.context/templates sync ^\.\/.*$ ./c.js ``` ## Production mode ``` Hash: 0a1b2c3d4e5f6a7b8c9d Version: webpack 4.29.6 Asset Size Chunks Chunk Names 1.hash.worker.js 588 bytes [emitted] hash.worker.js 1.27 KiB [emitted] output.js 1.06 KiB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 326 bytes [entry] [rendered] > ./example.js main [0] ./example.js 229 bytes {0} [built] single entry ./example.js main [1] (webpack)/node_modules/worker-loader/dist/cjs.js?name=hash.worker.js!./worker.js 97 bytes {0} [not cacheable] [built] cjs require worker-loader?name=hash.worker.js!./worker [0] ./example.js 1:13-66 Child worker: Asset Size Chunks Chunk Names 1.hash.worker.js 588 bytes 1 [emitted] hash.worker.js 1.27 KiB 0 [emitted] main Entrypoint main = hash.worker.js chunk {0} hash.worker.js (main) 162 bytes >{1}< [entry] [rendered] > !!./worker.js main [0] ./worker.js 162 bytes {0} [built] single entry !!./worker.js main chunk {1} 1.hash.worker.js 457 bytes <{0}> [rendered] > [0] ./worker.js 3:1-5:3 [1] ../require.context/templates sync ^\.\/.*$ 217 bytes {1} [built] amd require context ../require.context/templates [0] ./worker.js 3:1-5:3 [2] ../require.context/templates/a.js 80 bytes {1} [optional] [built] context element ./a [1] ../require.context/templates sync ^\.\/.*$ ./a context element ./a.js [1] ../require.context/templates sync ^\.\/.*$ ./a.js [3] ../require.context/templates/b.js 80 bytes {1} [optional] [built] context element ./b [1] ../require.context/templates sync ^\.\/.*$ ./b context element ./b.js [1] ../require.context/templates sync ^\.\/.*$ ./b.js [4] ../require.context/templates/c.js 80 bytes {1} [optional] [built] context element ./c [1] ../require.context/templates sync ^\.\/.*$ ./c context element ./c.js [1] ../require.context/templates sync ^\.\/.*$ ./c.js ``` webpack-4.30.0/examples/web-worker/build.js000066400000000000000000000000331345416772700205650ustar00rootroot00000000000000require("../build-common");webpack-4.30.0/examples/web-worker/example.js000066400000000000000000000003451345416772700211270ustar00rootroot00000000000000var Worker = require("worker-loader?name=hash.worker.js!./worker"); var worker = new Worker; worker.postMessage("b"); worker.onmessage = function(event) { var templateB = event.data; // "This text was generated by template B" } webpack-4.30.0/examples/web-worker/template.md000066400000000000000000000006161345416772700212740ustar00rootroot00000000000000# example.js ```javascript _{{example.js}}_ ``` # worker.js ```javascript _{{worker.js}}_ ``` # dist/output.js ```javascript _{{dist/output.js}}_ ``` # dist/[hash].worker.js ```javascript _{{dist/hash.worker.js}}_ ``` # dist/1.[hash].worker.js ```javascript _{{dist/1.hash.worker.js}}_ ``` # Info ## Unoptimized ``` _{{stdout}}_ ``` ## Production mode ``` _{{production:stdout}}_ ``` webpack-4.30.0/examples/web-worker/webpack.config.js000066400000000000000000000006421345416772700223540ustar00rootroot00000000000000var webpack = require("../../"); module.exports = { // mode: "development" || "production", plugins: [ new webpack.LoaderOptionsPlugin({ options: { worker: { output: { filename: "hash.worker.js", chunkFilename: "[id].hash.worker.js" } } } }) ], optimization: { occurrenceOrder: true // To keep filename consistent between different modes (for example building only) } }; webpack-4.30.0/examples/web-worker/worker.js000066400000000000000000000002421345416772700210010ustar00rootroot00000000000000onmessage = function(event) { var template = event.data; require(["../require.context/templates/" + event.data], function(tmpl) { postMessage(tmpl()); }); } webpack-4.30.0/hot/000077500000000000000000000000001345416772700140245ustar00rootroot00000000000000webpack-4.30.0/hot/dev-server.js000066400000000000000000000031541345416772700164470ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals window __webpack_hash__ */ if (module.hot) { var lastHash; var upToDate = function upToDate() { return lastHash.indexOf(__webpack_hash__) >= 0; }; var log = require("./log"); var check = function check() { module.hot .check(true) .then(function(updatedModules) { if (!updatedModules) { log("warning", "[HMR] Cannot find update. Need to do a full reload!"); log( "warning", "[HMR] (Probably because of restarting the webpack-dev-server)" ); window.location.reload(); return; } if (!upToDate()) { check(); } require("./log-apply-result")(updatedModules, updatedModules); if (upToDate()) { log("info", "[HMR] App is up to date."); } }) .catch(function(err) { var status = module.hot.status(); if (["abort", "fail"].indexOf(status) >= 0) { log( "warning", "[HMR] Cannot apply update. Need to do a full reload!" ); log("warning", "[HMR] " + (err.stack || err.message)); window.location.reload(); } else { log("warning", "[HMR] Update failed: " + (err.stack || err.message)); } }); }; var hotEmitter = require("./emitter"); hotEmitter.on("webpackHotUpdate", function(currentHash) { lastHash = currentHash; if (!upToDate() && module.hot.status() === "idle") { log("info", "[HMR] Checking for updates on the server..."); check(); } }); log("info", "[HMR] Waiting for update signal from WDS..."); } else { throw new Error("[HMR] Hot Module Replacement is disabled."); } webpack-4.30.0/hot/emitter.js000066400000000000000000000001131345416772700160260ustar00rootroot00000000000000var EventEmitter = require("events"); module.exports = new EventEmitter(); webpack-4.30.0/hot/log-apply-result.js000066400000000000000000000024261345416772700176060ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ module.exports = function(updatedModules, renewedModules) { var unacceptedModules = updatedModules.filter(function(moduleId) { return renewedModules && renewedModules.indexOf(moduleId) < 0; }); var log = require("./log"); if (unacceptedModules.length > 0) { log( "warning", "[HMR] The following modules couldn't be hot updated: (They would need a full reload!)" ); unacceptedModules.forEach(function(moduleId) { log("warning", "[HMR] - " + moduleId); }); } if (!renewedModules || renewedModules.length === 0) { log("info", "[HMR] Nothing hot updated."); } else { log("info", "[HMR] Updated modules:"); renewedModules.forEach(function(moduleId) { if (typeof moduleId === "string" && moduleId.indexOf("!") !== -1) { var parts = moduleId.split("!"); log.groupCollapsed("info", "[HMR] - " + parts.pop()); log("info", "[HMR] - " + moduleId); log.groupEnd("info"); } else { log("info", "[HMR] - " + moduleId); } }); var numberIds = renewedModules.every(function(moduleId) { return typeof moduleId === "number"; }); if (numberIds) log( "info", "[HMR] Consider using the NamedModulesPlugin for module names." ); } }; webpack-4.30.0/hot/log.js000066400000000000000000000021561345416772700151470ustar00rootroot00000000000000var logLevel = "info"; function dummy() {} function shouldLog(level) { var shouldLog = (logLevel === "info" && level === "info") || (["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") || (["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error"); return shouldLog; } function logGroup(logFn) { return function(level, msg) { if (shouldLog(level)) { logFn(msg); } }; } module.exports = function(level, msg) { if (shouldLog(level)) { if (level === "info") { console.log(msg); } else if (level === "warning") { console.warn(msg); } else if (level === "error") { console.error(msg); } } }; /* eslint-disable node/no-unsupported-features/node-builtins */ var group = console.group || dummy; var groupCollapsed = console.groupCollapsed || dummy; var groupEnd = console.groupEnd || dummy; /* eslint-enable node/no-unsupported-features/node-builtins */ module.exports.group = logGroup(group); module.exports.groupCollapsed = logGroup(groupCollapsed); module.exports.groupEnd = logGroup(groupEnd); module.exports.setLogLevel = function(level) { logLevel = level; }; webpack-4.30.0/hot/only-dev-server.js000066400000000000000000000050611345416772700174250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals __webpack_hash__ */ if (module.hot) { var lastHash; var upToDate = function upToDate() { return lastHash.indexOf(__webpack_hash__) >= 0; }; var log = require("./log"); var check = function check() { module.hot .check() .then(function(updatedModules) { if (!updatedModules) { log("warning", "[HMR] Cannot find update. Need to do a full reload!"); log( "warning", "[HMR] (Probably because of restarting the webpack-dev-server)" ); return; } return module.hot .apply({ ignoreUnaccepted: true, ignoreDeclined: true, ignoreErrored: true, onUnaccepted: function(data) { log( "warning", "Ignored an update to unaccepted module " + data.chain.join(" -> ") ); }, onDeclined: function(data) { log( "warning", "Ignored an update to declined module " + data.chain.join(" -> ") ); }, onErrored: function(data) { log("error", data.error); log( "warning", "Ignored an error while updating module " + data.moduleId + " (" + data.type + ")" ); } }) .then(function(renewedModules) { if (!upToDate()) { check(); } require("./log-apply-result")(updatedModules, renewedModules); if (upToDate()) { log("info", "[HMR] App is up to date."); } }); }) .catch(function(err) { var status = module.hot.status(); if (["abort", "fail"].indexOf(status) >= 0) { log( "warning", "[HMR] Cannot check for update. Need to do a full reload!" ); log("warning", "[HMR] " + (err.stack || err.message)); } else { log( "warning", "[HMR] Update check failed: " + (err.stack || err.message) ); } }); }; var hotEmitter = require("./emitter"); hotEmitter.on("webpackHotUpdate", function(currentHash) { lastHash = currentHash; if (!upToDate()) { var status = module.hot.status(); if (status === "idle") { log("info", "[HMR] Checking for updates on the server..."); check(); } else if (["abort", "fail"].indexOf(status) >= 0) { log( "warning", "[HMR] Cannot apply update as a previous update " + status + "ed. Need to do a full reload!" ); } } }); log("info", "[HMR] Waiting for update signal from WDS..."); } else { throw new Error("[HMR] Hot Module Replacement is disabled."); } webpack-4.30.0/hot/poll.js000066400000000000000000000022331345416772700153300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals __resourceQuery */ if (module.hot) { var hotPollInterval = +__resourceQuery.substr(1) || 10 * 60 * 1000; var log = require("./log"); var checkForUpdate = function checkForUpdate(fromUpdate) { if (module.hot.status() === "idle") { module.hot .check(true) .then(function(updatedModules) { if (!updatedModules) { if (fromUpdate) log("info", "[HMR] Update applied."); return; } require("./log-apply-result")(updatedModules, updatedModules); checkForUpdate(true); }) .catch(function(err) { var status = module.hot.status(); if (["abort", "fail"].indexOf(status) >= 0) { log("warning", "[HMR] Cannot apply update."); log("warning", "[HMR] " + (err.stack || err.message)); log("warning", "[HMR] You need to restart the application!"); } else { log( "warning", "[HMR] Update failed: " + (err.stack || err.message) ); } }); } }; setInterval(checkForUpdate, hotPollInterval); } else { throw new Error("[HMR] Hot Module Replacement is disabled."); } webpack-4.30.0/hot/signal.js000066400000000000000000000032051345416772700156370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals __resourceQuery */ if (module.hot) { var log = require("./log"); var checkForUpdate = function checkForUpdate(fromUpdate) { module.hot .check() .then(function(updatedModules) { if (!updatedModules) { if (fromUpdate) log("info", "[HMR] Update applied."); else log("warning", "[HMR] Cannot find update."); return; } return module.hot .apply({ ignoreUnaccepted: true, onUnaccepted: function(data) { log( "warning", "Ignored an update to unaccepted module " + data.chain.join(" -> ") ); } }) .then(function(renewedModules) { require("./log-apply-result")(updatedModules, renewedModules); checkForUpdate(true); return null; }); }) .catch(function(err) { var status = module.hot.status(); if (["abort", "fail"].indexOf(status) >= 0) { log("warning", "[HMR] Cannot apply update."); log("warning", "[HMR] " + (err.stack || err.message)); log("warning", "[HMR] You need to restart the application!"); } else { log("warning", "[HMR] Update failed: " + (err.stack || err.message)); } }); }; process.on(__resourceQuery.substr(1) || "SIGUSR2", function() { if (module.hot.status() !== "idle") { log( "warning", "[HMR] Got signal but currently in " + module.hot.status() + " state." ); log("warning", "[HMR] Need to be in idle state to start hot update."); return; } checkForUpdate(); }); } else { throw new Error("[HMR] Hot Module Replacement is disabled."); } webpack-4.30.0/lib/000077500000000000000000000000001345416772700140005ustar00rootroot00000000000000webpack-4.30.0/lib/APIPlugin.js000066400000000000000000000043151345416772700161310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./dependencies/ConstDependency"); const ParserHelpers = require("./ParserHelpers"); const NullFactory = require("./NullFactory"); /* eslint-disable camelcase */ const REPLACEMENTS = { __webpack_require__: "__webpack_require__", __webpack_public_path__: "__webpack_require__.p", __webpack_modules__: "__webpack_require__.m", __webpack_chunk_load__: "__webpack_require__.e", __non_webpack_require__: "require", __webpack_nonce__: "__webpack_require__.nc", "require.onError": "__webpack_require__.oe" }; const NO_WEBPACK_REQUIRE = { __non_webpack_require__: true }; const REPLACEMENT_TYPES = { __webpack_public_path__: "string", __webpack_require__: "function", __webpack_modules__: "object", __webpack_chunk_load__: "function", __webpack_nonce__: "string" }; /* eslint-enable camelcase */ class APIPlugin { apply(compiler) { compiler.hooks.compilation.tap( "APIPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); const handler = parser => { Object.keys(REPLACEMENTS).forEach(key => { parser.hooks.expression .for(key) .tap( "APIPlugin", NO_WEBPACK_REQUIRE[key] ? ParserHelpers.toConstantDependency( parser, REPLACEMENTS[key] ) : ParserHelpers.toConstantDependencyWithWebpackRequire( parser, REPLACEMENTS[key] ) ); const type = REPLACEMENT_TYPES[key]; if (type) { parser.hooks.evaluateTypeof .for(key) .tap("APIPlugin", ParserHelpers.evaluateToString(type)); } }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("APIPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("APIPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("APIPlugin", handler); } ); } } module.exports = APIPlugin; webpack-4.30.0/lib/AmdMainTemplatePlugin.js000066400000000000000000000050311345416772700205160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); const Template = require("./Template"); /** @typedef {import("./Compilation")} Compilation */ /** * @typedef {Object} AmdMainTemplatePluginOptions * @param {string=} name the library name * @property {boolean=} requireAsWrapper */ class AmdMainTemplatePlugin { /** * @param {AmdMainTemplatePluginOptions} options the plugin options */ constructor(options) { if (!options || typeof options === "string") { this.name = options; this.requireAsWrapper = false; } else { this.name = options.name; this.requireAsWrapper = options.requireAsWrapper; } } /** * @param {Compilation} compilation the compilation instance * @returns {void} */ apply(compilation) { const { mainTemplate, chunkTemplate } = compilation; const onRenderWithEntry = (source, chunk, hash) => { const externals = chunk.getModules().filter(m => m.external); const externalsDepsArray = JSON.stringify( externals.map(m => typeof m.request === "object" ? m.request.amd : m.request ) ); const externalsArguments = externals .map( m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` ) .join(", "); if (this.requireAsWrapper) { return new ConcatSource( `require(${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});" ); } else if (this.name) { const name = mainTemplate.getAssetPath(this.name, { hash, chunk }); return new ConcatSource( `define(${JSON.stringify( name )}, ${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});" ); } else if (externalsArguments) { return new ConcatSource( `define(${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});" ); } else { return new ConcatSource("define(function() { return ", source, "});"); } }; for (const template of [mainTemplate, chunkTemplate]) { template.hooks.renderWithEntry.tap( "AmdMainTemplatePlugin", onRenderWithEntry ); } mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { if (this.name) { paths.push(this.name); } return paths; }); mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => { hash.update("exports amd"); if (this.name) { hash.update(this.name); } }); } } module.exports = AmdMainTemplatePlugin; webpack-4.30.0/lib/AsyncDependenciesBlock.js000066400000000000000000000046571345416772700207110ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependenciesBlock = require("./DependenciesBlock"); /** @typedef {import("./ChunkGroup")} ChunkGroup */ /** @typedef {import("./Module")} Module */ /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("./util/createHash").Hash} Hash */ /** @typedef {TODO} GroupOptions */ module.exports = class AsyncDependenciesBlock extends DependenciesBlock { /** * @param {GroupOptions} groupOptions options for the group * @param {Module} module the Module object * @param {DependencyLocation=} loc the line of code * @param {TODO=} request the request */ constructor(groupOptions, module, loc, request) { super(); if (typeof groupOptions === "string") { groupOptions = { name: groupOptions }; } else if (!groupOptions) { groupOptions = { name: undefined }; } this.groupOptions = groupOptions; /** @type {ChunkGroup=} */ this.chunkGroup = undefined; this.module = module; this.loc = loc; this.request = request; /** @type {DependenciesBlock} */ this.parent = undefined; } /** * @returns {string} The name of the chunk */ get chunkName() { return this.groupOptions.name; } /** * @param {string} value The new chunk name * @returns {void} */ set chunkName(value) { this.groupOptions.name = value; } /** * @returns {never} this throws and should never be called */ get chunks() { throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); } /** * @param {never} value setter value * @returns {never} this is going to throw therefore we should throw type * assertions by returning never */ set chunks(value) { throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); } /** * @param {Hash} hash the hash used to track block changes, from "crypto" module * @returns {void} */ updateHash(hash) { hash.update(JSON.stringify(this.groupOptions)); hash.update( (this.chunkGroup && this.chunkGroup.chunks .map(chunk => { return chunk.id !== null ? chunk.id : ""; }) .join(",")) || "" ); super.updateHash(hash); } /** * @returns {void} */ disconnect() { this.chunkGroup = undefined; super.disconnect(); } /** * @returns {void} */ unseal() { this.chunkGroup = undefined; super.unseal(); } /** * @returns {void} */ sortItems() { super.sortItems(); } }; webpack-4.30.0/lib/AsyncDependencyToInitialChunkError.js000066400000000000000000000015471345416772700232410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Sean Larkin @thelarkinn */ "use strict"; const WebpackError = require("./WebpackError"); /** @typedef {import("./Module")} Module */ class AsyncDependencyToInitialChunkError extends WebpackError { /** * Creates an instance of AsyncDependencyToInitialChunkError. * @param {string} chunkName Name of Chunk * @param {Module} module module tied to dependency * @param {TODO} loc location of dependency */ constructor(chunkName, module, loc) { super( `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` ); this.name = "AsyncDependencyToInitialChunkError"; this.module = module; this.loc = loc; Error.captureStackTrace(this, this.constructor); } } module.exports = AsyncDependencyToInitialChunkError; webpack-4.30.0/lib/AutomaticPrefetchPlugin.js000066400000000000000000000026001345416772700211220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("neo-async"); const PrefetchDependency = require("./dependencies/PrefetchDependency"); const NormalModule = require("./NormalModule"); /** @typedef {import("./Compiler")} Compiler */ class AutomaticPrefetchPlugin { /** * Apply the plugin * @param {Compiler} compiler Webpack Compiler * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap( "AutomaticPrefetchPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( PrefetchDependency, normalModuleFactory ); } ); let lastModules = null; compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => { lastModules = compilation.modules .filter(m => m instanceof NormalModule) .map((/** @type {NormalModule} */ m) => ({ context: m.context, request: m.request })); }); compiler.hooks.make.tapAsync( "AutomaticPrefetchPlugin", (compilation, callback) => { if (!lastModules) return callback(); asyncLib.forEach( lastModules, (m, callback) => { compilation.prefetch( m.context || compiler.context, new PrefetchDependency(m.request), callback ); }, callback ); } ); } } module.exports = AutomaticPrefetchPlugin; webpack-4.30.0/lib/BannerPlugin.js000066400000000000000000000056421345416772700167310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); const Template = require("./Template"); const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/BannerPlugin.json"); /** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ /** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ const wrapComment = str => { if (!str.includes("\n")) { return Template.toComment(str); } return `/*!\n * ${str .replace(/\*\//g, "* /") .split("\n") .join("\n * ")}\n */`; }; class BannerPlugin { /** * @param {BannerPluginArgument} options options object */ constructor(options) { if (arguments.length > 1) { throw new Error( "BannerPlugin only takes one argument (pass an options object)" ); } validateOptions(schema, options, "Banner Plugin"); if (typeof options === "string" || typeof options === "function") { options = { banner: options }; } /** @type {BannerPluginOptions} */ this.options = options; const bannerOption = options.banner; if (typeof bannerOption === "function") { const getBanner = bannerOption; this.banner = this.options.raw ? getBanner : data => wrapComment(getBanner(data)); } else { const banner = this.options.raw ? bannerOption : wrapComment(bannerOption); this.banner = () => banner; } } apply(compiler) { const options = this.options; const banner = this.banner; const matchObject = ModuleFilenameHelpers.matchObject.bind( undefined, options ); compiler.hooks.compilation.tap("BannerPlugin", compilation => { compilation.hooks.optimizeChunkAssets.tap("BannerPlugin", chunks => { for (const chunk of chunks) { if (options.entryOnly && !chunk.canBeInitial()) { continue; } for (const file of chunk.files) { if (!matchObject(file)) { continue; } let basename; let query = ""; let filename = file; const hash = compilation.hash; const querySplit = filename.indexOf("?"); if (querySplit >= 0) { query = filename.substr(querySplit); filename = filename.substr(0, querySplit); } const lastSlashIndex = filename.lastIndexOf("/"); if (lastSlashIndex === -1) { basename = filename; } else { basename = filename.substr(lastSlashIndex + 1); } const data = { hash, chunk, filename, basename, query }; const comment = compilation.getPath(banner(data), data); compilation.assets[file] = new ConcatSource( comment, "\n", compilation.assets[file] ); } } }); }); } } module.exports = BannerPlugin; webpack-4.30.0/lib/BasicEvaluatedExpression.js000066400000000000000000000110621345416772700212720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const TypeUnknown = 0; const TypeNull = 1; const TypeString = 2; const TypeNumber = 3; const TypeBoolean = 4; const TypeRegExp = 5; const TypeConditional = 6; const TypeArray = 7; const TypeConstArray = 8; const TypeIdentifier = 9; const TypeWrapped = 10; const TypeTemplateString = 11; class BasicEvaluatedExpression { constructor() { this.type = TypeUnknown; this.range = null; this.falsy = false; this.truthy = false; this.bool = null; this.number = null; this.regExp = null; this.string = null; this.quasis = null; this.parts = null; this.array = null; this.items = null; this.options = null; this.prefix = null; this.postfix = null; this.wrappedInnerExpressions = null; this.expression = null; } isNull() { return this.type === TypeNull; } isString() { return this.type === TypeString; } isNumber() { return this.type === TypeNumber; } isBoolean() { return this.type === TypeBoolean; } isRegExp() { return this.type === TypeRegExp; } isConditional() { return this.type === TypeConditional; } isArray() { return this.type === TypeArray; } isConstArray() { return this.type === TypeConstArray; } isIdentifier() { return this.type === TypeIdentifier; } isWrapped() { return this.type === TypeWrapped; } isTemplateString() { return this.type === TypeTemplateString; } isTruthy() { return this.truthy; } isFalsy() { return this.falsy; } asBool() { if (this.truthy) return true; if (this.falsy) return false; if (this.isBoolean()) return this.bool; if (this.isNull()) return false; if (this.isString()) return this.string !== ""; if (this.isNumber()) return this.number !== 0; if (this.isRegExp()) return true; if (this.isArray()) return true; if (this.isConstArray()) return true; if (this.isWrapped()) { return (this.prefix && this.prefix.asBool()) || (this.postfix && this.postfix.asBool()) ? true : undefined; } if (this.isTemplateString()) { const str = this.asString(); if (typeof str === "string") return str !== ""; } return undefined; } asString() { if (this.isBoolean()) return `${this.bool}`; if (this.isNull()) return "null"; if (this.isString()) return this.string; if (this.isNumber()) return `${this.number}`; if (this.isRegExp()) return `${this.regExp}`; if (this.isArray()) { let array = []; for (const item of this.items) { const itemStr = item.asString(); if (itemStr === undefined) return undefined; array.push(itemStr); } return `${array}`; } if (this.isConstArray()) return `${this.array}`; if (this.isTemplateString()) { let str = ""; for (const part of this.parts) { const partStr = part.asString(); if (partStr === undefined) return undefined; str += partStr; } return str; } return undefined; } setString(string) { this.type = TypeString; this.string = string; return this; } setNull() { this.type = TypeNull; return this; } setNumber(number) { this.type = TypeNumber; this.number = number; return this; } setBoolean(bool) { this.type = TypeBoolean; this.bool = bool; return this; } setRegExp(regExp) { this.type = TypeRegExp; this.regExp = regExp; return this; } setIdentifier(identifier) { this.type = TypeIdentifier; this.identifier = identifier; return this; } setWrapped(prefix, postfix, innerExpressions) { this.type = TypeWrapped; this.prefix = prefix; this.postfix = postfix; this.wrappedInnerExpressions = innerExpressions; return this; } setOptions(options) { this.type = TypeConditional; this.options = options; return this; } addOptions(options) { if (!this.options) { this.type = TypeConditional; this.options = []; } for (const item of options) { this.options.push(item); } return this; } setItems(items) { this.type = TypeArray; this.items = items; return this; } setArray(array) { this.type = TypeConstArray; this.array = array; return this; } setTemplateString(quasis, parts, kind) { this.type = TypeTemplateString; this.quasis = quasis; this.parts = parts; this.templateStringKind = kind; return this; } setTruthy() { this.falsy = false; this.truthy = true; return this; } setFalsy() { this.falsy = true; this.truthy = false; return this; } setRange(range) { this.range = range; return this; } setExpression(expression) { this.expression = expression; return this; } } module.exports = BasicEvaluatedExpression; webpack-4.30.0/lib/CachePlugin.js000066400000000000000000000055341345416772700165270ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("neo-async"); class CachePlugin { constructor(cache) { this.cache = cache || {}; this.FS_ACCURACY = 2000; } apply(compiler) { if (Array.isArray(compiler.compilers)) { compiler.compilers.forEach((c, idx) => { new CachePlugin((this.cache[idx] = this.cache[idx] || {})).apply(c); }); } else { const registerCacheToCompiler = (compiler, cache) => { compiler.hooks.thisCompilation.tap("CachePlugin", compilation => { compilation.cache = cache; compilation.hooks.childCompiler.tap( "CachePlugin", (childCompiler, compilerName, compilerIndex) => { if (cache) { let childCache; if (!cache.children) { cache.children = {}; } if (!cache.children[compilerName]) { cache.children[compilerName] = []; } if (cache.children[compilerName][compilerIndex]) { childCache = cache.children[compilerName][compilerIndex]; } else { cache.children[compilerName].push((childCache = {})); } registerCacheToCompiler(childCompiler, childCache); } } ); }); }; registerCacheToCompiler(compiler, this.cache); compiler.hooks.watchRun.tap("CachePlugin", () => { this.watching = true; }); compiler.hooks.run.tapAsync("CachePlugin", (compiler, callback) => { if (!compiler._lastCompilationFileDependencies) { return callback(); } const fs = compiler.inputFileSystem; const fileTs = (compiler.fileTimestamps = new Map()); asyncLib.forEach( compiler._lastCompilationFileDependencies, (file, callback) => { fs.stat(file, (err, stat) => { if (err) { if (err.code === "ENOENT") return callback(); return callback(err); } if (stat.mtime) this.applyMtime(+stat.mtime); fileTs.set(file, +stat.mtime || Infinity); callback(); }); }, err => { if (err) return callback(err); for (const [file, ts] of fileTs) { fileTs.set(file, ts + this.FS_ACCURACY); } callback(); } ); }); compiler.hooks.afterCompile.tap("CachePlugin", compilation => { compilation.compiler._lastCompilationFileDependencies = compilation.fileDependencies; compilation.compiler._lastCompilationContextDependencies = compilation.contextDependencies; }); } } /* istanbul ignore next */ applyMtime(mtime) { if (this.FS_ACCURACY > 1 && mtime % 2 !== 0) this.FS_ACCURACY = 1; else if (this.FS_ACCURACY > 10 && mtime % 20 !== 0) this.FS_ACCURACY = 10; else if (this.FS_ACCURACY > 100 && mtime % 200 !== 0) this.FS_ACCURACY = 100; else if (this.FS_ACCURACY > 1000 && mtime % 2000 !== 0) this.FS_ACCURACY = 1000; } } module.exports = CachePlugin; webpack-4.30.0/lib/CaseSensitiveModulesWarning.js000066400000000000000000000035671345416772700217750ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); /** @typedef {import("./Module")} Module */ /** * @param {Module[]} modules the modules to be sorted * @returns {Module[]} sorted version of original modules */ const sortModules = modules => { return modules.slice().sort((a, b) => { const aIdent = a.identifier(); const bIdent = b.identifier(); /* istanbul ignore next */ if (aIdent < bIdent) return -1; /* istanbul ignore next */ if (aIdent > bIdent) return 1; /* istanbul ignore next */ return 0; }); }; /** * @param {Module[]} modules each module from throw * @returns {string} each message from provided moduels */ const createModulesListMessage = modules => { return modules .map(m => { let message = `* ${m.identifier()}`; const validReasons = m.reasons.filter(reason => reason.module); if (validReasons.length > 0) { message += `\n Used by ${validReasons.length} module(s), i. e.`; message += `\n ${validReasons[0].module.identifier()}`; } return message; }) .join("\n"); }; class CaseSensitiveModulesWarning extends WebpackError { /** * Creates an instance of CaseSensitiveModulesWarning. * @param {Module[]} modules modules that were detected */ constructor(modules) { const sortedModules = sortModules(modules); const modulesList = createModulesListMessage(sortedModules); super(`There are multiple modules with names that only differ in casing. This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. Use equal casing. Compare these module identifiers: ${modulesList}`); this.name = "CaseSensitiveModulesWarning"; this.origin = this.module = sortedModules[0]; Error.captureStackTrace(this, this.constructor); } } module.exports = CaseSensitiveModulesWarning; webpack-4.30.0/lib/Chunk.js000066400000000000000000000542271345416772700154200ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const util = require("util"); const SortableSet = require("./util/SortableSet"); const intersect = require("./util/SetHelpers").intersect; const GraphHelpers = require("./GraphHelpers"); const Entrypoint = require("./Entrypoint"); let debugId = 1000; const ERR_CHUNK_ENTRY = "Chunk.entry was removed. Use hasRuntime()"; const ERR_CHUNK_INITIAL = "Chunk.initial was removed. Use canBeInitial/isOnlyInitial()"; /** @typedef {import("./Module")} Module */ /** @typedef {import("./ChunkGroup")} ChunkGroup */ /** @typedef {import("./ModuleReason")} ModuleReason */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("./util/createHash").Hash} Hash */ /** * @typedef {Object} WithId an object who has an id property * * @property {string | number} id the id of the object */ /** * Compare two Modules based on their ids for sorting * @param {Module} a module * @param {Module} b module * @returns {-1|0|1} sort value */ // TODO use @callback /** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */ /** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ /** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */ const sortModuleById = (a, b) => { if (a.id < b.id) return -1; if (b.id < a.id) return 1; return 0; }; /** * Compare two ChunkGroups based on their ids for sorting * @param {ChunkGroup} a chunk group * @param {ChunkGroup} b chunk group * @returns {-1|0|1} sort value */ const sortChunkGroupById = (a, b) => { if (a.id < b.id) return -1; if (b.id < a.id) return 1; return 0; }; /** * Compare two Identifiables , based on their ids for sorting * @param {Module} a first object with ident fn * @param {Module} b second object with ident fn * @returns {-1|0|1} The order number of the sort */ const sortByIdentifier = (a, b) => { if (a.identifier() > b.identifier()) return 1; if (a.identifier() < b.identifier()) return -1; return 0; }; /** * @returns {string} a concatenation of module identifiers sorted * @param {SortableSet} set to pull module identifiers from */ const getModulesIdent = set => { set.sort(); let str = ""; for (const m of set) { str += m.identifier() + "#"; } return str; }; /** * @template T * @param {SortableSet} set the sortable set to convert to array * @returns {Array} the array returned from Array.from(set) */ const getArray = set => Array.from(set); /** * @param {SortableSet} set the sortable Set to get the count/size of * @returns {number} the size of the modules */ const getModulesSize = set => { let size = 0; for (const module of set) { size += module.size(); } return size; }; /** * A Chunk is a unit of encapsulation for Modules. * Chunks are "rendered" into bundles that get emitted when the build completes. */ class Chunk { /** * @param {string=} name of chunk being created, is optional (for subclasses) */ constructor(name) { /** @type {number | null} */ this.id = null; /** @type {number[] | null} */ this.ids = null; /** @type {number} */ this.debugId = debugId++; /** @type {string} */ this.name = name; /** @type {boolean} */ this.preventIntegration = false; /** @type {Module=} */ this.entryModule = undefined; /** @private @type {SortableSet} */ this._modules = new SortableSet(undefined, sortByIdentifier); /** @type {string?} */ this.filenameTemplate = undefined; /** @private @type {SortableSet} */ this._groups = new SortableSet(undefined, sortChunkGroupById); /** @type {string[]} */ this.files = []; /** @type {boolean} */ this.rendered = false; /** @type {string=} */ this.hash = undefined; /** @type {Object} */ this.contentHash = Object.create(null); /** @type {string=} */ this.renderedHash = undefined; /** @type {string=} */ this.chunkReason = undefined; /** @type {boolean} */ this.extraAsync = false; this.removedModules = undefined; } /** * @deprecated Chunk.entry has been deprecated. Please use .hasRuntime() instead * @returns {never} Throws an error trying to access this property */ get entry() { throw new Error(ERR_CHUNK_ENTRY); } /** * @deprecated .entry has been deprecated. Please use .hasRuntime() instead * @param {never} data The data that was attempting to be set * @returns {never} Throws an error trying to access this property */ set entry(data) { throw new Error(ERR_CHUNK_ENTRY); } /** * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() * @returns {never} Throws an error trying to access this property */ get initial() { throw new Error(ERR_CHUNK_INITIAL); } /** * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() * @param {never} data The data attempting to be set * @returns {never} Throws an error trying to access this property */ set initial(data) { throw new Error(ERR_CHUNK_INITIAL); } /** * @returns {boolean} whether or not the Chunk will have a runtime */ hasRuntime() { for (const chunkGroup of this._groups) { if ( chunkGroup.isInitial() && chunkGroup instanceof Entrypoint && chunkGroup.getRuntimeChunk() === this ) { return true; } } return false; } /** * @returns {boolean} whether or not this chunk can be an initial chunk */ canBeInitial() { for (const chunkGroup of this._groups) { if (chunkGroup.isInitial()) return true; } return false; } /** * @returns {boolean} whether this chunk can only be an initial chunk */ isOnlyInitial() { if (this._groups.size <= 0) return false; for (const chunkGroup of this._groups) { if (!chunkGroup.isInitial()) return false; } return true; } /** * @returns {boolean} if this chunk contains the entry module */ hasEntryModule() { return !!this.entryModule; } /** * @param {Module} module the module that will be added to this chunk. * @returns {boolean} returns true if the chunk doesn't have the module and it was added */ addModule(module) { if (!this._modules.has(module)) { this._modules.add(module); return true; } return false; } /** * @param {Module} module the module that will be removed from this chunk * @returns {boolean} returns true if chunk exists and is successfully deleted */ removeModule(module) { if (this._modules.delete(module)) { module.removeChunk(this); return true; } return false; } /** * @param {Module[]} modules the new modules to be set * @returns {void} set new modules to this chunk and return nothing */ setModules(modules) { this._modules = new SortableSet(modules, sortByIdentifier); } /** * @returns {number} the amount of modules in chunk */ getNumberOfModules() { return this._modules.size; } /** * @returns {SortableSet} return the modules SortableSet for this chunk */ get modulesIterable() { return this._modules; } /** * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added * @returns {boolean} returns true if chunk is not apart of chunkGroup and is added successfully */ addGroup(chunkGroup) { if (this._groups.has(chunkGroup)) return false; this._groups.add(chunkGroup); return true; } /** * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from * @returns {boolean} returns true if chunk does exist in chunkGroup and is removed */ removeGroup(chunkGroup) { if (!this._groups.has(chunkGroup)) return false; this._groups.delete(chunkGroup); return true; } /** * @param {ChunkGroup} chunkGroup the chunkGroup to check * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup */ isInGroup(chunkGroup) { return this._groups.has(chunkGroup); } /** * @returns {number} the amount of groups said chunk is in */ getNumberOfGroups() { return this._groups.size; } /** * @returns {SortableSet} the chunkGroups that said chunk is referenced in */ get groupsIterable() { return this._groups; } /** * @param {Chunk} otherChunk the chunk to compare itself with * @returns {-1|0|1} this is a comparitor function like sort and returns -1, 0, or 1 based on sort order */ compareTo(otherChunk) { if (this.name && !otherChunk.name) return -1; if (!this.name && otherChunk.name) return 1; if (this.name < otherChunk.name) return -1; if (this.name > otherChunk.name) return 1; if (this._modules.size > otherChunk._modules.size) return -1; if (this._modules.size < otherChunk._modules.size) return 1; this._modules.sort(); otherChunk._modules.sort(); const a = this._modules[Symbol.iterator](); const b = otherChunk._modules[Symbol.iterator](); // eslint-disable-next-line no-constant-condition while (true) { const aItem = a.next(); if (aItem.done) return 0; const bItem = b.next(); const aModuleIdentifier = aItem.value.identifier(); const bModuleIdentifier = bItem.value.identifier(); if (aModuleIdentifier < bModuleIdentifier) return -1; if (aModuleIdentifier > bModuleIdentifier) return 1; } } /** * @param {Module} module Module to check * @returns {boolean} returns true if module does exist in this chunk */ containsModule(module) { return this._modules.has(module); } /** * @returns {Module[]} an array of modules (do not modify) */ getModules() { return this._modules.getFromCache(getArray); } getModulesIdent() { return this._modules.getFromUnorderedCache(getModulesIdent); } remove() { // cleanup modules // Array.from is used here to create a clone, because removeChunk modifies this._modules for (const module of Array.from(this._modules)) { module.removeChunk(this); } for (const chunkGroup of this._groups) { chunkGroup.removeChunk(this); } } /** * * @param {Module} module module to move * @param {Chunk} otherChunk other chunk to move it to * @returns {void} */ moveModule(module, otherChunk) { GraphHelpers.disconnectChunkAndModule(this, module); GraphHelpers.connectChunkAndModule(otherChunk, module); module.rewriteChunkInReasons(this, [otherChunk]); } /** * * @param {Chunk} otherChunk the chunk to integrate with * @param {ModuleReason} reason reason why the module is being integrated * @returns {boolean} returns true or false if integration succeeds or fails */ integrate(otherChunk, reason) { if (!this.canBeIntegrated(otherChunk)) { return false; } // Pick a new name for the integrated chunk if (this.name && otherChunk.name) { if (this.hasEntryModule() === otherChunk.hasEntryModule()) { // When both chunks have entry modules or none have one, use // shortest name if (this.name.length !== otherChunk.name.length) { this.name = this.name.length < otherChunk.name.length ? this.name : otherChunk.name; } else { this.name = this.name < otherChunk.name ? this.name : otherChunk.name; } } else if (otherChunk.hasEntryModule()) { // Pick the name of the chunk with the entry module this.name = otherChunk.name; } } else if (otherChunk.name) { this.name = otherChunk.name; } // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules for (const module of Array.from(otherChunk._modules)) { otherChunk.moveModule(module, this); } otherChunk._modules.clear(); if (otherChunk.entryModule) { this.entryModule = otherChunk.entryModule; } for (const chunkGroup of otherChunk._groups) { chunkGroup.replaceChunk(otherChunk, this); this.addGroup(chunkGroup); } otherChunk._groups.clear(); return true; } /** * @param {Chunk} newChunk the new chunk that will be split out of the current chunk * @returns {void} */ split(newChunk) { for (const chunkGroup of this._groups) { chunkGroup.insertChunk(newChunk, this); newChunk.addGroup(chunkGroup); } } isEmpty() { return this._modules.size === 0; } updateHash(hash) { hash.update(`${this.id} `); hash.update(this.ids ? this.ids.join(",") : ""); hash.update(`${this.name || ""} `); for (const m of this._modules) { hash.update(m.hash); } } canBeIntegrated(otherChunk) { if (this.preventIntegration || otherChunk.preventIntegration) { return false; } const isAvailable = (a, b) => { const queue = new Set(b.groupsIterable); for (const chunkGroup of queue) { if (a.isInGroup(chunkGroup)) continue; if (chunkGroup.isInitial()) return false; for (const parent of chunkGroup.parentsIterable) { queue.add(parent); } } return true; }; const selfHasRuntime = this.hasRuntime(); const otherChunkHasRuntime = otherChunk.hasRuntime(); if (selfHasRuntime !== otherChunkHasRuntime) { if (selfHasRuntime) { return isAvailable(this, otherChunk); } else if (otherChunkHasRuntime) { return isAvailable(otherChunk, this); } else { return false; } } if (this.hasEntryModule() || otherChunk.hasEntryModule()) { return false; } return true; } /** * * @param {number} size the size * @param {Object} options the options passed in * @returns {number} the multiplier returned */ addMultiplierAndOverhead(size, options) { const overhead = typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; const multiplicator = this.canBeInitial() ? options.entryChunkMultiplicator || 10 : 1; return size * multiplicator + overhead; } /** * @returns {number} the size of all modules */ modulesSize() { return this._modules.getFromUnorderedCache(getModulesSize); } /** * @param {Object} options the size display options * @returns {number} the chunk size */ size(options = {}) { return this.addMultiplierAndOverhead(this.modulesSize(), options); } /** * @param {Chunk} otherChunk the other chunk * @param {TODO} options the options for this function * @returns {number | false} the size, or false if it can't be integrated */ integratedSize(otherChunk, options) { // Chunk if it's possible to integrate this chunk if (!this.canBeIntegrated(otherChunk)) { return false; } let integratedModulesSize = this.modulesSize(); // only count modules that do not exist in this chunk! for (const otherModule of otherChunk._modules) { if (!this._modules.has(otherModule)) { integratedModulesSize += otherModule.size(); } } return this.addMultiplierAndOverhead(integratedModulesSize, options); } /** * @param {function(Module, Module): -1|0|1=} sortByFn a predicate function used to sort modules * @returns {void} */ sortModules(sortByFn) { this._modules.sortWith(sortByFn || sortModuleById); } sortItems() { this.sortModules(); } /** * @returns {Set} a set of all the async chunks */ getAllAsyncChunks() { const queue = new Set(); const chunks = new Set(); const initialChunks = intersect( Array.from(this.groupsIterable, g => new Set(g.chunks)) ); for (const chunkGroup of this.groupsIterable) { for (const child of chunkGroup.childrenIterable) { queue.add(child); } } for (const chunkGroup of queue) { for (const chunk of chunkGroup.chunks) { if (!initialChunks.has(chunk)) { chunks.add(chunk); } } for (const child of chunkGroup.childrenIterable) { queue.add(child); } } return chunks; } /** * @typedef {Object} ChunkMaps * @property {Record} hash * @property {Record>} contentHash * @property {Record} name */ /** * @param {boolean} realHash should the full hash or the rendered hash be used * @returns {ChunkMaps} the chunk map information */ getChunkMaps(realHash) { /** @type {Record} */ const chunkHashMap = Object.create(null); /** @type {Record>} */ const chunkContentHashMap = Object.create(null); /** @type {Record} */ const chunkNameMap = Object.create(null); for (const chunk of this.getAllAsyncChunks()) { chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash; for (const key of Object.keys(chunk.contentHash)) { if (!chunkContentHashMap[key]) { chunkContentHashMap[key] = Object.create(null); } chunkContentHashMap[key][chunk.id] = chunk.contentHash[key]; } if (chunk.name) { chunkNameMap[chunk.id] = chunk.name; } } return { hash: chunkHashMap, contentHash: chunkContentHashMap, name: chunkNameMap }; } /** * @returns {Record[]>} a record object of names to lists of child ids(?) */ getChildIdsByOrders() { const lists = new Map(); for (const group of this.groupsIterable) { if (group.chunks[group.chunks.length - 1] === this) { for (const childGroup of group.childrenIterable) { // TODO webpack 5 remove this check for options if (typeof childGroup.options === "object") { for (const key of Object.keys(childGroup.options)) { if (key.endsWith("Order")) { const name = key.substr(0, key.length - "Order".length); let list = lists.get(name); if (list === undefined) lists.set(name, (list = [])); list.push({ order: childGroup.options[key], group: childGroup }); } } } } } } const result = Object.create(null); for (const [name, list] of lists) { list.sort((a, b) => { const cmp = b.order - a.order; if (cmp !== 0) return cmp; // TODO webpack 5 remove this check of compareTo if (a.group.compareTo) { return a.group.compareTo(b.group); } return 0; }); result[name] = Array.from( list.reduce((set, item) => { for (const chunk of item.group.chunks) { set.add(chunk.id); } return set; }, new Set()) ); } return result; } getChildIdsByOrdersMap(includeDirectChildren) { const chunkMaps = Object.create(null); const addChildIdsByOrdersToMap = chunk => { const data = chunk.getChildIdsByOrders(); for (const key of Object.keys(data)) { let chunkMap = chunkMaps[key]; if (chunkMap === undefined) { chunkMaps[key] = chunkMap = Object.create(null); } chunkMap[chunk.id] = data[key]; } }; if (includeDirectChildren) { addChildIdsByOrdersToMap(this); } for (const chunk of this.getAllAsyncChunks()) { addChildIdsByOrdersToMap(chunk); } return chunkMaps; } /** * @typedef {Object} ChunkModuleMaps * @property {Record} id * @property {Record} hash */ /** * @param {ModuleFilterPredicate} filterFn function used to filter modules * @returns {ChunkModuleMaps} module map information */ getChunkModuleMaps(filterFn) { /** @type {Record} */ const chunkModuleIdMap = Object.create(null); /** @type {Record} */ const chunkModuleHashMap = Object.create(null); for (const chunk of this.getAllAsyncChunks()) { /** @type {(string|number)[]} */ let array; for (const module of chunk.modulesIterable) { if (filterFn(module)) { if (array === undefined) { array = []; chunkModuleIdMap[chunk.id] = array; } array.push(module.id); chunkModuleHashMap[module.id] = module.renderedHash; } } if (array !== undefined) { array.sort(); } } return { id: chunkModuleIdMap, hash: chunkModuleHashMap }; } /** * * @param {function(Module): boolean} filterFn predicate function used to filter modules * @param {function(Chunk): boolean} filterChunkFn predicate function used to filter chunks * @returns {boolean} return true if module exists in graph */ hasModuleInGraph(filterFn, filterChunkFn) { const queue = new Set(this.groupsIterable); const chunksProcessed = new Set(); for (const chunkGroup of queue) { for (const chunk of chunkGroup.chunks) { if (!chunksProcessed.has(chunk)) { chunksProcessed.add(chunk); if (!filterChunkFn || filterChunkFn(chunk)) { for (const module of chunk.modulesIterable) { if (filterFn(module)) { return true; } } } } } for (const child of chunkGroup.childrenIterable) { queue.add(child); } } return false; } toString() { return `Chunk[${Array.from(this._modules).join()}]`; } } // TODO remove in webpack 5 Object.defineProperty(Chunk.prototype, "forEachModule", { configurable: false, value: util.deprecate( /** * @deprecated * @this {Chunk} * @typedef {function(any, any, Set): void} ForEachModuleCallback * @param {ForEachModuleCallback} fn Callback function * @returns {void} */ function(fn) { this._modules.forEach(fn); }, "Chunk.forEachModule: Use for(const module of chunk.modulesIterable) instead" ) }); // TODO remove in webpack 5 Object.defineProperty(Chunk.prototype, "mapModules", { configurable: false, value: util.deprecate( /** * @deprecated * @this {Chunk} * @typedef {function(any, number): any} MapModulesCallback * @param {MapModulesCallback} fn Callback function * @returns {TODO[]} result of mapped modules */ function(fn) { return Array.from(this._modules, fn); }, "Chunk.mapModules: Use Array.from(chunk.modulesIterable, fn) instead" ) }); // TODO remove in webpack 5 Object.defineProperty(Chunk.prototype, "chunks", { configurable: false, get() { throw new Error("Chunk.chunks: Use ChunkGroup.getChildren() instead"); }, set() { throw new Error("Chunk.chunks: Use ChunkGroup.add/removeChild() instead"); } }); // TODO remove in webpack 5 Object.defineProperty(Chunk.prototype, "parents", { configurable: false, get() { throw new Error("Chunk.parents: Use ChunkGroup.getParents() instead"); }, set() { throw new Error("Chunk.parents: Use ChunkGroup.add/removeParent() instead"); } }); // TODO remove in webpack 5 Object.defineProperty(Chunk.prototype, "blocks", { configurable: false, get() { throw new Error("Chunk.blocks: Use ChunkGroup.getBlocks() instead"); }, set() { throw new Error("Chunk.blocks: Use ChunkGroup.add/removeBlock() instead"); } }); // TODO remove in webpack 5 Object.defineProperty(Chunk.prototype, "entrypoints", { configurable: false, get() { throw new Error( "Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead" ); }, set() { throw new Error("Chunk.entrypoints: Use Chunks.addGroup instead"); } }); module.exports = Chunk; webpack-4.30.0/lib/ChunkGroup.js000066400000000000000000000302001345416772700164160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const SortableSet = require("./util/SortableSet"); const compareLocations = require("./compareLocations"); /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Module")} Module */ /** @typedef {import("./ModuleReason")} ModuleReason */ /** @typedef {{module: Module, loc: TODO, request: string}} OriginRecord */ /** @typedef {string|{name: string}} ChunkGroupOptions */ let debugId = 5000; /** * @template T * @param {SortableSet} set set to convert to array. * @returns {T[]} the array format of existing set */ const getArray = set => Array.from(set); /** * A convenience method used to sort chunks based on their id's * @param {ChunkGroup} a first sorting comparator * @param {ChunkGroup} b second sorting comparator * @returns {1|0|-1} a sorting index to determine order */ const sortById = (a, b) => { if (a.id < b.id) return -1; if (b.id < a.id) return 1; return 0; }; /** * @param {OriginRecord} a the first comparator in sort * @param {OriginRecord} b the second comparator in sort * @returns {1|-1|0} returns sorting order as index */ const sortOrigin = (a, b) => { const aIdent = a.module ? a.module.identifier() : ""; const bIdent = b.module ? b.module.identifier() : ""; if (aIdent < bIdent) return -1; if (aIdent > bIdent) return 1; return compareLocations(a.loc, b.loc); }; class ChunkGroup { /** * Creates an instance of ChunkGroup. * @param {ChunkGroupOptions=} options chunk group options passed to chunkGroup */ constructor(options) { if (typeof options === "string") { options = { name: options }; } else if (!options) { options = { name: undefined }; } /** @type {number} */ this.groupDebugId = debugId++; this.options = options; /** @type {SortableSet} */ this._children = new SortableSet(undefined, sortById); this._parents = new SortableSet(undefined, sortById); this._blocks = new SortableSet(); /** @type {Chunk[]} */ this.chunks = []; /** @type {OriginRecord[]} */ this.origins = []; /** Indicies in top-down order */ /** @private @type {Map} */ this._moduleIndicies = new Map(); /** Indicies in bottom-up order */ /** @private @type {Map} */ this._moduleIndicies2 = new Map(); } /** * when a new chunk is added to a chunkGroup, addingOptions will occur. * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions * @returns {void} */ addOptions(options) { for (const key of Object.keys(options)) { if (this.options[key] === undefined) { this.options[key] = options[key]; } else if (this.options[key] !== options[key]) { if (key.endsWith("Order")) { this.options[key] = Math.max(this.options[key], options[key]); } else { throw new Error( `ChunkGroup.addOptions: No option merge strategy for ${key}` ); } } } } /** * returns the name of current ChunkGroup * @returns {string|undefined} returns the ChunkGroup name */ get name() { return this.options.name; } /** * sets a new name for current ChunkGroup * @param {string} value the new name for ChunkGroup * @returns {void} */ set name(value) { this.options.name = value; } /** * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's * @returns {string} a unique concatenation of chunk debugId's */ get debugId() { return Array.from(this.chunks, x => x.debugId).join("+"); } /** * get a unique id for ChunkGroup, made up of its member Chunk id's * @returns {string} a unique concatenation of chunk ids */ get id() { return Array.from(this.chunks, x => x.id).join("+"); } /** * Performs an unshift of a specific chunk * @param {Chunk} chunk chunk being unshifted * @returns {boolean} returns true if attempted chunk shift is accepted */ unshiftChunk(chunk) { const oldIdx = this.chunks.indexOf(chunk); if (oldIdx > 0) { this.chunks.splice(oldIdx, 1); this.chunks.unshift(chunk); } else if (oldIdx < 0) { this.chunks.unshift(chunk); return true; } return false; } /** * inserts a chunk before another existing chunk in group * @param {Chunk} chunk Chunk being inserted * @param {Chunk} before Placeholder/target chunk marking new chunk insertion point * @returns {boolean} return true if insertion was successful */ insertChunk(chunk, before) { const oldIdx = this.chunks.indexOf(chunk); const idx = this.chunks.indexOf(before); if (idx < 0) { throw new Error("before chunk not found"); } if (oldIdx >= 0 && oldIdx > idx) { this.chunks.splice(oldIdx, 1); this.chunks.splice(idx, 0, chunk); } else if (oldIdx < 0) { this.chunks.splice(idx, 0, chunk); return true; } return false; } /** * add a chunk into ChunkGroup. Is pushed on or prepended * @param {Chunk} chunk chunk being pushed into ChunkGroupS * @returns {boolean} returns true if chunk addition was ssuccesful. */ pushChunk(chunk) { const oldIdx = this.chunks.indexOf(chunk); if (oldIdx >= 0) { return false; } this.chunks.push(chunk); return true; } /** * @param {Chunk} oldChunk chunk to be replaced * @param {Chunk} newChunk New chunkt that will be replaced * @returns {boolean} rerturns true for */ replaceChunk(oldChunk, newChunk) { const oldIdx = this.chunks.indexOf(oldChunk); if (oldIdx < 0) return false; const newIdx = this.chunks.indexOf(newChunk); if (newIdx < 0) { this.chunks[oldIdx] = newChunk; return true; } if (newIdx < oldIdx) { this.chunks.splice(oldIdx, 1); return true; } else if (newIdx !== oldIdx) { this.chunks[oldIdx] = newChunk; this.chunks.splice(newIdx, 1); return true; } } removeChunk(chunk) { const idx = this.chunks.indexOf(chunk); if (idx >= 0) { this.chunks.splice(idx, 1); return true; } return false; } isInitial() { return false; } addChild(chunk) { if (this._children.has(chunk)) { return false; } this._children.add(chunk); return true; } getChildren() { return this._children.getFromCache(getArray); } getNumberOfChildren() { return this._children.size; } get childrenIterable() { return this._children; } removeChild(chunk) { if (!this._children.has(chunk)) { return false; } this._children.delete(chunk); chunk.removeParent(this); return true; } addParent(parentChunk) { if (!this._parents.has(parentChunk)) { this._parents.add(parentChunk); return true; } return false; } getParents() { return this._parents.getFromCache(getArray); } setParents(newParents) { this._parents.clear(); for (const p of newParents) { this._parents.add(p); } } getNumberOfParents() { return this._parents.size; } hasParent(parent) { return this._parents.has(parent); } get parentsIterable() { return this._parents; } removeParent(chunk) { if (this._parents.delete(chunk)) { chunk.removeChunk(this); return true; } return false; } /** * @returns {Array} - an array containing the blocks */ getBlocks() { return this._blocks.getFromCache(getArray); } getNumberOfBlocks() { return this._blocks.size; } hasBlock(block) { return this._blocks.has(block); } get blocksIterable() { return this._blocks; } addBlock(block) { if (!this._blocks.has(block)) { this._blocks.add(block); return true; } return false; } addOrigin(module, loc, request) { this.origins.push({ module, loc, request }); } containsModule(module) { for (const chunk of this.chunks) { if (chunk.containsModule(module)) return true; } return false; } getFiles() { const files = new Set(); for (const chunk of this.chunks) { for (const file of chunk.files) { files.add(file); } } return Array.from(files); } /** * @param {ModuleReason} reason reason for removing ChunkGroup * @returns {void} */ remove(reason) { // cleanup parents for (const parentChunkGroup of this._parents) { // remove this chunk from its parents parentChunkGroup._children.delete(this); // cleanup "sub chunks" for (const chunkGroup of this._children) { /** * remove this chunk as "intermediary" and connect * it "sub chunks" and parents directly */ // add parent to each "sub chunk" chunkGroup.addParent(parentChunkGroup); // add "sub chunk" to parent parentChunkGroup.addChild(chunkGroup); } } /** * we need to iterate again over the children * to remove this from the childs parents. * This can not be done in the above loop * as it is not guaranteed that `this._parents` contains anything. */ for (const chunkGroup of this._children) { // remove this as parent of every "sub chunk" chunkGroup._parents.delete(this); } // cleanup blocks for (const block of this._blocks) { block.chunkGroup = null; } // remove chunks for (const chunk of this.chunks) { chunk.removeGroup(this); } } sortItems() { this.origins.sort(sortOrigin); this._parents.sort(); this._children.sort(); } /** * Sorting predicate which allows current ChunkGroup to be compared against another. * Sorting values are based off of number of chunks in ChunkGroup. * * @param {ChunkGroup} otherGroup the chunkGroup to compare this against * @returns {-1|0|1} sort position for comparison */ compareTo(otherGroup) { if (this.chunks.length > otherGroup.chunks.length) return -1; if (this.chunks.length < otherGroup.chunks.length) return 1; const a = this.chunks[Symbol.iterator](); const b = otherGroup.chunks[Symbol.iterator](); // eslint-disable-next-line no-constant-condition while (true) { const aItem = a.next(); const bItem = b.next(); if (aItem.done) return 0; const cmp = aItem.value.compareTo(bItem.value); if (cmp !== 0) return cmp; } } getChildrenByOrders() { const lists = new Map(); for (const childGroup of this._children) { // TODO webpack 5 remove this check for options if (typeof childGroup.options === "object") { for (const key of Object.keys(childGroup.options)) { if (key.endsWith("Order")) { const name = key.substr(0, key.length - "Order".length); let list = lists.get(name); if (list === undefined) { lists.set(name, (list = [])); } list.push({ order: childGroup.options[key], group: childGroup }); } } } } const result = Object.create(null); for (const [name, list] of lists) { list.sort((a, b) => { const cmp = b.order - a.order; if (cmp !== 0) return cmp; // TODO webpack 5 remove this check of compareTo if (a.group.compareTo) { return a.group.compareTo(b.group); } return 0; }); result[name] = list.map(i => i.group); } return result; } /** * Sets the top-down index of a module in this ChunkGroup * @param {Module} module module for which the index should be set * @param {number} index the index of the module * @returns {void} */ setModuleIndex(module, index) { this._moduleIndicies.set(module, index); } /** * Gets the top-down index of a module in this ChunkGroup * @param {Module} module the module * @returns {number} index */ getModuleIndex(module) { return this._moduleIndicies.get(module); } /** * Sets the bottom-up index of a module in this ChunkGroup * @param {Module} module module for which the index should be set * @param {number} index the index of the module * @returns {void} */ setModuleIndex2(module, index) { this._moduleIndicies2.set(module, index); } /** * Gets the bottom-up index of a module in this ChunkGroup * @param {Module} module the module * @returns {number} index */ getModuleIndex2(module) { return this._moduleIndicies2.get(module); } checkConstraints() { const chunk = this; for (const child of chunk._children) { if (!child._parents.has(chunk)) { throw new Error( `checkConstraints: child missing parent ${chunk.debugId} -> ${ child.debugId }` ); } } for (const parentChunk of chunk._parents) { if (!parentChunk._children.has(chunk)) { throw new Error( `checkConstraints: parent missing child ${parentChunk.debugId} <- ${ chunk.debugId }` ); } } } } module.exports = ChunkGroup; webpack-4.30.0/lib/ChunkRenderError.js000066400000000000000000000013041345416772700175560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); /** @typedef {import("./Chunk")} Chunk */ class ChunkRenderError extends WebpackError { /** * Create a new ChunkRenderError * @param {Chunk} chunk A chunk * @param {string} file Related file * @param {Error} error Original error */ constructor(chunk, file, error) { super(); this.name = "ChunkRenderError"; this.error = error; this.message = error.message; this.details = error.stack; this.file = file; this.chunk = chunk; Error.captureStackTrace(this, this.constructor); } } module.exports = ChunkRenderError; webpack-4.30.0/lib/ChunkTemplate.js000066400000000000000000000047331345416772700171110ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { Tapable, SyncWaterfallHook, SyncHook } = require("tapable"); /** @typedef {import("./ModuleTemplate")} ModuleTemplate */ /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Module")} Module} */ /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ /** @typedef {import("./util/createHash").Hash} Hash} */ /** * @typedef {Object} RenderManifestOptions * @property {Chunk} chunk the chunk used to render * @property {string} hash * @property {string} fullHash * @property {TODO} outputOptions * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates * @property {Map} dependencyTemplates */ module.exports = class ChunkTemplate extends Tapable { constructor(outputOptions) { super(); this.outputOptions = outputOptions || {}; this.hooks = { /** @type {SyncWaterfallHook} */ renderManifest: new SyncWaterfallHook(["result", "options"]), modules: new SyncWaterfallHook([ "source", "chunk", "moduleTemplate", "dependencyTemplates" ]), render: new SyncWaterfallHook([ "source", "chunk", "moduleTemplate", "dependencyTemplates" ]), renderWithEntry: new SyncWaterfallHook(["source", "chunk"]), hash: new SyncHook(["hash"]), hashForChunk: new SyncHook(["hash", "chunk"]) }; } /** * * @param {RenderManifestOptions} options render manifest options * @returns {TODO[]} returns render manifest */ getRenderManifest(options) { const result = []; this.hooks.renderManifest.call(result, options); return result; } /** * Updates hash with information from this template * @param {Hash} hash the hash to update * @returns {void} */ updateHash(hash) { hash.update("ChunkTemplate"); hash.update("2"); this.hooks.hash.call(hash); } /** * TODO webpack 5: remove moduleTemplate and dependencyTemplates * Updates hash with chunk-specific information from this template * @param {Hash} hash the hash to update * @param {Chunk} chunk the chunk * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render * @param {Map} dependencyTemplates dependency templates * @returns {void} */ updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { this.updateHash(hash); this.hooks.hashForChunk.call(hash, chunk); } }; webpack-4.30.0/lib/CommentCompilationWarning.js000066400000000000000000000013541345416772700214700ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); /** @typedef {import("./Module")} Module */ /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ class CommentCompilationWarning extends WebpackError { /** * * @param {string} message warning message * @param {Module} module affected module * @param {DependencyLocation} loc affected lines of code */ constructor(message, module, loc) { super(message); this.name = "CommentCompilationWarning"; this.module = module; this.loc = loc; Error.captureStackTrace(this, this.constructor); } } module.exports = CommentCompilationWarning; webpack-4.30.0/lib/CompatibilityPlugin.js000066400000000000000000000037501345416772700203330ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./dependencies/ConstDependency"); const NullFactory = require("./NullFactory"); /** @typedef {import("./Compiler")} Compiler */ class CompatibilityPlugin { /** * Apply the plugin * @param {Compiler} compiler Webpack Compiler * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap( "CompatibilityPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); normalModuleFactory.hooks.parser .for("javascript/auto") .tap("CompatibilityPlugin", (parser, parserOptions) => { if ( parserOptions.browserify !== undefined && !parserOptions.browserify ) return; parser.hooks.call .for("require") .tap("CompatibilityPlugin", expr => { // support for browserify style require delegator: "require(o, !0)" if (expr.arguments.length !== 2) return; const second = parser.evaluateExpression(expr.arguments[1]); if (!second.isBoolean()) return; if (second.asBool() !== true) return; const dep = new ConstDependency("require", expr.callee.range); dep.loc = expr.loc; if (parser.state.current.dependencies.length > 1) { const last = parser.state.current.dependencies[ parser.state.current.dependencies.length - 1 ]; if ( last.critical && last.options && last.options.request === "." && last.userRequest === "." && last.options.recursive ) parser.state.current.dependencies.pop(); } parser.state.current.addDependency(dep); return true; }); }); } ); } } module.exports = CompatibilityPlugin; webpack-4.30.0/lib/Compilation.js000066400000000000000000002213221345416772700166160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("neo-async"); const util = require("util"); const { CachedSource } = require("webpack-sources"); const { Tapable, SyncHook, SyncBailHook, SyncWaterfallHook, AsyncSeriesHook } = require("tapable"); const EntryModuleNotFoundError = require("./EntryModuleNotFoundError"); const ModuleNotFoundError = require("./ModuleNotFoundError"); const ModuleDependencyWarning = require("./ModuleDependencyWarning"); const ModuleDependencyError = require("./ModuleDependencyError"); const ChunkGroup = require("./ChunkGroup"); const Chunk = require("./Chunk"); const Entrypoint = require("./Entrypoint"); const MainTemplate = require("./MainTemplate"); const ChunkTemplate = require("./ChunkTemplate"); const HotUpdateChunkTemplate = require("./HotUpdateChunkTemplate"); const ModuleTemplate = require("./ModuleTemplate"); const RuntimeTemplate = require("./RuntimeTemplate"); const ChunkRenderError = require("./ChunkRenderError"); const AsyncDependencyToInitialChunkError = require("./AsyncDependencyToInitialChunkError"); const Stats = require("./Stats"); const Semaphore = require("./util/Semaphore"); const createHash = require("./util/createHash"); const Queue = require("./util/Queue"); const SortableSet = require("./util/SortableSet"); const GraphHelpers = require("./GraphHelpers"); const ModuleDependency = require("./dependencies/ModuleDependency"); const compareLocations = require("./compareLocations"); /** @typedef {import("./Module")} Module */ /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("./WebpackError")} WebpackError */ /** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ /** @typedef {import("./dependencies/SingleEntryDependency")} SingleEntryDependency */ /** @typedef {import("./dependencies/MultiEntryDependency")} MultiEntryDependency */ /** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ /** @typedef {import("./dependencies/DependencyReference")} DependencyReference */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ /** @typedef {import("./util/createHash").Hash} Hash */ // TODO use @callback /** @typedef {{[assetName: string]: Source}} CompilationAssets */ /** @typedef {(err: Error|null, result?: Module) => void } ModuleCallback */ /** @typedef {(err?: Error|null, result?: Module) => void } ModuleChainCallback */ /** @typedef {(module: Module) => void} OnModuleCallback */ /** @typedef {(err?: Error|null) => void} Callback */ /** @typedef {(d: Dependency) => any} DepBlockVarDependenciesCallback */ /** @typedef {new (...args: any[]) => Dependency} DepConstructor */ /** @typedef {{apply: () => void}} Plugin */ /** * @typedef {Object} ModuleFactoryCreateDataContextInfo * @property {string} issuer * @property {string} compiler */ /** * @typedef {Object} ModuleFactoryCreateData * @property {ModuleFactoryCreateDataContextInfo} contextInfo * @property {any=} resolveOptions * @property {string} context * @property {Dependency[]} dependencies */ /** * @typedef {Object} ModuleFactory * @property {(data: ModuleFactoryCreateData, callback: ModuleCallback) => any} create */ /** * @typedef {Object} SortedDependency * @property {ModuleFactory} factory * @property {Dependency[]} dependencies */ /** * @typedef {Object} DependenciesBlockLike * @property {Dependency[]} dependencies * @property {AsyncDependenciesBlock[]} blocks * @property {DependenciesBlockVariable[]} variables */ /** * @param {Chunk} a first chunk to sort by id * @param {Chunk} b second chunk to sort by id * @returns {-1|0|1} sort value */ const byId = (a, b) => { if (typeof a.id !== typeof b.id) { return typeof a.id < typeof b.id ? -1 : 1; } if (a.id < b.id) return -1; if (a.id > b.id) return 1; return 0; }; /** * @param {Module} a first module to sort by * @param {Module} b second module to sort by * @returns {-1|0|1} sort value */ const byIdOrIdentifier = (a, b) => { if (typeof a.id !== typeof b.id) { return typeof a.id < typeof b.id ? -1 : 1; } if (a.id < b.id) return -1; if (a.id > b.id) return 1; const identA = a.identifier(); const identB = b.identifier(); if (identA < identB) return -1; if (identA > identB) return 1; return 0; }; /** * @param {Module} a first module to sort by * @param {Module} b second module to sort by * @returns {-1|0|1} sort value */ const byIndexOrIdentifier = (a, b) => { if (a.index < b.index) return -1; if (a.index > b.index) return 1; const identA = a.identifier(); const identB = b.identifier(); if (identA < identB) return -1; if (identA > identB) return 1; return 0; }; /** * @param {Compilation} a first compilation to sort by * @param {Compilation} b second compilation to sort by * @returns {-1|0|1} sort value */ const byNameOrHash = (a, b) => { if (a.name < b.name) return -1; if (a.name > b.name) return 1; if (a.fullHash < b.fullHash) return -1; if (a.fullHash > b.fullHash) return 1; return 0; }; /** * @template T * @param {Set} a first set * @param {Set} b second set * @returns {number} cmp */ const bySetSize = (a, b) => { return a.size - b.size; }; /** * @param {DependenciesBlockVariable[]} variables DepBlock Variables to iterate over * @param {DepBlockVarDependenciesCallback} fn callback to apply on iterated elements * @returns {void} */ const iterationBlockVariable = (variables, fn) => { for ( let indexVariable = 0; indexVariable < variables.length; indexVariable++ ) { const varDep = variables[indexVariable].dependencies; for (let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { fn(varDep[indexVDep]); } } }; /** * @template T * @param {T[]} arr array of elements to iterate over * @param {function(T): void} fn callback applied to each element * @returns {void} */ const iterationOfArrayCallback = (arr, fn) => { for (let index = 0; index < arr.length; index++) { fn(arr[index]); } }; /** * @template T * @param {Set} set set to add items to * @param {Set} otherSet set to add items from * @returns {void} */ const addAllToSet = (set, otherSet) => { for (const item of otherSet) { set.add(item); } }; class Compilation extends Tapable { /** * Creates an instance of Compilation. * @param {Compiler} compiler the compiler which created the compilation */ constructor(compiler) { super(); this.hooks = { /** @type {SyncHook} */ buildModule: new SyncHook(["module"]), /** @type {SyncHook} */ rebuildModule: new SyncHook(["module"]), /** @type {SyncHook} */ failedModule: new SyncHook(["module", "error"]), /** @type {SyncHook} */ succeedModule: new SyncHook(["module"]), /** @type {SyncHook} */ addEntry: new SyncHook(["entry", "name"]), /** @type {SyncHook} */ failedEntry: new SyncHook(["entry", "name", "error"]), /** @type {SyncHook} */ succeedEntry: new SyncHook(["entry", "name", "module"]), /** @type {SyncWaterfallHook} */ dependencyReference: new SyncWaterfallHook([ "dependencyReference", "dependency", "module" ]), /** @type {AsyncSeriesHook} */ finishModules: new AsyncSeriesHook(["modules"]), /** @type {SyncHook} */ finishRebuildingModule: new SyncHook(["module"]), /** @type {SyncHook} */ unseal: new SyncHook([]), /** @type {SyncHook} */ seal: new SyncHook([]), /** @type {SyncHook} */ beforeChunks: new SyncHook([]), /** @type {SyncHook} */ afterChunks: new SyncHook(["chunks"]), /** @type {SyncBailHook} */ optimizeDependenciesBasic: new SyncBailHook(["modules"]), /** @type {SyncBailHook} */ optimizeDependencies: new SyncBailHook(["modules"]), /** @type {SyncBailHook} */ optimizeDependenciesAdvanced: new SyncBailHook(["modules"]), /** @type {SyncBailHook} */ afterOptimizeDependencies: new SyncHook(["modules"]), /** @type {SyncHook} */ optimize: new SyncHook([]), /** @type {SyncBailHook} */ optimizeModulesBasic: new SyncBailHook(["modules"]), /** @type {SyncBailHook} */ optimizeModules: new SyncBailHook(["modules"]), /** @type {SyncBailHook} */ optimizeModulesAdvanced: new SyncBailHook(["modules"]), /** @type {SyncHook} */ afterOptimizeModules: new SyncHook(["modules"]), /** @type {SyncBailHook} */ optimizeChunksBasic: new SyncBailHook(["chunks", "chunkGroups"]), /** @type {SyncBailHook} */ optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), /** @type {SyncBailHook} */ optimizeChunksAdvanced: new SyncBailHook(["chunks", "chunkGroups"]), /** @type {SyncHook} */ afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), /** @type {AsyncSeriesHook} */ optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), /** @type {SyncHook} */ afterOptimizeTree: new SyncHook(["chunks", "modules"]), /** @type {SyncBailHook} */ optimizeChunkModulesBasic: new SyncBailHook(["chunks", "modules"]), /** @type {SyncBailHook} */ optimizeChunkModules: new SyncBailHook(["chunks", "modules"]), /** @type {SyncBailHook} */ optimizeChunkModulesAdvanced: new SyncBailHook(["chunks", "modules"]), /** @type {SyncHook} */ afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), /** @type {SyncBailHook} */ shouldRecord: new SyncBailHook([]), /** @type {SyncHook} */ reviveModules: new SyncHook(["modules", "records"]), /** @type {SyncHook} */ optimizeModuleOrder: new SyncHook(["modules"]), /** @type {SyncHook} */ advancedOptimizeModuleOrder: new SyncHook(["modules"]), /** @type {SyncHook} */ beforeModuleIds: new SyncHook(["modules"]), /** @type {SyncHook} */ moduleIds: new SyncHook(["modules"]), /** @type {SyncHook} */ optimizeModuleIds: new SyncHook(["modules"]), /** @type {SyncHook} */ afterOptimizeModuleIds: new SyncHook(["modules"]), /** @type {SyncHook} */ reviveChunks: new SyncHook(["chunks", "records"]), /** @type {SyncHook} */ optimizeChunkOrder: new SyncHook(["chunks"]), /** @type {SyncHook} */ beforeChunkIds: new SyncHook(["chunks"]), /** @type {SyncHook} */ optimizeChunkIds: new SyncHook(["chunks"]), /** @type {SyncHook} */ afterOptimizeChunkIds: new SyncHook(["chunks"]), /** @type {SyncHook} */ recordModules: new SyncHook(["modules", "records"]), /** @type {SyncHook} */ recordChunks: new SyncHook(["chunks", "records"]), /** @type {SyncHook} */ beforeHash: new SyncHook([]), /** @type {SyncHook} */ contentHash: new SyncHook(["chunk"]), /** @type {SyncHook} */ afterHash: new SyncHook([]), /** @type {SyncHook} */ recordHash: new SyncHook(["records"]), /** @type {SyncHook} */ record: new SyncHook(["compilation", "records"]), /** @type {SyncHook} */ beforeModuleAssets: new SyncHook([]), /** @type {SyncBailHook} */ shouldGenerateChunkAssets: new SyncBailHook([]), /** @type {SyncHook} */ beforeChunkAssets: new SyncHook([]), /** @type {SyncHook} */ additionalChunkAssets: new SyncHook(["chunks"]), /** @type {AsyncSeriesHook} */ additionalAssets: new AsyncSeriesHook([]), /** @type {AsyncSeriesHook} */ optimizeChunkAssets: new AsyncSeriesHook(["chunks"]), /** @type {SyncHook} */ afterOptimizeChunkAssets: new SyncHook(["chunks"]), /** @type {AsyncSeriesHook} */ optimizeAssets: new AsyncSeriesHook(["assets"]), /** @type {SyncHook} */ afterOptimizeAssets: new SyncHook(["assets"]), /** @type {SyncBailHook} */ needAdditionalSeal: new SyncBailHook([]), /** @type {AsyncSeriesHook} */ afterSeal: new AsyncSeriesHook([]), /** @type {SyncHook} */ chunkHash: new SyncHook(["chunk", "chunkHash"]), /** @type {SyncHook} */ moduleAsset: new SyncHook(["module", "filename"]), /** @type {SyncHook} */ chunkAsset: new SyncHook(["chunk", "filename"]), /** @type {SyncWaterfallHook} */ assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate /** @type {SyncBailHook} */ needAdditionalPass: new SyncBailHook([]), /** @type {SyncHook} */ childCompiler: new SyncHook([ "childCompiler", "compilerName", "compilerIndex" ]), // TODO the following hooks are weirdly located here // TODO move them for webpack 5 /** @type {SyncHook} */ normalModuleLoader: new SyncHook(["loaderContext", "module"]), /** @type {SyncBailHook} */ optimizeExtractedChunksBasic: new SyncBailHook(["chunks"]), /** @type {SyncBailHook} */ optimizeExtractedChunks: new SyncBailHook(["chunks"]), /** @type {SyncBailHook} */ optimizeExtractedChunksAdvanced: new SyncBailHook(["chunks"]), /** @type {SyncHook} */ afterOptimizeExtractedChunks: new SyncHook(["chunks"]) }; this._pluginCompat.tap("Compilation", options => { switch (options.name) { case "optimize-tree": case "additional-assets": case "optimize-chunk-assets": case "optimize-assets": case "after-seal": options.async = true; break; } }); /** @type {string=} */ this.name = undefined; /** @type {Compiler} */ this.compiler = compiler; this.resolverFactory = compiler.resolverFactory; this.inputFileSystem = compiler.inputFileSystem; this.requestShortener = compiler.requestShortener; const options = compiler.options; this.options = options; this.outputOptions = options && options.output; /** @type {boolean=} */ this.bail = options && options.bail; this.profile = options && options.profile; this.performance = options && options.performance; this.mainTemplate = new MainTemplate(this.outputOptions); this.chunkTemplate = new ChunkTemplate(this.outputOptions); this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate( this.outputOptions ); this.runtimeTemplate = new RuntimeTemplate( this.outputOptions, this.requestShortener ); this.moduleTemplates = { javascript: new ModuleTemplate(this.runtimeTemplate, "javascript"), webassembly: new ModuleTemplate(this.runtimeTemplate, "webassembly") }; this.semaphore = new Semaphore(options.parallelism || 100); this.entries = []; /** @private @type {{name: string, request: string, module: Module}[]} */ this._preparedEntrypoints = []; this.entrypoints = new Map(); /** @type {Chunk[]} */ this.chunks = []; /** @type {ChunkGroup[]} */ this.chunkGroups = []; /** @type {Map} */ this.namedChunkGroups = new Map(); /** @type {Map} */ this.namedChunks = new Map(); /** @type {Module[]} */ this.modules = []; /** @private @type {Map} */ this._modules = new Map(); this.cache = null; this.records = null; /** @type {string[]} */ this.additionalChunkAssets = []; /** @type {CompilationAssets} */ this.assets = {}; /** @type {WebpackError[]} */ this.errors = []; /** @type {WebpackError[]} */ this.warnings = []; /** @type {Compilation[]} */ this.children = []; /** @type {Map} */ this.dependencyFactories = new Map(); /** @type {Map} */ this.dependencyTemplates = new Map(); // TODO refactor this in webpack 5 to a custom DependencyTemplates class with a hash property // @ts-ignore this.dependencyTemplates.set("hash", ""); this.childrenCounters = {}; /** @type {Set} */ this.usedChunkIds = null; /** @type {Set} */ this.usedModuleIds = null; /** @type {Map=} */ this.fileTimestamps = undefined; /** @type {Map=} */ this.contextTimestamps = undefined; /** @type {Set=} */ this.compilationDependencies = undefined; /** @private @type {Map} */ this._buildingModules = new Map(); /** @private @type {Map} */ this._rebuildingModules = new Map(); /** @type {Set} */ this.emittedAssets = new Set(); } getStats() { return new Stats(this); } /** * @typedef {Object} AddModuleResult * @property {Module} module the added or existing module * @property {boolean} issuer was this the first request for this module * @property {boolean} build should the module be build * @property {boolean} dependencies should dependencies be walked */ /** * @param {Module} module module to be added that was created * @param {any=} cacheGroup cacheGroup it is apart of * @returns {AddModuleResult} returns meta about whether or not the module had built * had an issuer, or any dependnecies */ addModule(module, cacheGroup) { const identifier = module.identifier(); const alreadyAddedModule = this._modules.get(identifier); if (alreadyAddedModule) { return { module: alreadyAddedModule, issuer: false, build: false, dependencies: false }; } const cacheName = (cacheGroup || "m") + identifier; if (this.cache && this.cache[cacheName]) { const cacheModule = this.cache[cacheName]; if (typeof cacheModule.updateCacheModule === "function") { cacheModule.updateCacheModule(module); } let rebuild = true; if (this.fileTimestamps && this.contextTimestamps) { rebuild = cacheModule.needRebuild( this.fileTimestamps, this.contextTimestamps ); } if (!rebuild) { cacheModule.disconnect(); this._modules.set(identifier, cacheModule); this.modules.push(cacheModule); for (const err of cacheModule.errors) { this.errors.push(err); } for (const err of cacheModule.warnings) { this.warnings.push(err); } return { module: cacheModule, issuer: true, build: false, dependencies: true }; } cacheModule.unbuild(); module = cacheModule; } this._modules.set(identifier, module); if (this.cache) { this.cache[cacheName] = module; } this.modules.push(module); return { module: module, issuer: true, build: true, dependencies: true }; } /** * Fetches a module from a compilation by its identifier * @param {Module} module the module provided * @returns {Module} the module requested */ getModule(module) { const identifier = module.identifier(); return this._modules.get(identifier); } /** * Attempts to search for a module by its identifier * @param {string} identifier identifier (usually path) for module * @returns {Module|undefined} attempt to search for module and return it, else undefined */ findModule(identifier) { return this._modules.get(identifier); } /** * @param {Module} module module with its callback list * @param {Callback} callback the callback function * @returns {void} */ waitForBuildingFinished(module, callback) { let callbackList = this._buildingModules.get(module); if (callbackList) { callbackList.push(() => callback()); } else { process.nextTick(callback); } } /** * Builds the module object * * @param {Module} module module to be built * @param {boolean} optional optional flag * @param {Module=} origin origin module this module build was requested from * @param {Dependency[]=} dependencies optional dependencies from the module to be built * @param {TODO} thisCallback the callback * @returns {TODO} returns the callback function with results */ buildModule(module, optional, origin, dependencies, thisCallback) { let callbackList = this._buildingModules.get(module); if (callbackList) { callbackList.push(thisCallback); return; } this._buildingModules.set(module, (callbackList = [thisCallback])); const callback = err => { this._buildingModules.delete(module); for (const cb of callbackList) { cb(err); } }; this.hooks.buildModule.call(module); module.build( this.options, this, this.resolverFactory.get("normal", module.resolveOptions), this.inputFileSystem, error => { const errors = module.errors; for (let indexError = 0; indexError < errors.length; indexError++) { const err = errors[indexError]; err.origin = origin; err.dependencies = dependencies; if (optional) { this.warnings.push(err); } else { this.errors.push(err); } } const warnings = module.warnings; for ( let indexWarning = 0; indexWarning < warnings.length; indexWarning++ ) { const war = warnings[indexWarning]; war.origin = origin; war.dependencies = dependencies; this.warnings.push(war); } const originalMap = module.dependencies.reduce((map, v, i) => { map.set(v, i); return map; }, new Map()); module.dependencies.sort((a, b) => { const cmp = compareLocations(a.loc, b.loc); if (cmp) return cmp; return originalMap.get(a) - originalMap.get(b); }); if (error) { this.hooks.failedModule.call(module, error); return callback(error); } this.hooks.succeedModule.call(module); return callback(); } ); } /** * @param {Module} module to be processed for deps * @param {ModuleCallback} callback callback to be triggered * @returns {void} */ processModuleDependencies(module, callback) { const dependencies = new Map(); const addDependency = dep => { const resourceIdent = dep.getResourceIdentifier(); if (resourceIdent) { const factory = this.dependencyFactories.get(dep.constructor); if (factory === undefined) { throw new Error( `No module factory available for dependency type: ${ dep.constructor.name }` ); } let innerMap = dependencies.get(factory); if (innerMap === undefined) { dependencies.set(factory, (innerMap = new Map())); } let list = innerMap.get(resourceIdent); if (list === undefined) innerMap.set(resourceIdent, (list = [])); list.push(dep); } }; const addDependenciesBlock = block => { if (block.dependencies) { iterationOfArrayCallback(block.dependencies, addDependency); } if (block.blocks) { iterationOfArrayCallback(block.blocks, addDependenciesBlock); } if (block.variables) { iterationBlockVariable(block.variables, addDependency); } }; try { addDependenciesBlock(module); } catch (e) { callback(e); } const sortedDependencies = []; for (const pair1 of dependencies) { for (const pair2 of pair1[1]) { sortedDependencies.push({ factory: pair1[0], dependencies: pair2[1] }); } } this.addModuleDependencies( module, sortedDependencies, this.bail, null, true, callback ); } /** * @param {Module} module module to add deps to * @param {SortedDependency[]} dependencies set of sorted dependencies to iterate through * @param {(boolean|null)=} bail whether to bail or not * @param {TODO} cacheGroup optional cacheGroup * @param {boolean} recursive whether it is recursive traversal * @param {function} callback callback for when dependencies are finished being added * @returns {void} */ addModuleDependencies( module, dependencies, bail, cacheGroup, recursive, callback ) { const start = this.profile && Date.now(); const currentProfile = this.profile && {}; asyncLib.forEach( dependencies, (item, callback) => { const dependencies = item.dependencies; const errorAndCallback = err => { err.origin = module; err.dependencies = dependencies; this.errors.push(err); if (bail) { callback(err); } else { callback(); } }; const warningAndCallback = err => { err.origin = module; this.warnings.push(err); callback(); }; const semaphore = this.semaphore; semaphore.acquire(() => { const factory = item.factory; factory.create( { contextInfo: { issuer: module.nameForCondition && module.nameForCondition(), compiler: this.compiler.name }, resolveOptions: module.resolveOptions, context: module.context, dependencies: dependencies }, (err, dependentModule) => { let afterFactory; const isOptional = () => { return dependencies.every(d => d.optional); }; const errorOrWarningAndCallback = err => { if (isOptional()) { return warningAndCallback(err); } else { return errorAndCallback(err); } }; if (err) { semaphore.release(); return errorOrWarningAndCallback( new ModuleNotFoundError(module, err) ); } if (!dependentModule) { semaphore.release(); return process.nextTick(callback); } if (currentProfile) { afterFactory = Date.now(); currentProfile.factory = afterFactory - start; } const iterationDependencies = depend => { for (let index = 0; index < depend.length; index++) { const dep = depend[index]; dep.module = dependentModule; dependentModule.addReason(module, dep); } }; const addModuleResult = this.addModule( dependentModule, cacheGroup ); dependentModule = addModuleResult.module; iterationDependencies(dependencies); const afterBuild = () => { if (currentProfile) { const afterBuilding = Date.now(); currentProfile.building = afterBuilding - afterFactory; } if (recursive && addModuleResult.dependencies) { this.processModuleDependencies(dependentModule, callback); } else { return callback(); } }; if (addModuleResult.issuer) { if (currentProfile) { dependentModule.profile = currentProfile; } dependentModule.issuer = module; } else { if (this.profile) { if (module.profile) { const time = Date.now() - start; if ( !module.profile.dependencies || time > module.profile.dependencies ) { module.profile.dependencies = time; } } } } if (addModuleResult.build) { this.buildModule( dependentModule, isOptional(), module, dependencies, err => { if (err) { semaphore.release(); return errorOrWarningAndCallback(err); } if (currentProfile) { const afterBuilding = Date.now(); currentProfile.building = afterBuilding - afterFactory; } semaphore.release(); afterBuild(); } ); } else { semaphore.release(); this.waitForBuildingFinished(dependentModule, afterBuild); } } ); }); }, err => { // In V8, the Error objects keep a reference to the functions on the stack. These warnings & // errors are created inside closures that keep a reference to the Compilation, so errors are // leaking the Compilation object. if (err) { // eslint-disable-next-line no-self-assign err.stack = err.stack; return callback(err); } return process.nextTick(callback); } ); } /** * * @param {string} context context string path * @param {Dependency} dependency dependency used to create Module chain * @param {OnModuleCallback} onModule function invoked on modules creation * @param {ModuleChainCallback} callback callback for when module chain is complete * @returns {void} will throw if dependency instance is not a valid Dependency */ _addModuleChain(context, dependency, onModule, callback) { const start = this.profile && Date.now(); const currentProfile = this.profile && {}; const errorAndCallback = this.bail ? err => { callback(err); } : err => { err.dependencies = [dependency]; this.errors.push(err); callback(); }; if ( typeof dependency !== "object" || dependency === null || !dependency.constructor ) { throw new Error("Parameter 'dependency' must be a Dependency"); } const Dep = /** @type {DepConstructor} */ (dependency.constructor); const moduleFactory = this.dependencyFactories.get(Dep); if (!moduleFactory) { throw new Error( `No dependency factory available for this dependency type: ${ dependency.constructor.name }` ); } this.semaphore.acquire(() => { moduleFactory.create( { contextInfo: { issuer: "", compiler: this.compiler.name }, context: context, dependencies: [dependency] }, (err, module) => { if (err) { this.semaphore.release(); return errorAndCallback(new EntryModuleNotFoundError(err)); } let afterFactory; if (currentProfile) { afterFactory = Date.now(); currentProfile.factory = afterFactory - start; } const addModuleResult = this.addModule(module); module = addModuleResult.module; onModule(module); dependency.module = module; module.addReason(null, dependency); const afterBuild = () => { if (currentProfile) { const afterBuilding = Date.now(); currentProfile.building = afterBuilding - afterFactory; } if (addModuleResult.dependencies) { this.processModuleDependencies(module, err => { if (err) return callback(err); callback(null, module); }); } else { return callback(null, module); } }; if (addModuleResult.issuer) { if (currentProfile) { module.profile = currentProfile; } } if (addModuleResult.build) { this.buildModule(module, false, null, null, err => { if (err) { this.semaphore.release(); return errorAndCallback(err); } if (currentProfile) { const afterBuilding = Date.now(); currentProfile.building = afterBuilding - afterFactory; } this.semaphore.release(); afterBuild(); }); } else { this.semaphore.release(); this.waitForBuildingFinished(module, afterBuild); } } ); }); } /** * * @param {string} context context path for entry * @param {Dependency} entry entry dependency being created * @param {string} name name of entry * @param {ModuleCallback} callback callback function * @returns {void} returns */ addEntry(context, entry, name, callback) { this.hooks.addEntry.call(entry, name); const slot = { name: name, // TODO webpack 5 remove `request` request: null, module: null }; if (entry instanceof ModuleDependency) { slot.request = entry.request; } // TODO webpack 5: merge modules instead when multiple entry modules are supported const idx = this._preparedEntrypoints.findIndex(slot => slot.name === name); if (idx >= 0) { // Overwrite existing entrypoint this._preparedEntrypoints[idx] = slot; } else { this._preparedEntrypoints.push(slot); } this._addModuleChain( context, entry, module => { this.entries.push(module); }, (err, module) => { if (err) { this.hooks.failedEntry.call(entry, name, err); return callback(err); } if (module) { slot.module = module; } else { const idx = this._preparedEntrypoints.indexOf(slot); if (idx >= 0) { this._preparedEntrypoints.splice(idx, 1); } } this.hooks.succeedEntry.call(entry, name, module); return callback(null, module); } ); } /** * @param {string} context context path string * @param {Dependency} dependency dep used to create module * @param {ModuleCallback} callback module callback sending module up a level * @returns {void} */ prefetch(context, dependency, callback) { this._addModuleChain( context, dependency, module => { module.prefetched = true; }, callback ); } /** * @param {Module} module module to be rebuilt * @param {Callback} thisCallback callback when module finishes rebuilding * @returns {void} */ rebuildModule(module, thisCallback) { let callbackList = this._rebuildingModules.get(module); if (callbackList) { callbackList.push(thisCallback); return; } this._rebuildingModules.set(module, (callbackList = [thisCallback])); const callback = err => { this._rebuildingModules.delete(module); for (const cb of callbackList) { cb(err); } }; this.hooks.rebuildModule.call(module); const oldDependencies = module.dependencies.slice(); const oldVariables = module.variables.slice(); const oldBlocks = module.blocks.slice(); module.unbuild(); this.buildModule(module, false, module, null, err => { if (err) { this.hooks.finishRebuildingModule.call(module); return callback(err); } this.processModuleDependencies(module, err => { if (err) return callback(err); this.removeReasonsOfDependencyBlock(module, { dependencies: oldDependencies, variables: oldVariables, blocks: oldBlocks }); this.hooks.finishRebuildingModule.call(module); callback(); }); }); } finish(callback) { const modules = this.modules; this.hooks.finishModules.callAsync(modules, err => { if (err) return callback(err); for (let index = 0; index < modules.length; index++) { const module = modules[index]; this.reportDependencyErrorsAndWarnings(module, [module]); } callback(); }); } unseal() { this.hooks.unseal.call(); this.chunks.length = 0; this.chunkGroups.length = 0; this.namedChunks.clear(); this.namedChunkGroups.clear(); this.additionalChunkAssets.length = 0; this.assets = {}; for (const module of this.modules) { module.unseal(); } } /** * @param {Callback} callback signals when the seal method is finishes * @returns {void} */ seal(callback) { this.hooks.seal.call(); while ( this.hooks.optimizeDependenciesBasic.call(this.modules) || this.hooks.optimizeDependencies.call(this.modules) || this.hooks.optimizeDependenciesAdvanced.call(this.modules) ) { /* empty */ } this.hooks.afterOptimizeDependencies.call(this.modules); this.hooks.beforeChunks.call(); for (const preparedEntrypoint of this._preparedEntrypoints) { const module = preparedEntrypoint.module; const name = preparedEntrypoint.name; const chunk = this.addChunk(name); const entrypoint = new Entrypoint(name); entrypoint.setRuntimeChunk(chunk); entrypoint.addOrigin(null, name, preparedEntrypoint.request); this.namedChunkGroups.set(name, entrypoint); this.entrypoints.set(name, entrypoint); this.chunkGroups.push(entrypoint); GraphHelpers.connectChunkGroupAndChunk(entrypoint, chunk); GraphHelpers.connectChunkAndModule(chunk, module); chunk.entryModule = module; chunk.name = name; this.assignDepth(module); } this.processDependenciesBlocksForChunkGroups(this.chunkGroups.slice()); this.sortModules(this.modules); this.hooks.afterChunks.call(this.chunks); this.hooks.optimize.call(); while ( this.hooks.optimizeModulesBasic.call(this.modules) || this.hooks.optimizeModules.call(this.modules) || this.hooks.optimizeModulesAdvanced.call(this.modules) ) { /* empty */ } this.hooks.afterOptimizeModules.call(this.modules); while ( this.hooks.optimizeChunksBasic.call(this.chunks, this.chunkGroups) || this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups) || this.hooks.optimizeChunksAdvanced.call(this.chunks, this.chunkGroups) ) { /* empty */ } this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { if (err) { return callback(err); } this.hooks.afterOptimizeTree.call(this.chunks, this.modules); while ( this.hooks.optimizeChunkModulesBasic.call(this.chunks, this.modules) || this.hooks.optimizeChunkModules.call(this.chunks, this.modules) || this.hooks.optimizeChunkModulesAdvanced.call(this.chunks, this.modules) ) { /* empty */ } this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); const shouldRecord = this.hooks.shouldRecord.call() !== false; this.hooks.reviveModules.call(this.modules, this.records); this.hooks.optimizeModuleOrder.call(this.modules); this.hooks.advancedOptimizeModuleOrder.call(this.modules); this.hooks.beforeModuleIds.call(this.modules); this.hooks.moduleIds.call(this.modules); this.applyModuleIds(); this.hooks.optimizeModuleIds.call(this.modules); this.hooks.afterOptimizeModuleIds.call(this.modules); this.sortItemsWithModuleIds(); this.hooks.reviveChunks.call(this.chunks, this.records); this.hooks.optimizeChunkOrder.call(this.chunks); this.hooks.beforeChunkIds.call(this.chunks); this.applyChunkIds(); this.hooks.optimizeChunkIds.call(this.chunks); this.hooks.afterOptimizeChunkIds.call(this.chunks); this.sortItemsWithChunkIds(); if (shouldRecord) { this.hooks.recordModules.call(this.modules, this.records); this.hooks.recordChunks.call(this.chunks, this.records); } this.hooks.beforeHash.call(); this.createHash(); this.hooks.afterHash.call(); if (shouldRecord) { this.hooks.recordHash.call(this.records); } this.hooks.beforeModuleAssets.call(); this.createModuleAssets(); if (this.hooks.shouldGenerateChunkAssets.call() !== false) { this.hooks.beforeChunkAssets.call(); this.createChunkAssets(); } this.hooks.additionalChunkAssets.call(this.chunks); this.summarizeDependencies(); if (shouldRecord) { this.hooks.record.call(this, this.records); } this.hooks.additionalAssets.callAsync(err => { if (err) { return callback(err); } this.hooks.optimizeChunkAssets.callAsync(this.chunks, err => { if (err) { return callback(err); } this.hooks.afterOptimizeChunkAssets.call(this.chunks); this.hooks.optimizeAssets.callAsync(this.assets, err => { if (err) { return callback(err); } this.hooks.afterOptimizeAssets.call(this.assets); if (this.hooks.needAdditionalSeal.call()) { this.unseal(); return this.seal(callback); } return this.hooks.afterSeal.callAsync(callback); }); }); }); }); } /** * @param {Module[]} modules the modules array on compilation to perform the sort for * @returns {void} */ sortModules(modules) { // TODO webpack 5: this should only be enabled when `moduleIds: "natural"` // TODO move it into a plugin (NaturalModuleIdsPlugin) and use this in WebpackOptionsApply // TODO remove this method modules.sort(byIndexOrIdentifier); } /** * @param {Module} module moulde to report from * @param {DependenciesBlock[]} blocks blocks to report from * @returns {void} */ reportDependencyErrorsAndWarnings(module, blocks) { for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { const block = blocks[indexBlock]; const dependencies = block.dependencies; for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { const d = dependencies[indexDep]; const warnings = d.getWarnings(); if (warnings) { for (let indexWar = 0; indexWar < warnings.length; indexWar++) { const w = warnings[indexWar]; const warning = new ModuleDependencyWarning(module, w, d.loc); this.warnings.push(warning); } } const errors = d.getErrors(); if (errors) { for (let indexErr = 0; indexErr < errors.length; indexErr++) { const e = errors[indexErr]; const error = new ModuleDependencyError(module, e, d.loc); this.errors.push(error); } } } this.reportDependencyErrorsAndWarnings(module, block.blocks); } } /** * @param {TODO} groupOptions options for the chunk group * @param {Module} module the module the references the chunk group * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) * @param {string} request the request from which the the chunk group is referenced * @returns {ChunkGroup} the new or existing chunk group */ addChunkInGroup(groupOptions, module, loc, request) { if (typeof groupOptions === "string") { groupOptions = { name: groupOptions }; } const name = groupOptions.name; if (name) { const chunkGroup = this.namedChunkGroups.get(name); if (chunkGroup !== undefined) { chunkGroup.addOptions(groupOptions); if (module) { chunkGroup.addOrigin(module, loc, request); } return chunkGroup; } } const chunkGroup = new ChunkGroup(groupOptions); if (module) chunkGroup.addOrigin(module, loc, request); const chunk = this.addChunk(name); GraphHelpers.connectChunkGroupAndChunk(chunkGroup, chunk); this.chunkGroups.push(chunkGroup); if (name) { this.namedChunkGroups.set(name, chunkGroup); } return chunkGroup; } /** * This method first looks to see if a name is provided for a new chunk, * and first looks to see if any named chunks already exist and reuse that chunk instead. * * @param {string=} name optional chunk name to be provided * @returns {Chunk} create a chunk (invoked during seal event) */ addChunk(name) { if (name) { const chunk = this.namedChunks.get(name); if (chunk !== undefined) { return chunk; } } const chunk = new Chunk(name); this.chunks.push(chunk); if (name) { this.namedChunks.set(name, chunk); } return chunk; } /** * @param {Module} module module to assign depth * @returns {void} */ assignDepth(module) { const queue = new Set([module]); let depth; module.depth = 0; /** * @param {Module} module module for processeing * @returns {void} */ const enqueueJob = module => { const d = module.depth; if (typeof d === "number" && d <= depth) return; queue.add(module); module.depth = depth; }; /** * @param {Dependency} dependency dependency to assign depth to * @returns {void} */ const assignDepthToDependency = dependency => { if (dependency.module) { enqueueJob(dependency.module); } }; /** * @param {DependenciesBlock} block block to assign depth to * @returns {void} */ const assignDepthToDependencyBlock = block => { if (block.variables) { iterationBlockVariable(block.variables, assignDepthToDependency); } if (block.dependencies) { iterationOfArrayCallback(block.dependencies, assignDepthToDependency); } if (block.blocks) { iterationOfArrayCallback(block.blocks, assignDepthToDependencyBlock); } }; for (module of queue) { queue.delete(module); depth = module.depth; depth++; assignDepthToDependencyBlock(module); } } /** * @param {Module} module the module containing the dependency * @param {Dependency} dependency the dependency * @returns {DependencyReference} a reference for the dependency */ getDependencyReference(module, dependency) { // TODO remove dep.getReference existence check in webpack 5 if (typeof dependency.getReference !== "function") return null; const ref = dependency.getReference(); if (!ref) return null; return this.hooks.dependencyReference.call(ref, dependency, module); } /** * This method creates the Chunk graph from the Module graph * @private * @param {TODO[]} inputChunkGroups chunk groups which are processed * @returns {void} */ processDependenciesBlocksForChunkGroups(inputChunkGroups) { // Process is splitting into two parts: // Part one traverse the module graph and builds a very basic chunks graph // in chunkDependencies. // Part two traverse every possible way through the basic chunk graph and // tracks the available modules. While traversing it connects chunks with // eachother and Blocks with Chunks. It stops traversing when all modules // for a chunk are already available. So it doesn't connect unneeded chunks. /** @type {Map} */ const chunkDependencies = new Map(); const allCreatedChunkGroups = new Set(); // PREPARE /** @type {Map} */ const blockInfoMap = new Map(); /** * @param {Dependency} d dependency to iterate over * @returns {void} */ const iteratorDependency = d => { // We skip Dependencies without Reference const ref = this.getDependencyReference(currentModule, d); if (!ref) { return; } // We skip Dependencies without Module pointer const refModule = ref.module; if (!refModule) { return; } // We skip weak Dependencies if (ref.weak) { return; } blockInfoModules.add(refModule); }; /** * @param {AsyncDependenciesBlock} b blocks to prepare * @returns {void} */ const iteratorBlockPrepare = b => { blockInfoBlocks.push(b); blockQueue.push(b); }; /** @type {Module} */ let currentModule; /** @type {DependenciesBlock} */ let block; /** @type {DependenciesBlock[]} */ let blockQueue; /** @type {Set} */ let blockInfoModules; /** @type {AsyncDependenciesBlock[]} */ let blockInfoBlocks; for (const module of this.modules) { blockQueue = [module]; currentModule = module; while (blockQueue.length > 0) { block = blockQueue.pop(); blockInfoModules = new Set(); blockInfoBlocks = []; if (block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } if (block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if (block.blocks) { iterationOfArrayCallback(block.blocks, iteratorBlockPrepare); } const blockInfo = { modules: Array.from(blockInfoModules), blocks: blockInfoBlocks }; blockInfoMap.set(block, blockInfo); } } // PART ONE /** @type {Map} */ const chunkGroupCounters = new Map(); for (const chunkGroup of inputChunkGroups) { chunkGroupCounters.set(chunkGroup, { index: 0, index2: 0 }); } let nextFreeModuleIndex = 0; let nextFreeModuleIndex2 = 0; /** @type {Map} */ const blockChunkGroups = new Map(); /** @type {Set} */ const blocksWithNestedBlocks = new Set(); const ADD_AND_ENTER_MODULE = 0; const ENTER_MODULE = 1; const PROCESS_BLOCK = 2; const LEAVE_MODULE = 3; /** * @typedef {Object} QueueItem * @property {number} action * @property {DependenciesBlock} block * @property {Module} module * @property {Chunk} chunk * @property {ChunkGroup} chunkGroup */ /** * @param {ChunkGroup} chunkGroup chunk group * @returns {QueueItem} queue item */ const chunkGroupToQueueItem = chunkGroup => ({ action: ENTER_MODULE, block: chunkGroup.chunks[0].entryModule, module: chunkGroup.chunks[0].entryModule, chunk: chunkGroup.chunks[0], chunkGroup }); // Start with the provided modules/chunks /** @type {QueueItem[]} */ let queue = inputChunkGroups.map(chunkGroupToQueueItem).reverse(); /** @type {QueueItem[]} */ let queueDelayed = []; /** @type {Module} */ let module; /** @type {Chunk} */ let chunk; /** @type {ChunkGroup} */ let chunkGroup; // For each async Block in graph /** * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock * @returns {void} */ const iteratorBlock = b => { // 1. We create a chunk for this Block // but only once (blockChunkGroups map) let c = blockChunkGroups.get(b); if (c === undefined) { c = this.namedChunkGroups.get(b.chunkName); if (c && c.isInitial()) { this.errors.push( new AsyncDependencyToInitialChunkError(b.chunkName, module, b.loc) ); c = chunkGroup; } else { c = this.addChunkInGroup( b.groupOptions || b.chunkName, module, b.loc, b.request ); chunkGroupCounters.set(c, { index: 0, index2: 0 }); blockChunkGroups.set(b, c); allCreatedChunkGroups.add(c); } } else { // TODO webpack 5 remove addOptions check if (c.addOptions) c.addOptions(b.groupOptions); c.addOrigin(module, b.loc, b.request); } // 2. We store the Block+Chunk mapping as dependency for the chunk let deps = chunkDependencies.get(chunkGroup); if (!deps) chunkDependencies.set(chunkGroup, (deps = [])); deps.push({ block: b, chunkGroup: c, couldBeFiltered: true }); // 3. We enqueue the DependenciesBlock for traversal queueDelayed.push({ action: PROCESS_BLOCK, block: b, module: module, chunk: c.chunks[0], chunkGroup: c }); }; // Iterative traversal of the Module graph // Recursive would be simpler to write but could result in Stack Overflows while (queue.length) { while (queue.length) { const queueItem = queue.pop(); module = queueItem.module; block = queueItem.block; chunk = queueItem.chunk; chunkGroup = queueItem.chunkGroup; switch (queueItem.action) { case ADD_AND_ENTER_MODULE: { // We connect Module and Chunk when not already done if (chunk.addModule(module)) { module.addChunk(chunk); } else { // already connected, skip it break; } } // fallthrough case ENTER_MODULE: { if (chunkGroup !== undefined) { const index = chunkGroup.getModuleIndex(module); if (index === undefined) { chunkGroup.setModuleIndex( module, chunkGroupCounters.get(chunkGroup).index++ ); } } if (module.index === null) { module.index = nextFreeModuleIndex++; } queue.push({ action: LEAVE_MODULE, block, module, chunk, chunkGroup }); } // fallthrough case PROCESS_BLOCK: { // get prepared block info const blockInfo = blockInfoMap.get(block); // Traverse all referenced modules for (let i = blockInfo.modules.length - 1; i >= 0; i--) { const refModule = blockInfo.modules[i]; if (chunk.containsModule(refModule)) { // skip early if already connected continue; } // enqueue the add and enter to enter in the correct order // this is relevant with circular dependencies queue.push({ action: ADD_AND_ENTER_MODULE, block: refModule, module: refModule, chunk, chunkGroup }); } // Traverse all Blocks iterationOfArrayCallback(blockInfo.blocks, iteratorBlock); if (blockInfo.blocks.length > 0 && module !== block) { blocksWithNestedBlocks.add(block); } break; } case LEAVE_MODULE: { if (chunkGroup !== undefined) { const index = chunkGroup.getModuleIndex2(module); if (index === undefined) { chunkGroup.setModuleIndex2( module, chunkGroupCounters.get(chunkGroup).index2++ ); } } if (module.index2 === null) { module.index2 = nextFreeModuleIndex2++; } break; } } } const tempQueue = queue; queue = queueDelayed.reverse(); queueDelayed = tempQueue; } // PART TWO /** @type {Set} */ let newAvailableModules; /** * @typedef {Object} ChunkGroupInfo * @property {Set} minAvailableModules current minimal set of modules available at this point * @property {Set[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules */ /** @type {Map} */ const chunkGroupInfoMap = new Map(); /** @type {Queue} */ const queue2 = new Queue(inputChunkGroups); for (const chunkGroup of inputChunkGroups) { chunkGroupInfoMap.set(chunkGroup, { minAvailableModules: undefined, availableModulesToBeMerged: [new Set()] }); } /** * Helper function to check if all modules of a chunk are available * * @param {ChunkGroup} chunkGroup the chunkGroup to scan * @param {Set} availableModules the comparitor set * @returns {boolean} return true if all modules of a chunk are available */ const areModulesAvailable = (chunkGroup, availableModules) => { for (const chunk of chunkGroup.chunks) { for (const module of chunk.modulesIterable) { if (!availableModules.has(module)) return false; } } return true; }; // For each edge in the basic chunk graph /** * @param {TODO} dep the dependency used for filtering * @returns {boolean} used to filter "edges" (aka Dependencies) that were pointing * to modules that are already available. Also filters circular dependencies in the chunks graph */ const filterFn = dep => { const depChunkGroup = dep.chunkGroup; if (!dep.couldBeFiltered) return true; if (blocksWithNestedBlocks.has(dep.block)) return true; if (areModulesAvailable(depChunkGroup, newAvailableModules)) { return false; // break all modules are already available } dep.couldBeFiltered = false; return true; }; // Iterative traversing of the basic chunk graph while (queue2.length) { chunkGroup = queue2.dequeue(); const info = chunkGroupInfoMap.get(chunkGroup); const availableModulesToBeMerged = info.availableModulesToBeMerged; let minAvailableModules = info.minAvailableModules; // 1. Get minimal available modules // It doesn't make sense to traverse a chunk again with more available modules. // This step calculates the minimal available modules and skips traversal when // the list didn't shrink. availableModulesToBeMerged.sort(bySetSize); let changed = false; for (const availableModules of availableModulesToBeMerged) { if (minAvailableModules === undefined) { minAvailableModules = new Set(availableModules); info.minAvailableModules = minAvailableModules; changed = true; } else { for (const m of minAvailableModules) { if (!availableModules.has(m)) { minAvailableModules.delete(m); changed = true; } } } } availableModulesToBeMerged.length = 0; if (!changed) continue; // 2. Get the edges at this point of the graph const deps = chunkDependencies.get(chunkGroup); if (!deps) continue; if (deps.length === 0) continue; // 3. Create a new Set of available modules at this points newAvailableModules = new Set(minAvailableModules); for (const chunk of chunkGroup.chunks) { for (const m of chunk.modulesIterable) { newAvailableModules.add(m); } } // 4. Foreach remaining edge const nextChunkGroups = new Set(); for (let i = 0; i < deps.length; i++) { const dep = deps[i]; // Filter inline, rather than creating a new array from `.filter()` if (!filterFn(dep)) { continue; } const depChunkGroup = dep.chunkGroup; const depBlock = dep.block; // 5. Connect block with chunk GraphHelpers.connectDependenciesBlockAndChunkGroup( depBlock, depChunkGroup ); // 6. Connect chunk with parent GraphHelpers.connectChunkGroupParentAndChild(chunkGroup, depChunkGroup); nextChunkGroups.add(depChunkGroup); } // 7. Enqueue further traversal for (const nextChunkGroup of nextChunkGroups) { let nextInfo = chunkGroupInfoMap.get(nextChunkGroup); if (nextInfo === undefined) { nextInfo = { minAvailableModules: undefined, availableModulesToBeMerged: [] }; chunkGroupInfoMap.set(nextChunkGroup, nextInfo); } nextInfo.availableModulesToBeMerged.push(newAvailableModules); // As queue deduplicates enqueued items this makes sure that a ChunkGroup // is not enqueued twice queue2.enqueue(nextChunkGroup); } } // Remove all unconnected chunk groups for (const chunkGroup of allCreatedChunkGroups) { if (chunkGroup.getNumberOfParents() === 0) { for (const chunk of chunkGroup.chunks) { const idx = this.chunks.indexOf(chunk); if (idx >= 0) this.chunks.splice(idx, 1); chunk.remove("unconnected"); } chunkGroup.remove("unconnected"); } } } /** * * @param {Module} module module relationship for removal * @param {DependenciesBlockLike} block //TODO: good description * @returns {void} */ removeReasonsOfDependencyBlock(module, block) { const iteratorDependency = d => { if (!d.module) { return; } if (d.module.removeReason(module, d)) { for (const chunk of d.module.chunksIterable) { this.patchChunksAfterReasonRemoval(d.module, chunk); } } }; if (block.blocks) { iterationOfArrayCallback(block.blocks, block => this.removeReasonsOfDependencyBlock(module, block) ); } if (block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if (block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } } /** * @param {Module} module module to patch tie * @param {Chunk} chunk chunk to patch tie * @returns {void} */ patchChunksAfterReasonRemoval(module, chunk) { if (!module.hasReasons()) { this.removeReasonsOfDependencyBlock(module, module); } if (!module.hasReasonForChunk(chunk)) { if (module.removeChunk(chunk)) { this.removeChunkFromDependencies(module, chunk); } } } /** * * @param {DependenciesBlock} block block tie for Chunk * @param {Chunk} chunk chunk to remove from dep * @returns {void} */ removeChunkFromDependencies(block, chunk) { const iteratorDependency = d => { if (!d.module) { return; } this.patchChunksAfterReasonRemoval(d.module, chunk); }; const blocks = block.blocks; for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { const asyncBlock = blocks[indexBlock]; // Grab all chunks from the first Block's AsyncDepBlock const chunks = asyncBlock.chunkGroup.chunks; // For each chunk in chunkGroup for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const iteratedChunk = chunks[indexChunk]; asyncBlock.chunkGroup.removeChunk(iteratedChunk); asyncBlock.chunkGroup.removeParent(iteratedChunk); // Recurse this.removeChunkFromDependencies(block, iteratedChunk); } } if (block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if (block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } } applyModuleIds() { const unusedIds = []; let nextFreeModuleId = 0; const usedIds = new Set(); if (this.usedModuleIds) { for (const id of this.usedModuleIds) { usedIds.add(id); } } const modules1 = this.modules; for (let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { const module1 = modules1[indexModule1]; if (module1.id !== null) { usedIds.add(module1.id); } } if (usedIds.size > 0) { let usedIdMax = -1; for (const usedIdKey of usedIds) { if (typeof usedIdKey !== "number") { continue; } usedIdMax = Math.max(usedIdMax, usedIdKey); } let lengthFreeModules = (nextFreeModuleId = usedIdMax + 1); while (lengthFreeModules--) { if (!usedIds.has(lengthFreeModules)) { unusedIds.push(lengthFreeModules); } } } const modules2 = this.modules; for (let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) { const module2 = modules2[indexModule2]; if (module2.id === null) { if (unusedIds.length > 0) { module2.id = unusedIds.pop(); } else { module2.id = nextFreeModuleId++; } } } } applyChunkIds() { /** @type {Set} */ const usedIds = new Set(); // Get used ids from usedChunkIds property (i. e. from records) if (this.usedChunkIds) { for (const id of this.usedChunkIds) { if (typeof id !== "number") { continue; } usedIds.add(id); } } // Get used ids from existing chunks const chunks = this.chunks; for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const chunk = chunks[indexChunk]; const usedIdValue = chunk.id; if (typeof usedIdValue !== "number") { continue; } usedIds.add(usedIdValue); } // Calculate maximum assigned chunk id let nextFreeChunkId = -1; for (const id of usedIds) { nextFreeChunkId = Math.max(nextFreeChunkId, id); } nextFreeChunkId++; // Determine free chunk ids from 0 to maximum /** @type {number[]} */ const unusedIds = []; if (nextFreeChunkId > 0) { let index = nextFreeChunkId; while (index--) { if (!usedIds.has(index)) { unusedIds.push(index); } } } // Assign ids to chunk which has no id for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const chunk = chunks[indexChunk]; if (chunk.id === null) { if (unusedIds.length > 0) { chunk.id = unusedIds.pop(); } else { chunk.id = nextFreeChunkId++; } } if (!chunk.ids) { chunk.ids = [chunk.id]; } } } sortItemsWithModuleIds() { this.modules.sort(byIdOrIdentifier); const modules = this.modules; for (let indexModule = 0; indexModule < modules.length; indexModule++) { modules[indexModule].sortItems(false); } const chunks = this.chunks; for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { chunks[indexChunk].sortItems(); } chunks.sort((a, b) => a.compareTo(b)); } sortItemsWithChunkIds() { for (const chunkGroup of this.chunkGroups) { chunkGroup.sortItems(); } this.chunks.sort(byId); for ( let indexModule = 0; indexModule < this.modules.length; indexModule++ ) { this.modules[indexModule].sortItems(true); } const chunks = this.chunks; for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { chunks[indexChunk].sortItems(); } /** * Used to sort errors and warnings in compilation. this.warnings, and * this.errors contribute to the compilation hash and therefore should be * updated whenever other references (having a chunk id) are sorted. This preserves the hash * integrity * * @param {WebpackError} a first WebpackError instance (including subclasses) * @param {WebpackError} b second WebpackError instance (including subclasses) * @returns {-1|0|1} sort order index */ const byMessage = (a, b) => { const ma = `${a.message}`; const mb = `${b.message}`; if (ma < mb) return -1; if (mb < ma) return 1; return 0; }; this.errors.sort(byMessage); this.warnings.sort(byMessage); this.children.sort(byNameOrHash); } summarizeDependencies() { this.fileDependencies = new SortableSet(this.compilationDependencies); this.contextDependencies = new SortableSet(); this.missingDependencies = new SortableSet(); for ( let indexChildren = 0; indexChildren < this.children.length; indexChildren++ ) { const child = this.children[indexChildren]; addAllToSet(this.fileDependencies, child.fileDependencies); addAllToSet(this.contextDependencies, child.contextDependencies); addAllToSet(this.missingDependencies, child.missingDependencies); } for ( let indexModule = 0; indexModule < this.modules.length; indexModule++ ) { const module = this.modules[indexModule]; if (module.buildInfo.fileDependencies) { addAllToSet(this.fileDependencies, module.buildInfo.fileDependencies); } if (module.buildInfo.contextDependencies) { addAllToSet( this.contextDependencies, module.buildInfo.contextDependencies ); } } for (const error of this.errors) { if ( typeof error.missing === "object" && error.missing && error.missing[Symbol.iterator] ) { addAllToSet(this.missingDependencies, error.missing); } } this.fileDependencies.sort(); this.contextDependencies.sort(); this.missingDependencies.sort(); } createHash() { const outputOptions = this.outputOptions; const hashFunction = outputOptions.hashFunction; const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; const hash = createHash(hashFunction); if (outputOptions.hashSalt) { hash.update(outputOptions.hashSalt); } this.mainTemplate.updateHash(hash); this.chunkTemplate.updateHash(hash); for (const key of Object.keys(this.moduleTemplates).sort()) { this.moduleTemplates[key].updateHash(hash); } for (const child of this.children) { hash.update(child.hash); } for (const warning of this.warnings) { hash.update(`${warning.message}`); } for (const error of this.errors) { hash.update(`${error.message}`); } const modules = this.modules; for (let i = 0; i < modules.length; i++) { const module = modules[i]; const moduleHash = createHash(hashFunction); module.updateHash(moduleHash); module.hash = moduleHash.digest(hashDigest); module.renderedHash = module.hash.substr(0, hashDigestLength); } // clone needed as sort below is inplace mutation const chunks = this.chunks.slice(); /** * sort here will bring all "falsy" values to the beginning * this is needed as the "hasRuntime()" chunks are dependent on the * hashes of the non-runtime chunks. */ chunks.sort((a, b) => { const aEntry = a.hasRuntime(); const bEntry = b.hasRuntime(); if (aEntry && !bEntry) return 1; if (!aEntry && bEntry) return -1; return byId(a, b); }); for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const chunkHash = createHash(hashFunction); try { if (outputOptions.hashSalt) { chunkHash.update(outputOptions.hashSalt); } chunk.updateHash(chunkHash); const template = chunk.hasRuntime() ? this.mainTemplate : this.chunkTemplate; template.updateHashForChunk( chunkHash, chunk, this.moduleTemplates.javascript, this.dependencyTemplates ); this.hooks.chunkHash.call(chunk, chunkHash); chunk.hash = chunkHash.digest(hashDigest); hash.update(chunk.hash); chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); this.hooks.contentHash.call(chunk); } catch (err) { this.errors.push(new ChunkRenderError(chunk, "", err)); } } this.fullHash = hash.digest(hashDigest); this.hash = this.fullHash.substr(0, hashDigestLength); } /** * @param {string} update extra information * @returns {void} */ modifyHash(update) { const outputOptions = this.outputOptions; const hashFunction = outputOptions.hashFunction; const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; const hash = createHash(hashFunction); hash.update(this.fullHash); hash.update(update); this.fullHash = hash.digest(hashDigest); this.hash = this.fullHash.substr(0, hashDigestLength); } createModuleAssets() { for (let i = 0; i < this.modules.length; i++) { const module = this.modules[i]; if (module.buildInfo.assets) { for (const assetName of Object.keys(module.buildInfo.assets)) { const fileName = this.getPath(assetName); this.assets[fileName] = module.buildInfo.assets[assetName]; this.hooks.moduleAsset.call(module, fileName); } } } } createChunkAssets() { const outputOptions = this.outputOptions; const cachedSourceMap = new Map(); /** @type {Map} */ const alreadyWrittenFiles = new Map(); for (let i = 0; i < this.chunks.length; i++) { const chunk = this.chunks[i]; chunk.files = []; let source; let file; let filenameTemplate; try { const template = chunk.hasRuntime() ? this.mainTemplate : this.chunkTemplate; const manifest = template.getRenderManifest({ chunk, hash: this.hash, fullHash: this.fullHash, outputOptions, moduleTemplates: this.moduleTemplates, dependencyTemplates: this.dependencyTemplates }); // [{ render(), filenameTemplate, pathOptions, identifier, hash }] for (const fileManifest of manifest) { const cacheName = fileManifest.identifier; const usedHash = fileManifest.hash; filenameTemplate = fileManifest.filenameTemplate; file = this.getPath(filenameTemplate, fileManifest.pathOptions); // check if the same filename was already written by another chunk const alreadyWritten = alreadyWrittenFiles.get(file); if (alreadyWritten !== undefined) { if (alreadyWritten.hash === usedHash) { if (this.cache) { this.cache[cacheName] = { hash: usedHash, source: alreadyWritten.source }; } chunk.files.push(file); this.hooks.chunkAsset.call(chunk, file); continue; } else { throw new Error( `Conflict: Multiple chunks emit assets to the same filename ${file}` + ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` ); } } if ( this.cache && this.cache[cacheName] && this.cache[cacheName].hash === usedHash ) { source = this.cache[cacheName].source; } else { source = fileManifest.render(); // Ensure that source is a cached source to avoid additional cost because of repeated access if (!(source instanceof CachedSource)) { const cacheEntry = cachedSourceMap.get(source); if (cacheEntry) { source = cacheEntry; } else { const cachedSource = new CachedSource(source); cachedSourceMap.set(source, cachedSource); source = cachedSource; } } if (this.cache) { this.cache[cacheName] = { hash: usedHash, source }; } } if (this.assets[file] && this.assets[file] !== source) { throw new Error( `Conflict: Multiple assets emit to the same filename ${file}` ); } this.assets[file] = source; chunk.files.push(file); this.hooks.chunkAsset.call(chunk, file); alreadyWrittenFiles.set(file, { hash: usedHash, source, chunk }); } } catch (err) { this.errors.push( new ChunkRenderError(chunk, file || filenameTemplate, err) ); } } } /** * @param {string} filename used to get asset path with hash * @param {TODO=} data // TODO: figure out this param type * @returns {string} interpolated path */ getPath(filename, data) { data = data || {}; data.hash = data.hash || this.hash; return this.mainTemplate.getAssetPath(filename, data); } /** * This function allows you to run another instance of webpack inside of webpack however as * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins * from parent (or top level compiler) and creates a child Compilation * * @param {string} name name of the child compiler * @param {TODO} outputOptions // Need to convert config schema to types for this * @param {Plugin[]} plugins webpack plugins that will be applied * @returns {Compiler} creates a child Compiler instance */ createChildCompiler(name, outputOptions, plugins) { const idx = this.childrenCounters[name] || 0; this.childrenCounters[name] = idx + 1; return this.compiler.createChildCompiler( this, name, idx, outputOptions, plugins ); } checkConstraints() { /** @type {Set} */ const usedIds = new Set(); const modules = this.modules; for (let indexModule = 0; indexModule < modules.length; indexModule++) { const moduleId = modules[indexModule].id; if (moduleId === null) continue; if (usedIds.has(moduleId)) { throw new Error(`checkConstraints: duplicate module id ${moduleId}`); } usedIds.add(moduleId); } const chunks = this.chunks; for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const chunk = chunks[indexChunk]; if (chunks.indexOf(chunk) !== indexChunk) { throw new Error( `checkConstraints: duplicate chunk in compilation ${chunk.debugId}` ); } } for (const chunkGroup of this.chunkGroups) { chunkGroup.checkConstraints(); } } } // TODO remove in webpack 5 Compilation.prototype.applyPlugins = util.deprecate( /** * @deprecated * @param {string} name Name * @param {any[]} args Other arguments * @returns {void} * @this {Compilation} */ function(name, ...args) { this.hooks[ name.replace(/[- ]([a-z])/g, match => match[1].toUpperCase()) ].call(...args); }, "Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead" ); // TODO remove in webpack 5 Object.defineProperty(Compilation.prototype, "moduleTemplate", { configurable: false, get: util.deprecate( /** * @deprecated * @this {Compilation} * @returns {TODO} module template */ function() { return this.moduleTemplates.javascript; }, "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead" ), set: util.deprecate( /** * @deprecated * @param {ModuleTemplate} value Template value * @this {Compilation} * @returns {void} */ function(value) { this.moduleTemplates.javascript = value; }, "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead." ) }); module.exports = Compilation; webpack-4.30.0/lib/Compiler.js000066400000000000000000000470231345416772700161160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const parseJson = require("json-parse-better-errors"); const asyncLib = require("neo-async"); const path = require("path"); const { Source } = require("webpack-sources"); const util = require("util"); const { Tapable, SyncHook, SyncBailHook, AsyncParallelHook, AsyncSeriesHook } = require("tapable"); const Compilation = require("./Compilation"); const Stats = require("./Stats"); const Watching = require("./Watching"); const NormalModuleFactory = require("./NormalModuleFactory"); const ContextModuleFactory = require("./ContextModuleFactory"); const ResolverFactory = require("./ResolverFactory"); const RequestShortener = require("./RequestShortener"); const { makePathsRelative } = require("./util/identifier"); const ConcurrentCompilationError = require("./ConcurrentCompilationError"); /** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ /** * @typedef {Object} CompilationParams * @property {NormalModuleFactory} normalModuleFactory * @property {ContextModuleFactory} contextModuleFactory * @property {Set} compilationDependencies */ class Compiler extends Tapable { constructor(context) { super(); this.hooks = { /** @type {SyncBailHook} */ shouldEmit: new SyncBailHook(["compilation"]), /** @type {AsyncSeriesHook} */ done: new AsyncSeriesHook(["stats"]), /** @type {AsyncSeriesHook<>} */ additionalPass: new AsyncSeriesHook([]), /** @type {AsyncSeriesHook} */ beforeRun: new AsyncSeriesHook(["compiler"]), /** @type {AsyncSeriesHook} */ run: new AsyncSeriesHook(["compiler"]), /** @type {AsyncSeriesHook} */ emit: new AsyncSeriesHook(["compilation"]), /** @type {AsyncSeriesHook} */ afterEmit: new AsyncSeriesHook(["compilation"]), /** @type {SyncHook} */ thisCompilation: new SyncHook(["compilation", "params"]), /** @type {SyncHook} */ compilation: new SyncHook(["compilation", "params"]), /** @type {SyncHook} */ normalModuleFactory: new SyncHook(["normalModuleFactory"]), /** @type {SyncHook} */ contextModuleFactory: new SyncHook(["contextModulefactory"]), /** @type {AsyncSeriesHook} */ beforeCompile: new AsyncSeriesHook(["params"]), /** @type {SyncHook} */ compile: new SyncHook(["params"]), /** @type {AsyncParallelHook} */ make: new AsyncParallelHook(["compilation"]), /** @type {AsyncSeriesHook} */ afterCompile: new AsyncSeriesHook(["compilation"]), /** @type {AsyncSeriesHook} */ watchRun: new AsyncSeriesHook(["compiler"]), /** @type {SyncHook} */ failed: new SyncHook(["error"]), /** @type {SyncHook} */ invalid: new SyncHook(["filename", "changeTime"]), /** @type {SyncHook} */ watchClose: new SyncHook([]), // TODO the following hooks are weirdly located here // TODO move them for webpack 5 /** @type {SyncHook} */ environment: new SyncHook([]), /** @type {SyncHook} */ afterEnvironment: new SyncHook([]), /** @type {SyncHook} */ afterPlugins: new SyncHook(["compiler"]), /** @type {SyncHook} */ afterResolvers: new SyncHook(["compiler"]), /** @type {SyncBailHook} */ entryOption: new SyncBailHook(["context", "entry"]) }; this._pluginCompat.tap("Compiler", options => { switch (options.name) { case "additional-pass": case "before-run": case "run": case "emit": case "after-emit": case "before-compile": case "make": case "after-compile": case "watch-run": options.async = true; break; } }); /** @type {string=} */ this.name = undefined; /** @type {Compilation=} */ this.parentCompilation = undefined; /** @type {string} */ this.outputPath = ""; this.outputFileSystem = null; this.inputFileSystem = null; /** @type {string|null} */ this.recordsInputPath = null; /** @type {string|null} */ this.recordsOutputPath = null; this.records = {}; this.removedFiles = new Set(); /** @type {Map} */ this.fileTimestamps = new Map(); /** @type {Map} */ this.contextTimestamps = new Map(); /** @type {ResolverFactory} */ this.resolverFactory = new ResolverFactory(); // TODO remove in webpack 5 this.resolvers = { normal: { plugins: util.deprecate((hook, fn) => { this.resolverFactory.plugin("resolver normal", resolver => { resolver.plugin(hook, fn); }); }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), apply: util.deprecate((...args) => { this.resolverFactory.plugin("resolver normal", resolver => { resolver.apply(...args); }); }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.apply(/* … */);\n}); instead.') }, loader: { plugins: util.deprecate((hook, fn) => { this.resolverFactory.plugin("resolver loader", resolver => { resolver.plugin(hook, fn); }); }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), apply: util.deprecate((...args) => { this.resolverFactory.plugin("resolver loader", resolver => { resolver.apply(...args); }); }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.apply(/* … */);\n}); instead.') }, context: { plugins: util.deprecate((hook, fn) => { this.resolverFactory.plugin("resolver context", resolver => { resolver.plugin(hook, fn); }); }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), apply: util.deprecate((...args) => { this.resolverFactory.plugin("resolver context", resolver => { resolver.apply(...args); }); }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.apply(/* … */);\n}); instead.') } }; /** @type {WebpackOptions} */ this.options = /** @type {WebpackOptions} */ ({}); this.context = context; this.requestShortener = new RequestShortener(context); /** @type {boolean} */ this.running = false; /** @type {boolean} */ this.watchMode = false; /** @private @type {WeakMap }>} */ this._assetEmittingSourceCache = new WeakMap(); /** @private @type {Map} */ this._assetEmittingWrittenFiles = new Map(); } watch(watchOptions, handler) { if (this.running) return handler(new ConcurrentCompilationError()); this.running = true; this.watchMode = true; this.fileTimestamps = new Map(); this.contextTimestamps = new Map(); this.removedFiles = new Set(); return new Watching(this, watchOptions, handler); } run(callback) { if (this.running) return callback(new ConcurrentCompilationError()); const finalCallback = (err, stats) => { this.running = false; if (err) { this.hooks.failed.call(err); } if (callback !== undefined) return callback(err, stats); }; const startTime = Date.now(); this.running = true; const onCompiled = (err, compilation) => { if (err) return finalCallback(err); if (this.hooks.shouldEmit.call(compilation) === false) { const stats = new Stats(compilation); stats.startTime = startTime; stats.endTime = Date.now(); this.hooks.done.callAsync(stats, err => { if (err) return finalCallback(err); return finalCallback(null, stats); }); return; } this.emitAssets(compilation, err => { if (err) return finalCallback(err); if (compilation.hooks.needAdditionalPass.call()) { compilation.needAdditionalPass = true; const stats = new Stats(compilation); stats.startTime = startTime; stats.endTime = Date.now(); this.hooks.done.callAsync(stats, err => { if (err) return finalCallback(err); this.hooks.additionalPass.callAsync(err => { if (err) return finalCallback(err); this.compile(onCompiled); }); }); return; } this.emitRecords(err => { if (err) return finalCallback(err); const stats = new Stats(compilation); stats.startTime = startTime; stats.endTime = Date.now(); this.hooks.done.callAsync(stats, err => { if (err) return finalCallback(err); return finalCallback(null, stats); }); }); }); }; this.hooks.beforeRun.callAsync(this, err => { if (err) return finalCallback(err); this.hooks.run.callAsync(this, err => { if (err) return finalCallback(err); this.readRecords(err => { if (err) return finalCallback(err); this.compile(onCompiled); }); }); }); } runAsChild(callback) { this.compile((err, compilation) => { if (err) return callback(err); this.parentCompilation.children.push(compilation); for (const name of Object.keys(compilation.assets)) { this.parentCompilation.assets[name] = compilation.assets[name]; } const entries = Array.from( compilation.entrypoints.values(), ep => ep.chunks ).reduce((array, chunks) => { return array.concat(chunks); }, []); return callback(null, entries, compilation); }); } purgeInputFileSystem() { if (this.inputFileSystem && this.inputFileSystem.purge) { this.inputFileSystem.purge(); } } emitAssets(compilation, callback) { let outputPath; const emitFiles = err => { if (err) return callback(err); asyncLib.forEachLimit( compilation.assets, 15, (source, file, callback) => { let targetFile = file; const queryStringIdx = targetFile.indexOf("?"); if (queryStringIdx >= 0) { targetFile = targetFile.substr(0, queryStringIdx); } const writeOut = err => { if (err) return callback(err); const targetPath = this.outputFileSystem.join( outputPath, targetFile ); // TODO webpack 5 remove futureEmitAssets option and make it on by default if (this.options.output.futureEmitAssets) { // check if the target file has already been written by this Compiler const targetFileGeneration = this._assetEmittingWrittenFiles.get( targetPath ); // create an cache entry for this Source if not already existing let cacheEntry = this._assetEmittingSourceCache.get(source); if (cacheEntry === undefined) { cacheEntry = { sizeOnlySource: undefined, writtenTo: new Map() }; this._assetEmittingSourceCache.set(source, cacheEntry); } // if the target file has already been written if (targetFileGeneration !== undefined) { // check if the Source has been written to this target file const writtenGeneration = cacheEntry.writtenTo.get(targetPath); if (writtenGeneration === targetFileGeneration) { // if yes, we skip writing the file // as it's already there // (we assume one doesn't remove files while the Compiler is running) return callback(); } } // get the binary (Buffer) content from the Source /** @type {Buffer} */ let content; if (typeof source.buffer === "function") { content = source.buffer(); } else { const bufferOrString = source.source(); if (Buffer.isBuffer(bufferOrString)) { content = bufferOrString; } else { content = Buffer.from(bufferOrString, "utf8"); } } // Create a replacement resource which only allows to ask for size // This allows to GC all memory allocated by the Source // (expect when the Source is stored in any other cache) cacheEntry.sizeOnlySource = new SizeOnlySource(content.length); compilation.assets[file] = cacheEntry.sizeOnlySource; // Write the file to output file system this.outputFileSystem.writeFile(targetPath, content, err => { if (err) return callback(err); // information marker that the asset has been emitted compilation.emittedAssets.add(file); // cache the information that the Source has been written to that location const newGeneration = targetFileGeneration === undefined ? 1 : targetFileGeneration + 1; cacheEntry.writtenTo.set(targetPath, newGeneration); this._assetEmittingWrittenFiles.set(targetPath, newGeneration); callback(); }); } else { if (source.existsAt === targetPath) { source.emitted = false; return callback(); } let content = source.source(); if (!Buffer.isBuffer(content)) { content = Buffer.from(content, "utf8"); } source.existsAt = targetPath; source.emitted = true; this.outputFileSystem.writeFile(targetPath, content, callback); } }; if (targetFile.match(/\/|\\/)) { const dir = path.dirname(targetFile); this.outputFileSystem.mkdirp( this.outputFileSystem.join(outputPath, dir), writeOut ); } else { writeOut(); } }, err => { if (err) return callback(err); this.hooks.afterEmit.callAsync(compilation, err => { if (err) return callback(err); return callback(); }); } ); }; this.hooks.emit.callAsync(compilation, err => { if (err) return callback(err); outputPath = compilation.getPath(this.outputPath); this.outputFileSystem.mkdirp(outputPath, emitFiles); }); } emitRecords(callback) { if (!this.recordsOutputPath) return callback(); const idx1 = this.recordsOutputPath.lastIndexOf("/"); const idx2 = this.recordsOutputPath.lastIndexOf("\\"); let recordsOutputPathDirectory = null; if (idx1 > idx2) { recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); } else if (idx1 < idx2) { recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); } const writeFile = () => { this.outputFileSystem.writeFile( this.recordsOutputPath, JSON.stringify(this.records, undefined, 2), callback ); }; if (!recordsOutputPathDirectory) { return writeFile(); } this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { if (err) return callback(err); writeFile(); }); } readRecords(callback) { if (!this.recordsInputPath) { this.records = {}; return callback(); } this.inputFileSystem.stat(this.recordsInputPath, err => { // It doesn't exist // We can ignore this. if (err) return callback(); this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { if (err) return callback(err); try { this.records = parseJson(content.toString("utf-8")); } catch (e) { e.message = "Cannot parse records: " + e.message; return callback(e); } return callback(); }); }); } createChildCompiler( compilation, compilerName, compilerIndex, outputOptions, plugins ) { const childCompiler = new Compiler(this.context); if (Array.isArray(plugins)) { for (const plugin of plugins) { plugin.apply(childCompiler); } } for (const name in this.hooks) { if ( ![ "make", "compile", "emit", "afterEmit", "invalid", "done", "thisCompilation" ].includes(name) ) { if (childCompiler.hooks[name]) { childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); } } } childCompiler.name = compilerName; childCompiler.outputPath = this.outputPath; childCompiler.inputFileSystem = this.inputFileSystem; childCompiler.outputFileSystem = null; childCompiler.resolverFactory = this.resolverFactory; childCompiler.fileTimestamps = this.fileTimestamps; childCompiler.contextTimestamps = this.contextTimestamps; const relativeCompilerName = makePathsRelative(this.context, compilerName); if (!this.records[relativeCompilerName]) { this.records[relativeCompilerName] = []; } if (this.records[relativeCompilerName][compilerIndex]) { childCompiler.records = this.records[relativeCompilerName][compilerIndex]; } else { this.records[relativeCompilerName].push((childCompiler.records = {})); } childCompiler.options = Object.create(this.options); childCompiler.options.output = Object.create(childCompiler.options.output); for (const name in outputOptions) { childCompiler.options.output[name] = outputOptions[name]; } childCompiler.parentCompilation = compilation; compilation.hooks.childCompiler.call( childCompiler, compilerName, compilerIndex ); return childCompiler; } isChild() { return !!this.parentCompilation; } createCompilation() { return new Compilation(this); } newCompilation(params) { const compilation = this.createCompilation(); compilation.fileTimestamps = this.fileTimestamps; compilation.contextTimestamps = this.contextTimestamps; compilation.name = this.name; compilation.records = this.records; compilation.compilationDependencies = params.compilationDependencies; this.hooks.thisCompilation.call(compilation, params); this.hooks.compilation.call(compilation, params); return compilation; } createNormalModuleFactory() { const normalModuleFactory = new NormalModuleFactory( this.options.context, this.resolverFactory, this.options.module || {} ); this.hooks.normalModuleFactory.call(normalModuleFactory); return normalModuleFactory; } createContextModuleFactory() { const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); this.hooks.contextModuleFactory.call(contextModuleFactory); return contextModuleFactory; } newCompilationParams() { const params = { normalModuleFactory: this.createNormalModuleFactory(), contextModuleFactory: this.createContextModuleFactory(), compilationDependencies: new Set() }; return params; } compile(callback) { const params = this.newCompilationParams(); this.hooks.beforeCompile.callAsync(params, err => { if (err) return callback(err); this.hooks.compile.call(params); const compilation = this.newCompilation(params); this.hooks.make.callAsync(compilation, err => { if (err) return callback(err); compilation.finish(err => { if (err) return callback(err); compilation.seal(err => { if (err) return callback(err); this.hooks.afterCompile.callAsync(compilation, err => { if (err) return callback(err); return callback(null, compilation); }); }); }); }); }); } } module.exports = Compiler; class SizeOnlySource extends Source { constructor(size) { super(); this._size = size; } _error() { return new Error( "Content and Map of this Source is no longer available (only size() is supported)" ); } size() { return this._size; } /** * @param {any} options options * @returns {string} the source */ source(options) { throw this._error(); } node() { throw this._error(); } listMap() { throw this._error(); } map() { throw this._error(); } listNode() { throw this._error(); } updateHash() { throw this._error(); } } webpack-4.30.0/lib/ConcurrentCompilationError.js000066400000000000000000000007541345416772700216770ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Maksim Nazarjev @acupofspirt */ "use strict"; const WebpackError = require("./WebpackError"); module.exports = class ConcurrentCompilationError extends WebpackError { constructor() { super(); this.name = "ConcurrentCompilationError"; this.message = "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/ConstPlugin.js000066400000000000000000000231421345416772700166050ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./dependencies/ConstDependency"); const NullFactory = require("./NullFactory"); const ParserHelpers = require("./ParserHelpers"); const getQuery = request => { const i = request.indexOf("?"); return i !== -1 ? request.substr(i) : ""; }; const collectDeclaration = (declarations, pattern) => { const stack = [pattern]; while (stack.length > 0) { const node = stack.pop(); switch (node.type) { case "Identifier": declarations.add(node.name); break; case "ArrayPattern": for (const element of node.elements) { if (element) { stack.push(element); } } break; case "AssignmentPattern": stack.push(node.left); break; case "ObjectPattern": for (const property of node.properties) { stack.push(property.value); } break; case "RestElement": stack.push(node.argument); break; } } }; const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { const declarations = new Set(); const stack = [branch]; while (stack.length > 0) { const node = stack.pop(); // Some node could be `null` or `undefined`. if (!node) continue; switch (node.type) { // Walk through control statements to look for hoisted declarations. // Some branches are skipped since they do not allow declarations. case "BlockStatement": for (const stmt of node.body) { stack.push(stmt); } break; case "IfStatement": stack.push(node.consequent); stack.push(node.alternate); break; case "ForStatement": stack.push(node.init); stack.push(node.body); break; case "ForInStatement": case "ForOfStatement": stack.push(node.left); stack.push(node.body); break; case "DoWhileStatement": case "WhileStatement": case "LabeledStatement": stack.push(node.body); break; case "SwitchStatement": for (const cs of node.cases) { for (const consequent of cs.consequent) { stack.push(consequent); } } break; case "TryStatement": stack.push(node.block); if (node.handler) { stack.push(node.handler.body); } stack.push(node.finalizer); break; case "FunctionDeclaration": if (includeFunctionDeclarations) { collectDeclaration(declarations, node.id); } break; case "VariableDeclaration": if (node.kind === "var") { for (const decl of node.declarations) { collectDeclaration(declarations, decl.id); } } break; } } return Array.from(declarations); }; class ConstPlugin { apply(compiler) { compiler.hooks.compilation.tap( "ConstPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); const handler = parser => { parser.hooks.statementIf.tap("ConstPlugin", statement => { const param = parser.evaluateExpression(statement.test); const bool = param.asBool(); if (typeof bool === "boolean") { if (statement.test.type !== "Literal") { const dep = new ConstDependency(`${bool}`, param.range); dep.loc = statement.loc; parser.state.current.addDependency(dep); } const branchToRemove = bool ? statement.alternate : statement.consequent; if (branchToRemove) { // Before removing the dead branch, the hoisted declarations // must be collected. // // Given the following code: // // if (true) f() else g() // if (false) { // function f() {} // const g = function g() {} // if (someTest) { // let a = 1 // var x, {y, z} = obj // } // } else { // … // } // // the generated code is: // // if (true) f() else {} // if (false) { // var f, x, y, z; (in loose mode) // var x, y, z; (in strict mode) // } else { // … // } // // NOTE: When code runs in strict mode, `var` declarations // are hoisted but `function` declarations don't. // let declarations; if (parser.scope.isStrict) { // If the code runs in strict mode, variable declarations // using `var` must be hoisted. declarations = getHoistedDeclarations(branchToRemove, false); } else { // Otherwise, collect all hoisted declaration. declarations = getHoistedDeclarations(branchToRemove, true); } let replacement; if (declarations.length > 0) { replacement = `{ var ${declarations.join(", ")}; }`; } else { replacement = "{}"; } const dep = new ConstDependency( replacement, branchToRemove.range ); dep.loc = branchToRemove.loc; parser.state.current.addDependency(dep); } return bool; } }); parser.hooks.expressionConditionalOperator.tap( "ConstPlugin", expression => { const param = parser.evaluateExpression(expression.test); const bool = param.asBool(); if (typeof bool === "boolean") { if (expression.test.type !== "Literal") { const dep = new ConstDependency(` ${bool}`, param.range); dep.loc = expression.loc; parser.state.current.addDependency(dep); } // Expressions do not hoist. // It is safe to remove the dead branch. // // Given the following code: // // false ? someExpression() : otherExpression(); // // the generated code is: // // false ? undefined : otherExpression(); // const branchToRemove = bool ? expression.alternate : expression.consequent; const dep = new ConstDependency( "undefined", branchToRemove.range ); dep.loc = branchToRemove.loc; parser.state.current.addDependency(dep); return bool; } } ); parser.hooks.expressionLogicalOperator.tap( "ConstPlugin", expression => { if ( expression.operator === "&&" || expression.operator === "||" ) { const param = parser.evaluateExpression(expression.left); const bool = param.asBool(); if (typeof bool === "boolean") { // Expressions do not hoist. // It is safe to remove the dead branch. // // ------------------------------------------ // // Given the following code: // // falsyExpression() && someExpression(); // // the generated code is: // // falsyExpression() && false; // // ------------------------------------------ // // Given the following code: // // truthyExpression() && someExpression(); // // the generated code is: // // true && someExpression(); // // ------------------------------------------ // // Given the following code: // // truthyExpression() || someExpression(); // // the generated code is: // // truthyExpression() || false; // // ------------------------------------------ // // Given the following code: // // falsyExpression() || someExpression(); // // the generated code is: // // false && someExpression(); // const keepRight = (expression.operator === "&&" && bool) || (expression.operator === "||" && !bool); if (param.isBoolean() || keepRight) { // for case like // // return'development'===process.env.NODE_ENV&&'foo' // // we need a space before the bool to prevent result like // // returnfalse&&'foo' // const dep = new ConstDependency(` ${bool}`, param.range); dep.loc = expression.loc; parser.state.current.addDependency(dep); } else { parser.walkExpression(expression.left); } if (!keepRight) { const dep = new ConstDependency( "false", expression.right.range ); dep.loc = expression.loc; parser.state.current.addDependency(dep); } return keepRight; } } } ); parser.hooks.evaluateIdentifier .for("__resourceQuery") .tap("ConstPlugin", expr => { if (!parser.state.module) return; return ParserHelpers.evaluateToString( getQuery(parser.state.module.resource) )(expr); }); parser.hooks.expression .for("__resourceQuery") .tap("ConstPlugin", () => { if (!parser.state.module) return; parser.state.current.addVariable( "__resourceQuery", JSON.stringify(getQuery(parser.state.module.resource)) ); return true; }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("ConstPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("ConstPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("ConstPlugin", handler); } ); } } module.exports = ConstPlugin; webpack-4.30.0/lib/ContextExclusionPlugin.js000066400000000000000000000013211345416772700210300ustar00rootroot00000000000000"use strict"; /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ class ContextExclusionPlugin { /** * @param {RegExp} negativeMatcher Matcher regular expression */ constructor(negativeMatcher) { this.negativeMatcher = negativeMatcher; } /** * Apply the plugin * @param {Compiler} compiler Webpack Compiler * @returns {void} */ apply(compiler) { compiler.hooks.contextModuleFactory.tap("ContextExclusionPlugin", cmf => { cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files => { return files.filter(filePath => !this.negativeMatcher.test(filePath)); }); }); } } module.exports = ContextExclusionPlugin; webpack-4.30.0/lib/ContextModule.js000066400000000000000000000600401345416772700171300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const util = require("util"); const { OriginalSource, RawSource } = require("webpack-sources"); const Module = require("./Module"); const AsyncDependenciesBlock = require("./AsyncDependenciesBlock"); const Template = require("./Template"); const contextify = require("./util/identifier").contextify; /** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ /** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ /** * @callback ResolveDependenciesCallback * @param {Error=} err * @param {ContextElementDependency[]} dependencies */ /** * @callback ResolveDependencies * @param {TODO} fs * @param {TODO} options * @param {ResolveDependenciesCallback} callback */ class ContextModule extends Module { // type ContextMode = "sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once" // type ContextOptions = { resource: string, recursive: boolean, regExp: RegExp, addon?: string, mode?: ContextMode, chunkName?: string, include?: RegExp, exclude?: RegExp, groupOptions?: Object } // resolveDependencies: (fs: FS, options: ContextOptions, (err: Error?, dependencies: Dependency[]) => void) => void // options: ContextOptions /** * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context * @param {TODO} options options object */ constructor(resolveDependencies, options) { let resource; let resourceQuery; const queryIdx = options.resource.indexOf("?"); if (queryIdx >= 0) { resource = options.resource.substr(0, queryIdx); resourceQuery = options.resource.substr(queryIdx); } else { resource = options.resource; resourceQuery = ""; } super("javascript/dynamic", resource); // Info from Factory this.resolveDependencies = resolveDependencies; this.options = Object.assign({}, options, { resource: resource, resourceQuery: resourceQuery }); if (options.resolveOptions !== undefined) { this.resolveOptions = options.resolveOptions; } // Info from Build this._contextDependencies = new Set([this.context]); if (typeof options.mode !== "string") { throw new Error("options.mode is a required option"); } this._identifier = this._createIdentifier(); } updateCacheModule(module) { this.resolveDependencies = module.resolveDependencies; this.options = module.options; this.resolveOptions = module.resolveOptions; } prettyRegExp(regexString) { // remove the "/" at the front and the beginning // "/foo/" -> "foo" return regexString.substring(1, regexString.length - 1); } _createIdentifier() { let identifier = this.context; if (this.options.resourceQuery) { identifier += ` ${this.options.resourceQuery}`; } if (this.options.mode) { identifier += ` ${this.options.mode}`; } if (!this.options.recursive) { identifier += " nonrecursive"; } if (this.options.addon) { identifier += ` ${this.options.addon}`; } if (this.options.regExp) { identifier += ` ${this.options.regExp}`; } if (this.options.include) { identifier += ` include: ${this.options.include}`; } if (this.options.exclude) { identifier += ` exclude: ${this.options.exclude}`; } if (this.options.groupOptions) { identifier += ` groupOptions: ${JSON.stringify( this.options.groupOptions )}`; } if (this.options.namespaceObject === "strict") { identifier += " strict namespace object"; } else if (this.options.namespaceObject) { identifier += " namespace object"; } return identifier; } identifier() { return this._identifier; } readableIdentifier(requestShortener) { let identifier = requestShortener.shorten(this.context); if (this.options.resourceQuery) { identifier += ` ${this.options.resourceQuery}`; } if (this.options.mode) { identifier += ` ${this.options.mode}`; } if (!this.options.recursive) { identifier += " nonrecursive"; } if (this.options.addon) { identifier += ` ${requestShortener.shorten(this.options.addon)}`; } if (this.options.regExp) { identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; } if (this.options.include) { identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; } if (this.options.exclude) { identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; } if (this.options.groupOptions) { const groupOptions = this.options.groupOptions; for (const key of Object.keys(groupOptions)) { identifier += ` ${key}: ${groupOptions[key]}`; } } if (this.options.namespaceObject === "strict") { identifier += " strict namespace object"; } else if (this.options.namespaceObject) { identifier += " namespace object"; } return identifier; } libIdent(options) { let identifier = contextify(options.context, this.context); if (this.options.mode) { identifier += ` ${this.options.mode}`; } if (this.options.recursive) { identifier += " recursive"; } if (this.options.addon) { identifier += ` ${contextify(options.context, this.options.addon)}`; } if (this.options.regExp) { identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; } if (this.options.include) { identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; } if (this.options.exclude) { identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; } return identifier; } needRebuild(fileTimestamps, contextTimestamps) { const ts = contextTimestamps.get(this.context); if (!ts) { return true; } return ts >= this.buildInfo.builtTime; } build(options, compilation, resolver, fs, callback) { this.built = true; this.buildMeta = {}; this.buildInfo = { builtTime: Date.now(), contextDependencies: this._contextDependencies }; this.resolveDependencies(fs, this.options, (err, dependencies) => { if (err) return callback(err); // abort if something failed // this will create an empty context if (!dependencies) { callback(); return; } // enhance dependencies with meta info for (const dep of dependencies) { dep.loc = { name: dep.userRequest }; dep.request = this.options.addon + dep.request; } if (this.options.mode === "sync" || this.options.mode === "eager") { // if we have an sync or eager context // just add all dependencies and continue this.dependencies = dependencies; } else if (this.options.mode === "lazy-once") { // for the lazy-once mode create a new async dependency block // and add that block to this context if (dependencies.length > 0) { const block = new AsyncDependenciesBlock( Object.assign({}, this.options.groupOptions, { name: this.options.chunkName }), this ); for (const dep of dependencies) { block.addDependency(dep); } this.addBlock(block); } } else if ( this.options.mode === "weak" || this.options.mode === "async-weak" ) { // we mark all dependencies as weak for (const dep of dependencies) { dep.weak = true; } this.dependencies = dependencies; } else if (this.options.mode === "lazy") { // if we are lazy create a new async dependency block per dependency // and add all blocks to this context let index = 0; for (const dep of dependencies) { let chunkName = this.options.chunkName; if (chunkName) { if (!/\[(index|request)\]/.test(chunkName)) { chunkName += "[index]"; } chunkName = chunkName.replace(/\[index\]/g, index++); chunkName = chunkName.replace( /\[request\]/g, Template.toPath(dep.userRequest) ); } const block = new AsyncDependenciesBlock( Object.assign({}, this.options.groupOptions, { name: chunkName }), dep.module, dep.loc, dep.userRequest ); block.addDependency(dep); this.addBlock(block); } } else { callback( new Error(`Unsupported mode "${this.options.mode}" in context`) ); return; } callback(); }); } getUserRequestMap(dependencies) { // if we filter first we get a new array // therefor we dont need to create a clone of dependencies explicitly // therefore the order of this is !important! return dependencies .filter(dependency => dependency.module) .sort((a, b) => { if (a.userRequest === b.userRequest) { return 0; } return a.userRequest < b.userRequest ? -1 : 1; }) .reduce((map, dep) => { map[dep.userRequest] = dep.module.id; return map; }, Object.create(null)); } getFakeMap(dependencies) { if (!this.options.namespaceObject) { return 9; } // if we filter first we get a new array // therefor we dont need to create a clone of dependencies explicitly // therefore the order of this is !important! let hasNonHarmony = false; let hasNamespace = false; let hasNamed = false; const fakeMap = dependencies .filter(dependency => dependency.module) .sort((a, b) => { return b.module.id - a.module.id; }) .reduce((map, dep) => { const exportsType = dep.module.buildMeta && dep.module.buildMeta.exportsType; const id = dep.module.id; if (!exportsType) { map[id] = this.options.namespaceObject === "strict" ? 1 : 7; hasNonHarmony = true; } else if (exportsType === "namespace") { map[id] = 9; hasNamespace = true; } else if (exportsType === "named") { map[id] = 3; hasNamed = true; } return map; }, Object.create(null)); if (!hasNamespace && hasNonHarmony && !hasNamed) { return this.options.namespaceObject === "strict" ? 1 : 7; } if (hasNamespace && !hasNonHarmony && !hasNamed) { return 9; } if (!hasNamespace && !hasNonHarmony && hasNamed) { return 3; } if (!hasNamespace && !hasNonHarmony && !hasNamed) { return 9; } return fakeMap; } getFakeMapInitStatement(fakeMap) { return typeof fakeMap === "object" ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` : ""; } getReturn(type) { if (type === 9) { return "__webpack_require__(id)"; } return `__webpack_require__.t(id, ${type})`; } getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") { if (typeof fakeMap === "number") { return `return ${this.getReturn(fakeMap)};`; } return `return __webpack_require__.t(id, ${fakeMapDataExpression})`; } getSyncSource(dependencies, id) { const map = this.getUserRequestMap(dependencies); const fakeMap = this.getFakeMap(dependencies); const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); return `var map = ${JSON.stringify(map, null, "\t")}; ${this.getFakeMapInitStatement(fakeMap)} function webpackContext(req) { var id = webpackContextResolve(req); ${returnModuleObject} } function webpackContextResolve(req) { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = ${JSON.stringify(id)};`; } getWeakSyncSource(dependencies, id) { const map = this.getUserRequestMap(dependencies); const fakeMap = this.getFakeMap(dependencies); const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); return `var map = ${JSON.stringify(map, null, "\t")}; ${this.getFakeMapInitStatement(fakeMap)} function webpackContext(req) { var id = webpackContextResolve(req); if(!__webpack_require__.m[id]) { var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); e.code = 'MODULE_NOT_FOUND'; throw e; } ${returnModuleObject} } function webpackContextResolve(req) { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; webpackContext.id = ${JSON.stringify(id)}; module.exports = webpackContext;`; } getAsyncWeakSource(dependencies, id) { const map = this.getUserRequestMap(dependencies); const fakeMap = this.getFakeMap(dependencies); const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); return `var map = ${JSON.stringify(map, null, "\t")}; ${this.getFakeMapInitStatement(fakeMap)} function webpackAsyncContext(req) { return webpackAsyncContextResolve(req).then(function(id) { if(!__webpack_require__.m[id]) { var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); e.code = 'MODULE_NOT_FOUND'; throw e; } ${returnModuleObject} }); } function webpackAsyncContextResolve(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncaught exception popping up in devtools return Promise.resolve().then(function() { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.resolve = webpackAsyncContextResolve; webpackAsyncContext.id = ${JSON.stringify(id)}; module.exports = webpackAsyncContext;`; } getEagerSource(dependencies, id) { const map = this.getUserRequestMap(dependencies); const fakeMap = this.getFakeMap(dependencies); const thenFunction = fakeMap !== 9 ? `function(id) { ${this.getReturnModuleObjectSource(fakeMap)} }` : "__webpack_require__"; return `var map = ${JSON.stringify(map, null, "\t")}; ${this.getFakeMapInitStatement(fakeMap)} function webpackAsyncContext(req) { return webpackAsyncContextResolve(req).then(${thenFunction}); } function webpackAsyncContextResolve(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncaught exception popping up in devtools return Promise.resolve().then(function() { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.resolve = webpackAsyncContextResolve; webpackAsyncContext.id = ${JSON.stringify(id)}; module.exports = webpackAsyncContext;`; } getLazyOnceSource(block, dependencies, id, runtimeTemplate) { const promise = runtimeTemplate.blockPromise({ block, message: "lazy-once context" }); const map = this.getUserRequestMap(dependencies); const fakeMap = this.getFakeMap(dependencies); const thenFunction = fakeMap !== 9 ? `function(id) { ${this.getReturnModuleObjectSource(fakeMap)}; }` : "__webpack_require__"; return `var map = ${JSON.stringify(map, null, "\t")}; ${this.getFakeMapInitStatement(fakeMap)} function webpackAsyncContext(req) { return webpackAsyncContextResolve(req).then(${thenFunction}); } function webpackAsyncContextResolve(req) { return ${promise}.then(function() { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return map[req]; }); } webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.resolve = webpackAsyncContextResolve; webpackAsyncContext.id = ${JSON.stringify(id)}; module.exports = webpackAsyncContext;`; } getLazySource(blocks, id) { let hasMultipleOrNoChunks = false; let hasNoChunk = true; const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0])); const hasFakeMap = typeof fakeMap === "object"; const map = blocks .filter(block => block.dependencies[0].module) .map(block => { const chunks = block.chunkGroup ? block.chunkGroup.chunks : []; if (chunks.length > 0) { hasNoChunk = false; } if (chunks.length !== 1) { hasMultipleOrNoChunks = true; } return { dependency: block.dependencies[0], block: block, userRequest: block.dependencies[0].userRequest, chunks }; }) .sort((a, b) => { if (a.userRequest === b.userRequest) return 0; return a.userRequest < b.userRequest ? -1 : 1; }) .reduce((map, item) => { const chunks = item.chunks; if (hasNoChunk && !hasFakeMap) { map[item.userRequest] = item.dependency.module.id; } else { const arrayStart = [item.dependency.module.id]; if (typeof fakeMap === "object") { arrayStart.push(fakeMap[item.dependency.module.id]); } map[item.userRequest] = arrayStart.concat( chunks.map(chunk => chunk.id) ); } return map; }, Object.create(null)); const shortMode = hasNoChunk && !hasFakeMap; const chunksStartPosition = hasFakeMap ? 2 : 1; const requestPrefix = hasNoChunk ? "Promise.resolve()" : hasMultipleOrNoChunks ? `Promise.all(ids.slice(${chunksStartPosition}).map(__webpack_require__.e))` : `__webpack_require__.e(ids[${chunksStartPosition}])`; const returnModuleObject = this.getReturnModuleObjectSource( fakeMap, shortMode ? "invalid" : "ids[1]" ); const webpackAsyncContext = requestPrefix === "Promise.resolve()" ? `${shortMode ? "" : ""} function webpackAsyncContext(req) { return Promise.resolve().then(function() { if(!__webpack_require__.o(map, req)) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} ${returnModuleObject} }); }` : `function webpackAsyncContext(req) { if(!__webpack_require__.o(map, req)) { return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } var ids = map[req], id = ids[0]; return ${requestPrefix}.then(function() { ${returnModuleObject} }); }`; return `var map = ${JSON.stringify(map, null, "\t")}; ${webpackAsyncContext} webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = ${JSON.stringify(id)}; module.exports = webpackAsyncContext;`; } getSourceForEmptyContext(id) { return `function webpackEmptyContext(req) { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } webpackEmptyContext.keys = function() { return []; }; webpackEmptyContext.resolve = webpackEmptyContext; module.exports = webpackEmptyContext; webpackEmptyContext.id = ${JSON.stringify(id)};`; } getSourceForEmptyAsyncContext(id) { return `function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncaught exception popping up in devtools return Promise.resolve().then(function() { var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`; } getSourceString(asyncMode, runtimeTemplate) { if (asyncMode === "lazy") { if (this.blocks && this.blocks.length > 0) { return this.getLazySource(this.blocks, this.id); } return this.getSourceForEmptyAsyncContext(this.id); } if (asyncMode === "eager") { if (this.dependencies && this.dependencies.length > 0) { return this.getEagerSource(this.dependencies, this.id); } return this.getSourceForEmptyAsyncContext(this.id); } if (asyncMode === "lazy-once") { const block = this.blocks[0]; if (block) { return this.getLazyOnceSource( block, block.dependencies, this.id, runtimeTemplate ); } return this.getSourceForEmptyAsyncContext(this.id); } if (asyncMode === "async-weak") { if (this.dependencies && this.dependencies.length > 0) { return this.getAsyncWeakSource(this.dependencies, this.id); } return this.getSourceForEmptyAsyncContext(this.id); } if (asyncMode === "weak") { if (this.dependencies && this.dependencies.length > 0) { return this.getWeakSyncSource(this.dependencies, this.id); } } if (this.dependencies && this.dependencies.length > 0) { return this.getSyncSource(this.dependencies, this.id); } return this.getSourceForEmptyContext(this.id); } getSource(sourceString) { if (this.useSourceMap) { return new OriginalSource(sourceString, this.identifier()); } return new RawSource(sourceString); } source(dependencyTemplates, runtimeTemplate) { return this.getSource( this.getSourceString(this.options.mode, runtimeTemplate) ); } size() { // base penalty const initialSize = 160; // if we dont have dependencies we stop here. return this.dependencies.reduce((size, dependency) => { const element = /** @type {ContextElementDependency} */ (dependency); return size + 5 + element.userRequest.length; }, initialSize); } } // TODO remove in webpack 5 Object.defineProperty(ContextModule.prototype, "recursive", { configurable: false, get: util.deprecate( /** * @deprecated * @this {ContextModule} * @returns {boolean} is recursive */ function() { return this.options.recursive; }, "ContextModule.recursive has been moved to ContextModule.options.recursive" ), set: util.deprecate( /** * @deprecated * @this {ContextModule} * @param {boolean} value is recursive * @returns {void} */ function(value) { this.options.recursive = value; }, "ContextModule.recursive has been moved to ContextModule.options.recursive" ) }); // TODO remove in webpack 5 Object.defineProperty(ContextModule.prototype, "regExp", { configurable: false, get: util.deprecate( /** * @deprecated * @this {ContextModule} * @returns {RegExp} regular expression */ function() { return this.options.regExp; }, "ContextModule.regExp has been moved to ContextModule.options.regExp" ), set: util.deprecate( /** * @deprecated * @this {ContextModule} * @param {RegExp} value Regular expression * @returns {void} */ function(value) { this.options.regExp = value; }, "ContextModule.regExp has been moved to ContextModule.options.regExp" ) }); // TODO remove in webpack 5 Object.defineProperty(ContextModule.prototype, "addon", { configurable: false, get: util.deprecate( /** * @deprecated * @this {ContextModule} * @returns {string} addon */ function() { return this.options.addon; }, "ContextModule.addon has been moved to ContextModule.options.addon" ), set: util.deprecate( /** * @deprecated * @this {ContextModule} * @param {string} value addon * @returns {void} */ function(value) { this.options.addon = value; }, "ContextModule.addon has been moved to ContextModule.options.addon" ) }); // TODO remove in webpack 5 Object.defineProperty(ContextModule.prototype, "async", { configurable: false, get: util.deprecate( /** * @deprecated * @this {ContextModule} * @returns {boolean} is async */ function() { return this.options.mode; }, "ContextModule.async has been moved to ContextModule.options.mode" ), set: util.deprecate( /** * @deprecated * @this {ContextModule} * @param {ContextMode} value Context mode * @returns {void} */ function(value) { this.options.mode = value; }, "ContextModule.async has been moved to ContextModule.options.mode" ) }); // TODO remove in webpack 5 Object.defineProperty(ContextModule.prototype, "chunkName", { configurable: false, get: util.deprecate( /** * @deprecated * @this {ContextModule} * @returns {string} chunk name */ function() { return this.options.chunkName; }, "ContextModule.chunkName has been moved to ContextModule.options.chunkName" ), set: util.deprecate( /** * @deprecated * @this {ContextModule} * @param {string} value chunk name * @returns {void} */ function(value) { this.options.chunkName = value; }, "ContextModule.chunkName has been moved to ContextModule.options.chunkName" ) }); module.exports = ContextModule; webpack-4.30.0/lib/ContextModuleFactory.js000066400000000000000000000147211345416772700204650ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("neo-async"); const path = require("path"); const { Tapable, AsyncSeriesWaterfallHook, SyncWaterfallHook } = require("tapable"); const ContextModule = require("./ContextModule"); const ContextElementDependency = require("./dependencies/ContextElementDependency"); /** @typedef {import("./Module")} Module */ const EMPTY_RESOLVE_OPTIONS = {}; module.exports = class ContextModuleFactory extends Tapable { constructor(resolverFactory) { super(); this.hooks = { /** @type {AsyncSeriesWaterfallHook} */ beforeResolve: new AsyncSeriesWaterfallHook(["data"]), /** @type {AsyncSeriesWaterfallHook} */ afterResolve: new AsyncSeriesWaterfallHook(["data"]), /** @type {SyncWaterfallHook} */ contextModuleFiles: new SyncWaterfallHook(["files"]), /** @type {SyncWaterfallHook} */ alternatives: new AsyncSeriesWaterfallHook(["modules"]) }; this._pluginCompat.tap("ContextModuleFactory", options => { switch (options.name) { case "before-resolve": case "after-resolve": case "alternatives": options.async = true; break; } }); this.resolverFactory = resolverFactory; } create(data, callback) { const context = data.context; const dependencies = data.dependencies; const resolveOptions = data.resolveOptions; const dependency = dependencies[0]; this.hooks.beforeResolve.callAsync( Object.assign( { context: context, dependencies: dependencies, resolveOptions }, dependency.options ), (err, beforeResolveResult) => { if (err) return callback(err); // Ignored if (!beforeResolveResult) return callback(); const context = beforeResolveResult.context; const request = beforeResolveResult.request; const resolveOptions = beforeResolveResult.resolveOptions; let loaders, resource, loadersPrefix = ""; const idx = request.lastIndexOf("!"); if (idx >= 0) { let loadersRequest = request.substr(0, idx + 1); let i; for ( i = 0; i < loadersRequest.length && loadersRequest[i] === "!"; i++ ) { loadersPrefix += "!"; } loadersRequest = loadersRequest .substr(i) .replace(/!+$/, "") .replace(/!!+/g, "!"); if (loadersRequest === "") { loaders = []; } else { loaders = loadersRequest.split("!"); } resource = request.substr(idx + 1); } else { loaders = []; resource = request; } const contextResolver = this.resolverFactory.get( "context", resolveOptions || EMPTY_RESOLVE_OPTIONS ); const loaderResolver = this.resolverFactory.get( "loader", EMPTY_RESOLVE_OPTIONS ); asyncLib.parallel( [ callback => { contextResolver.resolve( {}, context, resource, {}, (err, result) => { if (err) return callback(err); callback(null, result); } ); }, callback => { asyncLib.map( loaders, (loader, callback) => { loaderResolver.resolve( {}, context, loader, {}, (err, result) => { if (err) return callback(err); callback(null, result); } ); }, callback ); } ], (err, result) => { if (err) return callback(err); this.hooks.afterResolve.callAsync( Object.assign( { addon: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""), resource: result[0], resolveDependencies: this.resolveDependencies.bind(this) }, beforeResolveResult ), (err, result) => { if (err) return callback(err); // Ignored if (!result) return callback(); return callback( null, new ContextModule(result.resolveDependencies, result) ); } ); } ); } ); } resolveDependencies(fs, options, callback) { const cmf = this; let resource = options.resource; let resourceQuery = options.resourceQuery; let recursive = options.recursive; let regExp = options.regExp; let include = options.include; let exclude = options.exclude; if (!regExp || !resource) return callback(null, []); const addDirectory = (directory, callback) => { fs.readdir(directory, (err, files) => { if (err) return callback(err); files = cmf.hooks.contextModuleFiles.call(files); if (!files || files.length === 0) return callback(null, []); asyncLib.map( files.filter(p => p.indexOf(".") !== 0), (segment, callback) => { const subResource = path.join(directory, segment); if (!exclude || !subResource.match(exclude)) { fs.stat(subResource, (err, stat) => { if (err) { if (err.code === "ENOENT") { // ENOENT is ok here because the file may have been deleted between // the readdir and stat calls. return callback(); } else { return callback(err); } } if (stat.isDirectory()) { if (!recursive) return callback(); addDirectory.call(this, subResource, callback); } else if ( stat.isFile() && (!include || subResource.match(include)) ) { const obj = { context: resource, request: "." + subResource.substr(resource.length).replace(/\\/g, "/") }; this.hooks.alternatives.callAsync( [obj], (err, alternatives) => { if (err) return callback(err); alternatives = alternatives .filter(obj => regExp.test(obj.request)) .map(obj => { const dep = new ContextElementDependency( obj.request + resourceQuery, obj.request ); dep.optional = true; return dep; }); callback(null, alternatives); } ); } else { callback(); } }); } else { callback(); } }, (err, result) => { if (err) return callback(err); if (!result) return callback(null, []); callback( null, result.filter(Boolean).reduce((a, i) => a.concat(i), []) ); } ); }); }; addDirectory(resource, callback); } }; webpack-4.30.0/lib/ContextReplacementPlugin.js000066400000000000000000000100331345416772700213160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const ContextElementDependency = require("./dependencies/ContextElementDependency"); class ContextReplacementPlugin { constructor( resourceRegExp, newContentResource, newContentRecursive, newContentRegExp ) { this.resourceRegExp = resourceRegExp; if (typeof newContentResource === "function") { this.newContentCallback = newContentResource; } else if ( typeof newContentResource === "string" && typeof newContentRecursive === "object" ) { this.newContentResource = newContentResource; this.newContentCreateContextMap = (fs, callback) => { callback(null, newContentRecursive); }; } else if ( typeof newContentResource === "string" && typeof newContentRecursive === "function" ) { this.newContentResource = newContentResource; this.newContentCreateContextMap = newContentRecursive; } else { if (typeof newContentResource !== "string") { newContentRegExp = newContentRecursive; newContentRecursive = newContentResource; newContentResource = undefined; } if (typeof newContentRecursive !== "boolean") { newContentRegExp = newContentRecursive; newContentRecursive = undefined; } this.newContentResource = newContentResource; this.newContentRecursive = newContentRecursive; this.newContentRegExp = newContentRegExp; } } apply(compiler) { const resourceRegExp = this.resourceRegExp; const newContentCallback = this.newContentCallback; const newContentResource = this.newContentResource; const newContentRecursive = this.newContentRecursive; const newContentRegExp = this.newContentRegExp; const newContentCreateContextMap = this.newContentCreateContextMap; compiler.hooks.contextModuleFactory.tap("ContextReplacementPlugin", cmf => { cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => { if (!result) return; if (resourceRegExp.test(result.request)) { if (newContentResource !== undefined) { result.request = newContentResource; } if (newContentRecursive !== undefined) { result.recursive = newContentRecursive; } if (newContentRegExp !== undefined) { result.regExp = newContentRegExp; } if (typeof newContentCallback === "function") { newContentCallback(result); } else { for (const d of result.dependencies) { if (d.critical) d.critical = false; } } } return result; }); cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => { if (!result) return; if (resourceRegExp.test(result.resource)) { if (newContentResource !== undefined) { result.resource = path.resolve(result.resource, newContentResource); } if (newContentRecursive !== undefined) { result.recursive = newContentRecursive; } if (newContentRegExp !== undefined) { result.regExp = newContentRegExp; } if (typeof newContentCreateContextMap === "function") { result.resolveDependencies = createResolveDependenciesFromContextMap( newContentCreateContextMap ); } if (typeof newContentCallback === "function") { const origResource = result.resource; newContentCallback(result); if (result.resource !== origResource) { result.resource = path.resolve(origResource, result.resource); } } else { for (const d of result.dependencies) { if (d.critical) d.critical = false; } } } return result; }); }); } } const createResolveDependenciesFromContextMap = createContextMap => { const resolveDependenciesFromContextMap = (fs, options, callback) => { createContextMap(fs, (err, map) => { if (err) return callback(err); const dependencies = Object.keys(map).map(key => { return new ContextElementDependency( map[key] + options.resourceQuery, key ); }); callback(null, dependencies); }); }; return resolveDependenciesFromContextMap; }; module.exports = ContextReplacementPlugin; webpack-4.30.0/lib/DefinePlugin.js000066400000000000000000000176341345416772700167220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./dependencies/ConstDependency"); const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); const ParserHelpers = require("./ParserHelpers"); const NullFactory = require("./NullFactory"); /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Parser")} Parser */ /** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */ /** @typedef {CodeValuePrimitive|Record|RuntimeValue} CodeValue */ class RuntimeValue { constructor(fn, fileDependencies) { this.fn = fn; this.fileDependencies = fileDependencies || []; } exec(parser) { if (this.fileDependencies === true) { parser.state.module.buildInfo.cacheable = false; } else { for (const fileDependency of this.fileDependencies) { parser.state.module.buildInfo.fileDependencies.add(fileDependency); } } return this.fn({ module: parser.state.module }); } } const stringifyObj = (obj, parser) => { return ( "Object({" + Object.keys(obj) .map(key => { const code = obj[key]; return JSON.stringify(key) + ":" + toCode(code, parser); }) .join(",") + "})" ); }; /** * Convert code to a string that evaluates * @param {CodeValue} code Code to evaluate * @param {Parser} parser Parser * @returns {string} code converted to string that evaluates */ const toCode = (code, parser) => { if (code === null) { return "null"; } if (code === undefined) { return "undefined"; } if (code instanceof RuntimeValue) { return toCode(code.exec(parser), parser); } if (code instanceof RegExp && code.toString) { return code.toString(); } if (typeof code === "function" && code.toString) { return "(" + code.toString() + ")"; } if (typeof code === "object") { return stringifyObj(code, parser); } return code + ""; }; class DefinePlugin { /** * Create a new define plugin * @param {Record} definitions A map of global object definitions */ constructor(definitions) { this.definitions = definitions; } static runtimeValue(fn, fileDependencies) { return new RuntimeValue(fn, fileDependencies); } /** * Apply the plugin * @param {Compiler} compiler Webpack compiler * @returns {void} */ apply(compiler) { const definitions = this.definitions; compiler.hooks.compilation.tap( "DefinePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); /** * Handler * @param {Parser} parser Parser * @returns {void} */ const handler = parser => { /** * Walk definitions * @param {Object} definitions Definitions map * @param {string} prefix Prefix string * @returns {void} */ const walkDefinitions = (definitions, prefix) => { Object.keys(definitions).forEach(key => { const code = definitions[key]; if ( code && typeof code === "object" && !(code instanceof RuntimeValue) && !(code instanceof RegExp) ) { walkDefinitions(code, prefix + key + "."); applyObjectDefine(prefix + key, code); return; } applyDefineKey(prefix, key); applyDefine(prefix + key, code); }); }; /** * Apply define key * @param {string} prefix Prefix * @param {string} key Key * @returns {void} */ const applyDefineKey = (prefix, key) => { const splittedKey = key.split("."); splittedKey.slice(1).forEach((_, i) => { const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); parser.hooks.canRename .for(fullKey) .tap("DefinePlugin", ParserHelpers.approve); }); }; /** * Apply Code * @param {string} key Key * @param {CodeValue} code Code * @returns {void} */ const applyDefine = (key, code) => { const isTypeof = /^typeof\s+/.test(key); if (isTypeof) key = key.replace(/^typeof\s+/, ""); let recurse = false; let recurseTypeof = false; if (!isTypeof) { parser.hooks.canRename .for(key) .tap("DefinePlugin", ParserHelpers.approve); parser.hooks.evaluateIdentifier .for(key) .tap("DefinePlugin", expr => { /** * this is needed in case there is a recursion in the DefinePlugin * to prevent an endless recursion * e.g.: new DefinePlugin({ * "a": "b", * "b": "a" * }); */ if (recurse) return; recurse = true; const res = parser.evaluate(toCode(code, parser)); recurse = false; res.setRange(expr.range); return res; }); parser.hooks.expression.for(key).tap("DefinePlugin", expr => { const strCode = toCode(code, parser); if (/__webpack_require__/.test(strCode)) { return ParserHelpers.toConstantDependencyWithWebpackRequire( parser, strCode )(expr); } else { return ParserHelpers.toConstantDependency(parser, strCode)( expr ); } }); } parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { /** * this is needed in case there is a recursion in the DefinePlugin * to prevent an endless recursion * e.g.: new DefinePlugin({ * "typeof a": "typeof b", * "typeof b": "typeof a" * }); */ if (recurseTypeof) return; recurseTypeof = true; const typeofCode = isTypeof ? toCode(code, parser) : "typeof (" + toCode(code, parser) + ")"; const res = parser.evaluate(typeofCode); recurseTypeof = false; res.setRange(expr.range); return res; }); parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { const typeofCode = isTypeof ? toCode(code, parser) : "typeof (" + toCode(code, parser) + ")"; const res = parser.evaluate(typeofCode); if (!res.isString()) return; return ParserHelpers.toConstantDependency( parser, JSON.stringify(res.string) ).bind(parser)(expr); }); }; /** * Apply Object * @param {string} key Key * @param {Object} obj Object * @returns {void} */ const applyObjectDefine = (key, obj) => { parser.hooks.canRename .for(key) .tap("DefinePlugin", ParserHelpers.approve); parser.hooks.evaluateIdentifier .for(key) .tap("DefinePlugin", expr => new BasicEvaluatedExpression().setTruthy().setRange(expr.range) ); parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { return ParserHelpers.evaluateToString("object")(expr); }); parser.hooks.expression.for(key).tap("DefinePlugin", expr => { const strCode = stringifyObj(obj, parser); if (/__webpack_require__/.test(strCode)) { return ParserHelpers.toConstantDependencyWithWebpackRequire( parser, strCode )(expr); } else { return ParserHelpers.toConstantDependency(parser, strCode)( expr ); } }); parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { return ParserHelpers.toConstantDependency( parser, JSON.stringify("object") )(expr); }); }; walkDefinitions(definitions, ""); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("DefinePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("DefinePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("DefinePlugin", handler); } ); } } module.exports = DefinePlugin; webpack-4.30.0/lib/DelegatedModule.js000066400000000000000000000054271345416772700173720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { OriginalSource, RawSource } = require("webpack-sources"); const Module = require("./Module"); const WebpackMissingModule = require("./dependencies/WebpackMissingModule"); const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); /** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ /** @typedef {import("./util/createHash").Hash} Hash */ class DelegatedModule extends Module { constructor(sourceRequest, data, type, userRequest, originalRequest) { super("javascript/dynamic", null); // Info from Factory this.sourceRequest = sourceRequest; this.request = data.id; this.type = type; this.userRequest = userRequest; this.originalRequest = originalRequest; this.delegateData = data; // Build info this.delegatedSourceDependency = undefined; } libIdent(options) { return typeof this.originalRequest === "string" ? this.originalRequest : this.originalRequest.libIdent(options); } identifier() { return `delegated ${JSON.stringify(this.request)} from ${ this.sourceRequest }`; } readableIdentifier() { return `delegated ${this.userRequest} from ${this.sourceRequest}`; } needRebuild() { return false; } build(options, compilation, resolver, fs, callback) { this.built = true; this.buildMeta = Object.assign({}, this.delegateData.buildMeta); this.buildInfo = {}; this.delegatedSourceDependency = new DelegatedSourceDependency( this.sourceRequest ); this.addDependency(this.delegatedSourceDependency); this.addDependency( new DelegatedExportsDependency(this, this.delegateData.exports || true) ); callback(); } source(depTemplates, runtime) { const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); const sourceModule = dep.module; let str; if (!sourceModule) { str = WebpackMissingModule.moduleCode(this.sourceRequest); } else { str = `module.exports = (${runtime.moduleExports({ module: sourceModule, request: dep.request })})`; switch (this.type) { case "require": str += `(${JSON.stringify(this.request)})`; break; case "object": str += `[${JSON.stringify(this.request)}]`; break; } str += ";"; } if (this.useSourceMap) { return new OriginalSource(str, this.identifier()); } else { return new RawSource(str); } } size() { return 42; } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { hash.update(this.type); hash.update(JSON.stringify(this.request)); super.updateHash(hash); } } module.exports = DelegatedModule; webpack-4.30.0/lib/DelegatedModuleFactoryPlugin.js000066400000000000000000000045041345416772700220740ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DelegatedModule = require("./DelegatedModule"); // options.source // options.type // options.context // options.scope // options.content class DelegatedModuleFactoryPlugin { constructor(options) { this.options = options; options.type = options.type || "require"; options.extensions = options.extensions || [ "", ".wasm", ".mjs", ".js", ".json" ]; } apply(normalModuleFactory) { const scope = this.options.scope; if (scope) { normalModuleFactory.hooks.factory.tap( "DelegatedModuleFactoryPlugin", factory => (data, callback) => { const dependency = data.dependencies[0]; const request = dependency.request; if (request && request.indexOf(scope + "/") === 0) { const innerRequest = "." + request.substr(scope.length); let resolved; if (innerRequest in this.options.content) { resolved = this.options.content[innerRequest]; return callback( null, new DelegatedModule( this.options.source, resolved, this.options.type, innerRequest, request ) ); } for (let i = 0; i < this.options.extensions.length; i++) { const extension = this.options.extensions[i]; const requestPlusExt = innerRequest + extension; if (requestPlusExt in this.options.content) { resolved = this.options.content[requestPlusExt]; return callback( null, new DelegatedModule( this.options.source, resolved, this.options.type, requestPlusExt, request + extension ) ); } } } return factory(data, callback); } ); } else { normalModuleFactory.hooks.module.tap( "DelegatedModuleFactoryPlugin", module => { if (module.libIdent) { const request = module.libIdent(this.options); if (request && request in this.options.content) { const resolved = this.options.content[request]; return new DelegatedModule( this.options.source, resolved, this.options.type, request, module ); } } return module; } ); } } } module.exports = DelegatedModuleFactoryPlugin; webpack-4.30.0/lib/DelegatedPlugin.js000066400000000000000000000020221345416772700173670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); const NullFactory = require("./NullFactory"); class DelegatedPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.hooks.compilation.tap( "DelegatedPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( DelegatedSourceDependency, normalModuleFactory ); compilation.dependencyFactories.set( DelegatedExportsDependency, new NullFactory() ); } ); compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => { new DelegatedModuleFactoryPlugin(this.options).apply(normalModuleFactory); }); } } module.exports = DelegatedPlugin; webpack-4.30.0/lib/DependenciesBlock.js000066400000000000000000000064261345416772700177070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependenciesBlockVariable = require("./DependenciesBlockVariable"); /** @typedef {import("./ChunkGroup")} ChunkGroup */ /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ /** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ /** @typedef {import("./util/createHash").Hash} Hash */ class DependenciesBlock { constructor() { /** @type {Dependency[]} */ this.dependencies = []; /** @type {AsyncDependenciesBlock[]} */ this.blocks = []; /** @type {DependenciesBlockVariable[]} */ this.variables = []; } /** * Adds a DependencyBlock to DependencyBlock relationship. * This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting) * * @param {AsyncDependenciesBlock} block block being added * @returns {void} */ addBlock(block) { this.blocks.push(block); block.parent = this; } /** * @param {string} name name of dependency * @param {string} expression expression string for variable * @param {Dependency[]} dependencies dependency instances tied to variable * @returns {void} */ addVariable(name, expression, dependencies) { for (let v of this.variables) { if (v.name === name && v.expression === expression) { return; } } this.variables.push( new DependenciesBlockVariable(name, expression, dependencies) ); } /** * @param {Dependency} dependency dependency being tied to block. * This is an "edge" pointing to another "node" on module graph. * @returns {void} */ addDependency(dependency) { this.dependencies.push(dependency); } /** * @param {Dependency} dependency dependency being removed * @returns {void} */ removeDependency(dependency) { const idx = this.dependencies.indexOf(dependency); if (idx >= 0) { this.dependencies.splice(idx, 1); } } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { for (const dep of this.dependencies) dep.updateHash(hash); for (const block of this.blocks) block.updateHash(hash); for (const variable of this.variables) variable.updateHash(hash); } disconnect() { for (const dep of this.dependencies) dep.disconnect(); for (const block of this.blocks) block.disconnect(); for (const variable of this.variables) variable.disconnect(); } unseal() { for (const block of this.blocks) block.unseal(); } /** * @param {DependencyFilterFunction} filter filter function for dependencies, gets passed all dependency ties from current instance * @returns {boolean} returns boolean for filter */ hasDependencies(filter) { if (filter) { for (const dep of this.dependencies) { if (filter(dep)) return true; } } else { if (this.dependencies.length > 0) { return true; } } for (const block of this.blocks) { if (block.hasDependencies(filter)) return true; } for (const variable of this.variables) { if (variable.hasDependencies(filter)) return true; } return false; } sortItems() { for (const block of this.blocks) block.sortItems(); } } module.exports = DependenciesBlock; webpack-4.30.0/lib/DependenciesBlockVariable.js000066400000000000000000000042231345416772700213460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { RawSource, ReplaceSource } = require("webpack-sources"); /** @typedef {import("./Dependency")} Dependency */ /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("./util/createHash").Hash} Hash */ /** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ /** @typedef {Map} DependencyTemplates */ class DependenciesBlockVariable { /** * Creates an instance of DependenciesBlockVariable. * @param {string} name name of DependenciesBlockVariable * @param {string} expression expression string * @param {Dependency[]=} dependencies dependencies tied to this varaiable */ constructor(name, expression, dependencies) { this.name = name; this.expression = expression; this.dependencies = dependencies || []; } /** * @param {Hash} hash hash for instance to update * @returns {void} */ updateHash(hash) { hash.update(this.name); hash.update(this.expression); for (const d of this.dependencies) { d.updateHash(hash); } } /** * @param {DependencyTemplates} dependencyTemplates Dependency constructors and templates Map. * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate to generate expression souce * @returns {ReplaceSource} returns constructed source for expression via templates */ expressionSource(dependencyTemplates, runtimeTemplate) { const source = new ReplaceSource(new RawSource(this.expression)); for (const dep of this.dependencies) { const template = dependencyTemplates.get(dep.constructor); if (!template) { throw new Error(`No template for dependency: ${dep.constructor.name}`); } template.apply(dep, source, runtimeTemplate, dependencyTemplates); } return source; } disconnect() { for (const d of this.dependencies) { d.disconnect(); } } hasDependencies(filter) { if (filter) { return this.dependencies.some(filter); } return this.dependencies.length > 0; } } module.exports = DependenciesBlockVariable; webpack-4.30.0/lib/Dependency.js000066400000000000000000000037441345416772700164240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const util = require("util"); const compareLocations = require("./compareLocations"); const DependencyReference = require("./dependencies/DependencyReference"); /** @typedef {import("./Module")} Module */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** * @typedef {Object} DependencyTemplate * @property {function(Dependency, Source, RuntimeTemplate, Map): void} apply */ /** @typedef {Object} SourcePosition * @property {number} line * @property {number=} column */ /** @typedef {Object} RealDependencyLocation * @property {SourcePosition} start * @property {SourcePosition=} end * @property {number=} index */ /** @typedef {Object} SynteticDependencyLocation * @property {string} name * @property {number=} index */ /** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */ class Dependency { constructor() { /** @type {Module|null} */ this.module = null; // TODO remove in webpack 5 /** @type {boolean} */ this.weak = false; /** @type {boolean} */ this.optional = false; /** @type {DependencyLocation} */ this.loc = undefined; } getResourceIdentifier() { return null; } // Returns the referenced module and export getReference() { if (!this.module) return null; return new DependencyReference(this.module, true, this.weak); } // Returns the exported names getExports() { return null; } getWarnings() { return null; } getErrors() { return null; } updateHash(hash) { hash.update((this.module && this.module.id) + ""); } disconnect() { this.module = null; } } // TODO remove in webpack 5 Dependency.compare = util.deprecate( (a, b) => compareLocations(a.loc, b.loc), "Dependency.compare is deprecated and will be removed in the next major version" ); module.exports = Dependency; webpack-4.30.0/lib/DllEntryPlugin.js000066400000000000000000000023701345416772700172540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DllEntryDependency = require("./dependencies/DllEntryDependency"); const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); const DllModuleFactory = require("./DllModuleFactory"); class DllEntryPlugin { constructor(context, entries, name) { this.context = context; this.entries = entries; this.name = name; } apply(compiler) { compiler.hooks.compilation.tap( "DllEntryPlugin", (compilation, { normalModuleFactory }) => { const dllModuleFactory = new DllModuleFactory(); compilation.dependencyFactories.set( DllEntryDependency, dllModuleFactory ); compilation.dependencyFactories.set( SingleEntryDependency, normalModuleFactory ); } ); compiler.hooks.make.tapAsync("DllEntryPlugin", (compilation, callback) => { compilation.addEntry( this.context, new DllEntryDependency( this.entries.map((e, idx) => { const dep = new SingleEntryDependency(e); dep.loc = { name: this.name, index: idx }; return dep; }), this.name ), this.name, callback ); }); } } module.exports = DllEntryPlugin; webpack-4.30.0/lib/DllModule.js000066400000000000000000000021331345416772700162160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { RawSource } = require("webpack-sources"); const Module = require("./Module"); /** @typedef {import("./util/createHash").Hash} Hash */ class DllModule extends Module { constructor(context, dependencies, name, type) { super("javascript/dynamic", context); // Info from Factory this.dependencies = dependencies; this.name = name; this.type = type; } identifier() { return `dll ${this.name}`; } readableIdentifier() { return `dll ${this.name}`; } build(options, compilation, resolver, fs, callback) { this.built = true; this.buildMeta = {}; this.buildInfo = {}; return callback(); } source() { return new RawSource("module.exports = __webpack_require__;"); } needRebuild() { return false; } size() { return 12; } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { hash.update("dll module"); hash.update(this.name || ""); super.updateHash(hash); } } module.exports = DllModule; webpack-4.30.0/lib/DllModuleFactory.js000066400000000000000000000010301345416772700175410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { Tapable } = require("tapable"); const DllModule = require("./DllModule"); class DllModuleFactory extends Tapable { constructor() { super(); this.hooks = {}; } create(data, callback) { const dependency = data.dependencies[0]; callback( null, new DllModule( data.context, dependency.dependencies, dependency.name, dependency.type ) ); } } module.exports = DllModuleFactory; webpack-4.30.0/lib/DllPlugin.js000066400000000000000000000026331345416772700162340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DllEntryPlugin = require("./DllEntryPlugin"); const LibManifestPlugin = require("./LibManifestPlugin"); const FlagInitialModulesAsUsedPlugin = require("./FlagInitialModulesAsUsedPlugin"); const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/DllPlugin.json"); /** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ class DllPlugin { /** * @param {DllPluginOptions} options options object */ constructor(options) { validateOptions(schema, options, "Dll Plugin"); this.options = options; } apply(compiler) { compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => { const itemToPlugin = (item, name) => { if (Array.isArray(item)) { return new DllEntryPlugin(context, item, name); } throw new Error("DllPlugin: supply an Array as entry"); }; if (typeof entry === "object" && !Array.isArray(entry)) { Object.keys(entry).forEach(name => { itemToPlugin(entry[name], name).apply(compiler); }); } else { itemToPlugin(entry, "main").apply(compiler); } return true; }); new LibManifestPlugin(this.options).apply(compiler); if (!this.options.entryOnly) { new FlagInitialModulesAsUsedPlugin("DllPlugin").apply(compiler); } } } module.exports = DllPlugin; webpack-4.30.0/lib/DllReferencePlugin.js000066400000000000000000000116001345416772700200450ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const parseJson = require("json-parse-better-errors"); const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); const NullFactory = require("./NullFactory"); const makePathsRelative = require("./util/identifier").makePathsRelative; const WebpackError = require("./WebpackError"); const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/DllReferencePlugin.json"); /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ class DllReferencePlugin { /** * @param {DllReferencePluginOptions} options options object */ constructor(options) { validateOptions(schema, options, "Dll Reference Plugin"); this.options = options; } apply(compiler) { compiler.hooks.compilation.tap( "DllReferencePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( DelegatedSourceDependency, normalModuleFactory ); compilation.dependencyFactories.set( DelegatedExportsDependency, new NullFactory() ); } ); compiler.hooks.beforeCompile.tapAsync( "DllReferencePlugin", (params, callback) => { if ("manifest" in this.options) { const manifest = this.options.manifest; if (typeof manifest === "string") { params.compilationDependencies.add(manifest); compiler.inputFileSystem.readFile(manifest, (err, result) => { if (err) return callback(err); // Catch errors parsing the manifest so that blank // or malformed manifest files don't kill the process. try { params["dll reference " + manifest] = parseJson( result.toString("utf-8") ); } catch (e) { // Store the error in the params so that it can // be added as a compilation error later on. const manifestPath = makePathsRelative( compiler.options.context, manifest ); params[ "dll reference parse error " + manifest ] = new DllManifestError(manifestPath, e.message); } return callback(); }); return; } } return callback(); } ); compiler.hooks.compile.tap("DllReferencePlugin", params => { let name = this.options.name; let sourceType = this.options.sourceType; let content = "content" in this.options ? this.options.content : undefined; if ("manifest" in this.options) { let manifestParameter = this.options.manifest; let manifest; if (typeof manifestParameter === "string") { // If there was an error parsing the manifest // file, exit now because the error will be added // as a compilation error in the "compilation" hook. if (params["dll reference parse error " + manifestParameter]) { return; } manifest = /** @type {DllReferencePluginOptionsManifest} */ (params[ "dll reference " + manifestParameter ]); } else { manifest = manifestParameter; } if (manifest) { if (!name) name = manifest.name; if (!sourceType) sourceType = manifest.type; if (!content) content = manifest.content; } } const externals = {}; const source = "dll-reference " + name; externals[source] = name; const normalModuleFactory = params.normalModuleFactory; new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply( normalModuleFactory ); new DelegatedModuleFactoryPlugin({ source: source, type: this.options.type, scope: this.options.scope, context: this.options.context || compiler.options.context, content, extensions: this.options.extensions }).apply(normalModuleFactory); }); compiler.hooks.compilation.tap( "DllReferencePlugin", (compilation, params) => { if ("manifest" in this.options) { let manifest = this.options.manifest; if (typeof manifest === "string") { // If there was an error parsing the manifest file, add the // error as a compilation error to make the compilation fail. let e = params["dll reference parse error " + manifest]; if (e) { compilation.errors.push(e); } } } } ); } } class DllManifestError extends WebpackError { constructor(filename, message) { super(); this.name = "DllManifestError"; this.message = `Dll manifest ${filename}\n${message}`; Error.captureStackTrace(this, this.constructor); } } module.exports = DllReferencePlugin; webpack-4.30.0/lib/DynamicEntryPlugin.js000066400000000000000000000054071345416772700201310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Naoyuki Kanezawa @nkzawa */ "use strict"; const MultiEntryDependency = require("./dependencies/MultiEntryDependency"); const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); const MultiModuleFactory = require("./MultiModuleFactory"); const MultiEntryPlugin = require("./MultiEntryPlugin"); const SingleEntryPlugin = require("./SingleEntryPlugin"); /** @typedef {import("../declarations/WebpackOptions").EntryDynamic} EntryDynamic */ /** @typedef {import("../declarations/WebpackOptions").EntryStatic} EntryStatic */ /** @typedef {import("./Compiler")} Compiler */ class DynamicEntryPlugin { /** * @param {string} context the context path * @param {EntryDynamic} entry the entry value */ constructor(context, entry) { this.context = context; this.entry = entry; } /** * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap( "DynamicEntryPlugin", (compilation, { normalModuleFactory }) => { const multiModuleFactory = new MultiModuleFactory(); compilation.dependencyFactories.set( MultiEntryDependency, multiModuleFactory ); compilation.dependencyFactories.set( SingleEntryDependency, normalModuleFactory ); } ); compiler.hooks.make.tapAsync( "DynamicEntryPlugin", (compilation, callback) => { /** * @param {string|string[]} entry entry value or array of entry values * @param {string} name name of entry * @returns {Promise} returns the promise resolving the Compilation#addEntry function */ const addEntry = (entry, name) => { const dep = DynamicEntryPlugin.createDependency(entry, name); return new Promise((resolve, reject) => { compilation.addEntry(this.context, dep, name, err => { if (err) return reject(err); resolve(); }); }); }; Promise.resolve(this.entry()).then(entry => { if (typeof entry === "string" || Array.isArray(entry)) { addEntry(entry, "main").then(() => callback(), callback); } else if (typeof entry === "object") { Promise.all( Object.keys(entry).map(name => { return addEntry(entry[name], name); }) ).then(() => callback(), callback); } }); } ); } } module.exports = DynamicEntryPlugin; /** * @param {string|string[]} entry entry value or array of entry paths * @param {string} name name of entry * @returns {SingleEntryDependency|MultiEntryDependency} returns dep */ DynamicEntryPlugin.createDependency = (entry, name) => { if (Array.isArray(entry)) { return MultiEntryPlugin.createDependency(entry, name); } else { return SingleEntryPlugin.createDependency(entry, name); } }; webpack-4.30.0/lib/EntryModuleNotFoundError.js000066400000000000000000000007331345416772700212770ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); class EntryModuleNotFoundError extends WebpackError { constructor(err) { super("Entry module not found: " + err); this.name = "EntryModuleNotFoundError"; this.details = err.details; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = EntryModuleNotFoundError; webpack-4.30.0/lib/EntryOptionPlugin.js000066400000000000000000000027311345416772700200120ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const SingleEntryPlugin = require("./SingleEntryPlugin"); const MultiEntryPlugin = require("./MultiEntryPlugin"); const DynamicEntryPlugin = require("./DynamicEntryPlugin"); /** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */ /** @typedef {import("./Compiler")} Compiler */ /** * @param {string} context context path * @param {EntryItem} item entry array or single path * @param {string} name entry key name * @returns {SingleEntryPlugin | MultiEntryPlugin} returns either a single or multi entry plugin */ const itemToPlugin = (context, item, name) => { if (Array.isArray(item)) { return new MultiEntryPlugin(context, item, name); } return new SingleEntryPlugin(context, item, name); }; module.exports = class EntryOptionPlugin { /** * @param {Compiler} compiler the compiler instance one is tapping into * @returns {void} */ apply(compiler) { compiler.hooks.entryOption.tap("EntryOptionPlugin", (context, entry) => { if (typeof entry === "string" || Array.isArray(entry)) { itemToPlugin(context, entry, "main").apply(compiler); } else if (typeof entry === "object") { for (const name of Object.keys(entry)) { itemToPlugin(context, entry[name], name).apply(compiler); } } else if (typeof entry === "function") { new DynamicEntryPlugin(context, entry).apply(compiler); } return true; }); } }; webpack-4.30.0/lib/Entrypoint.js000066400000000000000000000034041345416772700165120ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ChunkGroup = require("./ChunkGroup"); /** @typedef {import("./Chunk")} Chunk */ /** * Entrypoint serves as an encapsulation primitive for chunks that are * a part of a single ChunkGroup. They represent all bundles that need to be loaded for a * single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects * inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks. */ class Entrypoint extends ChunkGroup { /** * Creates an instance of Entrypoint. * @param {string} name the name of the entrypoint */ constructor(name) { super(name); /** @type {Chunk=} */ this.runtimeChunk = undefined; } /** * isInitial will always return true for Entrypoint ChunkGroup. * @returns {true} returns true as all entrypoints are initial ChunkGroups */ isInitial() { return true; } /** * Sets the runtimeChunk for an entrypoint. * @param {Chunk} chunk the chunk being set as the runtime chunk. * @returns {void} */ setRuntimeChunk(chunk) { this.runtimeChunk = chunk; } /** * Fetches the chunk reference containing the webpack bootstrap code * @returns {Chunk} returns the runtime chunk or first chunk in `this.chunks` */ getRuntimeChunk() { return this.runtimeChunk || this.chunks[0]; } /** * @param {Chunk} oldChunk chunk to be replaced * @param {Chunk} newChunk New chunkt that will be replaced * @returns {boolean} rerturns true for */ replaceChunk(oldChunk, newChunk) { if (this.runtimeChunk === oldChunk) this.runtimeChunk = newChunk; return super.replaceChunk(oldChunk, newChunk); } } module.exports = Entrypoint; webpack-4.30.0/lib/EnvironmentPlugin.js000066400000000000000000000040111345416772700200150ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Authors Simen Brekken @simenbrekken, Einar Löve @einarlove */ "use strict"; /** @typedef {import("./Compiler")} Compiler */ const WebpackError = require("./WebpackError"); const DefinePlugin = require("./DefinePlugin"); const needsEnvVarFix = ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 && process.platform === "win32"; class EnvironmentPlugin { constructor(...keys) { if (keys.length === 1 && Array.isArray(keys[0])) { this.keys = keys[0]; this.defaultValues = {}; } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") { this.keys = Object.keys(keys[0]); this.defaultValues = keys[0]; } else { this.keys = keys; this.defaultValues = {}; } } /** * @param {Compiler} compiler webpack compiler instance * @returns {void} */ apply(compiler) { const definitions = this.keys.reduce((defs, key) => { // TODO remove once the fix has made its way into Node 8. // Work around https://github.com/nodejs/node/pull/18463, // affecting Node 8 & 9 by performing an OS-level // operation that always succeeds before reading // environment variables: if (needsEnvVarFix) require("os").cpus(); const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key]; if (value === undefined) { compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => { const error = new WebpackError( `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` + "You can pass an object with default values to suppress this warning.\n" + "See https://webpack.js.org/plugins/environment-plugin for example." ); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } defs[`process.env.${key}`] = value === undefined ? "undefined" : JSON.stringify(value); return defs; }, {}); new DefinePlugin(definitions).apply(compiler); } } module.exports = EnvironmentPlugin; webpack-4.30.0/lib/ErrorHelpers.js000066400000000000000000000026431345416772700167570ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const loaderFlag = "LOADER_EXECUTION"; const webpackOptionsFlag = "WEBPACK_OPTIONS"; exports.cutOffByFlag = (stack, flag) => { stack = stack.split("\n"); for (let i = 0; i < stack.length; i++) { if (stack[i].includes(flag)) { stack.length = i; } } return stack.join("\n"); }; exports.cutOffLoaderExecution = stack => exports.cutOffByFlag(stack, loaderFlag); exports.cutOffWebpackOptions = stack => exports.cutOffByFlag(stack, webpackOptionsFlag); exports.cutOffMultilineMessage = (stack, message) => { stack = stack.split("\n"); message = message.split("\n"); return stack .reduce( (acc, line, idx) => line.includes(message[idx]) ? acc : acc.concat(line), [] ) .join("\n"); }; exports.cutOffMessage = (stack, message) => { const nextLine = stack.indexOf("\n"); if (nextLine === -1) { return stack === message ? "" : stack; } else { const firstLine = stack.substr(0, nextLine); return firstLine === message ? stack.substr(nextLine + 1) : stack; } }; exports.cleanUp = (stack, message) => { stack = exports.cutOffLoaderExecution(stack); stack = exports.cutOffMessage(stack, message); return stack; }; exports.cleanUpWebpackOptions = (stack, message) => { stack = exports.cutOffWebpackOptions(stack); stack = exports.cutOffMultilineMessage(stack, message); return stack; }; webpack-4.30.0/lib/EvalDevToolModulePlugin.js000066400000000000000000000014301345416772700210450ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const EvalDevToolModuleTemplatePlugin = require("./EvalDevToolModuleTemplatePlugin"); class EvalDevToolModulePlugin { constructor(options) { this.sourceUrlComment = options.sourceUrlComment; this.moduleFilenameTemplate = options.moduleFilenameTemplate; this.namespace = options.namespace; } apply(compiler) { compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { new EvalDevToolModuleTemplatePlugin({ sourceUrlComment: this.sourceUrlComment, moduleFilenameTemplate: this.moduleFilenameTemplate, namespace: this.namespace }).apply(compilation.moduleTemplates.javascript); }); } } module.exports = EvalDevToolModulePlugin; webpack-4.30.0/lib/EvalDevToolModuleTemplatePlugin.js000066400000000000000000000032231345416772700225430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { RawSource } = require("webpack-sources"); const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); const cache = new WeakMap(); class EvalDevToolModuleTemplatePlugin { constructor(options) { this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]?[loaders]"; this.namespace = options.namespace || ""; } apply(moduleTemplate) { moduleTemplate.hooks.module.tap( "EvalDevToolModuleTemplatePlugin", (source, module) => { const cacheEntry = cache.get(source); if (cacheEntry !== undefined) return cacheEntry; const content = source.source(); const str = ModuleFilenameHelpers.createFilename( module, { moduleFilenameTemplate: this.moduleFilenameTemplate, namespace: this.namespace }, moduleTemplate.runtimeTemplate.requestShortener ); const footer = "\n" + this.sourceUrlComment.replace( /\[url\]/g, encodeURI(str) .replace(/%2F/g, "/") .replace(/%20/g, "_") .replace(/%5E/g, "^") .replace(/%5C/g, "\\") .replace(/^\//, "") ); const result = new RawSource( `eval(${JSON.stringify(content + footer)});` ); cache.set(source, result); return result; } ); moduleTemplate.hooks.hash.tap("EvalDevToolModuleTemplatePlugin", hash => { hash.update("EvalDevToolModuleTemplatePlugin"); hash.update("2"); }); } } module.exports = EvalDevToolModuleTemplatePlugin; webpack-4.30.0/lib/EvalSourceMapDevToolModuleTemplatePlugin.js000066400000000000000000000062111345416772700243620ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { RawSource } = require("webpack-sources"); const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); const cache = new WeakMap(); class EvalSourceMapDevToolModuleTemplatePlugin { constructor(compilation, options) { this.compilation = compilation; this.sourceMapComment = options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]"; this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack://[namespace]/[resource-path]?[hash]"; this.namespace = options.namespace || ""; this.options = options; } apply(moduleTemplate) { const self = this; const options = this.options; const matchModule = ModuleFilenameHelpers.matchObject.bind( ModuleFilenameHelpers, options ); moduleTemplate.hooks.module.tap( "EvalSourceMapDevToolModuleTemplatePlugin", (source, module) => { const cachedSource = cache.get(source); if (cachedSource !== undefined) { return cachedSource; } if (!matchModule(module.resource)) { return source; } /** @type {{ [key: string]: TODO; }} */ let sourceMap; let content; if (source.sourceAndMap) { const sourceAndMap = source.sourceAndMap(options); sourceMap = sourceAndMap.map; content = sourceAndMap.source; } else { sourceMap = source.map(options); content = source.source(); } if (!sourceMap) { return source; } // Clone (flat) the sourcemap to ensure that the mutations below do not persist. sourceMap = Object.keys(sourceMap).reduce((obj, key) => { obj[key] = sourceMap[key]; return obj; }, {}); const modules = sourceMap.sources.map(source => { const module = self.compilation.findModule(source); return module || source; }); let moduleFilenames = modules.map(module => { return ModuleFilenameHelpers.createFilename( module, { moduleFilenameTemplate: self.moduleFilenameTemplate, namespace: self.namespace }, moduleTemplate.runtimeTemplate.requestShortener ); }); moduleFilenames = ModuleFilenameHelpers.replaceDuplicates( moduleFilenames, (filename, i, n) => { for (let j = 0; j < n; j++) filename += "*"; return filename; } ); sourceMap.sources = moduleFilenames; sourceMap.sourceRoot = options.sourceRoot || ""; sourceMap.file = `${module.id}.js`; const footer = self.sourceMapComment.replace( /\[url\]/g, `data:application/json;charset=utf-8;base64,${Buffer.from( JSON.stringify(sourceMap), "utf8" ).toString("base64")}` ) + `\n//# sourceURL=webpack-internal:///${module.id}\n`; // workaround for chrome bug const evalSource = new RawSource( `eval(${JSON.stringify(content + footer)});` ); cache.set(source, evalSource); return evalSource; } ); moduleTemplate.hooks.hash.tap( "EvalSourceMapDevToolModuleTemplatePlugin", hash => { hash.update("eval-source-map"); hash.update("2"); } ); } } module.exports = EvalSourceMapDevToolModuleTemplatePlugin; webpack-4.30.0/lib/EvalSourceMapDevToolPlugin.js000066400000000000000000000020471345416772700215230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const EvalSourceMapDevToolModuleTemplatePlugin = require("./EvalSourceMapDevToolModuleTemplatePlugin"); const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); class EvalSourceMapDevToolPlugin { constructor(options) { if (arguments.length > 1) { throw new Error( "EvalSourceMapDevToolPlugin only takes one argument (pass an options object)" ); } if (typeof options === "string") { options = { append: options }; } if (!options) options = {}; this.options = options; } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap( "EvalSourceMapDevToolPlugin", compilation => { new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); new EvalSourceMapDevToolModuleTemplatePlugin( compilation, options ).apply(compilation.moduleTemplates.javascript); } ); } } module.exports = EvalSourceMapDevToolPlugin; webpack-4.30.0/lib/ExportPropertyMainTemplatePlugin.js000066400000000000000000000025021345416772700230430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); /** @typedef {import("./Compilation")} Compilation */ /** * @param {string[]} accessor the accessor to convert to path * @returns {string} the path */ const accessorToObjectAccess = accessor => { return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); }; class ExportPropertyMainTemplatePlugin { /** * @param {string|string[]} property the name of the property to export */ constructor(property) { this.property = property; } /** * @param {Compilation} compilation the compilation instance * @returns {void} */ apply(compilation) { const { mainTemplate, chunkTemplate } = compilation; const onRenderWithEntry = (source, chunk, hash) => { const postfix = `${accessorToObjectAccess([].concat(this.property))}`; return new ConcatSource(source, postfix); }; for (const template of [mainTemplate, chunkTemplate]) { template.hooks.renderWithEntry.tap( "ExportPropertyMainTemplatePlugin", onRenderWithEntry ); } mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => { hash.update("export property"); hash.update(`${this.property}`); }); } } module.exports = ExportPropertyMainTemplatePlugin; webpack-4.30.0/lib/ExtendedAPIPlugin.js000066400000000000000000000046741345416772700176220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("./Template"); const ConstDependency = require("./dependencies/ConstDependency"); const ParserHelpers = require("./ParserHelpers"); const NullFactory = require("./NullFactory"); const REPLACEMENTS = { // eslint-disable-next-line camelcase __webpack_hash__: "__webpack_require__.h", // eslint-disable-next-line camelcase __webpack_chunkname__: "__webpack_require__.cn" }; const REPLACEMENT_TYPES = { // eslint-disable-next-line camelcase __webpack_hash__: "string", // eslint-disable-next-line camelcase __webpack_chunkname__: "string" }; class ExtendedAPIPlugin { apply(compiler) { compiler.hooks.compilation.tap( "ExtendedAPIPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); const mainTemplate = compilation.mainTemplate; mainTemplate.hooks.requireExtensions.tap( "ExtendedAPIPlugin", (source, chunk, hash) => { const buf = [source]; buf.push(""); buf.push("// __webpack_hash__"); buf.push(`${mainTemplate.requireFn}.h = ${JSON.stringify(hash)};`); buf.push(""); buf.push("// __webpack_chunkname__"); buf.push( `${mainTemplate.requireFn}.cn = ${JSON.stringify(chunk.name)};` ); return Template.asString(buf); } ); mainTemplate.hooks.globalHash.tap("ExtendedAPIPlugin", () => true); const handler = (parser, parserOptions) => { Object.keys(REPLACEMENTS).forEach(key => { parser.hooks.expression .for(key) .tap( "ExtendedAPIPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire( parser, REPLACEMENTS[key] ) ); parser.hooks.evaluateTypeof .for(key) .tap( "ExtendedAPIPlugin", ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]) ); }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("ExtendedAPIPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("ExtendedAPIPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("ExtendedAPIPlugin", handler); } ); } } module.exports = ExtendedAPIPlugin; webpack-4.30.0/lib/ExternalModule.js000066400000000000000000000104441345416772700172710ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { OriginalSource, RawSource } = require("webpack-sources"); const Module = require("./Module"); const WebpackMissingModule = require("./dependencies/WebpackMissingModule"); const Template = require("./Template"); /** @typedef {import("./util/createHash").Hash} Hash */ class ExternalModule extends Module { constructor(request, type, userRequest) { super("javascript/dynamic", null); // Info from Factory this.request = request; this.externalType = type; this.userRequest = userRequest; this.external = true; } libIdent() { return this.userRequest; } chunkCondition(chunk) { return chunk.hasEntryModule(); } identifier() { return "external " + JSON.stringify(this.request); } readableIdentifier() { return "external " + JSON.stringify(this.request); } needRebuild() { return false; } build(options, compilation, resolver, fs, callback) { this.built = true; this.buildMeta = {}; this.buildInfo = {}; callback(); } getSourceForGlobalVariableExternal(variableName, type) { if (!Array.isArray(variableName)) { // make it an array as the look up works the same basically variableName = [variableName]; } // needed for e.g. window["some"]["thing"] const objectLookup = variableName .map(r => `[${JSON.stringify(r)}]`) .join(""); return `(function() { module.exports = ${type}${objectLookup}; }());`; } getSourceForCommonJsExternal(moduleAndSpecifiers) { if (!Array.isArray(moduleAndSpecifiers)) { return `module.exports = require(${JSON.stringify( moduleAndSpecifiers )});`; } const moduleName = moduleAndSpecifiers[0]; const objectLookup = moduleAndSpecifiers .slice(1) .map(r => `[${JSON.stringify(r)}]`) .join(""); return `module.exports = require(${JSON.stringify( moduleName )})${objectLookup};`; } checkExternalVariable(variableToCheck, request) { return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode( request )}}\n`; } getSourceForAmdOrUmdExternal(id, optional, request) { const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( `${id}` )}__`; const missingModuleError = optional ? this.checkExternalVariable(externalVariable, request) : ""; return `${missingModuleError}module.exports = ${externalVariable};`; } getSourceForDefaultCase(optional, request) { if (!Array.isArray(request)) { // make it an array as the look up works the same basically request = [request]; } const variableName = request[0]; const missingModuleError = optional ? this.checkExternalVariable(variableName, request.join(".")) : ""; const objectLookup = request .slice(1) .map(r => `[${JSON.stringify(r)}]`) .join(""); return `${missingModuleError}module.exports = ${variableName}${objectLookup};`; } getSourceString(runtime) { const request = typeof this.request === "object" && !Array.isArray(this.request) ? this.request[this.externalType] : this.request; switch (this.externalType) { case "this": case "window": case "self": return this.getSourceForGlobalVariableExternal( request, this.externalType ); case "global": return this.getSourceForGlobalVariableExternal( request, runtime.outputOptions.globalObject ); case "commonjs": case "commonjs2": return this.getSourceForCommonJsExternal(request); case "amd": case "amd-require": case "umd": case "umd2": case "system": return this.getSourceForAmdOrUmdExternal( this.id, this.optional, request ); default: return this.getSourceForDefaultCase(this.optional, request); } } getSource(sourceString) { if (this.useSourceMap) { return new OriginalSource(sourceString, this.identifier()); } return new RawSource(sourceString); } source(dependencyTemplates, runtime) { return this.getSource(this.getSourceString(runtime)); } size() { return 42; } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { hash.update(this.externalType); hash.update(JSON.stringify(this.request)); hash.update(JSON.stringify(Boolean(this.optional))); super.updateHash(hash); } } module.exports = ExternalModule; webpack-4.30.0/lib/ExternalModuleFactoryPlugin.js000066400000000000000000000056601345416772700220040ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ExternalModule = require("./ExternalModule"); class ExternalModuleFactoryPlugin { constructor(type, externals) { this.type = type; this.externals = externals; } apply(normalModuleFactory) { const globalType = this.type; normalModuleFactory.hooks.factory.tap( "ExternalModuleFactoryPlugin", factory => (data, callback) => { const context = data.context; const dependency = data.dependencies[0]; const handleExternal = (value, type, callback) => { if (typeof type === "function") { callback = type; type = undefined; } if (value === false) return factory(data, callback); if (value === true) value = dependency.request; if (type === undefined && /^[a-z0-9]+ /.test(value)) { const idx = value.indexOf(" "); type = value.substr(0, idx); value = value.substr(idx + 1); } callback( null, new ExternalModule(value, type || globalType, dependency.request) ); return true; }; const handleExternals = (externals, callback) => { if (typeof externals === "string") { if (externals === dependency.request) { return handleExternal(dependency.request, callback); } } else if (Array.isArray(externals)) { let i = 0; const next = () => { let asyncFlag; const handleExternalsAndCallback = (err, module) => { if (err) return callback(err); if (!module) { if (asyncFlag) { asyncFlag = false; return; } return next(); } callback(null, module); }; do { asyncFlag = true; if (i >= externals.length) return callback(); handleExternals(externals[i++], handleExternalsAndCallback); } while (!asyncFlag); asyncFlag = false; }; next(); return; } else if (externals instanceof RegExp) { if (externals.test(dependency.request)) { return handleExternal(dependency.request, callback); } } else if (typeof externals === "function") { externals.call( null, context, dependency.request, (err, value, type) => { if (err) return callback(err); if (value !== undefined) { handleExternal(value, type, callback); } else { callback(); } } ); return; } else if ( typeof externals === "object" && Object.prototype.hasOwnProperty.call(externals, dependency.request) ) { return handleExternal(externals[dependency.request], callback); } callback(); }; handleExternals(this.externals, (err, module) => { if (err) return callback(err); if (!module) return handleExternal(false, callback); return callback(null, module); }); } ); } } module.exports = ExternalModuleFactoryPlugin; webpack-4.30.0/lib/ExternalsPlugin.js000066400000000000000000000010421345416772700174570ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); class ExternalsPlugin { constructor(type, externals) { this.type = type; this.externals = externals; } apply(compiler) { compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { new ExternalModuleFactoryPlugin(this.type, this.externals).apply( normalModuleFactory ); }); } } module.exports = ExternalsPlugin; webpack-4.30.0/lib/FlagDependencyExportsPlugin.js000066400000000000000000000105161345416772700217550ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Queue = require("./util/Queue"); const addToSet = (a, b) => { let changed = false; for (const item of b) { if (!a.has(item)) { a.add(item); changed = true; } } return changed; }; class FlagDependencyExportsPlugin { apply(compiler) { compiler.hooks.compilation.tap( "FlagDependencyExportsPlugin", compilation => { compilation.hooks.finishModules.tap( "FlagDependencyExportsPlugin", modules => { const dependencies = new Map(); const queue = new Queue(); let module; let moduleWithExports; let moduleProvidedExports; let providedExportsAreTemporary; const processDependenciesBlock = depBlock => { for (const dep of depBlock.dependencies) { if (processDependency(dep)) return true; } for (const variable of depBlock.variables) { for (const dep of variable.dependencies) { if (processDependency(dep)) return true; } } for (const block of depBlock.blocks) { if (processDependenciesBlock(block)) return true; } return false; }; const processDependency = dep => { const exportDesc = dep.getExports && dep.getExports(); if (!exportDesc) return; moduleWithExports = true; const exports = exportDesc.exports; // break early if it's only in the worst state if (module.buildMeta.providedExports === true) { return true; } // break if it should move to the worst state if (exports === true) { module.buildMeta.providedExports = true; notifyDependencies(); return true; } // merge in new exports if (Array.isArray(exports)) { if (addToSet(moduleProvidedExports, exports)) { notifyDependencies(); } } // store dependencies const exportDeps = exportDesc.dependencies; if (exportDeps) { providedExportsAreTemporary = true; for (const exportDependency of exportDeps) { // add dependency for this module const set = dependencies.get(exportDependency); if (set === undefined) { dependencies.set(exportDependency, new Set([module])); } else { set.add(module); } } } return false; }; const notifyDependencies = () => { const deps = dependencies.get(module); if (deps !== undefined) { for (const dep of deps) { queue.enqueue(dep); } } }; // Start with all modules without provided exports for (const module of modules) { if (module.buildInfo.temporaryProvidedExports) { // Clear exports when they are temporary // and recreate them module.buildMeta.providedExports = null; queue.enqueue(module); } else if (!module.buildMeta.providedExports) { queue.enqueue(module); } } while (queue.length > 0) { module = queue.dequeue(); if (module.buildMeta.providedExports !== true) { moduleWithExports = module.buildMeta && module.buildMeta.exportsType; moduleProvidedExports = Array.isArray( module.buildMeta.providedExports ) ? new Set(module.buildMeta.providedExports) : new Set(); providedExportsAreTemporary = false; processDependenciesBlock(module); module.buildInfo.temporaryProvidedExports = providedExportsAreTemporary; if (!moduleWithExports) { module.buildMeta.providedExports = true; notifyDependencies(); } else if (module.buildMeta.providedExports !== true) { module.buildMeta.providedExports = Array.from( moduleProvidedExports ); } } } } ); const providedExportsCache = new WeakMap(); compilation.hooks.rebuildModule.tap( "FlagDependencyExportsPlugin", module => { providedExportsCache.set(module, module.buildMeta.providedExports); } ); compilation.hooks.finishRebuildingModule.tap( "FlagDependencyExportsPlugin", module => { module.buildMeta.providedExports = providedExportsCache.get(module); } ); } ); } } module.exports = FlagDependencyExportsPlugin; webpack-4.30.0/lib/FlagDependencyUsagePlugin.js000066400000000000000000000065271345416772700213640ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("./Module")} Module */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {false | true | string[]} UsedExports */ const addToSet = (a, b) => { for (const item of b) { if (!a.includes(item)) a.push(item); } return a; }; const isSubset = (biggerSet, subset) => { if (biggerSet === true) return true; if (subset === true) return false; return subset.every(item => biggerSet.indexOf(item) >= 0); }; class FlagDependencyUsagePlugin { apply(compiler) { compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { compilation.hooks.optimizeDependencies.tap( "FlagDependencyUsagePlugin", modules => { const processModule = (module, usedExports) => { module.used = true; if (module.usedExports === true) return; if (usedExports === true) { module.usedExports = true; } else if (Array.isArray(usedExports)) { const old = module.usedExports ? module.usedExports.length : -1; module.usedExports = addToSet( module.usedExports || [], usedExports ); if (module.usedExports.length === old) { return; } } else if (Array.isArray(module.usedExports)) { return; } else { module.usedExports = false; } // for a module without side effects we stop tracking usage here when no export is used // This module won't be evaluated in this case if (module.factoryMeta.sideEffectFree) { if (module.usedExports === false) return; if ( Array.isArray(module.usedExports) && module.usedExports.length === 0 ) return; } queue.push([module, module, module.usedExports]); }; const processDependenciesBlock = (module, depBlock, usedExports) => { for (const dep of depBlock.dependencies) { processDependency(module, dep); } for (const variable of depBlock.variables) { for (const dep of variable.dependencies) { processDependency(module, dep); } } for (const block of depBlock.blocks) { queue.push([module, block, usedExports]); } }; const processDependency = (module, dep) => { const reference = compilation.getDependencyReference(module, dep); if (!reference) return; const referenceModule = reference.module; const importedNames = reference.importedNames; const oldUsed = referenceModule.used; const oldUsedExports = referenceModule.usedExports; if ( !oldUsed || (importedNames && (!oldUsedExports || !isSubset(oldUsedExports, importedNames))) ) { processModule(referenceModule, importedNames); } }; for (const module of modules) { module.used = false; } /** @type {[Module, DependenciesBlock, UsedExports][]} */ const queue = []; for (const preparedEntrypoint of compilation._preparedEntrypoints) { if (preparedEntrypoint.module) { processModule(preparedEntrypoint.module, true); } } while (queue.length) { const queueItem = queue.pop(); processDependenciesBlock(queueItem[0], queueItem[1], queueItem[2]); } } ); }); } } module.exports = FlagDependencyUsagePlugin; webpack-4.30.0/lib/FlagInitialModulesAsUsedPlugin.js000066400000000000000000000014371345416772700223430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class FlagInitialModulesAsUsedPlugin { constructor(explanation) { this.explanation = explanation; } apply(compiler) { compiler.hooks.compilation.tap( "FlagInitialModulesAsUsedPlugin", compilation => { compilation.hooks.afterOptimizeChunks.tap( "FlagInitialModulesAsUsedPlugin", chunks => { for (const chunk of chunks) { if (!chunk.isOnlyInitial()) { return; } for (const module of chunk.modulesIterable) { module.used = true; module.usedExports = true; module.addReason(null, null, this.explanation); } } } ); } ); } } module.exports = FlagInitialModulesAsUsedPlugin; webpack-4.30.0/lib/FunctionModulePlugin.js000066400000000000000000000007171345416772700204550ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const FunctionModuleTemplatePlugin = require("./FunctionModuleTemplatePlugin"); class FunctionModulePlugin { apply(compiler) { compiler.hooks.compilation.tap("FunctionModulePlugin", compilation => { new FunctionModuleTemplatePlugin().apply( compilation.moduleTemplates.javascript ); }); } } module.exports = FunctionModulePlugin; webpack-4.30.0/lib/FunctionModuleTemplatePlugin.js000066400000000000000000000064221345416772700221500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); const Template = require("./Template"); class FunctionModuleTemplatePlugin { apply(moduleTemplate) { moduleTemplate.hooks.render.tap( "FunctionModuleTemplatePlugin", (moduleSource, module) => { const source = new ConcatSource(); const args = [module.moduleArgument]; // TODO remove HACK checking type for javascript if (module.type && module.type.startsWith("javascript")) { args.push(module.exportsArgument); if (module.hasDependencies(d => d.requireWebpackRequire !== false)) { args.push("__webpack_require__"); } } else if (module.type && module.type.startsWith("json")) { // no additional arguments needed } else { args.push(module.exportsArgument, "__webpack_require__"); } source.add("/***/ (function(" + args.join(", ") + ") {\n\n"); if (module.buildInfo.strict) source.add('"use strict";\n'); source.add(moduleSource); source.add("\n\n/***/ })"); return source; } ); moduleTemplate.hooks.package.tap( "FunctionModuleTemplatePlugin", (moduleSource, module) => { if (moduleTemplate.runtimeTemplate.outputOptions.pathinfo) { const source = new ConcatSource(); const req = module.readableIdentifier( moduleTemplate.runtimeTemplate.requestShortener ); const reqStr = req.replace(/\*\//g, "*_/"); const reqStrStar = "*".repeat(reqStr.length); source.add("/*!****" + reqStrStar + "****!*\\\n"); source.add(" !*** " + reqStr + " ***!\n"); source.add(" \\****" + reqStrStar + "****/\n"); if ( Array.isArray(module.buildMeta.providedExports) && module.buildMeta.providedExports.length === 0 ) { source.add(Template.toComment("no exports provided") + "\n"); } else if (Array.isArray(module.buildMeta.providedExports)) { source.add( Template.toComment( "exports provided: " + module.buildMeta.providedExports.join(", ") ) + "\n" ); } else if (module.buildMeta.providedExports) { source.add(Template.toComment("no static exports found") + "\n"); } if ( Array.isArray(module.usedExports) && module.usedExports.length === 0 ) { source.add(Template.toComment("no exports used") + "\n"); } else if (Array.isArray(module.usedExports)) { source.add( Template.toComment( "exports used: " + module.usedExports.join(", ") ) + "\n" ); } else if (module.usedExports) { source.add(Template.toComment("all exports used") + "\n"); } if (module.optimizationBailout) { for (const text of module.optimizationBailout) { let code; if (typeof text === "function") { code = text(moduleTemplate.runtimeTemplate.requestShortener); } else { code = text; } source.add(Template.toComment(`${code}`) + "\n"); } } source.add(moduleSource); return source; } return moduleSource; } ); moduleTemplate.hooks.hash.tap("FunctionModuleTemplatePlugin", hash => { hash.update("FunctionModuleTemplatePlugin"); hash.update("2"); }); } } module.exports = FunctionModuleTemplatePlugin; webpack-4.30.0/lib/Generator.js000066400000000000000000000033341345416772700162670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("./NormalModule")} NormalModule */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ /** * */ class Generator { static byType(map) { return new ByTypeGenerator(map); } /** * @abstract * @param {NormalModule} module module for which the code should be generated * @param {Map} dependencyTemplates mapping from dependencies to templates * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {string} type which kind of code should be generated * @returns {Source} generated code */ generate(module, dependencyTemplates, runtimeTemplate, type) { throw new Error("Generator.generate: must be overridden"); } } class ByTypeGenerator extends Generator { constructor(map) { super(); this.map = map; } /** * @param {NormalModule} module module for which the code should be generated * @param {Map} dependencyTemplates mapping from dependencies to templates * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {string} type which kind of code should be generated * @returns {Source} generated code */ generate(module, dependencyTemplates, runtimeTemplate, type) { const generator = this.map[type]; if (!generator) { throw new Error(`Generator.byType: no generator specified for ${type}`); } return generator.generate( module, dependencyTemplates, runtimeTemplate, type ); } } module.exports = Generator; webpack-4.30.0/lib/GraphHelpers.js000066400000000000000000000036731345416772700167330ustar00rootroot00000000000000/** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./ChunkGroup")} ChunkGroup */ /** @typedef {import("./Module")} Module */ /** @typedef {import("./DependenciesBlock")} DependenciesBlock */ /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** * @param {ChunkGroup} chunkGroup the ChunkGroup to connect * @param {Chunk} chunk chunk to tie to ChunkGroup * @returns {void} */ const connectChunkGroupAndChunk = (chunkGroup, chunk) => { if (chunkGroup.pushChunk(chunk)) { chunk.addGroup(chunkGroup); } }; /** * @param {ChunkGroup} parent parent ChunkGroup to connect * @param {ChunkGroup} child child ChunkGroup to connect * @returns {void} */ const connectChunkGroupParentAndChild = (parent, child) => { if (parent.addChild(child)) { child.addParent(parent); } }; /** * @param {Chunk} chunk Chunk to connect to Module * @param {Module} module Module to connect to Chunk * @returns {void} */ const connectChunkAndModule = (chunk, module) => { if (module.addChunk(chunk)) { chunk.addModule(module); } }; /** * @param {Chunk} chunk Chunk being disconnected * @param {Module} module Module being disconnected * @returns {void} */ const disconnectChunkAndModule = (chunk, module) => { chunk.removeModule(module); module.removeChunk(chunk); }; /** * @param {AsyncDependenciesBlock} depBlock DepBlock being tied to ChunkGroup * @param {ChunkGroup} chunkGroup ChunkGroup being tied to DepBlock * @returns {void} */ const connectDependenciesBlockAndChunkGroup = (depBlock, chunkGroup) => { if (chunkGroup.addBlock(depBlock)) { depBlock.chunkGroup = chunkGroup; } }; exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; exports.connectChunkAndModule = connectChunkAndModule; exports.disconnectChunkAndModule = disconnectChunkAndModule; exports.connectDependenciesBlockAndChunkGroup = connectDependenciesBlockAndChunkGroup; webpack-4.30.0/lib/HarmonyLinkingError.js000066400000000000000000000006301345416772700203000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const WebpackError = require("./WebpackError"); module.exports = class HarmonyLinkingError extends WebpackError { /** @param {string} message Error message */ constructor(message) { super(message); this.name = "HarmonyLinkingError"; this.hideStack = true; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/HashedModuleIdsPlugin.js000066400000000000000000000032171345416772700205220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const createHash = require("./util/createHash"); const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/HashedModuleIdsPlugin.json"); /** @typedef {import("../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ class HashedModuleIdsPlugin { /** * @param {HashedModuleIdsPluginOptions=} options options object */ constructor(options) { if (!options) options = {}; validateOptions(schema, options, "Hashed Module Ids Plugin"); /** @type {HashedModuleIdsPluginOptions} */ this.options = Object.assign( { context: null, hashFunction: "md4", hashDigest: "base64", hashDigestLength: 4 }, options ); } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { const usedIds = new Set(); compilation.hooks.beforeModuleIds.tap( "HashedModuleIdsPlugin", modules => { for (const module of modules) { if (module.id === null && module.libIdent) { const id = module.libIdent({ context: this.options.context || compiler.options.context }); const hash = createHash(options.hashFunction); hash.update(id); const hashId = hash.digest(options.hashDigest); let len = options.hashDigestLength; while (usedIds.has(hashId.substr(0, len))) len++; module.id = hashId.substr(0, len); usedIds.add(module.id); } } } ); }); } } module.exports = HashedModuleIdsPlugin; webpack-4.30.0/lib/HotModuleReplacement.runtime.js000066400000000000000000000413031345416772700221010ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*global $hash$ $requestTimeout$ installedModules $require$ hotDownloadManifest hotDownloadUpdateChunk hotDisposeChunk modules */ module.exports = function() { var hotApplyOnUpdate = true; // eslint-disable-next-line no-unused-vars var hotCurrentHash = $hash$; var hotRequestTimeout = $requestTimeout$; var hotCurrentModuleData = {}; var hotCurrentChildModule; // eslint-disable-next-line no-unused-vars var hotCurrentParents = []; // eslint-disable-next-line no-unused-vars var hotCurrentParentsTemp = []; // eslint-disable-next-line no-unused-vars function hotCreateRequire(moduleId) { var me = installedModules[moduleId]; if (!me) return $require$; var fn = function(request) { if (me.hot.active) { if (installedModules[request]) { if (installedModules[request].parents.indexOf(moduleId) === -1) { installedModules[request].parents.push(moduleId); } } else { hotCurrentParents = [moduleId]; hotCurrentChildModule = request; } if (me.children.indexOf(request) === -1) { me.children.push(request); } } else { console.warn( "[HMR] unexpected require(" + request + ") from disposed module " + moduleId ); hotCurrentParents = []; } return $require$(request); }; var ObjectFactory = function ObjectFactory(name) { return { configurable: true, enumerable: true, get: function() { return $require$[name]; }, set: function(value) { $require$[name] = value; } }; }; for (var name in $require$) { if ( Object.prototype.hasOwnProperty.call($require$, name) && name !== "e" && name !== "t" ) { Object.defineProperty(fn, name, ObjectFactory(name)); } } fn.e = function(chunkId) { if (hotStatus === "ready") hotSetStatus("prepare"); hotChunksLoading++; return $require$.e(chunkId).then(finishChunkLoading, function(err) { finishChunkLoading(); throw err; }); function finishChunkLoading() { hotChunksLoading--; if (hotStatus === "prepare") { if (!hotWaitingFilesMap[chunkId]) { hotEnsureUpdateChunk(chunkId); } if (hotChunksLoading === 0 && hotWaitingFiles === 0) { hotUpdateDownloaded(); } } } }; fn.t = function(value, mode) { if (mode & 1) value = fn(value); return $require$.t(value, mode & ~1); }; return fn; } // eslint-disable-next-line no-unused-vars function hotCreateModule(moduleId) { var hot = { // private stuff _acceptedDependencies: {}, _declinedDependencies: {}, _selfAccepted: false, _selfDeclined: false, _disposeHandlers: [], _main: hotCurrentChildModule !== moduleId, // Module API active: true, accept: function(dep, callback) { if (dep === undefined) hot._selfAccepted = true; else if (typeof dep === "function") hot._selfAccepted = dep; else if (typeof dep === "object") for (var i = 0; i < dep.length; i++) hot._acceptedDependencies[dep[i]] = callback || function() {}; else hot._acceptedDependencies[dep] = callback || function() {}; }, decline: function(dep) { if (dep === undefined) hot._selfDeclined = true; else if (typeof dep === "object") for (var i = 0; i < dep.length; i++) hot._declinedDependencies[dep[i]] = true; else hot._declinedDependencies[dep] = true; }, dispose: function(callback) { hot._disposeHandlers.push(callback); }, addDisposeHandler: function(callback) { hot._disposeHandlers.push(callback); }, removeDisposeHandler: function(callback) { var idx = hot._disposeHandlers.indexOf(callback); if (idx >= 0) hot._disposeHandlers.splice(idx, 1); }, // Management API check: hotCheck, apply: hotApply, status: function(l) { if (!l) return hotStatus; hotStatusHandlers.push(l); }, addStatusHandler: function(l) { hotStatusHandlers.push(l); }, removeStatusHandler: function(l) { var idx = hotStatusHandlers.indexOf(l); if (idx >= 0) hotStatusHandlers.splice(idx, 1); }, //inherit from previous dispose call data: hotCurrentModuleData[moduleId] }; hotCurrentChildModule = undefined; return hot; } var hotStatusHandlers = []; var hotStatus = "idle"; function hotSetStatus(newStatus) { hotStatus = newStatus; for (var i = 0; i < hotStatusHandlers.length; i++) hotStatusHandlers[i].call(null, newStatus); } // while downloading var hotWaitingFiles = 0; var hotChunksLoading = 0; var hotWaitingFilesMap = {}; var hotRequestedFilesMap = {}; var hotAvailableFilesMap = {}; var hotDeferred; // The update info var hotUpdate, hotUpdateNewHash; function toModuleId(id) { var isNumber = +id + "" === id; return isNumber ? +id : id; } function hotCheck(apply) { if (hotStatus !== "idle") { throw new Error("check() is only allowed in idle status"); } hotApplyOnUpdate = apply; hotSetStatus("check"); return hotDownloadManifest(hotRequestTimeout).then(function(update) { if (!update) { hotSetStatus("idle"); return null; } hotRequestedFilesMap = {}; hotWaitingFilesMap = {}; hotAvailableFilesMap = update.c; hotUpdateNewHash = update.h; hotSetStatus("prepare"); var promise = new Promise(function(resolve, reject) { hotDeferred = { resolve: resolve, reject: reject }; }); hotUpdate = {}; /*foreachInstalledChunks*/ // eslint-disable-next-line no-lone-blocks { /*globals chunkId */ hotEnsureUpdateChunk(chunkId); } if ( hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0 ) { hotUpdateDownloaded(); } return promise; }); } // eslint-disable-next-line no-unused-vars function hotAddUpdateChunk(chunkId, moreModules) { if (!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) return; hotRequestedFilesMap[chunkId] = false; for (var moduleId in moreModules) { if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { hotUpdate[moduleId] = moreModules[moduleId]; } } if (--hotWaitingFiles === 0 && hotChunksLoading === 0) { hotUpdateDownloaded(); } } function hotEnsureUpdateChunk(chunkId) { if (!hotAvailableFilesMap[chunkId]) { hotWaitingFilesMap[chunkId] = true; } else { hotRequestedFilesMap[chunkId] = true; hotWaitingFiles++; hotDownloadUpdateChunk(chunkId); } } function hotUpdateDownloaded() { hotSetStatus("ready"); var deferred = hotDeferred; hotDeferred = null; if (!deferred) return; if (hotApplyOnUpdate) { // Wrap deferred object in Promise to mark it as a well-handled Promise to // avoid triggering uncaught exception warning in Chrome. // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666 Promise.resolve() .then(function() { return hotApply(hotApplyOnUpdate); }) .then( function(result) { deferred.resolve(result); }, function(err) { deferred.reject(err); } ); } else { var outdatedModules = []; for (var id in hotUpdate) { if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { outdatedModules.push(toModuleId(id)); } } deferred.resolve(outdatedModules); } } function hotApply(options) { if (hotStatus !== "ready") throw new Error("apply() is only allowed in ready status"); options = options || {}; var cb; var i; var j; var module; var moduleId; function getAffectedStuff(updateModuleId) { var outdatedModules = [updateModuleId]; var outdatedDependencies = {}; var queue = outdatedModules.slice().map(function(id) { return { chain: [id], id: id }; }); while (queue.length > 0) { var queueItem = queue.pop(); var moduleId = queueItem.id; var chain = queueItem.chain; module = installedModules[moduleId]; if (!module || module.hot._selfAccepted) continue; if (module.hot._selfDeclined) { return { type: "self-declined", chain: chain, moduleId: moduleId }; } if (module.hot._main) { return { type: "unaccepted", chain: chain, moduleId: moduleId }; } for (var i = 0; i < module.parents.length; i++) { var parentId = module.parents[i]; var parent = installedModules[parentId]; if (!parent) continue; if (parent.hot._declinedDependencies[moduleId]) { return { type: "declined", chain: chain.concat([parentId]), moduleId: moduleId, parentId: parentId }; } if (outdatedModules.indexOf(parentId) !== -1) continue; if (parent.hot._acceptedDependencies[moduleId]) { if (!outdatedDependencies[parentId]) outdatedDependencies[parentId] = []; addAllToSet(outdatedDependencies[parentId], [moduleId]); continue; } delete outdatedDependencies[parentId]; outdatedModules.push(parentId); queue.push({ chain: chain.concat([parentId]), id: parentId }); } } return { type: "accepted", moduleId: updateModuleId, outdatedModules: outdatedModules, outdatedDependencies: outdatedDependencies }; } function addAllToSet(a, b) { for (var i = 0; i < b.length; i++) { var item = b[i]; if (a.indexOf(item) === -1) a.push(item); } } // at begin all updates modules are outdated // the "outdated" status can propagate to parents if they don't accept the children var outdatedDependencies = {}; var outdatedModules = []; var appliedUpdate = {}; var warnUnexpectedRequire = function warnUnexpectedRequire() { console.warn( "[HMR] unexpected require(" + result.moduleId + ") to disposed module" ); }; for (var id in hotUpdate) { if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { moduleId = toModuleId(id); /** @type {TODO} */ var result; if (hotUpdate[id]) { result = getAffectedStuff(moduleId); } else { result = { type: "disposed", moduleId: id }; } /** @type {Error|false} */ var abortError = false; var doApply = false; var doDispose = false; var chainInfo = ""; if (result.chain) { chainInfo = "\nUpdate propagation: " + result.chain.join(" -> "); } switch (result.type) { case "self-declined": if (options.onDeclined) options.onDeclined(result); if (!options.ignoreDeclined) abortError = new Error( "Aborted because of self decline: " + result.moduleId + chainInfo ); break; case "declined": if (options.onDeclined) options.onDeclined(result); if (!options.ignoreDeclined) abortError = new Error( "Aborted because of declined dependency: " + result.moduleId + " in " + result.parentId + chainInfo ); break; case "unaccepted": if (options.onUnaccepted) options.onUnaccepted(result); if (!options.ignoreUnaccepted) abortError = new Error( "Aborted because " + moduleId + " is not accepted" + chainInfo ); break; case "accepted": if (options.onAccepted) options.onAccepted(result); doApply = true; break; case "disposed": if (options.onDisposed) options.onDisposed(result); doDispose = true; break; default: throw new Error("Unexception type " + result.type); } if (abortError) { hotSetStatus("abort"); return Promise.reject(abortError); } if (doApply) { appliedUpdate[moduleId] = hotUpdate[moduleId]; addAllToSet(outdatedModules, result.outdatedModules); for (moduleId in result.outdatedDependencies) { if ( Object.prototype.hasOwnProperty.call( result.outdatedDependencies, moduleId ) ) { if (!outdatedDependencies[moduleId]) outdatedDependencies[moduleId] = []; addAllToSet( outdatedDependencies[moduleId], result.outdatedDependencies[moduleId] ); } } } if (doDispose) { addAllToSet(outdatedModules, [result.moduleId]); appliedUpdate[moduleId] = warnUnexpectedRequire; } } } // Store self accepted outdated modules to require them later by the module system var outdatedSelfAcceptedModules = []; for (i = 0; i < outdatedModules.length; i++) { moduleId = outdatedModules[i]; if ( installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted ) outdatedSelfAcceptedModules.push({ module: moduleId, errorHandler: installedModules[moduleId].hot._selfAccepted }); } // Now in "dispose" phase hotSetStatus("dispose"); Object.keys(hotAvailableFilesMap).forEach(function(chunkId) { if (hotAvailableFilesMap[chunkId] === false) { hotDisposeChunk(chunkId); } }); var idx; var queue = outdatedModules.slice(); while (queue.length > 0) { moduleId = queue.pop(); module = installedModules[moduleId]; if (!module) continue; var data = {}; // Call dispose handlers var disposeHandlers = module.hot._disposeHandlers; for (j = 0; j < disposeHandlers.length; j++) { cb = disposeHandlers[j]; cb(data); } hotCurrentModuleData[moduleId] = data; // disable module (this disables requires from this module) module.hot.active = false; // remove module from cache delete installedModules[moduleId]; // when disposing there is no need to call dispose handler delete outdatedDependencies[moduleId]; // remove "parents" references from all children for (j = 0; j < module.children.length; j++) { var child = installedModules[module.children[j]]; if (!child) continue; idx = child.parents.indexOf(moduleId); if (idx >= 0) { child.parents.splice(idx, 1); } } } // remove outdated dependency from module children var dependency; var moduleOutdatedDependencies; for (moduleId in outdatedDependencies) { if ( Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) ) { module = installedModules[moduleId]; if (module) { moduleOutdatedDependencies = outdatedDependencies[moduleId]; for (j = 0; j < moduleOutdatedDependencies.length; j++) { dependency = moduleOutdatedDependencies[j]; idx = module.children.indexOf(dependency); if (idx >= 0) module.children.splice(idx, 1); } } } } // Not in "apply" phase hotSetStatus("apply"); hotCurrentHash = hotUpdateNewHash; // insert new code for (moduleId in appliedUpdate) { if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { modules[moduleId] = appliedUpdate[moduleId]; } } // call accept handlers var error = null; for (moduleId in outdatedDependencies) { if ( Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) ) { module = installedModules[moduleId]; if (module) { moduleOutdatedDependencies = outdatedDependencies[moduleId]; var callbacks = []; for (i = 0; i < moduleOutdatedDependencies.length; i++) { dependency = moduleOutdatedDependencies[i]; cb = module.hot._acceptedDependencies[dependency]; if (cb) { if (callbacks.indexOf(cb) !== -1) continue; callbacks.push(cb); } } for (i = 0; i < callbacks.length; i++) { cb = callbacks[i]; try { cb(moduleOutdatedDependencies); } catch (err) { if (options.onErrored) { options.onErrored({ type: "accept-errored", moduleId: moduleId, dependencyId: moduleOutdatedDependencies[i], error: err }); } if (!options.ignoreErrored) { if (!error) error = err; } } } } } } // Load self accepted modules for (i = 0; i < outdatedSelfAcceptedModules.length; i++) { var item = outdatedSelfAcceptedModules[i]; moduleId = item.module; hotCurrentParents = [moduleId]; try { $require$(moduleId); } catch (err) { if (typeof item.errorHandler === "function") { try { item.errorHandler(err); } catch (err2) { if (options.onErrored) { options.onErrored({ type: "self-accept-error-handler-errored", moduleId: moduleId, error: err2, originalError: err }); } if (!options.ignoreErrored) { if (!error) error = err2; } if (!error) error = err; } } else { if (options.onErrored) { options.onErrored({ type: "self-accept-errored", moduleId: moduleId, error: err }); } if (!options.ignoreErrored) { if (!error) error = err; } } } } // handle errors in accept handlers and self accepted module load if (error) { hotSetStatus("fail"); return Promise.reject(error); } hotSetStatus("idle"); return new Promise(function(resolve) { resolve(outdatedModules); }); } }; webpack-4.30.0/lib/HotModuleReplacementPlugin.js000066400000000000000000000302301345416772700215730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { SyncBailHook } = require("tapable"); const { RawSource } = require("webpack-sources"); const Template = require("./Template"); const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency"); const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency"); const ConstDependency = require("./dependencies/ConstDependency"); const NullFactory = require("./NullFactory"); const ParserHelpers = require("./ParserHelpers"); module.exports = class HotModuleReplacementPlugin { constructor(options) { this.options = options || {}; this.multiStep = this.options.multiStep; this.fullBuildTimeout = this.options.fullBuildTimeout || 200; this.requestTimeout = this.options.requestTimeout || 10000; } apply(compiler) { const multiStep = this.multiStep; const fullBuildTimeout = this.fullBuildTimeout; const requestTimeout = this.requestTimeout; const hotUpdateChunkFilename = compiler.options.output.hotUpdateChunkFilename; const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename; compiler.hooks.additionalPass.tapAsync( "HotModuleReplacementPlugin", callback => { if (multiStep) return setTimeout(callback, fullBuildTimeout); return callback(); } ); const addParserPlugins = (parser, parserOptions) => { parser.hooks.expression .for("__webpack_hash__") .tap( "HotModuleReplacementPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire( parser, "__webpack_require__.h()" ) ); parser.hooks.evaluateTypeof .for("__webpack_hash__") .tap( "HotModuleReplacementPlugin", ParserHelpers.evaluateToString("string") ); parser.hooks.evaluateIdentifier.for("module.hot").tap( { name: "HotModuleReplacementPlugin", before: "NodeStuffPlugin" }, expr => { return ParserHelpers.evaluateToIdentifier( "module.hot", !!parser.state.compilation.hotUpdateChunkTemplate )(expr); } ); // TODO webpack 5: refactor this, no custom hooks if (!parser.hooks.hotAcceptCallback) { parser.hooks.hotAcceptCallback = new SyncBailHook([ "expression", "requests" ]); } if (!parser.hooks.hotAcceptWithoutCallback) { parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ "expression", "requests" ]); } parser.hooks.call .for("module.hot.accept") .tap("HotModuleReplacementPlugin", expr => { if (!parser.state.compilation.hotUpdateChunkTemplate) { return false; } if (expr.arguments.length >= 1) { const arg = parser.evaluateExpression(expr.arguments[0]); let params = []; let requests = []; if (arg.isString()) { params = [arg]; } else if (arg.isArray()) { params = arg.items.filter(param => param.isString()); } if (params.length > 0) { params.forEach((param, idx) => { const request = param.string; const dep = new ModuleHotAcceptDependency(request, param.range); dep.optional = true; dep.loc = Object.create(expr.loc); dep.loc.index = idx; parser.state.module.addDependency(dep); requests.push(request); }); if (expr.arguments.length > 1) { parser.hooks.hotAcceptCallback.call( expr.arguments[1], requests ); parser.walkExpression(expr.arguments[1]); // other args are ignored return true; } else { parser.hooks.hotAcceptWithoutCallback.call(expr, requests); return true; } } } }); parser.hooks.call .for("module.hot.decline") .tap("HotModuleReplacementPlugin", expr => { if (!parser.state.compilation.hotUpdateChunkTemplate) { return false; } if (expr.arguments.length === 1) { const arg = parser.evaluateExpression(expr.arguments[0]); let params = []; if (arg.isString()) { params = [arg]; } else if (arg.isArray()) { params = arg.items.filter(param => param.isString()); } params.forEach((param, idx) => { const dep = new ModuleHotDeclineDependency( param.string, param.range ); dep.optional = true; dep.loc = Object.create(expr.loc); dep.loc.index = idx; parser.state.module.addDependency(dep); }); } }); parser.hooks.expression .for("module.hot") .tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal); }; compiler.hooks.compilation.tap( "HotModuleReplacementPlugin", (compilation, { normalModuleFactory }) => { const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; if (!hotUpdateChunkTemplate) return; compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); compilation.dependencyFactories.set( ModuleHotAcceptDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ModuleHotAcceptDependency, new ModuleHotAcceptDependency.Template() ); compilation.dependencyFactories.set( ModuleHotDeclineDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template() ); compilation.hooks.record.tap( "HotModuleReplacementPlugin", (compilation, records) => { if (records.hash === compilation.hash) return; records.hash = compilation.hash; records.moduleHashs = {}; for (const module of compilation.modules) { const identifier = module.identifier(); records.moduleHashs[identifier] = module.hash; } records.chunkHashs = {}; for (const chunk of compilation.chunks) { records.chunkHashs[chunk.id] = chunk.hash; } records.chunkModuleIds = {}; for (const chunk of compilation.chunks) { records.chunkModuleIds[chunk.id] = Array.from( chunk.modulesIterable, m => m.id ); } } ); let initialPass = false; let recompilation = false; compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => { let records = compilation.records; if (!records) { initialPass = true; return; } if (!records.hash) initialPass = true; const preHash = records.preHash || "x"; const prepreHash = records.prepreHash || "x"; if (preHash === compilation.hash) { recompilation = true; compilation.modifyHash(prepreHash); return; } records.prepreHash = records.hash || "x"; records.preHash = compilation.hash; compilation.modifyHash(records.prepreHash); }); compilation.hooks.shouldGenerateChunkAssets.tap( "HotModuleReplacementPlugin", () => { if (multiStep && !recompilation && !initialPass) return false; } ); compilation.hooks.needAdditionalPass.tap( "HotModuleReplacementPlugin", () => { if (multiStep && !recompilation && !initialPass) return true; } ); compilation.hooks.additionalChunkAssets.tap( "HotModuleReplacementPlugin", () => { const records = compilation.records; if (records.hash === compilation.hash) return; if ( !records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds ) return; for (const module of compilation.modules) { const identifier = module.identifier(); let hash = module.hash; module.hotUpdate = records.moduleHashs[identifier] !== hash; } const hotUpdateMainContent = { h: compilation.hash, c: {} }; for (const key of Object.keys(records.chunkHashs)) { const chunkId = isNaN(+key) ? key : +key; const currentChunk = compilation.chunks.find( chunk => `${chunk.id}` === key ); if (currentChunk) { const newModules = currentChunk .getModules() .filter(module => module.hotUpdate); const allModules = new Set(); for (const module of currentChunk.modulesIterable) { allModules.add(module.id); } const removedModules = records.chunkModuleIds[chunkId].filter( id => !allModules.has(id) ); if (newModules.length > 0 || removedModules.length > 0) { const source = hotUpdateChunkTemplate.render( chunkId, newModules, removedModules, compilation.hash, compilation.moduleTemplates.javascript, compilation.dependencyTemplates ); const filename = compilation.getPath(hotUpdateChunkFilename, { hash: records.hash, chunk: currentChunk }); compilation.additionalChunkAssets.push(filename); compilation.assets[filename] = source; hotUpdateMainContent.c[chunkId] = true; currentChunk.files.push(filename); compilation.hooks.chunkAsset.call(currentChunk, filename); } } else { hotUpdateMainContent.c[chunkId] = false; } } const source = new RawSource(JSON.stringify(hotUpdateMainContent)); const filename = compilation.getPath(hotUpdateMainFilename, { hash: records.hash }); compilation.assets[filename] = source; } ); const mainTemplate = compilation.mainTemplate; mainTemplate.hooks.hash.tap("HotModuleReplacementPlugin", hash => { hash.update("HotMainTemplateDecorator"); }); mainTemplate.hooks.moduleRequire.tap( "HotModuleReplacementPlugin", (_, chunk, hash, varModuleId) => { return `hotCreateRequire(${varModuleId})`; } ); mainTemplate.hooks.requireExtensions.tap( "HotModuleReplacementPlugin", source => { const buf = [source]; buf.push(""); buf.push("// __webpack_hash__"); buf.push( mainTemplate.requireFn + ".h = function() { return hotCurrentHash; };" ); return Template.asString(buf); } ); const needChunkLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.chunks.length > 1) return true; if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; mainTemplate.hooks.bootstrap.tap( "HotModuleReplacementPlugin", (source, chunk, hash) => { source = mainTemplate.hooks.hotBootstrap.call(source, chunk, hash); return Template.asString([ source, "", hotInitCode .replace(/\$require\$/g, mainTemplate.requireFn) .replace(/\$hash\$/g, JSON.stringify(hash)) .replace(/\$requestTimeout\$/g, requestTimeout) .replace( /\/\*foreachInstalledChunks\*\//g, needChunkLoadingCode(chunk) ? "for(var chunkId in installedChunks)" : `var chunkId = ${JSON.stringify(chunk.id)};` ) ]); } ); mainTemplate.hooks.globalHash.tap( "HotModuleReplacementPlugin", () => true ); mainTemplate.hooks.currentHash.tap( "HotModuleReplacementPlugin", (_, length) => { if (isFinite(length)) { return `hotCurrentHash.substr(0, ${length})`; } else { return "hotCurrentHash"; } } ); mainTemplate.hooks.moduleObj.tap( "HotModuleReplacementPlugin", (source, chunk, hash, varModuleId) => { return Template.asString([ `${source},`, `hot: hotCreateModule(${varModuleId}),`, "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),", "children: []" ]); } ); // TODO add HMR support for javascript/esm normalModuleFactory.hooks.parser .for("javascript/auto") .tap("HotModuleReplacementPlugin", addParserPlugins); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("HotModuleReplacementPlugin", addParserPlugins); compilation.hooks.normalModuleLoader.tap( "HotModuleReplacementPlugin", context => { context.hot = true; } ); } ); } }; const hotInitCode = Template.getFunctionContent( require("./HotModuleReplacement.runtime") ); webpack-4.30.0/lib/HotUpdateChunk.js000066400000000000000000000005041345416772700172230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Chunk = require("./Chunk"); class HotUpdateChunk extends Chunk { constructor() { super(); /** @type {(string|number)[]} */ this.removedModules = undefined; } } module.exports = HotUpdateChunk; webpack-4.30.0/lib/HotUpdateChunkTemplate.js000066400000000000000000000031301345416772700207150ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("./Template"); const HotUpdateChunk = require("./HotUpdateChunk"); const { Tapable, SyncWaterfallHook, SyncHook } = require("tapable"); module.exports = class HotUpdateChunkTemplate extends Tapable { constructor(outputOptions) { super(); this.outputOptions = outputOptions || {}; this.hooks = { modules: new SyncWaterfallHook([ "source", "modules", "removedModules", "moduleTemplate", "dependencyTemplates" ]), render: new SyncWaterfallHook([ "source", "modules", "removedModules", "hash", "id", "moduleTemplate", "dependencyTemplates" ]), hash: new SyncHook(["hash"]) }; } render( id, modules, removedModules, hash, moduleTemplate, dependencyTemplates ) { const hotUpdateChunk = new HotUpdateChunk(); hotUpdateChunk.id = id; hotUpdateChunk.setModules(modules); hotUpdateChunk.removedModules = removedModules; const modulesSource = Template.renderChunkModules( hotUpdateChunk, m => typeof m.source === "function", moduleTemplate, dependencyTemplates ); const core = this.hooks.modules.call( modulesSource, modules, removedModules, moduleTemplate, dependencyTemplates ); const source = this.hooks.render.call( core, modules, removedModules, hash, id, moduleTemplate, dependencyTemplates ); return source; } updateHash(hash) { hash.update("HotUpdateChunkTemplate"); hash.update("1"); this.hooks.hash.call(hash); } }; webpack-4.30.0/lib/IgnorePlugin.js000066400000000000000000000045741345416772700167520ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/IgnorePlugin.json"); /** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ /** @typedef {import("./Compiler")} Compiler */ class IgnorePlugin { /** * @param {IgnorePluginOptions} options IgnorePlugin options */ constructor(options) { // TODO webpack 5 remove this compat-layer if (arguments.length > 1 || options instanceof RegExp) { options = { resourceRegExp: arguments[0], contextRegExp: arguments[1] }; } validateOptions(schema, options, "IgnorePlugin"); this.options = options; /** @private @type {Function} */ this.checkIgnore = this.checkIgnore.bind(this); } /** * Note that if "contextRegExp" is given, both the "resourceRegExp" * and "contextRegExp" have to match. * * @param {TODO} result result * @returns {TODO|null} returns result or null if result should be ignored */ checkIgnore(result) { if (!result) return result; if ( "checkResource" in this.options && this.options.checkResource && this.options.checkResource(result.request, result.context) ) { // TODO webpack 5 remove checkContext, as checkResource already gets context if ("checkContext" in this.options && this.options.checkContext) { if (this.options.checkContext(result.context)) { return null; } } else { return null; } } if ( "resourceRegExp" in this.options && this.options.resourceRegExp && this.options.resourceRegExp.test(result.request) ) { if ("contextRegExp" in this.options && this.options.contextRegExp) { // if "contextRegExp" is given, // both the "resourceRegExp" and "contextRegExp" have to match. if (this.options.contextRegExp.test(result.context)) { return null; } } else { return null; } } return result; } /** * @param {Compiler} compiler Webpack Compiler * @returns {void} */ apply(compiler) { compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => { nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); }); compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => { cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); }); } } module.exports = IgnorePlugin; webpack-4.30.0/lib/JavascriptGenerator.js000066400000000000000000000133561345416772700203230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { RawSource, ReplaceSource } = require("webpack-sources"); // TODO: clean up this file // replace with newer constructs // TODO: remove DependencyVariables and replace them with something better class JavascriptGenerator { generate(module, dependencyTemplates, runtimeTemplate) { const originalSource = module.originalSource(); if (!originalSource) { return new RawSource("throw new Error('No source available');"); } const source = new ReplaceSource(originalSource); this.sourceBlock( module, module, [], dependencyTemplates, source, runtimeTemplate ); return source; } sourceBlock( module, block, availableVars, dependencyTemplates, source, runtimeTemplate ) { for (const dependency of block.dependencies) { this.sourceDependency( dependency, dependencyTemplates, source, runtimeTemplate ); } /** * Get the variables of all blocks that we need to inject. * These will contain the variable name and its expression. * The name will be added as a parameter in a IIFE the expression as its value. */ const vars = block.variables.reduce((result, value) => { const variable = this.sourceVariables( value, availableVars, dependencyTemplates, runtimeTemplate ); if (variable) { result.push(variable); } return result; }, []); /** * if we actually have variables * this is important as how #splitVariablesInUniqueNamedChunks works * it will always return an array in an array which would lead to a IIFE wrapper around * a module if we do this with an empty vars array. */ if (vars.length > 0) { /** * Split all variables up into chunks of unique names. * e.g. imagine you have the following variable names that need to be injected: * [foo, bar, baz, foo, some, more] * we can not inject "foo" twice, therefore we just make two IIFEs like so: * (function(foo, bar, baz){ * (function(foo, some, more){ * … * }(…)); * }(…)); * * "splitVariablesInUniqueNamedChunks" splits the variables shown above up to this: * [[foo, bar, baz], [foo, some, more]] */ const injectionVariableChunks = this.splitVariablesInUniqueNamedChunks( vars ); // create all the beginnings of IIFEs const functionWrapperStarts = injectionVariableChunks.map( variableChunk => { return this.variableInjectionFunctionWrapperStartCode( variableChunk.map(variable => variable.name) ); } ); // and all the ends const functionWrapperEnds = injectionVariableChunks.map(variableChunk => { return this.variableInjectionFunctionWrapperEndCode( module, variableChunk.map(variable => variable.expression), block ); }); // join them to one big string const varStartCode = functionWrapperStarts.join(""); // reverse the ends first before joining them, as the last added must be the inner most const varEndCode = functionWrapperEnds.reverse().join(""); // if we have anything, add it to the source if (varStartCode && varEndCode) { const start = block.range ? block.range[0] : -10; const end = block.range ? block.range[1] : module.originalSource().size() + 1; source.insert(start + 0.5, varStartCode); source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode); } } for (const childBlock of block.blocks) { this.sourceBlock( module, childBlock, availableVars.concat(vars), dependencyTemplates, source, runtimeTemplate ); } } sourceDependency(dependency, dependencyTemplates, source, runtimeTemplate) { const template = dependencyTemplates.get(dependency.constructor); if (!template) { throw new Error( "No template for dependency: " + dependency.constructor.name ); } template.apply(dependency, source, runtimeTemplate, dependencyTemplates); } sourceVariables( variable, availableVars, dependencyTemplates, runtimeTemplate ) { const name = variable.name; const expr = variable.expressionSource( dependencyTemplates, runtimeTemplate ); if ( availableVars.some( v => v.name === name && v.expression.source() === expr.source() ) ) { return; } return { name: name, expression: expr }; } /* * creates the start part of a IIFE around the module to inject a variable name * (function(…){ <- this part * }.call(…)) */ variableInjectionFunctionWrapperStartCode(varNames) { const args = varNames.join(", "); return `/* WEBPACK VAR INJECTION */(function(${args}) {`; } contextArgument(module, block) { if (this === block) { return module.exportsArgument; } return "this"; } /* * creates the end part of a IIFE around the module to inject a variable name * (function(…){ * }.call(…)) <- this part */ variableInjectionFunctionWrapperEndCode(module, varExpressions, block) { const firstParam = this.contextArgument(module, block); const furtherParams = varExpressions.map(e => e.source()).join(", "); return `}.call(${firstParam}, ${furtherParams}))`; } splitVariablesInUniqueNamedChunks(vars) { const startState = [[]]; return vars.reduce((chunks, variable) => { const current = chunks[chunks.length - 1]; // check if variable with same name exists already // if so create a new chunk of variables. const variableNameAlreadyExists = current.some( v => v.name === variable.name ); if (variableNameAlreadyExists) { // start new chunk with current variable chunks.push([variable]); } else { // else add it to current chunk current.push(variable); } return chunks; }, startState); } } module.exports = JavascriptGenerator; webpack-4.30.0/lib/JavascriptModulesPlugin.js000066400000000000000000000124021345416772700211530ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Parser = require("./Parser"); const Template = require("./Template"); const { ConcatSource } = require("webpack-sources"); const JavascriptGenerator = require("./JavascriptGenerator"); const createHash = require("./util/createHash"); class JavascriptModulesPlugin { apply(compiler) { compiler.hooks.compilation.tap( "JavascriptModulesPlugin", (compilation, { normalModuleFactory }) => { normalModuleFactory.hooks.createParser .for("javascript/auto") .tap("JavascriptModulesPlugin", options => { return new Parser(options, "auto"); }); normalModuleFactory.hooks.createParser .for("javascript/dynamic") .tap("JavascriptModulesPlugin", options => { return new Parser(options, "script"); }); normalModuleFactory.hooks.createParser .for("javascript/esm") .tap("JavascriptModulesPlugin", options => { return new Parser(options, "module"); }); normalModuleFactory.hooks.createGenerator .for("javascript/auto") .tap("JavascriptModulesPlugin", () => { return new JavascriptGenerator(); }); normalModuleFactory.hooks.createGenerator .for("javascript/dynamic") .tap("JavascriptModulesPlugin", () => { return new JavascriptGenerator(); }); normalModuleFactory.hooks.createGenerator .for("javascript/esm") .tap("JavascriptModulesPlugin", () => { return new JavascriptGenerator(); }); compilation.mainTemplate.hooks.renderManifest.tap( "JavascriptModulesPlugin", (result, options) => { const chunk = options.chunk; const hash = options.hash; const fullHash = options.fullHash; const outputOptions = options.outputOptions; const moduleTemplates = options.moduleTemplates; const dependencyTemplates = options.dependencyTemplates; const filenameTemplate = chunk.filenameTemplate || outputOptions.filename; const useChunkHash = compilation.mainTemplate.useChunkHash(chunk); result.push({ render: () => compilation.mainTemplate.render( hash, chunk, moduleTemplates.javascript, dependencyTemplates ), filenameTemplate, pathOptions: { noChunkHash: !useChunkHash, contentHashType: "javascript", chunk }, identifier: `chunk${chunk.id}`, hash: useChunkHash ? chunk.hash : fullHash }); return result; } ); compilation.mainTemplate.hooks.modules.tap( "JavascriptModulesPlugin", (source, chunk, hash, moduleTemplate, dependencyTemplates) => { return Template.renderChunkModules( chunk, m => typeof m.source === "function", moduleTemplate, dependencyTemplates, "/******/ " ); } ); compilation.chunkTemplate.hooks.renderManifest.tap( "JavascriptModulesPlugin", (result, options) => { const chunk = options.chunk; const outputOptions = options.outputOptions; const moduleTemplates = options.moduleTemplates; const dependencyTemplates = options.dependencyTemplates; const filenameTemplate = chunk.filenameTemplate || outputOptions.chunkFilename; result.push({ render: () => this.renderJavascript( compilation.chunkTemplate, chunk, moduleTemplates.javascript, dependencyTemplates ), filenameTemplate, pathOptions: { chunk, contentHashType: "javascript" }, identifier: `chunk${chunk.id}`, hash: chunk.hash }); return result; } ); compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { const outputOptions = compilation.outputOptions; const { hashSalt, hashDigest, hashDigestLength, hashFunction } = outputOptions; const hash = createHash(hashFunction); if (hashSalt) hash.update(hashSalt); const template = chunk.hasRuntime() ? compilation.mainTemplate : compilation.chunkTemplate; hash.update(`${chunk.id} `); hash.update(chunk.ids ? chunk.ids.join(",") : ""); template.updateHashForChunk( hash, chunk, compilation.moduleTemplates.javascript, compilation.dependencyTemplates ); for (const m of chunk.modulesIterable) { if (typeof m.source === "function") { hash.update(m.hash); } } chunk.contentHash.javascript = hash .digest(hashDigest) .substr(0, hashDigestLength); }); } ); } renderJavascript(chunkTemplate, chunk, moduleTemplate, dependencyTemplates) { const moduleSources = Template.renderChunkModules( chunk, m => typeof m.source === "function", moduleTemplate, dependencyTemplates ); const core = chunkTemplate.hooks.modules.call( moduleSources, chunk, moduleTemplate, dependencyTemplates ); let source = chunkTemplate.hooks.render.call( core, chunk, moduleTemplate, dependencyTemplates ); if (chunk.hasEntryModule()) { source = chunkTemplate.hooks.renderWithEntry.call(source, chunk); } chunk.rendered = true; return new ConcatSource(source, ";"); } } module.exports = JavascriptModulesPlugin; webpack-4.30.0/lib/JsonGenerator.js000066400000000000000000000026451345416772700171250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource, RawSource } = require("webpack-sources"); const stringifySafe = data => { const stringified = JSON.stringify(data); if (!stringified) { return undefined; // Invalid JSON } return stringified.replace(/\u2028|\u2029/g, str => str === "\u2029" ? "\\u2029" : "\\u2028" ); // invalid in JavaScript but valid JSON }; class JsonGenerator { generate(module, dependencyTemplates, runtimeTemplate) { const source = new ConcatSource(); const data = module.buildInfo.jsonData; if (data === undefined) { return new RawSource( runtimeTemplate.missingModuleStatement({ request: module.rawRequest }) ); } if ( Array.isArray(module.buildMeta.providedExports) && !module.isUsed("default") ) { // Only some exports are used: We can optimize here, by only generating a part of the JSON const reducedJson = {}; for (const exportName of module.buildMeta.providedExports) { if (exportName === "default") continue; const used = module.isUsed(exportName); if (used) { reducedJson[used] = data[exportName]; } } source.add( `${module.moduleArgument}.exports = ${stringifySafe(reducedJson)};` ); } else { source.add(`${module.moduleArgument}.exports = ${stringifySafe(data)};`); } return source; } } module.exports = JsonGenerator; webpack-4.30.0/lib/JsonModulesPlugin.js000066400000000000000000000012721345416772700177610ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const JsonParser = require("./JsonParser"); const JsonGenerator = require("./JsonGenerator"); class JsonModulesPlugin { apply(compiler) { compiler.hooks.compilation.tap( "JsonModulesPlugin", (compilation, { normalModuleFactory }) => { normalModuleFactory.hooks.createParser .for("json") .tap("JsonModulesPlugin", () => { return new JsonParser(); }); normalModuleFactory.hooks.createGenerator .for("json") .tap("JsonModulesPlugin", () => { return new JsonGenerator(); }); } ); } } module.exports = JsonModulesPlugin; webpack-4.30.0/lib/JsonParser.js000066400000000000000000000013661345416772700164320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const parseJson = require("json-parse-better-errors"); const JsonExportsDependency = require("./dependencies/JsonExportsDependency"); class JsonParser { constructor(options) { this.options = options; } parse(source, state) { const data = parseJson(source[0] === "\ufeff" ? source.slice(1) : source); state.module.buildInfo.jsonData = data; state.module.buildMeta.exportsType = "named"; if (typeof data === "object" && data) { state.module.addDependency(new JsonExportsDependency(Object.keys(data))); } state.module.addDependency(new JsonExportsDependency(["default"])); return state; } } module.exports = JsonParser; webpack-4.30.0/lib/LibManifestPlugin.js000066400000000000000000000043361345416772700177200ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const asyncLib = require("neo-async"); const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); class LibManifestPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.hooks.emit.tapAsync( "LibManifestPlugin", (compilation, callback) => { asyncLib.forEach( compilation.chunks, (chunk, callback) => { if (!chunk.isOnlyInitial()) { callback(); return; } const targetPath = compilation.getPath(this.options.path, { hash: compilation.hash, chunk }); const name = this.options.name && compilation.getPath(this.options.name, { hash: compilation.hash, chunk }); const manifest = { name, type: this.options.type, content: Array.from(chunk.modulesIterable, module => { if ( this.options.entryOnly && !module.reasons.some( r => r.dependency instanceof SingleEntryDependency ) ) { return; } if (module.libIdent) { const ident = module.libIdent({ context: this.options.context || compiler.options.context }); if (ident) { return { ident, data: { id: module.id, buildMeta: module.buildMeta } }; } } }) .filter(Boolean) .reduce((obj, item) => { obj[item.ident] = item.data; return obj; }, Object.create(null)) }; // Apply formatting to content if format flag is true; const manifestContent = this.options.format ? JSON.stringify(manifest, null, 2) : JSON.stringify(manifest); const content = Buffer.from(manifestContent, "utf8"); compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => { if (err) return callback(err); compiler.outputFileSystem.writeFile( targetPath, content, callback ); }); }, callback ); } ); } } module.exports = LibManifestPlugin; webpack-4.30.0/lib/LibraryTemplatePlugin.js000066400000000000000000000131761345416772700206250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin"); /** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ /** @typedef {import("./Compiler")} Compiler */ /** * @param {string[]} accessor the accessor to convert to path * @returns {string} the path */ const accessorToObjectAccess = accessor => { return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); }; /** * @param {string=} base the path prefix * @param {string|string[]|LibraryCustomUmdObject} accessor the accessor * @param {"amd" | "commonjs" | "root"} umdProperty property used when a custom umd object is provided * @param {string=} joinWith the element separator * @returns {string} the path */ const accessorAccess = (base, accessor, umdProperty, joinWith = "; ") => { const normalizedAccessor = typeof accessor === "object" && !Array.isArray(accessor) ? accessor[umdProperty] : accessor; const accessors = Array.isArray(normalizedAccessor) ? normalizedAccessor : [normalizedAccessor]; return accessors .map((_, idx) => { const a = base ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); if (idx === accessors.length - 1) return a; if (idx === 0 && base === undefined) { return `${a} = typeof ${a} === "object" ? ${a} : {}`; } return `${a} = ${a} || {}`; }) .join(joinWith); }; class LibraryTemplatePlugin { /** * @param {string|string[]|LibraryCustomUmdObject} name name of library * @param {string} target type of library * @param {boolean} umdNamedDefine setting this to true will name the UMD module * @param {string|TODO} auxiliaryComment comment in the UMD wrapper * @param {string|string[]} exportProperty which export should be exposed as library */ constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { this.name = name; this.target = target; this.umdNamedDefine = umdNamedDefine; this.auxiliaryComment = auxiliaryComment; this.exportProperty = exportProperty; } /** * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { compiler.hooks.thisCompilation.tap("LibraryTemplatePlugin", compilation => { if (this.exportProperty) { const ExportPropertyMainTemplatePlugin = require("./ExportPropertyMainTemplatePlugin"); new ExportPropertyMainTemplatePlugin(this.exportProperty).apply( compilation ); } switch (this.target) { case "var": if ( !this.name || (typeof this.name === "object" && !Array.isArray(this.name)) ) { throw new Error( "library name must be set and not an UMD custom object for non-UMD target" ); } new SetVarMainTemplatePlugin( `var ${accessorAccess(undefined, this.name, "root")}`, false ).apply(compilation); break; case "assign": new SetVarMainTemplatePlugin( accessorAccess(undefined, this.name, "root"), false ).apply(compilation); break; case "this": case "self": case "window": if (this.name) { new SetVarMainTemplatePlugin( accessorAccess(this.target, this.name, "root"), false ).apply(compilation); } else { new SetVarMainTemplatePlugin(this.target, true).apply(compilation); } break; case "global": if (this.name) { new SetVarMainTemplatePlugin( accessorAccess( compilation.runtimeTemplate.outputOptions.globalObject, this.name, "root" ), false ).apply(compilation); } else { new SetVarMainTemplatePlugin( compilation.runtimeTemplate.outputOptions.globalObject, true ).apply(compilation); } break; case "commonjs": if (this.name) { new SetVarMainTemplatePlugin( accessorAccess("exports", this.name, "commonjs"), false ).apply(compilation); } else { new SetVarMainTemplatePlugin("exports", true).apply(compilation); } break; case "commonjs2": case "commonjs-module": new SetVarMainTemplatePlugin("module.exports", false).apply( compilation ); break; case "amd": case "amd-require": { const AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); if (this.name && typeof this.name !== "string") { throw new Error("library name must be a string for amd target"); } new AmdMainTemplatePlugin({ name: this.name, requireAsWrapper: this.target === "amd-require" }).apply(compilation); break; } case "umd": case "umd2": { const UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); new UmdMainTemplatePlugin(this.name, { optionalAmdExternalAsGlobal: this.target === "umd2", namedDefine: this.umdNamedDefine, auxiliaryComment: this.auxiliaryComment }).apply(compilation); break; } case "jsonp": { const JsonpExportMainTemplatePlugin = require("./web/JsonpExportMainTemplatePlugin"); if (typeof this.name !== "string") throw new Error("library name must be a string for jsonp target"); new JsonpExportMainTemplatePlugin(this.name).apply(compilation); break; } case "system": { const SystemMainTemplatePlugin = require("./SystemMainTemplatePlugin"); new SystemMainTemplatePlugin({ name: this.name }).apply(compilation); break; } default: throw new Error(`${this.target} is not a valid Library target`); } }); } } module.exports = LibraryTemplatePlugin; webpack-4.30.0/lib/LoaderOptionsPlugin.js000066400000000000000000000027271345416772700203070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/LoaderOptionsPlugin.json"); /** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ class LoaderOptionsPlugin { /** * @param {LoaderOptionsPluginOptions} options options object */ constructor(options) { validateOptions(schema, options || {}, "Loader Options Plugin"); if (typeof options !== "object") options = {}; if (!options.test) { options.test = { test: () => true }; } this.options = options; } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => { compilation.hooks.normalModuleLoader.tap( "LoaderOptionsPlugin", (context, module) => { const resource = module.resource; if (!resource) return; const i = resource.indexOf("?"); if ( ModuleFilenameHelpers.matchObject( options, i < 0 ? resource : resource.substr(0, i) ) ) { for (const key of Object.keys(options)) { if (key === "include" || key === "exclude" || key === "test") { continue; } context[key] = options[key]; } } } ); }); } } module.exports = LoaderOptionsPlugin; webpack-4.30.0/lib/LoaderTargetPlugin.js000066400000000000000000000007401345416772700200730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class LoaderTargetPlugin { constructor(target) { this.target = target; } apply(compiler) { compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { compilation.hooks.normalModuleLoader.tap( "LoaderTargetPlugin", loaderContext => { loaderContext.target = this.target; } ); }); } } module.exports = LoaderTargetPlugin; webpack-4.30.0/lib/MainTemplate.js000066400000000000000000000403101345416772700167140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource, OriginalSource, PrefixSource, RawSource } = require("webpack-sources"); const { Tapable, SyncWaterfallHook, SyncHook, SyncBailHook } = require("tapable"); const Template = require("./Template"); /** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("./ModuleTemplate")} ModuleTemplate */ /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Module")} Module} */ /** @typedef {import("./util/createHash").Hash} Hash} */ /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ /** * @typedef {Object} RenderManifestOptions * @property {Chunk} chunk the chunk used to render * @property {string} hash * @property {string} fullHash * @property {TODO} outputOptions * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates * @property {Map} dependencyTemplates */ // require function shortcuts: // __webpack_require__.s = the module id of the entry point // __webpack_require__.c = the module cache // __webpack_require__.m = the module functions // __webpack_require__.p = the bundle public path // __webpack_require__.i = the identity function used for harmony imports // __webpack_require__.e = the chunk ensure function // __webpack_require__.d = the exported property define getter function // __webpack_require__.o = Object.prototype.hasOwnProperty.call // __webpack_require__.r = define compatibility on export // __webpack_require__.t = create a fake namespace object // __webpack_require__.n = compatibility get default export // __webpack_require__.h = the webpack hash // __webpack_require__.w = an object containing all installed WebAssembly.Instance export objects keyed by module id // __webpack_require__.oe = the uncaught error handler for the webpack runtime // __webpack_require__.nc = the script nonce module.exports = class MainTemplate extends Tapable { /** * * @param {TODO=} outputOptions output options for the MainTemplate */ constructor(outputOptions) { super(); /** @type {TODO?} */ this.outputOptions = outputOptions || {}; this.hooks = { /** @type {SyncWaterfallHook} */ renderManifest: new SyncWaterfallHook(["result", "options"]), modules: new SyncWaterfallHook([ "modules", "chunk", "hash", "moduleTemplate", "dependencyTemplates" ]), moduleObj: new SyncWaterfallHook([ "source", "chunk", "hash", "moduleIdExpression" ]), requireEnsure: new SyncWaterfallHook([ "source", "chunk", "hash", "chunkIdExpression" ]), bootstrap: new SyncWaterfallHook([ "source", "chunk", "hash", "moduleTemplate", "dependencyTemplates" ]), localVars: new SyncWaterfallHook(["source", "chunk", "hash"]), require: new SyncWaterfallHook(["source", "chunk", "hash"]), requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]), /** @type {SyncWaterfallHook} */ beforeStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), /** @type {SyncWaterfallHook} */ startup: new SyncWaterfallHook(["source", "chunk", "hash"]), render: new SyncWaterfallHook([ "source", "chunk", "hash", "moduleTemplate", "dependencyTemplates" ]), renderWithEntry: new SyncWaterfallHook(["source", "chunk", "hash"]), moduleRequire: new SyncWaterfallHook([ "source", "chunk", "hash", "moduleIdExpression" ]), addModule: new SyncWaterfallHook([ "source", "chunk", "hash", "moduleIdExpression", "moduleExpression" ]), currentHash: new SyncWaterfallHook(["source", "requestedLength"]), assetPath: new SyncWaterfallHook(["path", "options"]), hash: new SyncHook(["hash"]), hashForChunk: new SyncHook(["hash", "chunk"]), globalHashPaths: new SyncWaterfallHook(["paths"]), globalHash: new SyncBailHook(["chunk", "paths"]), // TODO this should be moved somewhere else // It's weird here hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"]) }; this.hooks.startup.tap("MainTemplate", (source, chunk, hash) => { /** @type {string[]} */ const buf = []; if (chunk.entryModule) { buf.push("// Load entry module and return exports"); buf.push( `return ${this.renderRequireFunctionForModule( hash, chunk, JSON.stringify(chunk.entryModule.id) )}(${this.requireFn}.s = ${JSON.stringify(chunk.entryModule.id)});` ); } return Template.asString(buf); }); this.hooks.render.tap( "MainTemplate", (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => { const source = new ConcatSource(); source.add("/******/ (function(modules) { // webpackBootstrap\n"); source.add(new PrefixSource("/******/", bootstrapSource)); source.add("/******/ })\n"); source.add( "/************************************************************************/\n" ); source.add("/******/ ("); source.add( this.hooks.modules.call( new RawSource(""), chunk, hash, moduleTemplate, dependencyTemplates ) ); source.add(")"); return source; } ); this.hooks.localVars.tap("MainTemplate", (source, chunk, hash) => { return Template.asString([ source, "// The module cache", "var installedModules = {};" ]); }); this.hooks.require.tap("MainTemplate", (source, chunk, hash) => { return Template.asString([ source, "// Check if module is in cache", "if(installedModules[moduleId]) {", Template.indent("return installedModules[moduleId].exports;"), "}", "// Create a new module (and put it into the cache)", "var module = installedModules[moduleId] = {", Template.indent(this.hooks.moduleObj.call("", chunk, hash, "moduleId")), "};", "", Template.asString( outputOptions.strictModuleExceptionHandling ? [ "// Execute the module function", "var threw = true;", "try {", Template.indent([ `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( hash, chunk, "moduleId" )});`, "threw = false;" ]), "} finally {", Template.indent([ "if(threw) delete installedModules[moduleId];" ]), "}" ] : [ "// Execute the module function", `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( hash, chunk, "moduleId" )});` ] ), "", "// Flag the module as loaded", "module.l = true;", "", "// Return the exports of the module", "return module.exports;" ]); }); this.hooks.moduleObj.tap( "MainTemplate", (source, chunk, hash, varModuleId) => { return Template.asString(["i: moduleId,", "l: false,", "exports: {}"]); } ); this.hooks.requireExtensions.tap("MainTemplate", (source, chunk, hash) => { const buf = []; const chunkMaps = chunk.getChunkMaps(); // Check if there are non initial chunks which need to be imported using require-ensure if (Object.keys(chunkMaps.hash).length) { buf.push("// This file contains only the entry chunk."); buf.push("// The chunk loading function for additional chunks"); buf.push(`${this.requireFn}.e = function requireEnsure(chunkId) {`); buf.push(Template.indent("var promises = [];")); buf.push( Template.indent( this.hooks.requireEnsure.call("", chunk, hash, "chunkId") ) ); buf.push(Template.indent("return Promise.all(promises);")); buf.push("};"); } else if ( chunk.hasModuleInGraph(m => m.blocks.some(b => b.chunkGroup && b.chunkGroup.chunks.length > 0) ) ) { // There async blocks in the graph, so we need to add an empty requireEnsure // function anyway. This can happen with multiple entrypoints. buf.push("// The chunk loading function for additional chunks"); buf.push("// Since all referenced chunks are already included"); buf.push("// in this file, this function is empty here."); buf.push(`${this.requireFn}.e = function requireEnsure() {`); buf.push(Template.indent("return Promise.resolve();")); buf.push("};"); } buf.push(""); buf.push("// expose the modules object (__webpack_modules__)"); buf.push(`${this.requireFn}.m = modules;`); buf.push(""); buf.push("// expose the module cache"); buf.push(`${this.requireFn}.c = installedModules;`); buf.push(""); buf.push("// define getter function for harmony exports"); buf.push(`${this.requireFn}.d = function(exports, name, getter) {`); buf.push( Template.indent([ `if(!${this.requireFn}.o(exports, name)) {`, Template.indent([ "Object.defineProperty(exports, name, { enumerable: true, get: getter });" ]), "}" ]) ); buf.push("};"); buf.push(""); buf.push("// define __esModule on exports"); buf.push(`${this.requireFn}.r = function(exports) {`); buf.push( Template.indent([ "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", Template.indent([ "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" ]), "}", "Object.defineProperty(exports, '__esModule', { value: true });" ]) ); buf.push("};"); buf.push(""); buf.push("// create a fake namespace object"); buf.push("// mode & 1: value is a module id, require it"); buf.push("// mode & 2: merge all properties of value into the ns"); buf.push("// mode & 4: return value when already ns object"); buf.push("// mode & 8|1: behave like require"); buf.push(`${this.requireFn}.t = function(value, mode) {`); buf.push( Template.indent([ `if(mode & 1) value = ${this.requireFn}(value);`, `if(mode & 8) return value;`, "if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;", "var ns = Object.create(null);", `${this.requireFn}.r(ns);`, "Object.defineProperty(ns, 'default', { enumerable: true, value: value });", "if(mode & 2 && typeof value != 'string') for(var key in value) " + `${this.requireFn}.d(ns, key, function(key) { ` + "return value[key]; " + "}.bind(null, key));", "return ns;" ]) ); buf.push("};"); buf.push(""); buf.push( "// getDefaultExport function for compatibility with non-harmony modules" ); buf.push(this.requireFn + ".n = function(module) {"); buf.push( Template.indent([ "var getter = module && module.__esModule ?", Template.indent([ "function getDefault() { return module['default']; } :", "function getModuleExports() { return module; };" ]), `${this.requireFn}.d(getter, 'a', getter);`, "return getter;" ]) ); buf.push("};"); buf.push(""); buf.push("// Object.prototype.hasOwnProperty.call"); buf.push( `${ this.requireFn }.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };` ); const publicPath = this.getPublicPath({ hash: hash }); buf.push(""); buf.push("// __webpack_public_path__"); buf.push(`${this.requireFn}.p = ${JSON.stringify(publicPath)};`); return Template.asString(buf); }); this.requireFn = "__webpack_require__"; } /** * * @param {RenderManifestOptions} options render manifest options * @returns {TODO[]} returns render manifest */ getRenderManifest(options) { const result = []; this.hooks.renderManifest.call(result, options); return result; } /** * TODO webpack 5: remove moduleTemplate and dependencyTemplates * @param {string} hash hash to be used for render call * @param {Chunk} chunk Chunk instance * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render * @param {Map} dependencyTemplates dependency templates * @returns {string[]} the generated source of the bootstrap code */ renderBootstrap(hash, chunk, moduleTemplate, dependencyTemplates) { const buf = []; buf.push( this.hooks.bootstrap.call( "", chunk, hash, moduleTemplate, dependencyTemplates ) ); buf.push(this.hooks.localVars.call("", chunk, hash)); buf.push(""); buf.push("// The require function"); buf.push(`function ${this.requireFn}(moduleId) {`); buf.push(Template.indent(this.hooks.require.call("", chunk, hash))); buf.push("}"); buf.push(""); buf.push( Template.asString(this.hooks.requireExtensions.call("", chunk, hash)) ); buf.push(""); buf.push(Template.asString(this.hooks.beforeStartup.call("", chunk, hash))); buf.push(Template.asString(this.hooks.startup.call("", chunk, hash))); return buf; } /** * @param {string} hash hash to be used for render call * @param {Chunk} chunk Chunk instance * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render * @param {Map} dependencyTemplates dependency templates * @returns {ConcatSource} the newly generated source from rendering */ render(hash, chunk, moduleTemplate, dependencyTemplates) { const buf = this.renderBootstrap( hash, chunk, moduleTemplate, dependencyTemplates ); let source = this.hooks.render.call( new OriginalSource( Template.prefix(buf, " \t") + "\n", "webpack/bootstrap" ), chunk, hash, moduleTemplate, dependencyTemplates ); if (chunk.hasEntryModule()) { source = this.hooks.renderWithEntry.call(source, chunk, hash); } if (!source) { throw new Error( "Compiler error: MainTemplate plugin 'render' should return something" ); } chunk.rendered = true; return new ConcatSource(source, ";"); } /** * * @param {string} hash hash for render fn * @param {Chunk} chunk Chunk instance for require * @param {(number|string)=} varModuleId module id * @returns {TODO} the moduleRequire hook call return signature */ renderRequireFunctionForModule(hash, chunk, varModuleId) { return this.hooks.moduleRequire.call( this.requireFn, chunk, hash, varModuleId ); } /** * * @param {string} hash hash for render add fn * @param {Chunk} chunk Chunk instance for require add fn * @param {(string|number)=} varModuleId module id * @param {Module} varModule Module instance * @returns {TODO} renderAddModule call */ renderAddModule(hash, chunk, varModuleId, varModule) { return this.hooks.addModule.call( `modules[${varModuleId}] = ${varModule};`, chunk, hash, varModuleId, varModule ); } /** * * @param {string} hash string hash * @param {number=} length length * @returns {string} call hook return */ renderCurrentHashCode(hash, length) { length = length || Infinity; return this.hooks.currentHash.call( JSON.stringify(hash.substr(0, length)), length ); } /** * * @param {object} options get public path options * @returns {string} hook call */ getPublicPath(options) { return this.hooks.assetPath.call( this.outputOptions.publicPath || "", options ); } getAssetPath(path, options) { return this.hooks.assetPath.call(path, options); } /** * Updates hash with information from this template * @param {Hash} hash the hash to update * @returns {void} */ updateHash(hash) { hash.update("maintemplate"); hash.update("3"); this.hooks.hash.call(hash); } /** * TODO webpack 5: remove moduleTemplate and dependencyTemplates * Updates hash with chunk-specific information from this template * @param {Hash} hash the hash to update * @param {Chunk} chunk the chunk * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render * @param {Map} dependencyTemplates dependency templates * @returns {void} */ updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { this.updateHash(hash); this.hooks.hashForChunk.call(hash, chunk); for (const line of this.renderBootstrap( "0000", chunk, moduleTemplate, dependencyTemplates )) { hash.update(line); } } useChunkHash(chunk) { const paths = this.hooks.globalHashPaths.call([]); return !this.hooks.globalHash.call(chunk, paths); } }; webpack-4.30.0/lib/MemoryOutputFileSystem.js000066400000000000000000000002131345416772700210300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ module.exports = require("memory-fs"); webpack-4.30.0/lib/Module.js000066400000000000000000000242071345416772700155700ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const util = require("util"); const DependenciesBlock = require("./DependenciesBlock"); const ModuleReason = require("./ModuleReason"); const SortableSet = require("./util/SortableSet"); const Template = require("./Template"); /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./WebpackError")} WebpackError */ /** @typedef {import("./util/createHash").Hash} Hash */ const EMPTY_RESOLVE_OPTIONS = {}; let debugId = 1000; const sortById = (a, b) => { return a.id - b.id; }; const sortByDebugId = (a, b) => { return a.debugId - b.debugId; }; /** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ class Module extends DependenciesBlock { constructor(type, context = null) { super(); /** @type {string} */ this.type = type; /** @type {string} */ this.context = context; // Unique Id /** @type {number} */ this.debugId = debugId++; // Hash /** @type {string} */ this.hash = undefined; /** @type {string} */ this.renderedHash = undefined; // Info from Factory /** @type {TODO} */ this.resolveOptions = EMPTY_RESOLVE_OPTIONS; /** @type {object} */ this.factoryMeta = {}; // Info from Build /** @type {WebpackError[]} */ this.warnings = []; /** @type {WebpackError[]} */ this.errors = []; /** @type {object} */ this.buildMeta = undefined; /** @type {object} */ this.buildInfo = undefined; // Graph (per Compilation) /** @type {ModuleReason[]} */ this.reasons = []; /** @type {SortableSet} */ this._chunks = new SortableSet(undefined, sortById); // Info from Compilation (per Compilation) /** @type {number|string} */ this.id = null; /** @type {number} */ this.index = null; /** @type {number} */ this.index2 = null; /** @type {number} */ this.depth = null; /** @type {Module} */ this.issuer = null; /** @type {undefined | object} */ this.profile = undefined; /** @type {boolean} */ this.prefetched = false; /** @type {boolean} */ this.built = false; // Info from Optimization (per Compilation) /** @type {null | boolean} */ this.used = null; /** @type {false | true | string[]} */ this.usedExports = null; /** @type {(string | OptimizationBailoutFunction)[]} */ this.optimizationBailout = []; // delayed operations /** @type {undefined | {oldChunk: Chunk, newChunks: Chunk[]}[] } */ this._rewriteChunkInReasons = undefined; /** @type {boolean} */ this.useSourceMap = false; // info from build this._source = null; } get exportsArgument() { return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; } get moduleArgument() { return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; } disconnect() { this.hash = undefined; this.renderedHash = undefined; this.reasons.length = 0; this._rewriteChunkInReasons = undefined; this._chunks.clear(); this.id = null; this.index = null; this.index2 = null; this.depth = null; this.issuer = null; this.profile = undefined; this.prefetched = false; this.built = false; this.used = null; this.usedExports = null; this.optimizationBailout.length = 0; super.disconnect(); } unseal() { this.id = null; this.index = null; this.index2 = null; this.depth = null; this._chunks.clear(); super.unseal(); } setChunks(chunks) { this._chunks = new SortableSet(chunks, sortById); } addChunk(chunk) { if (this._chunks.has(chunk)) return false; this._chunks.add(chunk); return true; } removeChunk(chunk) { if (this._chunks.delete(chunk)) { chunk.removeModule(this); return true; } return false; } isInChunk(chunk) { return this._chunks.has(chunk); } isEntryModule() { for (const chunk of this._chunks) { if (chunk.entryModule === this) return true; } return false; } get optional() { return ( this.reasons.length > 0 && this.reasons.every(r => r.dependency && r.dependency.optional) ); } /** * @returns {Chunk[]} all chunks which contain the module */ getChunks() { return Array.from(this._chunks); } getNumberOfChunks() { return this._chunks.size; } get chunksIterable() { return this._chunks; } hasEqualsChunks(otherModule) { if (this._chunks.size !== otherModule._chunks.size) return false; this._chunks.sortWith(sortByDebugId); otherModule._chunks.sortWith(sortByDebugId); const a = this._chunks[Symbol.iterator](); const b = otherModule._chunks[Symbol.iterator](); // eslint-disable-next-line no-constant-condition while (true) { const aItem = a.next(); const bItem = b.next(); if (aItem.done) return true; if (aItem.value !== bItem.value) return false; } } addReason(module, dependency, explanation) { this.reasons.push(new ModuleReason(module, dependency, explanation)); } removeReason(module, dependency) { for (let i = 0; i < this.reasons.length; i++) { let r = this.reasons[i]; if (r.module === module && r.dependency === dependency) { this.reasons.splice(i, 1); return true; } } return false; } hasReasonForChunk(chunk) { if (this._rewriteChunkInReasons) { for (const operation of this._rewriteChunkInReasons) { this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); } this._rewriteChunkInReasons = undefined; } for (let i = 0; i < this.reasons.length; i++) { if (this.reasons[i].hasChunk(chunk)) return true; } return false; } hasReasons() { return this.reasons.length > 0; } rewriteChunkInReasons(oldChunk, newChunks) { // This is expensive. Delay operation until we really need the data if (this._rewriteChunkInReasons === undefined) { this._rewriteChunkInReasons = []; } this._rewriteChunkInReasons.push({ oldChunk, newChunks }); } _doRewriteChunkInReasons(oldChunk, newChunks) { for (let i = 0; i < this.reasons.length; i++) { this.reasons[i].rewriteChunks(oldChunk, newChunks); } } /** * @param {string=} exportName the name of the export * @returns {boolean|string} false if the export isn't used, true if no exportName is provided and the module is used, or the name to access it if the export is used */ isUsed(exportName) { if (!exportName) return this.used !== false; if (this.used === null || this.usedExports === null) return exportName; if (!this.used) return false; if (!this.usedExports) return false; if (this.usedExports === true) return exportName; let idx = this.usedExports.indexOf(exportName); if (idx < 0) return false; // Mangle export name if possible if (this.isProvided(exportName)) { if (this.buildMeta.exportsType === "namespace") { return Template.numberToIdentifer(idx); } if ( this.buildMeta.exportsType === "named" && !this.usedExports.includes("default") ) { return Template.numberToIdentifer(idx); } } return exportName; } isProvided(exportName) { if (!Array.isArray(this.buildMeta.providedExports)) return null; return this.buildMeta.providedExports.includes(exportName); } toString() { return `Module[${this.id || this.debugId}]`; } needRebuild(fileTimestamps, contextTimestamps) { return true; } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { hash.update(`${this.id}`); hash.update(JSON.stringify(this.usedExports)); super.updateHash(hash); } sortItems(sortChunks) { super.sortItems(); if (sortChunks) this._chunks.sort(); this.reasons.sort((a, b) => { if (a.module === b.module) return 0; if (!a.module) return -1; if (!b.module) return 1; return sortById(a.module, b.module); }); if (Array.isArray(this.usedExports)) { this.usedExports.sort(); } } unbuild() { this.dependencies.length = 0; this.blocks.length = 0; this.variables.length = 0; this.buildMeta = undefined; this.buildInfo = undefined; this.disconnect(); } get arguments() { throw new Error("Module.arguments was removed, there is no replacement."); } set arguments(value) { throw new Error("Module.arguments was removed, there is no replacement."); } } // TODO remove in webpack 5 Object.defineProperty(Module.prototype, "forEachChunk", { configurable: false, value: util.deprecate( /** * @deprecated * @param {function(any, any, Set): void} fn callback function * @returns {void} * @this {Module} */ function(fn) { this._chunks.forEach(fn); }, "Module.forEachChunk: Use for(const chunk of module.chunksIterable) instead" ) }); // TODO remove in webpack 5 Object.defineProperty(Module.prototype, "mapChunks", { configurable: false, value: util.deprecate( /** * @deprecated * @param {function(any, any): void} fn Mapper function * @returns {Array} Array of chunks mapped * @this {Module} */ function(fn) { return Array.from(this._chunks, fn); }, "Module.mapChunks: Use Array.from(module.chunksIterable, fn) instead" ) }); // TODO remove in webpack 5 Object.defineProperty(Module.prototype, "entry", { configurable: false, get() { throw new Error("Module.entry was removed. Use Chunk.entryModule"); }, set() { throw new Error("Module.entry was removed. Use Chunk.entryModule"); } }); // TODO remove in webpack 5 Object.defineProperty(Module.prototype, "meta", { configurable: false, get: util.deprecate( /** * @deprecated * @returns {void} * @this {Module} */ function() { return this.buildMeta; }, "Module.meta was renamed to Module.buildMeta" ), set: util.deprecate( /** * @deprecated * @param {TODO} value Value * @returns {void} * @this {Module} */ function(value) { this.buildMeta = value; }, "Module.meta was renamed to Module.buildMeta" ) }); /** @type {function(): string} */ Module.prototype.identifier = null; /** @type {function(RequestShortener): string} */ Module.prototype.readableIdentifier = null; Module.prototype.build = null; Module.prototype.source = null; Module.prototype.size = null; Module.prototype.nameForCondition = null; /** @type {null | function(Chunk): boolean} */ Module.prototype.chunkCondition = null; Module.prototype.updateCacheModule = null; module.exports = Module; webpack-4.30.0/lib/ModuleBuildError.js000066400000000000000000000023131345416772700175540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const { cutOffLoaderExecution } = require("./ErrorHelpers"); class ModuleBuildError extends WebpackError { constructor(module, err, { from = null } = {}) { let message = "Module build failed"; let details = undefined; if (from) { message += ` (from ${from}):\n`; } else { message += ": "; } if (err !== null && typeof err === "object") { if (typeof err.stack === "string" && err.stack) { const stack = cutOffLoaderExecution(err.stack); if (!err.hideStack) { message += stack; } else { details = stack; if (typeof err.message === "string" && err.message) { message += err.message; } else { message += err; } } } else if (typeof err.message === "string" && err.message) { message += err.message; } else { message += err; } } else { message = err; } super(message); this.name = "ModuleBuildError"; this.details = details; this.module = module; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleBuildError; webpack-4.30.0/lib/ModuleDependencyError.js000066400000000000000000000014541345416772700206000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); /** @typedef {import("./Module")} Module */ class ModuleDependencyError extends WebpackError { /** * Creates an instance of ModuleDependencyError. * @param {Module} module module tied to dependency * @param {Error} err error thrown * @param {TODO} loc location of dependency */ constructor(module, err, loc) { super(err.message); this.name = "ModuleDependencyError"; this.details = err.stack .split("\n") .slice(1) .join("\n"); this.module = module; this.loc = loc; this.error = err; this.origin = module.issuer; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleDependencyError; webpack-4.30.0/lib/ModuleDependencyWarning.js000066400000000000000000000010521345416772700211060ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); module.exports = class ModuleDependencyWarning extends WebpackError { constructor(module, err, loc) { super(err.message); this.name = "ModuleDependencyWarning"; this.details = err.stack .split("\n") .slice(1) .join("\n"); this.module = module; this.loc = loc; this.error = err; this.origin = module.issuer; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/ModuleError.js000066400000000000000000000015131345416772700165750ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const { cleanUp } = require("./ErrorHelpers"); class ModuleError extends WebpackError { constructor(module, err, { from = null } = {}) { let message = "Module Error"; if (from) { message += ` (from ${from}):\n`; } else { message += ": "; } if (err && typeof err === "object" && err.message) { message += err.message; } else if (err) { message += err; } super(message); this.name = "ModuleError"; this.module = module; this.error = err; this.details = err && typeof err === "object" && err.stack ? cleanUp(err.stack, this.message) : undefined; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleError; webpack-4.30.0/lib/ModuleFilenameHelpers.js000066400000000000000000000125631345416772700205560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const createHash = require("./util/createHash"); const ModuleFilenameHelpers = exports; ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]"; ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = /\[all-?loaders\]\[resource\]/gi; ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]"; ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi; ModuleFilenameHelpers.RESOURCE = "[resource]"; ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi; ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]"; ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = /\[abs(olute)?-?resource-?path\]/gi; ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]"; ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi; ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]"; ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi; ModuleFilenameHelpers.LOADERS = "[loaders]"; ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi; ModuleFilenameHelpers.QUERY = "[query]"; ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi; ModuleFilenameHelpers.ID = "[id]"; ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi; ModuleFilenameHelpers.HASH = "[hash]"; ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi; ModuleFilenameHelpers.NAMESPACE = "[namespace]"; ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi; const getAfter = (str, token) => { const idx = str.indexOf(token); return idx < 0 ? "" : str.substr(idx); }; const getBefore = (str, token) => { const idx = str.lastIndexOf(token); return idx < 0 ? "" : str.substr(0, idx); }; const getHash = str => { const hash = createHash("md4"); hash.update(str); return hash.digest("hex").substr(0, 4); }; const asRegExp = test => { if (typeof test === "string") { test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); } return test; }; ModuleFilenameHelpers.createFilename = (module, options, requestShortener) => { const opts = Object.assign( { namespace: "", moduleFilenameTemplate: "" }, typeof options === "object" ? options : { moduleFilenameTemplate: options } ); let absoluteResourcePath; let hash; let identifier; let moduleId; let shortIdentifier; if (module === undefined) module = ""; if (typeof module === "string") { shortIdentifier = requestShortener.shorten(module); identifier = shortIdentifier; moduleId = ""; absoluteResourcePath = module.split("!").pop(); hash = getHash(identifier); } else { shortIdentifier = module.readableIdentifier(requestShortener); identifier = requestShortener.shorten(module.identifier()); moduleId = module.id; absoluteResourcePath = module .identifier() .split("!") .pop(); hash = getHash(identifier); } const resource = shortIdentifier.split("!").pop(); const loaders = getBefore(shortIdentifier, "!"); const allLoaders = getBefore(identifier, "!"); const query = getAfter(resource, "?"); const resourcePath = resource.substr(0, resource.length - query.length); if (typeof opts.moduleFilenameTemplate === "function") { return opts.moduleFilenameTemplate({ identifier: identifier, shortIdentifier: shortIdentifier, resource: resource, resourcePath: resourcePath, absoluteResourcePath: absoluteResourcePath, allLoaders: allLoaders, query: query, moduleId: moduleId, hash: hash, namespace: opts.namespace }); } return opts.moduleFilenameTemplate .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier) .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier) .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource) .replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath) .replace( ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, absoluteResourcePath ) .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders) .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders) .replace(ModuleFilenameHelpers.REGEXP_QUERY, query) .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId) .replace(ModuleFilenameHelpers.REGEXP_HASH, hash) .replace(ModuleFilenameHelpers.REGEXP_NAMESPACE, opts.namespace); }; ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => { const countMap = Object.create(null); const posMap = Object.create(null); array.forEach((item, idx) => { countMap[item] = countMap[item] || []; countMap[item].push(idx); posMap[item] = 0; }); if (comparator) { Object.keys(countMap).forEach(item => { countMap[item].sort(comparator); }); } return array.map((item, i) => { if (countMap[item].length > 1) { if (comparator && countMap[item][0] === i) return item; return fn(item, i, posMap[item]++); } else { return item; } }); }; ModuleFilenameHelpers.matchPart = (str, test) => { if (!test) return true; test = asRegExp(test); if (Array.isArray(test)) { return test.map(asRegExp).some(regExp => regExp.test(str)); } else { return test.test(str); } }; ModuleFilenameHelpers.matchObject = (obj, str) => { if (obj.test) { if (!ModuleFilenameHelpers.matchPart(str, obj.test)) { return false; } } if (obj.include) { if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { return false; } } if (obj.exclude) { if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { return false; } } return true; }; webpack-4.30.0/lib/ModuleNotFoundError.js000066400000000000000000000010041345416772700202450ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); class ModuleNotFoundError extends WebpackError { constructor(module, err) { super("Module not found: " + err); this.name = "ModuleNotFoundError"; this.details = err.details; this.missing = err.missing; this.module = module; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleNotFoundError; webpack-4.30.0/lib/ModuleParseError.js000066400000000000000000000030451345416772700175720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); /** @typedef {import("./Module")} Module */ class ModuleParseError extends WebpackError { /** * @param {Module} module the errored module * @param {string} source source code * @param {Error&any} err the parse error */ constructor(module, source, err) { let message = "Module parse failed: " + err.message; let loc = undefined; message += "\nYou may need an appropriate loader to handle this file type."; if ( err.loc && typeof err.loc === "object" && typeof err.loc.line === "number" ) { var lineNumber = err.loc.line; if (/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { // binary file message += "\n(Source code omitted for this binary file)"; } else { const sourceLines = source.split("\n"); const start = Math.max(0, lineNumber - 3); const linesBefore = sourceLines.slice(start, lineNumber - 1); const theLine = sourceLines[lineNumber - 1]; const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2); message += linesBefore.map(l => `\n| ${l}`).join("") + `\n> ${theLine}` + linesAfter.map(l => `\n| ${l}`).join(""); } loc = err.loc; } else { message += "\n" + err.stack; } super(message); this.name = "ModuleParseError"; this.module = module; this.loc = loc; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleParseError; webpack-4.30.0/lib/ModuleReason.js000066400000000000000000000022411345416772700167320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("./Module")} Module */ /** @typedef {import("./Dependency")} Dependency */ class ModuleReason { /** * @param {Module} module the referencing module * @param {Dependency} dependency the referencing dependency * @param {string=} explanation some extra detail */ constructor(module, dependency, explanation) { this.module = module; this.dependency = dependency; this.explanation = explanation; this._chunks = null; } hasChunk(chunk) { if (this._chunks) { if (this._chunks.has(chunk)) return true; } else if (this.module && this.module._chunks.has(chunk)) return true; return false; } rewriteChunks(oldChunk, newChunks) { if (!this._chunks) { if (this.module) { if (!this.module._chunks.has(oldChunk)) return; this._chunks = new Set(this.module._chunks); } else { this._chunks = new Set(); } } if (this._chunks.has(oldChunk)) { this._chunks.delete(oldChunk); for (let i = 0; i < newChunks.length; i++) { this._chunks.add(newChunks[i]); } } } } module.exports = ModuleReason; webpack-4.30.0/lib/ModuleTemplate.js000066400000000000000000000037351345416772700172670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { Tapable, SyncWaterfallHook, SyncHook } = require("tapable"); /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("./Module")} Module */ module.exports = class ModuleTemplate extends Tapable { constructor(runtimeTemplate, type) { super(); this.runtimeTemplate = runtimeTemplate; this.type = type; this.hooks = { content: new SyncWaterfallHook([ "source", "module", "options", "dependencyTemplates" ]), module: new SyncWaterfallHook([ "source", "module", "options", "dependencyTemplates" ]), render: new SyncWaterfallHook([ "source", "module", "options", "dependencyTemplates" ]), package: new SyncWaterfallHook([ "source", "module", "options", "dependencyTemplates" ]), hash: new SyncHook(["hash"]) }; } /** * @param {Module} module the module * @param {TODO} dependencyTemplates templates for dependencies * @param {TODO} options render options * @returns {Source} the source */ render(module, dependencyTemplates, options) { try { const moduleSource = module.source( dependencyTemplates, this.runtimeTemplate, this.type ); const moduleSourcePostContent = this.hooks.content.call( moduleSource, module, options, dependencyTemplates ); const moduleSourcePostModule = this.hooks.module.call( moduleSourcePostContent, module, options, dependencyTemplates ); const moduleSourcePostRender = this.hooks.render.call( moduleSourcePostModule, module, options, dependencyTemplates ); return this.hooks.package.call( moduleSourcePostRender, module, options, dependencyTemplates ); } catch (e) { e.message = `${module.identifier()}\n${e.message}`; throw e; } } updateHash(hash) { hash.update("1"); this.hooks.hash.call(hash); } }; webpack-4.30.0/lib/ModuleWarning.js000066400000000000000000000016051345416772700171130ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const { cleanUp } = require("./ErrorHelpers"); class ModuleWarning extends WebpackError { constructor(module, warning, { from = null } = {}) { let message = "Module Warning"; if (from) { message += ` (from ${from}):\n`; } else { message += ": "; } if (warning && typeof warning === "object" && warning.message) { message += warning.message; } else if (warning) { message += warning; } super(message); this.name = "ModuleWarning"; this.module = module; this.warning = warning; this.details = warning && typeof warning === "object" && warning.stack ? cleanUp(warning.stack, this.message) : undefined; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleWarning; webpack-4.30.0/lib/MultiCompiler.js000066400000000000000000000160601345416772700171260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { Tapable, SyncHook, MultiHook } = require("tapable"); const asyncLib = require("neo-async"); const MultiWatching = require("./MultiWatching"); const MultiStats = require("./MultiStats"); const ConcurrentCompilationError = require("./ConcurrentCompilationError"); module.exports = class MultiCompiler extends Tapable { constructor(compilers) { super(); this.hooks = { done: new SyncHook(["stats"]), invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), run: new MultiHook(compilers.map(c => c.hooks.run)), watchClose: new SyncHook([]), watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)) }; if (!Array.isArray(compilers)) { compilers = Object.keys(compilers).map(name => { compilers[name].name = name; return compilers[name]; }); } this.compilers = compilers; let doneCompilers = 0; let compilerStats = []; let index = 0; for (const compiler of this.compilers) { let compilerDone = false; const compilerIndex = index++; // eslint-disable-next-line no-loop-func compiler.hooks.done.tap("MultiCompiler", stats => { if (!compilerDone) { compilerDone = true; doneCompilers++; } compilerStats[compilerIndex] = stats; if (doneCompilers === this.compilers.length) { this.hooks.done.call(new MultiStats(compilerStats)); } }); // eslint-disable-next-line no-loop-func compiler.hooks.invalid.tap("MultiCompiler", () => { if (compilerDone) { compilerDone = false; doneCompilers--; } }); } this.running = false; } get outputPath() { let commonPath = this.compilers[0].outputPath; for (const compiler of this.compilers) { while ( compiler.outputPath.indexOf(commonPath) !== 0 && /[/\\]/.test(commonPath) ) { commonPath = commonPath.replace(/[/\\][^/\\]*$/, ""); } } if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; return commonPath; } get inputFileSystem() { throw new Error("Cannot read inputFileSystem of a MultiCompiler"); } get outputFileSystem() { throw new Error("Cannot read outputFileSystem of a MultiCompiler"); } set inputFileSystem(value) { for (const compiler of this.compilers) { compiler.inputFileSystem = value; } } set outputFileSystem(value) { for (const compiler of this.compilers) { compiler.outputFileSystem = value; } } validateDependencies(callback) { const edges = new Set(); const missing = []; const targetFound = compiler => { for (const edge of edges) { if (edge.target === compiler) { return true; } } return false; }; const sortEdges = (e1, e2) => { return ( e1.source.name.localeCompare(e2.source.name) || e1.target.name.localeCompare(e2.target.name) ); }; for (const source of this.compilers) { if (source.dependencies) { for (const dep of source.dependencies) { const target = this.compilers.find(c => c.name === dep); if (!target) { missing.push(dep); } else { edges.add({ source, target }); } } } } const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`); const stack = this.compilers.filter(c => !targetFound(c)); while (stack.length > 0) { const current = stack.pop(); for (const edge of edges) { if (edge.source === current) { edges.delete(edge); const target = edge.target; if (!targetFound(target)) { stack.push(target); } } } } if (edges.size > 0) { const lines = Array.from(edges) .sort(sortEdges) .map(edge => `${edge.source.name} -> ${edge.target.name}`); lines.unshift("Circular dependency found in compiler dependencies."); errors.unshift(lines.join("\n")); } if (errors.length > 0) { const message = errors.join("\n"); callback(new Error(message)); return false; } return true; } runWithDependencies(compilers, fn, callback) { const fulfilledNames = new Set(); let remainingCompilers = compilers; const isDependencyFulfilled = d => fulfilledNames.has(d); const getReadyCompilers = () => { let readyCompilers = []; let list = remainingCompilers; remainingCompilers = []; for (const c of list) { const ready = !c.dependencies || c.dependencies.every(isDependencyFulfilled); if (ready) { readyCompilers.push(c); } else { remainingCompilers.push(c); } } return readyCompilers; }; const runCompilers = callback => { if (remainingCompilers.length === 0) return callback(); asyncLib.map( getReadyCompilers(), (compiler, callback) => { fn(compiler, err => { if (err) return callback(err); fulfilledNames.add(compiler.name); runCompilers(callback); }); }, callback ); }; runCompilers(callback); } watch(watchOptions, handler) { if (this.running) return handler(new ConcurrentCompilationError()); let watchings = []; let allStats = this.compilers.map(() => null); let compilerStatus = this.compilers.map(() => false); if (this.validateDependencies(handler)) { this.running = true; this.runWithDependencies( this.compilers, (compiler, callback) => { const compilerIdx = this.compilers.indexOf(compiler); let firstRun = true; let watching = compiler.watch( Array.isArray(watchOptions) ? watchOptions[compilerIdx] : watchOptions, (err, stats) => { if (err) handler(err); if (stats) { allStats[compilerIdx] = stats; compilerStatus[compilerIdx] = "new"; if (compilerStatus.every(Boolean)) { const freshStats = allStats.filter((s, idx) => { return compilerStatus[idx] === "new"; }); compilerStatus.fill(true); const multiStats = new MultiStats(freshStats); handler(null, multiStats); } } if (firstRun && !err) { firstRun = false; callback(); } } ); watchings.push(watching); }, () => { // ignore } ); } return new MultiWatching(watchings, this); } run(callback) { if (this.running) { return callback(new ConcurrentCompilationError()); } const finalCallback = (err, stats) => { this.running = false; if (callback !== undefined) { return callback(err, stats); } }; const allStats = this.compilers.map(() => null); if (this.validateDependencies(callback)) { this.running = true; this.runWithDependencies( this.compilers, (compiler, callback) => { const compilerIdx = this.compilers.indexOf(compiler); compiler.run((err, stats) => { if (err) { return callback(err); } allStats[compilerIdx] = stats; callback(); }); }, err => { if (err) { return finalCallback(err); } finalCallback(null, new MultiStats(allStats)); } ); } } purgeInputFileSystem() { for (const compiler of this.compilers) { if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { compiler.inputFileSystem.purge(); } } } }; webpack-4.30.0/lib/MultiEntryPlugin.js000066400000000000000000000040161345416772700176320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const MultiEntryDependency = require("./dependencies/MultiEntryDependency"); const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); const MultiModuleFactory = require("./MultiModuleFactory"); /** @typedef {import("./Compiler")} Compiler */ class MultiEntryPlugin { /** * The MultiEntryPlugin is invoked whenever this.options.entry value is an array of paths * @param {string} context context path * @param {string[]} entries array of entry paths * @param {string} name entry key name */ constructor(context, entries, name) { this.context = context; this.entries = entries; this.name = name; } /** * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap( "MultiEntryPlugin", (compilation, { normalModuleFactory }) => { const multiModuleFactory = new MultiModuleFactory(); compilation.dependencyFactories.set( MultiEntryDependency, multiModuleFactory ); compilation.dependencyFactories.set( SingleEntryDependency, normalModuleFactory ); } ); compiler.hooks.make.tapAsync( "MultiEntryPlugin", (compilation, callback) => { const { context, entries, name } = this; const dep = MultiEntryPlugin.createDependency(entries, name); compilation.addEntry(context, dep, name, callback); } ); } /** * @param {string[]} entries each entry path string * @param {string} name name of the entry * @returns {MultiEntryDependency} returns a constructed Dependency */ static createDependency(entries, name) { return new MultiEntryDependency( entries.map((e, idx) => { const dep = new SingleEntryDependency(e); // Because entrypoints are not dependencies found in an // existing module, we give it a synthetic id dep.loc = { name, index: idx }; return dep; }), name ); } } module.exports = MultiEntryPlugin; webpack-4.30.0/lib/MultiModule.js000066400000000000000000000036011345416772700165760ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("./Module"); const Template = require("./Template"); const { RawSource } = require("webpack-sources"); /** @typedef {import("./util/createHash").Hash} Hash */ class MultiModule extends Module { constructor(context, dependencies, name) { super("javascript/dynamic", context); // Info from Factory this.dependencies = dependencies; this.name = name; this._identifier = `multi ${this.dependencies .map(d => d.request) .join(" ")}`; } identifier() { return this._identifier; } readableIdentifier(requestShortener) { return `multi ${this.dependencies .map(d => requestShortener.shorten(d.request)) .join(" ")}`; } build(options, compilation, resolver, fs, callback) { this.built = true; this.buildMeta = {}; this.buildInfo = {}; return callback(); } needRebuild() { return false; } size() { return 16 + this.dependencies.length * 12; } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { hash.update("multi module"); hash.update(this.name || ""); super.updateHash(hash); } source(dependencyTemplates, runtimeTemplate) { const str = []; let idx = 0; for (const dep of this.dependencies) { if (dep.module) { if (idx === this.dependencies.length - 1) { str.push("module.exports = "); } str.push("__webpack_require__("); if (runtimeTemplate.outputOptions.pathinfo) { str.push(Template.toComment(dep.request)); } str.push(`${JSON.stringify(dep.module.id)}`); str.push(")"); } else { const content = require("./dependencies/WebpackMissingModule").module( dep.request ); str.push(content); } str.push(";\n"); idx++; } return new RawSource(str.join("")); } } module.exports = MultiModule; webpack-4.30.0/lib/MultiModuleFactory.js000066400000000000000000000007511345416772700201310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { Tapable } = require("tapable"); const MultiModule = require("./MultiModule"); module.exports = class MultiModuleFactory extends Tapable { constructor() { super(); this.hooks = {}; } create(data, callback) { const dependency = data.dependencies[0]; callback( null, new MultiModule(data.context, dependency.dependencies, dependency.name) ); } }; webpack-4.30.0/lib/MultiStats.js000066400000000000000000000042621345416772700164530ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Stats = require("./Stats"); const optionOrFallback = (optionValue, fallbackValue) => optionValue !== undefined ? optionValue : fallbackValue; class MultiStats { constructor(stats) { this.stats = stats; this.hash = stats.map(stat => stat.hash).join(""); } hasErrors() { return this.stats .map(stat => stat.hasErrors()) .reduce((a, b) => a || b, false); } hasWarnings() { return this.stats .map(stat => stat.hasWarnings()) .reduce((a, b) => a || b, false); } toJson(options, forToString) { if (typeof options === "boolean" || typeof options === "string") { options = Stats.presetToOptions(options); } else if (!options) { options = {}; } const jsons = this.stats.map((stat, idx) => { const childOptions = Stats.getChildOptions(options, idx); const obj = stat.toJson(childOptions, forToString); obj.name = stat.compilation && stat.compilation.name; return obj; }); const showVersion = options.version === undefined ? jsons.every(j => j.version) : options.version !== false; const showHash = options.hash === undefined ? jsons.every(j => j.hash) : options.hash !== false; if (showVersion) { for (const j of jsons) { delete j.version; } } const obj = { errors: jsons.reduce((arr, j) => { return arr.concat( j.errors.map(msg => { return `(${j.name}) ${msg}`; }) ); }, []), warnings: jsons.reduce((arr, j) => { return arr.concat( j.warnings.map(msg => { return `(${j.name}) ${msg}`; }) ); }, []) }; if (showVersion) obj.version = require("../package.json").version; if (showHash) obj.hash = this.hash; if (options.children !== false) obj.children = jsons; return obj; } toString(options) { if (typeof options === "boolean" || typeof options === "string") { options = Stats.presetToOptions(options); } else if (!options) { options = {}; } const useColors = optionOrFallback(options.colors, false); const obj = this.toJson(options, true); return Stats.jsonToString(obj, useColors); } } module.exports = MultiStats; webpack-4.30.0/lib/MultiWatching.js000066400000000000000000000013121345416772700171120ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("neo-async"); class MultiWatching { constructor(watchings, compiler) { this.watchings = watchings; this.compiler = compiler; } invalidate() { for (const watching of this.watchings) { watching.invalidate(); } } close(callback) { asyncLib.forEach( this.watchings, (watching, finishedCallback) => { watching.close(finishedCallback); }, err => { this.compiler.hooks.watchClose.call(); if (typeof callback === "function") { this.compiler.running = false; callback(err); } } ); } } module.exports = MultiWatching; webpack-4.30.0/lib/NamedChunksPlugin.js000066400000000000000000000012231345416772700177130ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class NamedChunksPlugin { static defaultNameResolver(chunk) { return chunk.name || null; } constructor(nameResolver) { this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; } apply(compiler) { compiler.hooks.compilation.tap("NamedChunksPlugin", compilation => { compilation.hooks.beforeChunkIds.tap("NamedChunksPlugin", chunks => { for (const chunk of chunks) { if (chunk.id === null) { chunk.id = this.nameResolver(chunk); } } }); }); } } module.exports = NamedChunksPlugin; webpack-4.30.0/lib/NamedModulesPlugin.js000066400000000000000000000026751345416772700201040ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const createHash = require("./util/createHash"); const RequestShortener = require("./RequestShortener"); const getHash = str => { const hash = createHash("md4"); hash.update(str); return hash.digest("hex").substr(0, 4); }; class NamedModulesPlugin { constructor(options) { this.options = options || {}; } apply(compiler) { compiler.hooks.compilation.tap("NamedModulesPlugin", compilation => { compilation.hooks.beforeModuleIds.tap("NamedModulesPlugin", modules => { const namedModules = new Map(); const context = this.options.context || compiler.options.context; for (const module of modules) { if (module.id === null && module.libIdent) { module.id = module.libIdent({ context }); } if (module.id !== null) { const namedModule = namedModules.get(module.id); if (namedModule !== undefined) { namedModule.push(module); } else { namedModules.set(module.id, [module]); } } } for (const namedModule of namedModules.values()) { if (namedModule.length > 1) { for (const module of namedModule) { const requestShortener = new RequestShortener(context); module.id = `${module.id}?${getHash( requestShortener.shorten(module.identifier()) )}`; } } } }); }); } } module.exports = NamedModulesPlugin; webpack-4.30.0/lib/NoEmitOnErrorsPlugin.js000066400000000000000000000010571345416772700204050ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class NoEmitOnErrorsPlugin { apply(compiler) { compiler.hooks.shouldEmit.tap("NoEmitOnErrorsPlugin", compilation => { if (compilation.getStats().hasErrors()) return false; }); compiler.hooks.compilation.tap("NoEmitOnErrorsPlugin", compilation => { compilation.hooks.shouldRecord.tap("NoEmitOnErrorsPlugin", () => { if (compilation.getStats().hasErrors()) return false; }); }); } } module.exports = NoEmitOnErrorsPlugin; webpack-4.30.0/lib/NoModeWarning.js000066400000000000000000000013131345416772700170430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); module.exports = class NoModeWarning extends WebpackError { constructor(modules) { super(); this.name = "NoModeWarning"; this.message = "configuration\n" + "The 'mode' option has not been set, webpack will fallback to 'production' for this value. " + "Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" + "You can also set it to 'none' to disable any default behavior. " + "Learn more: https://webpack.js.org/concepts/mode/"; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/NodeStuffPlugin.js000066400000000000000000000131671345416772700174220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const ParserHelpers = require("./ParserHelpers"); const ConstDependency = require("./dependencies/ConstDependency"); const NullFactory = require("./NullFactory"); class NodeStuffPlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap( "NodeStuffPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); const handler = (parser, parserOptions) => { if (parserOptions.node === false) return; let localOptions = options; if (parserOptions.node) { localOptions = Object.assign({}, localOptions, parserOptions.node); } const setConstant = (expressionName, value) => { parser.hooks.expression .for(expressionName) .tap("NodeStuffPlugin", () => { parser.state.current.addVariable( expressionName, JSON.stringify(value) ); return true; }); }; const setModuleConstant = (expressionName, fn) => { parser.hooks.expression .for(expressionName) .tap("NodeStuffPlugin", () => { parser.state.current.addVariable( expressionName, JSON.stringify(fn(parser.state.module)) ); return true; }); }; const context = compiler.context; if (localOptions.__filename === "mock") { setConstant("__filename", "/index.js"); } else if (localOptions.__filename) { setModuleConstant("__filename", module => path.relative(context, module.resource) ); } parser.hooks.evaluateIdentifier .for("__filename") .tap("NodeStuffPlugin", expr => { if (!parser.state.module) return; const resource = parser.state.module.resource; const i = resource.indexOf("?"); return ParserHelpers.evaluateToString( i < 0 ? resource : resource.substr(0, i) )(expr); }); if (localOptions.__dirname === "mock") { setConstant("__dirname", "/"); } else if (localOptions.__dirname) { setModuleConstant("__dirname", module => path.relative(context, module.context) ); } parser.hooks.evaluateIdentifier .for("__dirname") .tap("NodeStuffPlugin", expr => { if (!parser.state.module) return; return ParserHelpers.evaluateToString( parser.state.module.context )(expr); }); parser.hooks.expression .for("require.main") .tap( "NodeStuffPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire( parser, "__webpack_require__.c[__webpack_require__.s]" ) ); parser.hooks.expression .for("require.extensions") .tap( "NodeStuffPlugin", ParserHelpers.expressionIsUnsupported( parser, "require.extensions is not supported by webpack. Use a loader instead." ) ); parser.hooks.expression .for("require.main.require") .tap( "NodeStuffPlugin", ParserHelpers.expressionIsUnsupported( parser, "require.main.require is not supported by webpack." ) ); parser.hooks.expression .for("module.parent.require") .tap( "NodeStuffPlugin", ParserHelpers.expressionIsUnsupported( parser, "module.parent.require is not supported by webpack." ) ); parser.hooks.expression .for("module.loaded") .tap("NodeStuffPlugin", expr => { parser.state.module.buildMeta.moduleConcatenationBailout = "module.loaded"; return ParserHelpers.toConstantDependency(parser, "module.l")( expr ); }); parser.hooks.expression .for("module.id") .tap("NodeStuffPlugin", expr => { parser.state.module.buildMeta.moduleConcatenationBailout = "module.id"; return ParserHelpers.toConstantDependency(parser, "module.i")( expr ); }); parser.hooks.expression .for("module.exports") .tap("NodeStuffPlugin", () => { const module = parser.state.module; const isHarmony = module.buildMeta && module.buildMeta.exportsType; if (!isHarmony) return true; }); parser.hooks.evaluateIdentifier .for("module.hot") .tap( "NodeStuffPlugin", ParserHelpers.evaluateToIdentifier("module.hot", false) ); parser.hooks.expression.for("module").tap("NodeStuffPlugin", () => { const module = parser.state.module; const isHarmony = module.buildMeta && module.buildMeta.exportsType; let moduleJsPath = path.join( __dirname, "..", "buildin", isHarmony ? "harmony-module.js" : "module.js" ); if (module.context) { moduleJsPath = path.relative( parser.state.module.context, moduleJsPath ); if (!/^[A-Z]:/i.test(moduleJsPath)) { moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`; } } return ParserHelpers.addParsedVariableToModule( parser, "module", `require(${JSON.stringify(moduleJsPath)})(module)` ); }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("NodeStuffPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("NodeStuffPlugin", handler); } ); } } module.exports = NodeStuffPlugin; webpack-4.30.0/lib/NormalModule.js000066400000000000000000000341411345416772700167370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NativeModule = require("module"); const { CachedSource, LineToLineMappedSource, OriginalSource, RawSource, SourceMapSource } = require("webpack-sources"); const { getContext, runLoaders } = require("loader-runner"); const WebpackError = require("./WebpackError"); const Module = require("./Module"); const ModuleParseError = require("./ModuleParseError"); const ModuleBuildError = require("./ModuleBuildError"); const ModuleError = require("./ModuleError"); const ModuleWarning = require("./ModuleWarning"); const createHash = require("./util/createHash"); const contextify = require("./util/identifier").contextify; /** @typedef {import("./util/createHash").Hash} Hash */ const asString = buf => { if (Buffer.isBuffer(buf)) { return buf.toString("utf-8"); } return buf; }; const asBuffer = str => { if (!Buffer.isBuffer(str)) { return Buffer.from(str, "utf-8"); } return str; }; class NonErrorEmittedError extends WebpackError { constructor(error) { super(); this.name = "NonErrorEmittedError"; this.message = "(Emitted value instead of an instance of Error) " + error; Error.captureStackTrace(this, this.constructor); } } /** * @typedef {Object} CachedSourceEntry * @property {TODO} source the generated source * @property {string} hash the hash value */ class NormalModule extends Module { constructor({ type, request, userRequest, rawRequest, loaders, resource, matchResource, parser, generator, resolveOptions }) { super(type, getContext(resource)); // Info from Factory this.request = request; this.userRequest = userRequest; this.rawRequest = rawRequest; this.binary = type.startsWith("webassembly"); this.parser = parser; this.generator = generator; this.resource = resource; this.matchResource = matchResource; this.loaders = loaders; if (resolveOptions !== undefined) this.resolveOptions = resolveOptions; // Info from Build this.error = null; this._source = null; this._buildHash = ""; this.buildTimestamp = undefined; /** @private @type {Map} */ this._cachedSources = new Map(); // Options for the NormalModule set by plugins // TODO refactor this -> options object filled from Factory this.useSourceMap = false; this.lineToLine = false; // Cache this._lastSuccessfulBuildMeta = {}; } identifier() { return this.request; } readableIdentifier(requestShortener) { return requestShortener.shorten(this.userRequest); } libIdent(options) { return contextify(options.context, this.userRequest); } nameForCondition() { const resource = this.matchResource || this.resource; const idx = resource.indexOf("?"); if (idx >= 0) return resource.substr(0, idx); return resource; } updateCacheModule(module) { this.type = module.type; this.request = module.request; this.userRequest = module.userRequest; this.rawRequest = module.rawRequest; this.parser = module.parser; this.generator = module.generator; this.resource = module.resource; this.matchResource = module.matchResource; this.loaders = module.loaders; this.resolveOptions = module.resolveOptions; } createSourceForAsset(name, content, sourceMap) { if (!sourceMap) { return new RawSource(content); } if (typeof sourceMap === "string") { return new OriginalSource(content, sourceMap); } return new SourceMapSource(content, name, sourceMap); } createLoaderContext(resolver, options, compilation, fs) { const requestShortener = compilation.runtimeTemplate.requestShortener; const loaderContext = { version: 2, emitWarning: warning => { if (!(warning instanceof Error)) { warning = new NonErrorEmittedError(warning); } const currentLoader = this.getCurrentLoader(loaderContext); this.warnings.push( new ModuleWarning(this, warning, { from: requestShortener.shorten(currentLoader.loader) }) ); }, emitError: error => { if (!(error instanceof Error)) { error = new NonErrorEmittedError(error); } const currentLoader = this.getCurrentLoader(loaderContext); this.errors.push( new ModuleError(this, error, { from: requestShortener.shorten(currentLoader.loader) }) ); }, // TODO remove in webpack 5 exec: (code, filename) => { // @ts-ignore Argument of type 'this' is not assignable to parameter of type 'Module'. const module = new NativeModule(filename, this); // @ts-ignore _nodeModulePaths is deprecated and undocumented Node.js API module.paths = NativeModule._nodeModulePaths(this.context); module.filename = filename; module._compile(code, filename); return module.exports; }, resolve(context, request, callback) { resolver.resolve({}, context, request, {}, callback); }, getResolve(options) { const child = options ? resolver.withOptions(options) : resolver; return (context, request, callback) => { if (callback) { child.resolve({}, context, request, {}, callback); } else { return new Promise((resolve, reject) => { child.resolve({}, context, request, {}, (err, result) => { if (err) reject(err); else resolve(result); }); }); } }; }, emitFile: (name, content, sourceMap) => { if (!this.buildInfo.assets) { this.buildInfo.assets = Object.create(null); } this.buildInfo.assets[name] = this.createSourceForAsset( name, content, sourceMap ); }, rootContext: options.context, webpack: true, sourceMap: !!this.useSourceMap, _module: this, _compilation: compilation, _compiler: compilation.compiler, fs: fs }; compilation.hooks.normalModuleLoader.call(loaderContext, this); if (options.loader) { Object.assign(loaderContext, options.loader); } return loaderContext; } getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { if ( this.loaders && this.loaders.length && index < this.loaders.length && index >= 0 && this.loaders[index] ) { return this.loaders[index]; } return null; } createSource(source, resourceBuffer, sourceMap) { // if there is no identifier return raw source if (!this.identifier) { return new RawSource(source); } // from here on we assume we have an identifier const identifier = this.identifier(); if (this.lineToLine && resourceBuffer) { return new LineToLineMappedSource( source, identifier, asString(resourceBuffer) ); } if (this.useSourceMap && sourceMap) { return new SourceMapSource(source, identifier, sourceMap); } if (Buffer.isBuffer(source)) { // @ts-ignore // TODO We need to fix @types/webpack-sources to allow RawSource to take a Buffer | string return new RawSource(source); } return new OriginalSource(source, identifier); } doBuild(options, compilation, resolver, fs, callback) { const loaderContext = this.createLoaderContext( resolver, options, compilation, fs ); runLoaders( { resource: this.resource, loaders: this.loaders, context: loaderContext, readResource: fs.readFile.bind(fs) }, (err, result) => { if (result) { this.buildInfo.cacheable = result.cacheable; this.buildInfo.fileDependencies = new Set(result.fileDependencies); this.buildInfo.contextDependencies = new Set( result.contextDependencies ); } if (err) { if (!(err instanceof Error)) { err = new NonErrorEmittedError(err); } const currentLoader = this.getCurrentLoader(loaderContext); const error = new ModuleBuildError(this, err, { from: currentLoader && compilation.runtimeTemplate.requestShortener.shorten( currentLoader.loader ) }); return callback(error); } const resourceBuffer = result.resourceBuffer; const source = result.result[0]; const sourceMap = result.result.length >= 1 ? result.result[1] : null; const extraInfo = result.result.length >= 2 ? result.result[2] : null; if (!Buffer.isBuffer(source) && typeof source !== "string") { const currentLoader = this.getCurrentLoader(loaderContext, 0); const err = new Error( `Final loader (${ currentLoader ? compilation.runtimeTemplate.requestShortener.shorten( currentLoader.loader ) : "unknown" }) didn't return a Buffer or String` ); const error = new ModuleBuildError(this, err); return callback(error); } this._source = this.createSource( this.binary ? asBuffer(source) : asString(source), resourceBuffer, sourceMap ); this._ast = typeof extraInfo === "object" && extraInfo !== null && extraInfo.webpackAST !== undefined ? extraInfo.webpackAST : null; return callback(); } ); } markModuleAsErrored(error) { // Restore build meta from successful build to keep importing state this.buildMeta = Object.assign({}, this._lastSuccessfulBuildMeta); this.error = error; this.errors.push(this.error); this._source = new RawSource( "throw new Error(" + JSON.stringify(this.error.message) + ");" ); this._ast = null; } applyNoParseRule(rule, content) { // must start with "rule" if rule is a string if (typeof rule === "string") { return content.indexOf(rule) === 0; } if (typeof rule === "function") { return rule(content); } // we assume rule is a regexp return rule.test(content); } // check if module should not be parsed // returns "true" if the module should !not! be parsed // returns "false" if the module !must! be parsed shouldPreventParsing(noParseRule, request) { // if no noParseRule exists, return false // the module !must! be parsed. if (!noParseRule) { return false; } // we only have one rule to check if (!Array.isArray(noParseRule)) { // returns "true" if the module is !not! to be parsed return this.applyNoParseRule(noParseRule, request); } for (let i = 0; i < noParseRule.length; i++) { const rule = noParseRule[i]; // early exit on first truthy match // this module is !not! to be parsed if (this.applyNoParseRule(rule, request)) { return true; } } // no match found, so this module !should! be parsed return false; } _initBuildHash(compilation) { const hash = createHash(compilation.outputOptions.hashFunction); if (this._source) { hash.update("source"); this._source.updateHash(hash); } hash.update("meta"); hash.update(JSON.stringify(this.buildMeta)); this._buildHash = hash.digest("hex"); } build(options, compilation, resolver, fs, callback) { this.buildTimestamp = Date.now(); this.built = true; this._source = null; this._ast = null; this._buildHash = ""; this.error = null; this.errors.length = 0; this.warnings.length = 0; this.buildMeta = {}; this.buildInfo = { cacheable: false, fileDependencies: new Set(), contextDependencies: new Set() }; return this.doBuild(options, compilation, resolver, fs, err => { this._cachedSources.clear(); // if we have an error mark module as failed and exit if (err) { this.markModuleAsErrored(err); this._initBuildHash(compilation); return callback(); } // check if this module should !not! be parsed. // if so, exit here; const noParseRule = options.module && options.module.noParse; if (this.shouldPreventParsing(noParseRule, this.request)) { this._initBuildHash(compilation); return callback(); } const handleParseError = e => { const source = this._source.source(); const error = new ModuleParseError(this, source, e); this.markModuleAsErrored(error); this._initBuildHash(compilation); return callback(); }; const handleParseResult = result => { this._lastSuccessfulBuildMeta = this.buildMeta; this._initBuildHash(compilation); return callback(); }; try { const result = this.parser.parse( this._ast || this._source.source(), { current: this, module: this, compilation: compilation, options: options }, (err, result) => { if (err) { handleParseError(err); } else { handleParseResult(result); } } ); if (result !== undefined) { // parse is sync handleParseResult(result); } } catch (e) { handleParseError(e); } }); } getHashDigest(dependencyTemplates) { // TODO webpack 5 refactor let dtHash = dependencyTemplates.get("hash"); return `${this.hash}-${dtHash}`; } source(dependencyTemplates, runtimeTemplate, type = "javascript") { const hashDigest = this.getHashDigest(dependencyTemplates); const cacheEntry = this._cachedSources.get(type); if (cacheEntry !== undefined && cacheEntry.hash === hashDigest) { // We can reuse the cached source return cacheEntry.source; } const source = this.generator.generate( this, dependencyTemplates, runtimeTemplate, type ); const cachedSource = new CachedSource(source); this._cachedSources.set(type, { source: cachedSource, hash: hashDigest }); return cachedSource; } originalSource() { return this._source; } needRebuild(fileTimestamps, contextTimestamps) { // always try to rebuild in case of an error if (this.error) return true; // always rebuild when module is not cacheable if (!this.buildInfo.cacheable) return true; // Check timestamps of all dependencies // Missing timestamp -> need rebuild // Timestamp bigger than buildTimestamp -> need rebuild for (const file of this.buildInfo.fileDependencies) { const timestamp = fileTimestamps.get(file); if (!timestamp) return true; if (timestamp >= this.buildTimestamp) return true; } for (const file of this.buildInfo.contextDependencies) { const timestamp = contextTimestamps.get(file); if (!timestamp) return true; if (timestamp >= this.buildTimestamp) return true; } // elsewise -> no rebuild needed return false; } size() { return this._source ? this._source.size() : -1; } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { hash.update(this._buildHash); super.updateHash(hash); } } module.exports = NormalModule; webpack-4.30.0/lib/NormalModuleFactory.js000066400000000000000000000326071345416772700202740ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const asyncLib = require("neo-async"); const { Tapable, AsyncSeriesWaterfallHook, SyncWaterfallHook, SyncBailHook, SyncHook, HookMap } = require("tapable"); const NormalModule = require("./NormalModule"); const RawModule = require("./RawModule"); const RuleSet = require("./RuleSet"); const cachedMerge = require("./util/cachedMerge"); const EMPTY_RESOLVE_OPTIONS = {}; const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; const loaderToIdent = data => { if (!data.options) { return data.loader; } if (typeof data.options === "string") { return data.loader + "?" + data.options; } if (typeof data.options !== "object") { throw new Error("loader options must be string or object"); } if (data.ident) { return data.loader + "??" + data.ident; } return data.loader + "?" + JSON.stringify(data.options); }; const identToLoaderRequest = resultString => { const idx = resultString.indexOf("?"); if (idx >= 0) { const loader = resultString.substr(0, idx); const options = resultString.substr(idx + 1); return { loader, options }; } else { return { loader: resultString, options: undefined }; } }; const dependencyCache = new WeakMap(); class NormalModuleFactory extends Tapable { constructor(context, resolverFactory, options) { super(); this.hooks = { resolver: new SyncWaterfallHook(["resolver"]), factory: new SyncWaterfallHook(["factory"]), beforeResolve: new AsyncSeriesWaterfallHook(["data"]), afterResolve: new AsyncSeriesWaterfallHook(["data"]), createModule: new SyncBailHook(["data"]), module: new SyncWaterfallHook(["module", "data"]), createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), createGenerator: new HookMap( () => new SyncBailHook(["generatorOptions"]) ), generator: new HookMap( () => new SyncHook(["generator", "generatorOptions"]) ) }; this._pluginCompat.tap("NormalModuleFactory", options => { switch (options.name) { case "before-resolve": case "after-resolve": options.async = true; break; case "parser": this.hooks.parser .for("javascript/auto") .tap(options.fn.name || "unnamed compat plugin", options.fn); return true; } let match; match = /^parser (.+)$/.exec(options.name); if (match) { this.hooks.parser .for(match[1]) .tap( options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); return true; } match = /^create-parser (.+)$/.exec(options.name); if (match) { this.hooks.createParser .for(match[1]) .tap( options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); return true; } }); this.resolverFactory = resolverFactory; this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules)); this.cachePredicate = typeof options.unsafeCache === "function" ? options.unsafeCache : Boolean.bind(null, options.unsafeCache); this.context = context || ""; this.parserCache = Object.create(null); this.generatorCache = Object.create(null); this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => { let resolver = this.hooks.resolver.call(null); // Ignored if (!resolver) return callback(); resolver(result, (err, data) => { if (err) return callback(err); // Ignored if (!data) return callback(); // direct module if (typeof data.source === "function") return callback(null, data); this.hooks.afterResolve.callAsync(data, (err, result) => { if (err) return callback(err); // Ignored if (!result) return callback(); let createdModule = this.hooks.createModule.call(result); if (!createdModule) { if (!result.request) { return callback(new Error("Empty dependency (no request)")); } createdModule = new NormalModule(result); } createdModule = this.hooks.module.call(createdModule, result); return callback(null, createdModule); }); }); }); this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => { const contextInfo = data.contextInfo; const context = data.context; const request = data.request; const loaderResolver = this.getResolver("loader"); const normalResolver = this.getResolver("normal", data.resolveOptions); let matchResource = undefined; let requestWithoutMatchResource = request; const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); if (matchResourceMatch) { matchResource = matchResourceMatch[1]; if (/^\.\.?\//.test(matchResource)) { matchResource = path.join(context, matchResource); } requestWithoutMatchResource = request.substr( matchResourceMatch[0].length ); } const noPreAutoLoaders = requestWithoutMatchResource.startsWith("-!"); const noAutoLoaders = noPreAutoLoaders || requestWithoutMatchResource.startsWith("!"); const noPrePostAutoLoaders = requestWithoutMatchResource.startsWith("!!"); let elements = requestWithoutMatchResource .replace(/^-?!+/, "") .replace(/!!+/g, "!") .split("!"); let resource = elements.pop(); elements = elements.map(identToLoaderRequest); asyncLib.parallel( [ callback => this.resolveRequestArray( contextInfo, context, elements, loaderResolver, callback ), callback => { if (resource === "" || resource[0] === "?") { return callback(null, { resource }); } normalResolver.resolve( contextInfo, context, resource, {}, (err, resource, resourceResolveData) => { if (err) return callback(err); callback(null, { resourceResolveData, resource }); } ); } ], (err, results) => { if (err) return callback(err); let loaders = results[0]; const resourceResolveData = results[1].resourceResolveData; resource = results[1].resource; // translate option idents try { for (const item of loaders) { if (typeof item.options === "string" && item.options[0] === "?") { const ident = item.options.substr(1); item.options = this.ruleSet.findOptionsByIdent(ident); item.ident = ident; } } } catch (e) { return callback(e); } if (resource === false) { // ignored return callback( null, new RawModule( "/* (ignored) */", `ignored ${context} ${request}`, `${request} (ignored)` ) ); } const userRequest = (matchResource !== undefined ? `${matchResource}!=!` : "") + loaders .map(loaderToIdent) .concat([resource]) .join("!"); let resourcePath = matchResource !== undefined ? matchResource : resource; let resourceQuery = ""; const queryIndex = resourcePath.indexOf("?"); if (queryIndex >= 0) { resourceQuery = resourcePath.substr(queryIndex); resourcePath = resourcePath.substr(0, queryIndex); } const result = this.ruleSet.exec({ resource: resourcePath, realResource: matchResource !== undefined ? resource.replace(/\?.*/, "") : resourcePath, resourceQuery, issuer: contextInfo.issuer, compiler: contextInfo.compiler }); const settings = {}; const useLoadersPost = []; const useLoaders = []; const useLoadersPre = []; for (const r of result) { if (r.type === "use") { if (r.enforce === "post" && !noPrePostAutoLoaders) { useLoadersPost.push(r.value); } else if ( r.enforce === "pre" && !noPreAutoLoaders && !noPrePostAutoLoaders ) { useLoadersPre.push(r.value); } else if ( !r.enforce && !noAutoLoaders && !noPrePostAutoLoaders ) { useLoaders.push(r.value); } } else if ( typeof r.value === "object" && r.value !== null && typeof settings[r.type] === "object" && settings[r.type] !== null ) { settings[r.type] = cachedMerge(settings[r.type], r.value); } else { settings[r.type] = r.value; } } asyncLib.parallel( [ this.resolveRequestArray.bind( this, contextInfo, this.context, useLoadersPost, loaderResolver ), this.resolveRequestArray.bind( this, contextInfo, this.context, useLoaders, loaderResolver ), this.resolveRequestArray.bind( this, contextInfo, this.context, useLoadersPre, loaderResolver ) ], (err, results) => { if (err) return callback(err); loaders = results[0].concat(loaders, results[1], results[2]); process.nextTick(() => { const type = settings.type; const resolveOptions = settings.resolve; callback(null, { context: context, request: loaders .map(loaderToIdent) .concat([resource]) .join("!"), dependencies: data.dependencies, userRequest, rawRequest: request, loaders, resource, matchResource, resourceResolveData, settings, type, parser: this.getParser(type, settings.parser), generator: this.getGenerator(type, settings.generator), resolveOptions }); }); } ); } ); }); } create(data, callback) { const dependencies = data.dependencies; const cacheEntry = dependencyCache.get(dependencies[0]); if (cacheEntry) return callback(null, cacheEntry); const context = data.context || this.context; const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; const request = dependencies[0].request; const contextInfo = data.contextInfo || {}; this.hooks.beforeResolve.callAsync( { contextInfo, resolveOptions, context, request, dependencies }, (err, result) => { if (err) return callback(err); // Ignored if (!result) return callback(); const factory = this.hooks.factory.call(null); // Ignored if (!factory) return callback(); factory(result, (err, module) => { if (err) return callback(err); if (module && this.cachePredicate(module)) { for (const d of dependencies) { dependencyCache.set(d, module); } } callback(null, module); }); } ); } resolveRequestArray(contextInfo, context, array, resolver, callback) { if (array.length === 0) return callback(null, []); asyncLib.map( array, (item, callback) => { resolver.resolve( contextInfo, context, item.loader, {}, (err, result) => { if ( err && /^[^/]*$/.test(item.loader) && !/-loader$/.test(item.loader) ) { return resolver.resolve( contextInfo, context, item.loader + "-loader", {}, err2 => { if (!err2) { err.message = err.message + "\n" + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + ` You need to specify '${ item.loader }-loader' instead of '${item.loader}',\n` + " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; } callback(err); } ); } if (err) return callback(err); const optionsOnly = item.options ? { options: item.options } : undefined; return callback( null, Object.assign({}, item, identToLoaderRequest(result), optionsOnly) ); } ); }, callback ); } getParser(type, parserOptions) { let ident = type; if (parserOptions) { if (parserOptions.ident) { ident = `${type}|${parserOptions.ident}`; } else { ident = JSON.stringify([type, parserOptions]); } } if (ident in this.parserCache) { return this.parserCache[ident]; } return (this.parserCache[ident] = this.createParser(type, parserOptions)); } createParser(type, parserOptions = {}) { const parser = this.hooks.createParser.for(type).call(parserOptions); if (!parser) { throw new Error(`No parser registered for ${type}`); } this.hooks.parser.for(type).call(parser, parserOptions); return parser; } getGenerator(type, generatorOptions) { let ident = type; if (generatorOptions) { if (generatorOptions.ident) { ident = `${type}|${generatorOptions.ident}`; } else { ident = JSON.stringify([type, generatorOptions]); } } if (ident in this.generatorCache) { return this.generatorCache[ident]; } return (this.generatorCache[ident] = this.createGenerator( type, generatorOptions )); } createGenerator(type, generatorOptions = {}) { const generator = this.hooks.createGenerator .for(type) .call(generatorOptions); if (!generator) { throw new Error(`No generator registered for ${type}`); } this.hooks.generator.for(type).call(generator, generatorOptions); return generator; } getResolver(type, resolveOptions) { return this.resolverFactory.get( type, resolveOptions || EMPTY_RESOLVE_OPTIONS ); } } module.exports = NormalModuleFactory; webpack-4.30.0/lib/NormalModuleReplacementPlugin.js000066400000000000000000000023761345416772700223030ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); class NormalModuleReplacementPlugin { constructor(resourceRegExp, newResource) { this.resourceRegExp = resourceRegExp; this.newResource = newResource; } apply(compiler) { const resourceRegExp = this.resourceRegExp; const newResource = this.newResource; compiler.hooks.normalModuleFactory.tap( "NormalModuleReplacementPlugin", nmf => { nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { if (!result) return; if (resourceRegExp.test(result.request)) { if (typeof newResource === "function") { newResource(result); } else { result.request = newResource; } } return result; }); nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { if (!result) return; if (resourceRegExp.test(result.resource)) { if (typeof newResource === "function") { newResource(result); } else { result.resource = path.resolve( path.dirname(result.resource), newResource ); } } return result; }); } ); } } module.exports = NormalModuleReplacementPlugin; webpack-4.30.0/lib/NullFactory.js000066400000000000000000000003311345416772700165750ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class NullFactory { create(data, callback) { return callback(); } } module.exports = NullFactory; webpack-4.30.0/lib/OptionsApply.js000066400000000000000000000003101345416772700167710ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class OptionsApply { process(options, compiler) {} } module.exports = OptionsApply; webpack-4.30.0/lib/OptionsDefaulter.js000066400000000000000000000036541345416772700176350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const getProperty = (obj, name) => { name = name.split("."); for (let i = 0; i < name.length - 1; i++) { obj = obj[name[i]]; if (typeof obj !== "object" || !obj || Array.isArray(obj)) return; } return obj[name.pop()]; }; const setProperty = (obj, name, value) => { name = name.split("."); for (let i = 0; i < name.length - 1; i++) { if (typeof obj[name[i]] !== "object" && obj[name[i]] !== undefined) return; if (Array.isArray(obj[name[i]])) return; if (!obj[name[i]]) obj[name[i]] = {}; obj = obj[name[i]]; } obj[name.pop()] = value; }; class OptionsDefaulter { constructor() { this.defaults = {}; this.config = {}; } process(options) { options = Object.assign({}, options); for (let name in this.defaults) { switch (this.config[name]) { case undefined: if (getProperty(options, name) === undefined) { setProperty(options, name, this.defaults[name]); } break; case "call": setProperty( options, name, this.defaults[name].call(this, getProperty(options, name), options) ); break; case "make": if (getProperty(options, name) === undefined) { setProperty(options, name, this.defaults[name].call(this, options)); } break; case "append": { let oldValue = getProperty(options, name); if (!Array.isArray(oldValue)) { oldValue = []; } oldValue.push(...this.defaults[name]); setProperty(options, name, oldValue); break; } default: throw new Error( "OptionsDefaulter cannot process " + this.config[name] ); } } return options; } set(name, config, def) { if (def !== undefined) { this.defaults[name] = def; this.config[name] = config; } else { this.defaults[name] = config; delete this.config[name]; } } } module.exports = OptionsDefaulter; webpack-4.30.0/lib/Parser.js000066400000000000000000002023741345416772700156020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API const acorn = require("acorn"); const acornDynamicImport = require("acorn-dynamic-import").default; const { Tapable, SyncBailHook, HookMap } = require("tapable"); const util = require("util"); const vm = require("vm"); const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); const StackedSetMap = require("./util/StackedSetMap"); const TrackingSet = require("./util/TrackingSet"); const acornParser = acorn.Parser.extend(acornDynamicImport); const joinRanges = (startRange, endRange) => { if (!endRange) return startRange; if (!startRange) return endRange; return [startRange[0], endRange[1]]; }; const defaultParserOptions = { ranges: true, locations: true, ecmaVersion: 2019, sourceType: "module", onComment: null }; // regexp to match at lease one "magic comment" const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); const EMPTY_ARRAY = []; const EMPTY_COMMENT_OPTIONS = { options: null, errors: null }; class Parser extends Tapable { constructor(options, sourceType = "auto") { super(); this.hooks = { evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), evaluate: new HookMap(() => new SyncBailHook(["expression"])), evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), evaluateDefinedIdentifier: new HookMap( () => new SyncBailHook(["expression"]) ), evaluateCallExpressionMember: new HookMap( () => new SyncBailHook(["expression", "param"]) ), statement: new SyncBailHook(["statement"]), statementIf: new SyncBailHook(["statement"]), label: new HookMap(() => new SyncBailHook(["statement"])), import: new SyncBailHook(["statement", "source"]), importSpecifier: new SyncBailHook([ "statement", "source", "exportName", "identifierName" ]), export: new SyncBailHook(["statement"]), exportImport: new SyncBailHook(["statement", "source"]), exportDeclaration: new SyncBailHook(["statement", "declaration"]), exportExpression: new SyncBailHook(["statement", "declaration"]), exportSpecifier: new SyncBailHook([ "statement", "identifierName", "exportName", "index" ]), exportImportSpecifier: new SyncBailHook([ "statement", "source", "identifierName", "exportName", "index" ]), varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), canRename: new HookMap(() => new SyncBailHook(["initExpression"])), rename: new HookMap(() => new SyncBailHook(["initExpression"])), assigned: new HookMap(() => new SyncBailHook(["expression"])), assign: new HookMap(() => new SyncBailHook(["expression"])), typeof: new HookMap(() => new SyncBailHook(["expression"])), importCall: new SyncBailHook(["expression"]), call: new HookMap(() => new SyncBailHook(["expression"])), callAnyMember: new HookMap(() => new SyncBailHook(["expression"])), new: new HookMap(() => new SyncBailHook(["expression"])), expression: new HookMap(() => new SyncBailHook(["expression"])), expressionAnyMember: new HookMap(() => new SyncBailHook(["expression"])), expressionConditionalOperator: new SyncBailHook(["expression"]), expressionLogicalOperator: new SyncBailHook(["expression"]), program: new SyncBailHook(["ast", "comments"]) }; const HOOK_MAP_COMPAT_CONFIG = { evaluateTypeof: /^evaluate typeof (.+)$/, evaluateIdentifier: /^evaluate Identifier (.+)$/, evaluateDefinedIdentifier: /^evaluate defined Identifier (.+)$/, evaluateCallExpressionMember: /^evaluate CallExpression .(.+)$/, evaluate: /^evaluate (.+)$/, label: /^label (.+)$/, varDeclarationLet: /^var-let (.+)$/, varDeclarationConst: /^var-const (.+)$/, varDeclarationVar: /^var-var (.+)$/, varDeclaration: /^var (.+)$/, canRename: /^can-rename (.+)$/, rename: /^rename (.+)$/, typeof: /^typeof (.+)$/, assigned: /^assigned (.+)$/, assign: /^assign (.+)$/, callAnyMember: /^call (.+)\.\*$/, call: /^call (.+)$/, new: /^new (.+)$/, expressionConditionalOperator: /^expression \?:$/, expressionAnyMember: /^expression (.+)\.\*$/, expression: /^expression (.+)$/ }; this._pluginCompat.tap("Parser", options => { for (const name of Object.keys(HOOK_MAP_COMPAT_CONFIG)) { const regexp = HOOK_MAP_COMPAT_CONFIG[name]; const match = regexp.exec(options.name); if (match) { if (match[1]) { this.hooks[name].tap( match[1], options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); } else { this.hooks[name].tap( options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); } return true; } } }); this.options = options; this.sourceType = sourceType; this.scope = undefined; this.state = undefined; this.comments = undefined; this.initializeEvaluating(); } initializeEvaluating() { this.hooks.evaluate.for("Literal").tap("Parser", expr => { switch (typeof expr.value) { case "number": return new BasicEvaluatedExpression() .setNumber(expr.value) .setRange(expr.range); case "string": return new BasicEvaluatedExpression() .setString(expr.value) .setRange(expr.range); case "boolean": return new BasicEvaluatedExpression() .setBoolean(expr.value) .setRange(expr.range); } if (expr.value === null) { return new BasicEvaluatedExpression().setNull().setRange(expr.range); } if (expr.value instanceof RegExp) { return new BasicEvaluatedExpression() .setRegExp(expr.value) .setRange(expr.range); } }); this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => { let left; let leftAsBool; let right; if (expr.operator === "&&") { left = this.evaluateExpression(expr.left); leftAsBool = left && left.asBool(); if (leftAsBool === false) return left.setRange(expr.range); if (leftAsBool !== true) return; right = this.evaluateExpression(expr.right); return right.setRange(expr.range); } else if (expr.operator === "||") { left = this.evaluateExpression(expr.left); leftAsBool = left && left.asBool(); if (leftAsBool === true) return left.setRange(expr.range); if (leftAsBool !== false) return; right = this.evaluateExpression(expr.right); return right.setRange(expr.range); } }); this.hooks.evaluate.for("BinaryExpression").tap("Parser", expr => { let left; let right; let res; if (expr.operator === "+") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; res = new BasicEvaluatedExpression(); if (left.isString()) { if (right.isString()) { res.setString(left.string + right.string); } else if (right.isNumber()) { res.setString(left.string + right.number); } else if ( right.isWrapped() && right.prefix && right.prefix.isString() ) { // "left" + ("prefix" + inner + "postfix") // => ("leftprefix" + inner + "postfix") res.setWrapped( new BasicEvaluatedExpression() .setString(left.string + right.prefix.string) .setRange(joinRanges(left.range, right.prefix.range)), right.postfix, right.wrappedInnerExpressions ); } else if (right.isWrapped()) { // "left" + ([null] + inner + "postfix") // => ("left" + inner + "postfix") res.setWrapped(left, right.postfix, right.wrappedInnerExpressions); } else { // "left" + expr // => ("left" + expr + "") res.setWrapped(left, null, [right]); } } else if (left.isNumber()) { if (right.isString()) { res.setString(left.number + right.string); } else if (right.isNumber()) { res.setNumber(left.number + right.number); } else { return; } } else if (left.isWrapped()) { if (left.postfix && left.postfix.isString() && right.isString()) { // ("prefix" + inner + "postfix") + "right" // => ("prefix" + inner + "postfixright") res.setWrapped( left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.string) .setRange(joinRanges(left.postfix.range, right.range)), left.wrappedInnerExpressions ); } else if ( left.postfix && left.postfix.isString() && right.isNumber() ) { // ("prefix" + inner + "postfix") + 123 // => ("prefix" + inner + "postfix123") res.setWrapped( left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.number) .setRange(joinRanges(left.postfix.range, right.range)), left.wrappedInnerExpressions ); } else if (right.isString()) { // ("prefix" + inner + [null]) + "right" // => ("prefix" + inner + "right") res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); } else if (right.isNumber()) { // ("prefix" + inner + [null]) + 123 // => ("prefix" + inner + "123") res.setWrapped( left.prefix, new BasicEvaluatedExpression() .setString(right.number + "") .setRange(right.range), left.wrappedInnerExpressions ); } else if (right.isWrapped()) { // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") res.setWrapped( left.prefix, right.postfix, left.wrappedInnerExpressions && right.wrappedInnerExpressions && left.wrappedInnerExpressions .concat(left.postfix ? [left.postfix] : []) .concat(right.prefix ? [right.prefix] : []) .concat(right.wrappedInnerExpressions) ); } else { // ("prefix" + inner + postfix) + expr // => ("prefix" + inner + postfix + expr + [null]) res.setWrapped( left.prefix, null, left.wrappedInnerExpressions && left.wrappedInnerExpressions.concat( left.postfix ? [left.postfix, right] : [right] ) ); } } else { if (right.isString()) { // left + "right" // => ([null] + left + "right") res.setWrapped(null, right, [left]); } else if (right.isWrapped()) { // left + (prefix + inner + "postfix") // => ([null] + left + prefix + inner + "postfix") res.setWrapped( null, right.postfix, right.wrappedInnerExpressions && (right.prefix ? [left, right.prefix] : [left]).concat( right.wrappedInnerExpressions ) ); } else { return; } } res.setRange(expr.range); return res; } else if (expr.operator === "-") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number - right.number); res.setRange(expr.range); return res; } else if (expr.operator === "*") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number * right.number); res.setRange(expr.range); return res; } else if (expr.operator === "/") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number / right.number); res.setRange(expr.range); return res; } else if (expr.operator === "**") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(Math.pow(left.number, right.number)); res.setRange(expr.range); return res; } else if (expr.operator === "==" || expr.operator === "===") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; res = new BasicEvaluatedExpression(); res.setRange(expr.range); if (left.isString() && right.isString()) { return res.setBoolean(left.string === right.string); } else if (left.isNumber() && right.isNumber()) { return res.setBoolean(left.number === right.number); } else if (left.isBoolean() && right.isBoolean()) { return res.setBoolean(left.bool === right.bool); } } else if (expr.operator === "!=" || expr.operator === "!==") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; res = new BasicEvaluatedExpression(); res.setRange(expr.range); if (left.isString() && right.isString()) { return res.setBoolean(left.string !== right.string); } else if (left.isNumber() && right.isNumber()) { return res.setBoolean(left.number !== right.number); } else if (left.isBoolean() && right.isBoolean()) { return res.setBoolean(left.bool !== right.bool); } } else if (expr.operator === "&") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number & right.number); res.setRange(expr.range); return res; } else if (expr.operator === "|") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number | right.number); res.setRange(expr.range); return res; } else if (expr.operator === "^") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number ^ right.number); res.setRange(expr.range); return res; } else if (expr.operator === ">>>") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number >>> right.number); res.setRange(expr.range); return res; } else if (expr.operator === ">>") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number >> right.number); res.setRange(expr.range); return res; } else if (expr.operator === "<<") { left = this.evaluateExpression(expr.left); right = this.evaluateExpression(expr.right); if (!left || !right) return; if (!left.isNumber() || !right.isNumber()) return; res = new BasicEvaluatedExpression(); res.setNumber(left.number << right.number); res.setRange(expr.range); return res; } }); this.hooks.evaluate.for("UnaryExpression").tap("Parser", expr => { if (expr.operator === "typeof") { let res; let name; if (expr.argument.type === "Identifier") { name = this.scope.renames.get(expr.argument.name) || expr.argument.name; if (!this.scope.definitions.has(name)) { const hook = this.hooks.evaluateTypeof.get(name); if (hook !== undefined) { res = hook.call(expr); if (res !== undefined) return res; } } } if (expr.argument.type === "MemberExpression") { const exprName = this.getNameForExpression(expr.argument); if (exprName && exprName.free) { const hook = this.hooks.evaluateTypeof.get(exprName.name); if (hook !== undefined) { res = hook.call(expr); if (res !== undefined) return res; } } } if (expr.argument.type === "FunctionExpression") { return new BasicEvaluatedExpression() .setString("function") .setRange(expr.range); } const arg = this.evaluateExpression(expr.argument); if (arg.isString() || arg.isWrapped()) { return new BasicEvaluatedExpression() .setString("string") .setRange(expr.range); } if (arg.isNumber()) { return new BasicEvaluatedExpression() .setString("number") .setRange(expr.range); } if (arg.isBoolean()) { return new BasicEvaluatedExpression() .setString("boolean") .setRange(expr.range); } if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) { return new BasicEvaluatedExpression() .setString("object") .setRange(expr.range); } } else if (expr.operator === "!") { const argument = this.evaluateExpression(expr.argument); if (!argument) return; if (argument.isBoolean()) { return new BasicEvaluatedExpression() .setBoolean(!argument.bool) .setRange(expr.range); } if (argument.isTruthy()) { return new BasicEvaluatedExpression() .setBoolean(false) .setRange(expr.range); } if (argument.isFalsy()) { return new BasicEvaluatedExpression() .setBoolean(true) .setRange(expr.range); } if (argument.isString()) { return new BasicEvaluatedExpression() .setBoolean(!argument.string) .setRange(expr.range); } if (argument.isNumber()) { return new BasicEvaluatedExpression() .setBoolean(!argument.number) .setRange(expr.range); } } else if (expr.operator === "~") { const argument = this.evaluateExpression(expr.argument); if (!argument) return; if (!argument.isNumber()) return; const res = new BasicEvaluatedExpression(); res.setNumber(~argument.number); res.setRange(expr.range); return res; } }); this.hooks.evaluateTypeof.for("undefined").tap("Parser", expr => { return new BasicEvaluatedExpression() .setString("undefined") .setRange(expr.range); }); this.hooks.evaluate.for("Identifier").tap("Parser", expr => { const name = this.scope.renames.get(expr.name) || expr.name; if (!this.scope.definitions.has(expr.name)) { const hook = this.hooks.evaluateIdentifier.get(name); if (hook !== undefined) { const result = hook.call(expr); if (result) return result; } return new BasicEvaluatedExpression() .setIdentifier(name) .setRange(expr.range); } else { const hook = this.hooks.evaluateDefinedIdentifier.get(name); if (hook !== undefined) { return hook.call(expr); } } }); this.hooks.evaluate.for("ThisExpression").tap("Parser", expr => { const name = this.scope.renames.get("this"); if (name) { const hook = this.hooks.evaluateIdentifier.get(name); if (hook !== undefined) { const result = hook.call(expr); if (result) return result; } return new BasicEvaluatedExpression() .setIdentifier(name) .setRange(expr.range); } }); this.hooks.evaluate.for("MemberExpression").tap("Parser", expression => { let exprName = this.getNameForExpression(expression); if (exprName) { if (exprName.free) { const hook = this.hooks.evaluateIdentifier.get(exprName.name); if (hook !== undefined) { const result = hook.call(expression); if (result) return result; } return new BasicEvaluatedExpression() .setIdentifier(exprName.name) .setRange(expression.range); } else { const hook = this.hooks.evaluateDefinedIdentifier.get(exprName.name); if (hook !== undefined) { return hook.call(expression); } } } }); this.hooks.evaluate.for("CallExpression").tap("Parser", expr => { if (expr.callee.type !== "MemberExpression") return; if ( expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier") ) return; const param = this.evaluateExpression(expr.callee.object); if (!param) return; const property = expr.callee.property.name || expr.callee.property.value; const hook = this.hooks.evaluateCallExpressionMember.get(property); if (hook !== undefined) { return hook.call(expr, param); } }); this.hooks.evaluateCallExpressionMember .for("replace") .tap("Parser", (expr, param) => { if (!param.isString()) return; if (expr.arguments.length !== 2) return; let arg1 = this.evaluateExpression(expr.arguments[0]); let arg2 = this.evaluateExpression(expr.arguments[1]); if (!arg1.isString() && !arg1.isRegExp()) return; arg1 = arg1.regExp || arg1.string; if (!arg2.isString()) return; arg2 = arg2.string; return new BasicEvaluatedExpression() .setString(param.string.replace(arg1, arg2)) .setRange(expr.range); }); ["substr", "substring"].forEach(fn => { this.hooks.evaluateCallExpressionMember .for(fn) .tap("Parser", (expr, param) => { if (!param.isString()) return; let arg1; let result, str = param.string; switch (expr.arguments.length) { case 1: arg1 = this.evaluateExpression(expr.arguments[0]); if (!arg1.isNumber()) return; result = str[fn](arg1.number); break; case 2: { arg1 = this.evaluateExpression(expr.arguments[0]); const arg2 = this.evaluateExpression(expr.arguments[1]); if (!arg1.isNumber()) return; if (!arg2.isNumber()) return; result = str[fn](arg1.number, arg2.number); break; } default: return; } return new BasicEvaluatedExpression() .setString(result) .setRange(expr.range); }); }); /** * @param {string} kind "cooked" | "raw" * @param {TODO} templateLiteralExpr TemplateLiteral expr * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template */ const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { const quasis = []; const parts = []; for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { const quasiExpr = templateLiteralExpr.quasis[i]; const quasi = quasiExpr.value[kind]; if (i > 0) { const prevExpr = parts[parts.length - 1]; const expr = this.evaluateExpression( templateLiteralExpr.expressions[i - 1] ); const exprAsString = expr.asString(); if (typeof exprAsString === "string") { // We can merge quasi + expr + quasi when expr // is a const string prevExpr.setString(prevExpr.string + exprAsString + quasi); prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); // We unset the expression as it doesn't match to a single expression prevExpr.setExpression(undefined); continue; } parts.push(expr); } const part = new BasicEvaluatedExpression() .setString(quasi) .setRange(quasiExpr.range) .setExpression(quasiExpr); quasis.push(part); parts.push(part); } return { quasis, parts }; }; this.hooks.evaluate.for("TemplateLiteral").tap("Parser", node => { const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); if (parts.length === 1) { return parts[0].setRange(node.range); } return new BasicEvaluatedExpression() .setTemplateString(quasis, parts, "cooked") .setRange(node.range); }); this.hooks.evaluate.for("TaggedTemplateExpression").tap("Parser", node => { if (this.evaluateExpression(node.tag).identifier !== "String.raw") return; const { quasis, parts } = getSimplifiedTemplateResult("raw", node.quasi); if (parts.length === 1) { return parts[0].setRange(node.range); } return new BasicEvaluatedExpression() .setTemplateString(quasis, parts, "raw") .setRange(node.range); }); this.hooks.evaluateCallExpressionMember .for("concat") .tap("Parser", (expr, param) => { if (!param.isString() && !param.isWrapped()) return; let stringSuffix = null; let hasUnknownParams = false; for (let i = expr.arguments.length - 1; i >= 0; i--) { const argExpr = this.evaluateExpression(expr.arguments[i]); if (!argExpr.isString() && !argExpr.isNumber()) { hasUnknownParams = true; break; } const value = argExpr.isString() ? argExpr.string : "" + argExpr.number; const newString = value + (stringSuffix ? stringSuffix.string : ""); const newRange = [ argExpr.range[0], (stringSuffix || argExpr).range[1] ]; stringSuffix = new BasicEvaluatedExpression() .setString(newString) .setRange(newRange); } if (hasUnknownParams) { const prefix = param.isString() ? param : param.prefix; return new BasicEvaluatedExpression() .setWrapped(prefix, stringSuffix) .setRange(expr.range); } else if (param.isWrapped()) { const postfix = stringSuffix || param.postfix; return new BasicEvaluatedExpression() .setWrapped(param.prefix, postfix) .setRange(expr.range); } else { const newString = param.string + (stringSuffix ? stringSuffix.string : ""); return new BasicEvaluatedExpression() .setString(newString) .setRange(expr.range); } }); this.hooks.evaluateCallExpressionMember .for("split") .tap("Parser", (expr, param) => { if (!param.isString()) return; if (expr.arguments.length !== 1) return; let result; const arg = this.evaluateExpression(expr.arguments[0]); if (arg.isString()) { result = param.string.split(arg.string); } else if (arg.isRegExp()) { result = param.string.split(arg.regExp); } else { return; } return new BasicEvaluatedExpression() .setArray(result) .setRange(expr.range); }); this.hooks.evaluate.for("ConditionalExpression").tap("Parser", expr => { const condition = this.evaluateExpression(expr.test); const conditionValue = condition.asBool(); let res; if (conditionValue === undefined) { const consequent = this.evaluateExpression(expr.consequent); const alternate = this.evaluateExpression(expr.alternate); if (!consequent || !alternate) return; res = new BasicEvaluatedExpression(); if (consequent.isConditional()) { res.setOptions(consequent.options); } else { res.setOptions([consequent]); } if (alternate.isConditional()) { res.addOptions(alternate.options); } else { res.addOptions([alternate]); } } else { res = this.evaluateExpression( conditionValue ? expr.consequent : expr.alternate ); } res.setRange(expr.range); return res; }); this.hooks.evaluate.for("ArrayExpression").tap("Parser", expr => { const items = expr.elements.map(element => { return element !== null && this.evaluateExpression(element); }); if (!items.every(Boolean)) return; return new BasicEvaluatedExpression() .setItems(items) .setRange(expr.range); }); } getRenameIdentifier(expr) { const result = this.evaluateExpression(expr); if (result && result.isIdentifier()) { return result.identifier; } } walkClass(classy) { if (classy.superClass) this.walkExpression(classy.superClass); if (classy.body && classy.body.type === "ClassBody") { const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = false; for (const methodDefinition of classy.body.body) { if (methodDefinition.type === "MethodDefinition") { this.walkMethodDefinition(methodDefinition); } } this.scope.topLevelScope = wasTopLevel; } } walkMethodDefinition(methodDefinition) { if (methodDefinition.computed && methodDefinition.key) { this.walkExpression(methodDefinition.key); } if (methodDefinition.value) { this.walkExpression(methodDefinition.value); } } // Prewalking iterates the scope for variable declarations prewalkStatements(statements) { for (let index = 0, len = statements.length; index < len; index++) { const statement = statements[index]; this.prewalkStatement(statement); } } // Walking iterates the statements and expressions and processes them walkStatements(statements) { for (let index = 0, len = statements.length; index < len; index++) { const statement = statements[index]; this.walkStatement(statement); } } prewalkStatement(statement) { switch (statement.type) { case "BlockStatement": this.prewalkBlockStatement(statement); break; case "ClassDeclaration": this.prewalkClassDeclaration(statement); break; case "DoWhileStatement": this.prewalkDoWhileStatement(statement); break; case "ExportAllDeclaration": this.prewalkExportAllDeclaration(statement); break; case "ExportDefaultDeclaration": this.prewalkExportDefaultDeclaration(statement); break; case "ExportNamedDeclaration": this.prewalkExportNamedDeclaration(statement); break; case "ForInStatement": this.prewalkForInStatement(statement); break; case "ForOfStatement": this.prewalkForOfStatement(statement); break; case "ForStatement": this.prewalkForStatement(statement); break; case "FunctionDeclaration": this.prewalkFunctionDeclaration(statement); break; case "IfStatement": this.prewalkIfStatement(statement); break; case "ImportDeclaration": this.prewalkImportDeclaration(statement); break; case "LabeledStatement": this.prewalkLabeledStatement(statement); break; case "SwitchStatement": this.prewalkSwitchStatement(statement); break; case "TryStatement": this.prewalkTryStatement(statement); break; case "VariableDeclaration": this.prewalkVariableDeclaration(statement); break; case "WhileStatement": this.prewalkWhileStatement(statement); break; case "WithStatement": this.prewalkWithStatement(statement); break; } } walkStatement(statement) { if (this.hooks.statement.call(statement) !== undefined) return; switch (statement.type) { case "BlockStatement": this.walkBlockStatement(statement); break; case "ClassDeclaration": this.walkClassDeclaration(statement); break; case "DoWhileStatement": this.walkDoWhileStatement(statement); break; case "ExportDefaultDeclaration": this.walkExportDefaultDeclaration(statement); break; case "ExportNamedDeclaration": this.walkExportNamedDeclaration(statement); break; case "ExpressionStatement": this.walkExpressionStatement(statement); break; case "ForInStatement": this.walkForInStatement(statement); break; case "ForOfStatement": this.walkForOfStatement(statement); break; case "ForStatement": this.walkForStatement(statement); break; case "FunctionDeclaration": this.walkFunctionDeclaration(statement); break; case "IfStatement": this.walkIfStatement(statement); break; case "LabeledStatement": this.walkLabeledStatement(statement); break; case "ReturnStatement": this.walkReturnStatement(statement); break; case "SwitchStatement": this.walkSwitchStatement(statement); break; case "ThrowStatement": this.walkThrowStatement(statement); break; case "TryStatement": this.walkTryStatement(statement); break; case "VariableDeclaration": this.walkVariableDeclaration(statement); break; case "WhileStatement": this.walkWhileStatement(statement); break; case "WithStatement": this.walkWithStatement(statement); break; } } // Real Statements prewalkBlockStatement(statement) { this.prewalkStatements(statement.body); } walkBlockStatement(statement) { this.walkStatements(statement.body); } walkExpressionStatement(statement) { this.walkExpression(statement.expression); } prewalkIfStatement(statement) { this.prewalkStatement(statement.consequent); if (statement.alternate) { this.prewalkStatement(statement.alternate); } } walkIfStatement(statement) { const result = this.hooks.statementIf.call(statement); if (result === undefined) { this.walkExpression(statement.test); this.walkStatement(statement.consequent); if (statement.alternate) { this.walkStatement(statement.alternate); } } else { if (result) { this.walkStatement(statement.consequent); } else if (statement.alternate) { this.walkStatement(statement.alternate); } } } prewalkLabeledStatement(statement) { this.prewalkStatement(statement.body); } walkLabeledStatement(statement) { const hook = this.hooks.label.get(statement.label.name); if (hook !== undefined) { const result = hook.call(statement); if (result === true) return; } this.walkStatement(statement.body); } prewalkWithStatement(statement) { this.prewalkStatement(statement.body); } walkWithStatement(statement) { this.walkExpression(statement.object); this.walkStatement(statement.body); } prewalkSwitchStatement(statement) { this.prewalkSwitchCases(statement.cases); } walkSwitchStatement(statement) { this.walkExpression(statement.discriminant); this.walkSwitchCases(statement.cases); } walkTerminatingStatement(statement) { if (statement.argument) this.walkExpression(statement.argument); } walkReturnStatement(statement) { this.walkTerminatingStatement(statement); } walkThrowStatement(statement) { this.walkTerminatingStatement(statement); } prewalkTryStatement(statement) { this.prewalkStatement(statement.block); } walkTryStatement(statement) { if (this.scope.inTry) { this.walkStatement(statement.block); } else { this.scope.inTry = true; this.walkStatement(statement.block); this.scope.inTry = false; } if (statement.handler) this.walkCatchClause(statement.handler); if (statement.finalizer) this.walkStatement(statement.finalizer); } prewalkWhileStatement(statement) { this.prewalkStatement(statement.body); } walkWhileStatement(statement) { this.walkExpression(statement.test); this.walkStatement(statement.body); } prewalkDoWhileStatement(statement) { this.prewalkStatement(statement.body); } walkDoWhileStatement(statement) { this.walkStatement(statement.body); this.walkExpression(statement.test); } prewalkForStatement(statement) { if (statement.init) { if (statement.init.type === "VariableDeclaration") { this.prewalkStatement(statement.init); } } this.prewalkStatement(statement.body); } walkForStatement(statement) { if (statement.init) { if (statement.init.type === "VariableDeclaration") { this.walkStatement(statement.init); } else { this.walkExpression(statement.init); } } if (statement.test) { this.walkExpression(statement.test); } if (statement.update) { this.walkExpression(statement.update); } this.walkStatement(statement.body); } prewalkForInStatement(statement) { if (statement.left.type === "VariableDeclaration") { this.prewalkVariableDeclaration(statement.left); } this.prewalkStatement(statement.body); } walkForInStatement(statement) { if (statement.left.type === "VariableDeclaration") { this.walkVariableDeclaration(statement.left); } else { this.walkPattern(statement.left); } this.walkExpression(statement.right); this.walkStatement(statement.body); } prewalkForOfStatement(statement) { if (statement.left.type === "VariableDeclaration") { this.prewalkVariableDeclaration(statement.left); } this.prewalkStatement(statement.body); } walkForOfStatement(statement) { if (statement.left.type === "VariableDeclaration") { this.walkVariableDeclaration(statement.left); } else { this.walkPattern(statement.left); } this.walkExpression(statement.right); this.walkStatement(statement.body); } // Declarations prewalkFunctionDeclaration(statement) { if (statement.id) { this.scope.renames.set(statement.id.name, null); this.scope.definitions.add(statement.id.name); } } walkFunctionDeclaration(statement) { const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = false; this.inScope(statement.params, () => { for (const param of statement.params) { this.walkPattern(param); } if (statement.body.type === "BlockStatement") { this.detectStrictMode(statement.body.body); this.prewalkStatement(statement.body); this.walkStatement(statement.body); } else { this.walkExpression(statement.body); } }); this.scope.topLevelScope = wasTopLevel; } prewalkImportDeclaration(statement) { const source = statement.source.value; this.hooks.import.call(statement, source); for (const specifier of statement.specifiers) { const name = specifier.local.name; this.scope.renames.set(name, null); this.scope.definitions.add(name); switch (specifier.type) { case "ImportDefaultSpecifier": this.hooks.importSpecifier.call(statement, source, "default", name); break; case "ImportSpecifier": this.hooks.importSpecifier.call( statement, source, specifier.imported.name, name ); break; case "ImportNamespaceSpecifier": this.hooks.importSpecifier.call(statement, source, null, name); break; } } } prewalkExportNamedDeclaration(statement) { let source; if (statement.source) { source = statement.source.value; this.hooks.exportImport.call(statement, source); } else { this.hooks.export.call(statement); } if (statement.declaration) { if ( !this.hooks.exportDeclaration.call(statement, statement.declaration) ) { const originalDefinitions = this.scope.definitions; const tracker = new TrackingSet(this.scope.definitions); this.scope.definitions = tracker; this.prewalkStatement(statement.declaration); const newDefs = Array.from(tracker.getAddedItems()); this.scope.definitions = originalDefinitions; for (let index = newDefs.length - 1; index >= 0; index--) { const def = newDefs[index]; this.hooks.exportSpecifier.call(statement, def, def, index); } } } if (statement.specifiers) { for ( let specifierIndex = 0; specifierIndex < statement.specifiers.length; specifierIndex++ ) { const specifier = statement.specifiers[specifierIndex]; switch (specifier.type) { case "ExportSpecifier": { const name = specifier.exported.name; if (source) { this.hooks.exportImportSpecifier.call( statement, source, specifier.local.name, name, specifierIndex ); } else { this.hooks.exportSpecifier.call( statement, specifier.local.name, name, specifierIndex ); } break; } } } } } walkExportNamedDeclaration(statement) { if (statement.declaration) { this.walkStatement(statement.declaration); } } prewalkExportDefaultDeclaration(statement) { if (statement.declaration.id) { const originalDefinitions = this.scope.definitions; const tracker = new TrackingSet(this.scope.definitions); this.scope.definitions = tracker; this.prewalkStatement(statement.declaration); const newDefs = Array.from(tracker.getAddedItems()); this.scope.definitions = originalDefinitions; for (let index = 0, len = newDefs.length; index < len; index++) { const def = newDefs[index]; this.hooks.exportSpecifier.call(statement, def, "default"); } } } walkExportDefaultDeclaration(statement) { this.hooks.export.call(statement); if ( statement.declaration.id && statement.declaration.type !== "FunctionExpression" && statement.declaration.type !== "ClassExpression" ) { if ( !this.hooks.exportDeclaration.call(statement, statement.declaration) ) { this.walkStatement(statement.declaration); } } else { // Acorn parses `export default function() {}` as `FunctionDeclaration` and // `export default class {}` as `ClassDeclaration`, both with `id = null`. // These nodes must be treated as expressions. if (statement.declaration.type === "FunctionDeclaration") { this.walkFunctionDeclaration(statement.declaration); } else if (statement.declaration.type === "ClassDeclaration") { this.walkClassDeclaration(statement.declaration); } else { this.walkExpression(statement.declaration); } if (!this.hooks.exportExpression.call(statement, statement.declaration)) { this.hooks.exportSpecifier.call( statement, statement.declaration, "default" ); } } } prewalkExportAllDeclaration(statement) { const source = statement.source.value; this.hooks.exportImport.call(statement, source); this.hooks.exportImportSpecifier.call(statement, source, null, null, 0); } prewalkVariableDeclaration(statement) { const hookMap = statement.kind === "const" ? this.hooks.varDeclarationConst : statement.kind === "let" ? this.hooks.varDeclarationLet : this.hooks.varDeclarationVar; for (const declarator of statement.declarations) { switch (declarator.type) { case "VariableDeclarator": { this.enterPattern(declarator.id, (name, decl) => { let hook = hookMap.get(name); if (hook === undefined || !hook.call(decl)) { hook = this.hooks.varDeclaration.get(name); if (hook === undefined || !hook.call(decl)) { this.scope.renames.set(name, null); this.scope.definitions.add(name); } } }); break; } } } } walkVariableDeclaration(statement) { for (const declarator of statement.declarations) { switch (declarator.type) { case "VariableDeclarator": { const renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init); if (renameIdentifier && declarator.id.type === "Identifier") { const hook = this.hooks.canRename.get(renameIdentifier); if (hook !== undefined && hook.call(declarator.init)) { // renaming with "var a = b;" const hook = this.hooks.rename.get(renameIdentifier); if (hook === undefined || !hook.call(declarator.init)) { this.scope.renames.set( declarator.id.name, this.scope.renames.get(renameIdentifier) || renameIdentifier ); this.scope.definitions.delete(declarator.id.name); } break; } } this.walkPattern(declarator.id); if (declarator.init) this.walkExpression(declarator.init); break; } } } } prewalkClassDeclaration(statement) { if (statement.id) { this.scope.renames.set(statement.id.name, null); this.scope.definitions.add(statement.id.name); } } walkClassDeclaration(statement) { this.walkClass(statement); } prewalkSwitchCases(switchCases) { for (let index = 0, len = switchCases.length; index < len; index++) { const switchCase = switchCases[index]; this.prewalkStatements(switchCase.consequent); } } walkSwitchCases(switchCases) { for (let index = 0, len = switchCases.length; index < len; index++) { const switchCase = switchCases[index]; if (switchCase.test) { this.walkExpression(switchCase.test); } this.walkStatements(switchCase.consequent); } } walkCatchClause(catchClause) { // Error binding is optional in catch clause since ECMAScript 2019 const errorBinding = catchClause.param === null ? EMPTY_ARRAY : [catchClause.param]; this.inScope(errorBinding, () => { this.prewalkStatement(catchClause.body); this.walkStatement(catchClause.body); }); } walkPattern(pattern) { switch (pattern.type) { case "ArrayPattern": this.walkArrayPattern(pattern); break; case "AssignmentPattern": this.walkAssignmentPattern(pattern); break; case "MemberExpression": this.walkMemberExpression(pattern); break; case "ObjectPattern": this.walkObjectPattern(pattern); break; case "RestElement": this.walkRestElement(pattern); break; } } walkAssignmentPattern(pattern) { this.walkExpression(pattern.right); this.walkPattern(pattern.left); } walkObjectPattern(pattern) { for (let i = 0, len = pattern.properties.length; i < len; i++) { const prop = pattern.properties[i]; if (prop) { if (prop.computed) this.walkExpression(prop.key); if (prop.value) this.walkPattern(prop.value); } } } walkArrayPattern(pattern) { for (let i = 0, len = pattern.elements.length; i < len; i++) { const element = pattern.elements[i]; if (element) this.walkPattern(element); } } walkRestElement(pattern) { this.walkPattern(pattern.argument); } walkExpressions(expressions) { for (const expression of expressions) { if (expression) { this.walkExpression(expression); } } } walkExpression(expression) { switch (expression.type) { case "ArrayExpression": this.walkArrayExpression(expression); break; case "ArrowFunctionExpression": this.walkArrowFunctionExpression(expression); break; case "AssignmentExpression": this.walkAssignmentExpression(expression); break; case "AwaitExpression": this.walkAwaitExpression(expression); break; case "BinaryExpression": this.walkBinaryExpression(expression); break; case "CallExpression": this.walkCallExpression(expression); break; case "ClassExpression": this.walkClassExpression(expression); break; case "ConditionalExpression": this.walkConditionalExpression(expression); break; case "FunctionExpression": this.walkFunctionExpression(expression); break; case "Identifier": this.walkIdentifier(expression); break; case "LogicalExpression": this.walkLogicalExpression(expression); break; case "MemberExpression": this.walkMemberExpression(expression); break; case "NewExpression": this.walkNewExpression(expression); break; case "ObjectExpression": this.walkObjectExpression(expression); break; case "SequenceExpression": this.walkSequenceExpression(expression); break; case "SpreadElement": this.walkSpreadElement(expression); break; case "TaggedTemplateExpression": this.walkTaggedTemplateExpression(expression); break; case "TemplateLiteral": this.walkTemplateLiteral(expression); break; case "ThisExpression": this.walkThisExpression(expression); break; case "UnaryExpression": this.walkUnaryExpression(expression); break; case "UpdateExpression": this.walkUpdateExpression(expression); break; case "YieldExpression": this.walkYieldExpression(expression); break; } } walkAwaitExpression(expression) { this.walkExpression(expression.argument); } walkArrayExpression(expression) { if (expression.elements) { this.walkExpressions(expression.elements); } } walkSpreadElement(expression) { if (expression.argument) { this.walkExpression(expression.argument); } } walkObjectExpression(expression) { for ( let propIndex = 0, len = expression.properties.length; propIndex < len; propIndex++ ) { const prop = expression.properties[propIndex]; if (prop.type === "SpreadElement") { this.walkExpression(prop.argument); continue; } if (prop.computed) { this.walkExpression(prop.key); } if (prop.shorthand) { this.scope.inShorthand = true; } this.walkExpression(prop.value); if (prop.shorthand) { this.scope.inShorthand = false; } } } walkFunctionExpression(expression) { const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = false; const scopeParams = expression.params; // Add function name in scope for recursive calls if (expression.id) { scopeParams.push(expression.id.name); } this.inScope(scopeParams, () => { for (const param of expression.params) { this.walkPattern(param); } if (expression.body.type === "BlockStatement") { this.detectStrictMode(expression.body.body); this.prewalkStatement(expression.body); this.walkStatement(expression.body); } else { this.walkExpression(expression.body); } }); this.scope.topLevelScope = wasTopLevel; } walkArrowFunctionExpression(expression) { this.inScope(expression.params, () => { for (const param of expression.params) { this.walkPattern(param); } if (expression.body.type === "BlockStatement") { this.detectStrictMode(expression.body.body); this.prewalkStatement(expression.body); this.walkStatement(expression.body); } else { this.walkExpression(expression.body); } }); } walkSequenceExpression(expression) { if (expression.expressions) this.walkExpressions(expression.expressions); } walkUpdateExpression(expression) { this.walkExpression(expression.argument); } walkUnaryExpression(expression) { if (expression.operator === "typeof") { const exprName = this.getNameForExpression(expression.argument); if (exprName && exprName.free) { const hook = this.hooks.typeof.get(exprName.name); if (hook !== undefined) { const result = hook.call(expression); if (result === true) return; } } } this.walkExpression(expression.argument); } walkLeftRightExpression(expression) { this.walkExpression(expression.left); this.walkExpression(expression.right); } walkBinaryExpression(expression) { this.walkLeftRightExpression(expression); } walkLogicalExpression(expression) { const result = this.hooks.expressionLogicalOperator.call(expression); if (result === undefined) { this.walkLeftRightExpression(expression); } else { if (result) { this.walkExpression(expression.right); } } } walkAssignmentExpression(expression) { const renameIdentifier = this.getRenameIdentifier(expression.right); if (expression.left.type === "Identifier" && renameIdentifier) { const hook = this.hooks.canRename.get(renameIdentifier); if (hook !== undefined && hook.call(expression.right)) { // renaming "a = b;" const hook = this.hooks.rename.get(renameIdentifier); if (hook === undefined || !hook.call(expression.right)) { this.scope.renames.set(expression.left.name, renameIdentifier); this.scope.definitions.delete(expression.left.name); } return; } } if (expression.left.type === "Identifier") { const assignedHook = this.hooks.assigned.get(expression.left.name); if (assignedHook === undefined || !assignedHook.call(expression)) { this.walkExpression(expression.right); } this.scope.renames.set(expression.left.name, null); const assignHook = this.hooks.assign.get(expression.left.name); if (assignHook === undefined || !assignHook.call(expression)) { this.walkExpression(expression.left); } return; } this.walkExpression(expression.right); this.walkPattern(expression.left); this.enterPattern(expression.left, (name, decl) => { this.scope.renames.set(name, null); }); } walkConditionalExpression(expression) { const result = this.hooks.expressionConditionalOperator.call(expression); if (result === undefined) { this.walkExpression(expression.test); this.walkExpression(expression.consequent); if (expression.alternate) { this.walkExpression(expression.alternate); } } else { if (result) { this.walkExpression(expression.consequent); } else if (expression.alternate) { this.walkExpression(expression.alternate); } } } walkNewExpression(expression) { const callee = this.evaluateExpression(expression.callee); if (callee.isIdentifier()) { const hook = this.hooks.new.get(callee.identifier); if (hook !== undefined) { const result = hook.call(expression); if (result === true) { return; } } } this.walkExpression(expression.callee); if (expression.arguments) { this.walkExpressions(expression.arguments); } } walkYieldExpression(expression) { if (expression.argument) { this.walkExpression(expression.argument); } } walkTemplateLiteral(expression) { if (expression.expressions) { this.walkExpressions(expression.expressions); } } walkTaggedTemplateExpression(expression) { if (expression.tag) { this.walkExpression(expression.tag); } if (expression.quasi && expression.quasi.expressions) { this.walkExpressions(expression.quasi.expressions); } } walkClassExpression(expression) { this.walkClass(expression); } _walkIIFE(functionExpression, options, currentThis) { const renameArgOrThis = argOrThis => { const renameIdentifier = this.getRenameIdentifier(argOrThis); if (renameIdentifier) { const hook = this.hooks.canRename.get(renameIdentifier); if (hook !== undefined && hook.call(argOrThis)) { const hook = this.hooks.rename.get(renameIdentifier); if (hook === undefined || !hook.call(argOrThis)) { return renameIdentifier; } } } this.walkExpression(argOrThis); }; const params = functionExpression.params; const renameThis = currentThis ? renameArgOrThis(currentThis) : null; const args = options.map(renameArgOrThis); const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = false; const scopeParams = params.filter((identifier, idx) => !args[idx]); // Add function name in scope for recursive calls if (functionExpression.id) { scopeParams.push(functionExpression.id.name); } this.inScope(scopeParams, () => { if (renameThis) { this.scope.renames.set("this", renameThis); } for (let i = 0; i < args.length; i++) { const param = args[i]; if (!param) continue; if (!params[i] || params[i].type !== "Identifier") continue; this.scope.renames.set(params[i].name, param); } if (functionExpression.body.type === "BlockStatement") { this.prewalkStatement(functionExpression.body); this.walkStatement(functionExpression.body); } else { this.walkExpression(functionExpression.body); } }); this.scope.topLevelScope = wasTopLevel; } walkCallExpression(expression) { if ( expression.callee.type === "MemberExpression" && expression.callee.object.type === "FunctionExpression" && !expression.callee.computed && (expression.callee.property.name === "call" || expression.callee.property.name === "bind") && expression.arguments.length > 0 ) { // (function(…) { }.call/bind(?, …)) this._walkIIFE( expression.callee.object, expression.arguments.slice(1), expression.arguments[0] ); } else if (expression.callee.type === "FunctionExpression") { // (function(…) { }(…)) this._walkIIFE(expression.callee, expression.arguments, null); } else if (expression.callee.type === "Import") { let result = this.hooks.importCall.call(expression); if (result === true) return; if (expression.arguments) this.walkExpressions(expression.arguments); } else { const callee = this.evaluateExpression(expression.callee); if (callee.isIdentifier()) { const callHook = this.hooks.call.get(callee.identifier); if (callHook !== undefined) { let result = callHook.call(expression); if (result === true) return; } let identifier = callee.identifier.replace(/\.[^.]+$/, ""); if (identifier !== callee.identifier) { const callAnyHook = this.hooks.callAnyMember.get(identifier); if (callAnyHook !== undefined) { let result = callAnyHook.call(expression); if (result === true) return; } } } if (expression.callee) this.walkExpression(expression.callee); if (expression.arguments) this.walkExpressions(expression.arguments); } } walkMemberExpression(expression) { const exprName = this.getNameForExpression(expression); if (exprName && exprName.free) { const expressionHook = this.hooks.expression.get(exprName.name); if (expressionHook !== undefined) { const result = expressionHook.call(expression); if (result === true) return; } const expressionAnyMemberHook = this.hooks.expressionAnyMember.get( exprName.nameGeneral ); if (expressionAnyMemberHook !== undefined) { const result = expressionAnyMemberHook.call(expression); if (result === true) return; } } this.walkExpression(expression.object); if (expression.computed === true) this.walkExpression(expression.property); } walkThisExpression(expression) { const expressionHook = this.hooks.expression.get("this"); if (expressionHook !== undefined) { expressionHook.call(expression); } } walkIdentifier(expression) { if (!this.scope.definitions.has(expression.name)) { const hook = this.hooks.expression.get( this.scope.renames.get(expression.name) || expression.name ); if (hook !== undefined) { const result = hook.call(expression); if (result === true) return; } } } inScope(params, fn) { const oldScope = this.scope; this.scope = { topLevelScope: oldScope.topLevelScope, inTry: false, inShorthand: false, isStrict: oldScope.isStrict, definitions: oldScope.definitions.createChild(), renames: oldScope.renames.createChild() }; this.scope.renames.set("this", null); for (const param of params) { if (typeof param !== "string") { this.enterPattern(param, param => { this.scope.renames.set(param, null); this.scope.definitions.add(param); }); } else if (param) { this.scope.renames.set(param, null); this.scope.definitions.add(param); } } fn(); this.scope = oldScope; } detectStrictMode(statements) { const isStrict = statements.length >= 1 && statements[0].type === "ExpressionStatement" && statements[0].expression.type === "Literal" && statements[0].expression.value === "use strict"; if (isStrict) { this.scope.isStrict = true; } } enterPattern(pattern, onIdent) { if (!pattern) return; switch (pattern.type) { case "ArrayPattern": this.enterArrayPattern(pattern, onIdent); break; case "AssignmentPattern": this.enterAssignmentPattern(pattern, onIdent); break; case "Identifier": this.enterIdentifier(pattern, onIdent); break; case "ObjectPattern": this.enterObjectPattern(pattern, onIdent); break; case "RestElement": this.enterRestElement(pattern, onIdent); break; } } enterIdentifier(pattern, onIdent) { onIdent(pattern.name, pattern); } enterObjectPattern(pattern, onIdent) { for ( let propIndex = 0, len = pattern.properties.length; propIndex < len; propIndex++ ) { const prop = pattern.properties[propIndex]; this.enterPattern(prop.value, onIdent); } } enterArrayPattern(pattern, onIdent) { for ( let elementIndex = 0, len = pattern.elements.length; elementIndex < len; elementIndex++ ) { const element = pattern.elements[elementIndex]; this.enterPattern(element, onIdent); } } enterRestElement(pattern, onIdent) { this.enterPattern(pattern.argument, onIdent); } enterAssignmentPattern(pattern, onIdent) { this.enterPattern(pattern.left, onIdent); } evaluateExpression(expression) { try { const hook = this.hooks.evaluate.get(expression.type); if (hook !== undefined) { const result = hook.call(expression); if (result !== undefined) { if (result) { result.setExpression(expression); } return result; } } } catch (e) { console.warn(e); // ignore error } return new BasicEvaluatedExpression() .setRange(expression.range) .setExpression(expression); } parseString(expression) { switch (expression.type) { case "BinaryExpression": if (expression.operator === "+") { return ( this.parseString(expression.left) + this.parseString(expression.right) ); } break; case "Literal": return expression.value + ""; } throw new Error( expression.type + " is not supported as parameter for require" ); } parseCalculatedString(expression) { switch (expression.type) { case "BinaryExpression": if (expression.operator === "+") { const left = this.parseCalculatedString(expression.left); const right = this.parseCalculatedString(expression.right); if (left.code) { return { range: left.range, value: left.value, code: true, conditional: false }; } else if (right.code) { return { range: [ left.range[0], right.range ? right.range[1] : left.range[1] ], value: left.value + right.value, code: true, conditional: false }; } else { return { range: [left.range[0], right.range[1]], value: left.value + right.value, code: false, conditional: false }; } } break; case "ConditionalExpression": { const consequent = this.parseCalculatedString(expression.consequent); const alternate = this.parseCalculatedString(expression.alternate); const items = []; if (consequent.conditional) { items.push(...consequent.conditional); } else if (!consequent.code) { items.push(consequent); } else { break; } if (alternate.conditional) { items.push(...alternate.conditional); } else if (!alternate.code) { items.push(alternate); } else { break; } return { range: undefined, value: "", code: true, conditional: items }; } case "Literal": return { range: expression.range, value: expression.value + "", code: false, conditional: false }; } return { range: undefined, value: "", code: true, conditional: false }; } parse(source, initialState) { let ast; let comments; if (typeof source === "object" && source !== null) { ast = source; comments = source.comments; } else { comments = []; ast = Parser.parse(source, { sourceType: this.sourceType, onComment: comments }); } const oldScope = this.scope; const oldState = this.state; const oldComments = this.comments; this.scope = { topLevelScope: true, inTry: false, inShorthand: false, isStrict: false, definitions: new StackedSetMap(), renames: new StackedSetMap() }; const state = (this.state = initialState || {}); this.comments = comments; if (this.hooks.program.call(ast, comments) === undefined) { this.detectStrictMode(ast.body); this.prewalkStatements(ast.body); this.walkStatements(ast.body); } this.scope = oldScope; this.state = oldState; this.comments = oldComments; return state; } evaluate(source) { const ast = Parser.parse("(" + source + ")", { sourceType: this.sourceType, locations: false }); // TODO(https://github.com/acornjs/acorn/issues/741) // @ts-ignore if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { throw new Error("evaluate: Source is not a expression"); } // TODO(https://github.com/acornjs/acorn/issues/741) // @ts-ignore return this.evaluateExpression(ast.body[0].expression); } getComments(range) { return this.comments.filter( comment => comment.range[0] >= range[0] && comment.range[1] <= range[1] ); } parseCommentOptions(range) { const comments = this.getComments(range); if (comments.length === 0) { return EMPTY_COMMENT_OPTIONS; } let options = {}; let errors = []; for (const comment of comments) { const { value } = comment; if (value && webpackCommentRegExp.test(value)) { // try compile only if webpack options comment is present try { const val = vm.runInNewContext(`(function(){return {${value}};})()`); Object.assign(options, val); } catch (e) { e.comment = comment; errors.push(e); } } } return { options, errors }; } getNameForExpression(expression) { let expr = expression; const exprName = []; while ( expr.type === "MemberExpression" && expr.property.type === (expr.computed ? "Literal" : "Identifier") ) { exprName.push(expr.computed ? expr.property.value : expr.property.name); expr = expr.object; } let free; if (expr.type === "Identifier") { free = !this.scope.definitions.has(expr.name); exprName.push(this.scope.renames.get(expr.name) || expr.name); } else if ( expr.type === "ThisExpression" && this.scope.renames.get("this") ) { free = true; exprName.push(this.scope.renames.get("this")); } else if (expr.type === "ThisExpression") { free = this.scope.topLevelScope; exprName.push("this"); } else { return null; } let prefix = ""; for (let i = exprName.length - 1; i >= 2; i--) { prefix += exprName[i] + "."; } if (exprName.length > 1) { prefix += exprName[1]; } const name = prefix ? prefix + "." + exprName[0] : exprName[0]; const nameGeneral = prefix; return { name, nameGeneral, free }; } static parse(code, options) { const type = options ? options.sourceType : "module"; const parserOptions = Object.assign( Object.create(null), defaultParserOptions, options ); if (type === "auto") { parserOptions.sourceType = "module"; } let ast; let error; let threw = false; try { ast = acornParser.parse(code, parserOptions); } catch (e) { error = e; threw = true; } if (threw && type === "auto") { parserOptions.sourceType = "script"; if (Array.isArray(parserOptions.onComment)) { parserOptions.onComment.length = 0; } try { ast = acornParser.parse(code, parserOptions); threw = false; } catch (e) { threw = true; } } if (threw) { throw error; } return ast; } } // TODO remove in webpack 5 Object.defineProperty(Parser.prototype, "getCommentOptions", { configurable: false, value: util.deprecate( /** * @deprecated * @param {TODO} range Range * @returns {void} * @this {Parser} */ function(range) { return this.parseCommentOptions(range).options; }, "Parser.getCommentOptions: Use Parser.parseCommentOptions(range) instead" ) }); module.exports = Parser; webpack-4.30.0/lib/ParserHelpers.js000066400000000000000000000054341345416772700171230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); const ConstDependency = require("./dependencies/ConstDependency"); const UnsupportedFeatureWarning = require("./UnsupportedFeatureWarning"); const ParserHelpers = exports; ParserHelpers.addParsedVariableToModule = (parser, name, expression) => { if (!parser.state.current.addVariable) return false; var deps = []; parser.parse(expression, { current: { addDependency: dep => { dep.userRequest = name; deps.push(dep); } }, module: parser.state.module }); parser.state.current.addVariable(name, expression, deps); return true; }; ParserHelpers.requireFileAsExpression = (context, pathToModule) => { var moduleJsPath = path.relative(context, pathToModule); if (!/^[A-Z]:/i.test(moduleJsPath)) { moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); } return "require(" + JSON.stringify(moduleJsPath) + ")"; }; ParserHelpers.toConstantDependency = (parser, value) => { return function constDependency(expr) { var dep = new ConstDependency(value, expr.range, false); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; }; }; ParserHelpers.toConstantDependencyWithWebpackRequire = (parser, value) => { return function constDependencyWithWebpackRequire(expr) { var dep = new ConstDependency(value, expr.range, true); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; }; }; ParserHelpers.evaluateToString = value => { return function stringExpression(expr) { return new BasicEvaluatedExpression().setString(value).setRange(expr.range); }; }; ParserHelpers.evaluateToBoolean = value => { return function booleanExpression(expr) { return new BasicEvaluatedExpression() .setBoolean(value) .setRange(expr.range); }; }; ParserHelpers.evaluateToIdentifier = (identifier, truthy) => { return function identifierExpression(expr) { let evex = new BasicEvaluatedExpression() .setIdentifier(identifier) .setRange(expr.range); if (truthy === true) { evex = evex.setTruthy(); } else if (truthy === false) { evex = evex.setFalsy(); } return evex; }; }; ParserHelpers.expressionIsUnsupported = (parser, message) => { return function unsupportedExpression(expr) { var dep = new ConstDependency("(void 0)", expr.range, false); dep.loc = expr.loc; parser.state.current.addDependency(dep); if (!parser.state.module) return; parser.state.module.warnings.push( new UnsupportedFeatureWarning(parser.state.module, message, expr.loc) ); return true; }; }; ParserHelpers.skipTraversal = function skipTraversal() { return true; }; ParserHelpers.approve = function approve() { return true; }; webpack-4.30.0/lib/PrefetchPlugin.js000066400000000000000000000015051345416772700172560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const PrefetchDependency = require("./dependencies/PrefetchDependency"); class PrefetchPlugin { constructor(context, request) { if (!request) { this.request = context; } else { this.context = context; this.request = request; } } apply(compiler) { compiler.hooks.compilation.tap( "PrefetchPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( PrefetchDependency, normalModuleFactory ); } ); compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { compilation.prefetch( this.context || compiler.context, new PrefetchDependency(this.request), callback ); }); } } module.exports = PrefetchPlugin; webpack-4.30.0/lib/ProgressPlugin.js000066400000000000000000000233041345416772700173230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/ProgressPlugin.json"); /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ const createDefaultHandler = profile => { let lineCaretPosition = 0; let lastMessage = ""; let lastState; let lastStateTime; const defaultHandler = (percentage, msg, ...args) => { let state = msg; const details = args; if (percentage < 1) { percentage = Math.floor(percentage * 100); msg = `${percentage}% ${msg}`; if (percentage < 100) { msg = ` ${msg}`; } if (percentage < 10) { msg = ` ${msg}`; } for (let detail of details) { if (!detail) continue; if (detail.length > 40) { detail = `...${detail.substr(detail.length - 39)}`; } msg += ` ${detail}`; } } if (profile) { state = state.replace(/^\d+\/\d+\s+/, ""); if (percentage === 0) { lastState = null; lastStateTime = Date.now(); } else if (state !== lastState || percentage === 1) { const now = Date.now(); if (lastState) { const stateMsg = `${now - lastStateTime}ms ${lastState}`; goToLineStart(stateMsg); process.stderr.write(stateMsg + "\n"); lineCaretPosition = 0; } lastState = state; lastStateTime = now; } } if (lastMessage !== msg) { goToLineStart(msg); process.stderr.write(msg); lastMessage = msg; } }; const goToLineStart = nextMessage => { let str = ""; for (; lineCaretPosition > nextMessage.length; lineCaretPosition--) { str += "\b \b"; } for (var i = 0; i < lineCaretPosition; i++) { str += "\b"; } lineCaretPosition = nextMessage.length; if (str) process.stderr.write(str); }; return defaultHandler; }; class ProgressPlugin { /** * @param {ProgressPluginArgument} options options */ constructor(options) { if (typeof options === "function") { options = { handler: options }; } options = options || {}; validateOptions(schema, options, "Progress Plugin"); options = Object.assign({}, ProgressPlugin.defaultOptions, options); this.profile = options.profile; this.handler = options.handler; this.modulesCount = options.modulesCount; this.showEntries = options.entries; this.showModules = options.modules; this.showActiveModules = options.activeModules; } apply(compiler) { const { modulesCount } = this; const handler = this.handler || createDefaultHandler(this.profile); const showEntries = this.showEntries; const showModules = this.showModules; const showActiveModules = this.showActiveModules; if (compiler.compilers) { const states = new Array(compiler.compilers.length); compiler.compilers.forEach((compiler, idx) => { new ProgressPlugin((p, msg, ...args) => { states[idx] = [p, msg, ...args]; handler( states .map(state => (state && state[0]) || 0) .reduce((a, b) => a + b) / states.length, `[${idx}] ${msg}`, ...args ); }).apply(compiler); }); } else { let lastModulesCount = 0; let lastEntriesCount = 0; let moduleCount = modulesCount; let entriesCount = 1; let doneModules = 0; let doneEntries = 0; const activeModules = new Set(); let lastActiveModule = ""; const update = () => { const percentByModules = doneModules / Math.max(lastModulesCount, moduleCount); const percentByEntries = doneEntries / Math.max(lastEntriesCount, entriesCount); const items = [ 0.1 + Math.max(percentByModules, percentByEntries) * 0.6, "building" ]; if (showEntries) { items.push(`${doneEntries}/${entriesCount} entries`); } if (showModules) { items.push(`${doneModules}/${moduleCount} modules`); } if (showActiveModules) { items.push(`${activeModules.size} active`); items.push(lastActiveModule); } handler(...items); }; const moduleAdd = module => { moduleCount++; if (showActiveModules) { const ident = module.identifier(); if (ident) { activeModules.add(ident); lastActiveModule = ident; } } update(); }; const entryAdd = (entry, name) => { entriesCount++; update(); }; const moduleDone = module => { doneModules++; if (showActiveModules) { const ident = module.identifier(); if (ident) { activeModules.delete(ident); if (lastActiveModule === ident) { lastActiveModule = ""; for (const m of activeModules) { lastActiveModule = m; } } } } update(); }; const entryDone = (entry, name) => { doneEntries++; update(); }; compiler.hooks.compilation.tap("ProgressPlugin", compilation => { if (compilation.compiler.isChild()) return; lastModulesCount = moduleCount; lastEntriesCount = entriesCount; moduleCount = entriesCount = 0; doneModules = doneEntries = 0; handler(0, "compiling"); compilation.hooks.buildModule.tap("ProgressPlugin", moduleAdd); compilation.hooks.failedModule.tap("ProgressPlugin", moduleDone); compilation.hooks.succeedModule.tap("ProgressPlugin", moduleDone); compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); const hooks = { finishModules: "finish module graph", seal: "sealing", beforeChunks: "chunk graph", afterChunks: "after chunk graph", optimizeDependenciesBasic: "basic dependencies optimization", optimizeDependencies: "dependencies optimization", optimizeDependenciesAdvanced: "advanced dependencies optimization", afterOptimizeDependencies: "after dependencies optimization", optimize: "optimizing", optimizeModulesBasic: "basic module optimization", optimizeModules: "module optimization", optimizeModulesAdvanced: "advanced module optimization", afterOptimizeModules: "after module optimization", optimizeChunksBasic: "basic chunk optimization", optimizeChunks: "chunk optimization", optimizeChunksAdvanced: "advanced chunk optimization", afterOptimizeChunks: "after chunk optimization", optimizeTree: "module and chunk tree optimization", afterOptimizeTree: "after module and chunk tree optimization", optimizeChunkModulesBasic: "basic chunk modules optimization", optimizeChunkModules: "chunk modules optimization", optimizeChunkModulesAdvanced: "advanced chunk modules optimization", afterOptimizeChunkModules: "after chunk modules optimization", reviveModules: "module reviving", optimizeModuleOrder: "module order optimization", advancedOptimizeModuleOrder: "advanced module order optimization", beforeModuleIds: "before module ids", moduleIds: "module ids", optimizeModuleIds: "module id optimization", afterOptimizeModuleIds: "module id optimization", reviveChunks: "chunk reviving", optimizeChunkOrder: "chunk order optimization", beforeChunkIds: "before chunk ids", optimizeChunkIds: "chunk id optimization", afterOptimizeChunkIds: "after chunk id optimization", recordModules: "record modules", recordChunks: "record chunks", beforeHash: "hashing", contentHash: "content hashing", afterHash: "after hashing", recordHash: "record hash", beforeModuleAssets: "module assets processing", beforeChunkAssets: "chunk assets processing", additionalChunkAssets: "additional chunk assets processing", record: "recording", additionalAssets: "additional asset processing", optimizeChunkAssets: "chunk asset optimization", afterOptimizeChunkAssets: "after chunk asset optimization", optimizeAssets: "asset optimization", afterOptimizeAssets: "after asset optimization", afterSeal: "after seal" }; const numberOfHooks = Object.keys(hooks).length; Object.keys(hooks).forEach((name, idx) => { const title = hooks[name]; const percentage = (idx / numberOfHooks) * 0.25 + 0.7; compilation.hooks[name].intercept({ name: "ProgressPlugin", context: true, call: () => { handler(percentage, title); }, tap: (context, tap) => { if (context) { // p is percentage from 0 to 1 // args is any number of messages in a hierarchical matter context.reportProgress = (p, ...args) => { handler(percentage, title, tap.name, ...args); }; } handler(percentage, title, tap.name); } }); }); }); compiler.hooks.emit.intercept({ name: "ProgressPlugin", context: true, call: () => { handler(0.95, "emitting"); }, tap: (context, tap) => { if (context) { context.reportProgress = (p, ...args) => { handler(0.95, "emitting", tap.name, ...args); }; } handler(0.95, "emitting", tap.name); } }); compiler.hooks.afterEmit.intercept({ name: "ProgressPlugin", context: true, call: () => { handler(0.98, "after emitting"); }, tap: (context, tap) => { if (context) { context.reportProgress = (p, ...args) => { handler(0.98, "after emitting", tap.name, ...args); }; } handler(0.98, "after emitting", tap.name); } }); compiler.hooks.done.tap("ProgressPlugin", () => { handler(1, ""); }); } } } ProgressPlugin.defaultOptions = { profile: false, modulesCount: 500, modules: true, activeModules: true, // TODO webpack 5 default this to true entries: false }; module.exports = ProgressPlugin; webpack-4.30.0/lib/ProvidePlugin.js000066400000000000000000000045301345416772700171270ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ParserHelpers = require("./ParserHelpers"); const ConstDependency = require("./dependencies/ConstDependency"); const NullFactory = require("./NullFactory"); class ProvidePlugin { constructor(definitions) { this.definitions = definitions; } apply(compiler) { const definitions = this.definitions; compiler.hooks.compilation.tap( "ProvidePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); const handler = (parser, parserOptions) => { Object.keys(definitions).forEach(name => { var request = [].concat(definitions[name]); var splittedName = name.split("."); if (splittedName.length > 0) { splittedName.slice(1).forEach((_, i) => { const name = splittedName.slice(0, i + 1).join("."); parser.hooks.canRename .for(name) .tap("ProvidePlugin", ParserHelpers.approve); }); } parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { let nameIdentifier = name; const scopedName = name.includes("."); let expression = `require(${JSON.stringify(request[0])})`; if (scopedName) { nameIdentifier = `__webpack_provided_${name.replace( /\./g, "_dot_" )}`; } if (request.length > 1) { expression += request .slice(1) .map(r => `[${JSON.stringify(r)}]`) .join(""); } if ( !ParserHelpers.addParsedVariableToModule( parser, nameIdentifier, expression ) ) { return false; } if (scopedName) { ParserHelpers.toConstantDependency(parser, nameIdentifier)( expr ); } return true; }); }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("ProvidePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("ProvidePlugin", handler); // Disable ProvidePlugin for javascript/esm, see https://github.com/webpack/webpack/issues/7032 } ); } } module.exports = ProvidePlugin; webpack-4.30.0/lib/RawModule.js000066400000000000000000000022441345416772700162370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("./Module"); const { OriginalSource, RawSource } = require("webpack-sources"); module.exports = class RawModule extends Module { constructor(source, identifier, readableIdentifier) { super("javascript/dynamic", null); this.sourceStr = source; this.identifierStr = identifier || this.sourceStr; this.readableIdentifierStr = readableIdentifier || this.identifierStr; this.built = false; } identifier() { return this.identifierStr; } size() { return this.sourceStr.length; } readableIdentifier(requestShortener) { return requestShortener.shorten(this.readableIdentifierStr); } needRebuild() { return false; } build(options, compilations, resolver, fs, callback) { this.built = true; this.buildMeta = {}; this.buildInfo = { cacheable: true }; callback(); } source() { if (this.useSourceMap) { return new OriginalSource(this.sourceStr, this.identifier()); } else { return new RawSource(this.sourceStr); } } updateHash(hash) { hash.update(this.sourceStr); super.updateHash(hash); } }; webpack-4.30.0/lib/RecordIdsPlugin.js000066400000000000000000000145611345416772700174020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const identifierUtils = require("./util/identifier"); /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Module")} Module */ /** * @typedef {Object} RecordsChunks * @property {Record=} byName * @property {Record=} bySource * @property {number[]=} usedIds */ /** * @typedef {Object} RecordsModules * @property {Record=} byIdentifier * @property {Record=} bySource * @property {Record=} usedIds */ /** * @typedef {Object} Records * @property {RecordsChunks=} chunks * @property {RecordsModules=} modules */ class RecordIdsPlugin { /** * @param {Object} options Options object * @param {boolean=} options.portableIds true, when ids need to be portable */ constructor(options) { this.options = options || {}; } /** * @param {Compiler} compiler the Compiler * @returns {void} */ apply(compiler) { const portableIds = this.options.portableIds; compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { compilation.hooks.recordModules.tap( "RecordIdsPlugin", /** * @param {Module[]} modules the modules array * @param {Records} records the records object * @returns {void} */ (modules, records) => { if (!records.modules) records.modules = {}; if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; if (!records.modules.usedIds) records.modules.usedIds = {}; for (const module of modules) { if (typeof module.id !== "number") continue; const identifier = portableIds ? identifierUtils.makePathsRelative( compiler.context, module.identifier(), compilation.cache ) : module.identifier(); records.modules.byIdentifier[identifier] = module.id; records.modules.usedIds[module.id] = module.id; } } ); compilation.hooks.reviveModules.tap( "RecordIdsPlugin", /** * @param {Module[]} modules the modules array * @param {Records} records the records object * @returns {void} */ (modules, records) => { if (!records.modules) return; if (records.modules.byIdentifier) { /** @type {Set} */ const usedIds = new Set(); for (const module of modules) { if (module.id !== null) continue; const identifier = portableIds ? identifierUtils.makePathsRelative( compiler.context, module.identifier(), compilation.cache ) : module.identifier(); const id = records.modules.byIdentifier[identifier]; if (id === undefined) continue; if (usedIds.has(id)) continue; usedIds.add(id); module.id = id; } } if (Array.isArray(records.modules.usedIds)) { compilation.usedModuleIds = new Set(records.modules.usedIds); } } ); /** * @param {Module} module the module * @returns {string} the (portable) identifier */ const getModuleIdentifier = module => { if (portableIds) { return identifierUtils.makePathsRelative( compiler.context, module.identifier(), compilation.cache ); } return module.identifier(); }; /** * @param {Chunk} chunk the chunk * @returns {string[]} sources of the chunk */ const getChunkSources = chunk => { /** @type {string[]} */ const sources = []; for (const chunkGroup of chunk.groupsIterable) { const index = chunkGroup.chunks.indexOf(chunk); for (const origin of chunkGroup.origins) { if (origin.module) { if (origin.request) { sources.push( `${index} ${getModuleIdentifier(origin.module)} ${ origin.request }` ); } else if (typeof origin.loc === "string") { sources.push( `${index} ${getModuleIdentifier(origin.module)} ${origin.loc}` ); } else if ( origin.loc && typeof origin.loc === "object" && origin.loc.start ) { sources.push( `${index} ${getModuleIdentifier( origin.module )} ${JSON.stringify(origin.loc.start)}` ); } } } } return sources; }; compilation.hooks.recordChunks.tap( "RecordIdsPlugin", /** * @param {Chunk[]} chunks the chunks array * @param {Records} records the records object * @returns {void} */ (chunks, records) => { if (!records.chunks) records.chunks = {}; if (!records.chunks.byName) records.chunks.byName = {}; if (!records.chunks.bySource) records.chunks.bySource = {}; /** @type {Set} */ const usedIds = new Set(); for (const chunk of chunks) { if (typeof chunk.id !== "number") continue; const name = chunk.name; if (name) records.chunks.byName[name] = chunk.id; const sources = getChunkSources(chunk); for (const source of sources) { records.chunks.bySource[source] = chunk.id; } usedIds.add(chunk.id); } records.chunks.usedIds = Array.from(usedIds).sort(); } ); compilation.hooks.reviveChunks.tap( "RecordIdsPlugin", /** * @param {Chunk[]} chunks the chunks array * @param {Records} records the records object * @returns {void} */ (chunks, records) => { if (!records.chunks) return; /** @type {Set} */ const usedIds = new Set(); if (records.chunks.byName) { for (const chunk of chunks) { if (chunk.id !== null) continue; if (!chunk.name) continue; const id = records.chunks.byName[chunk.name]; if (id === undefined) continue; if (usedIds.has(id)) continue; usedIds.add(id); chunk.id = id; } } if (records.chunks.bySource) { for (const chunk of chunks) { const sources = getChunkSources(chunk); for (const source of sources) { const id = records.chunks.bySource[source]; if (id === undefined) continue; if (usedIds.has(id)) continue; usedIds.add(id); chunk.id = id; break; } } } if (Array.isArray(records.chunks.usedIds)) { compilation.usedChunkIds = new Set(records.chunks.usedIds); } } ); }); } } module.exports = RecordIdsPlugin; webpack-4.30.0/lib/RemovedPluginError.js000066400000000000000000000003451345416772700201320ustar00rootroot00000000000000"use strict"; const WebpackError = require("./WebpackError"); module.exports = class RemovedPluginError extends WebpackError { constructor(message) { super(message); Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/RequestShortener.js000066400000000000000000000050621345416772700176630ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g; const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g; const SEPARATOR_REGEXP = /[/\\]$/; const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g; const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g; const MATCH_RESOURCE_REGEXP = /!=!/; const normalizeBackSlashDirection = request => { return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); }; const createRegExpForPath = path => { const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&"); return new RegExp(`(^|!)${regexpTypePartial}`, "g"); }; class RequestShortener { constructor(directory) { directory = normalizeBackSlashDirection(directory); if (SEPARATOR_REGEXP.test(directory)) { directory = directory.substr(0, directory.length - 1); } if (directory) { this.currentDirectoryRegExp = createRegExpForPath(directory); } const dirname = path.dirname(directory); const endsWithSeparator = SEPARATOR_REGEXP.test(dirname); const parentDirectory = endsWithSeparator ? dirname.substr(0, dirname.length - 1) : dirname; if (parentDirectory && parentDirectory !== directory) { this.parentDirectoryRegExp = createRegExpForPath(parentDirectory); } if (__dirname.length >= 2) { const buildins = normalizeBackSlashDirection(path.join(__dirname, "..")); const buildinsAsModule = this.currentDirectoryRegExp && this.currentDirectoryRegExp.test(buildins); this.buildinsAsModule = buildinsAsModule; this.buildinsRegExp = createRegExpForPath(buildins); } this.cache = new Map(); } shorten(request) { if (!request) return request; const cacheEntry = this.cache.get(request); if (cacheEntry !== undefined) { return cacheEntry; } let result = normalizeBackSlashDirection(request); if (this.buildinsAsModule && this.buildinsRegExp) { result = result.replace(this.buildinsRegExp, "!(webpack)"); } if (this.currentDirectoryRegExp) { result = result.replace(this.currentDirectoryRegExp, "!."); } if (this.parentDirectoryRegExp) { result = result.replace(this.parentDirectoryRegExp, "!.."); } if (!this.buildinsAsModule && this.buildinsRegExp) { result = result.replace(this.buildinsRegExp, "!(webpack)"); } result = result.replace(INDEX_JS_REGEXP, "$1"); result = result.replace(FRONT_OR_BACK_BANG_REGEXP, ""); result = result.replace(MATCH_RESOURCE_REGEXP, " = "); this.cache.set(request, result); return result; } } module.exports = RequestShortener; webpack-4.30.0/lib/RequireJsStuffPlugin.js000066400000000000000000000034111345416772700204350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ParserHelpers = require("./ParserHelpers"); const ConstDependency = require("./dependencies/ConstDependency"); const NullFactory = require("./NullFactory"); module.exports = class RequireJsStuffPlugin { apply(compiler) { compiler.hooks.compilation.tap( "RequireJsStuffPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set( ConstDependency, new ConstDependency.Template() ); const handler = (parser, parserOptions) => { if (parserOptions.requireJs !== undefined && !parserOptions.requireJs) return; parser.hooks.call .for("require.config") .tap( "RequireJsStuffPlugin", ParserHelpers.toConstantDependency(parser, "undefined") ); parser.hooks.call .for("requirejs.config") .tap( "RequireJsStuffPlugin", ParserHelpers.toConstantDependency(parser, "undefined") ); parser.hooks.expression .for("require.version") .tap( "RequireJsStuffPlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("0.0.0") ) ); parser.hooks.expression .for("requirejs.onError") .tap( "RequireJsStuffPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire( parser, "__webpack_require__.oe" ) ); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("RequireJsStuffPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("RequireJsStuffPlugin", handler); } ); } }; webpack-4.30.0/lib/ResolverFactory.js000066400000000000000000000044411345416772700174720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { Tapable, HookMap, SyncHook, SyncWaterfallHook } = require("tapable"); const Factory = require("enhanced-resolve").ResolverFactory; /** @typedef {import("enhanced-resolve").Resolver} Resolver */ module.exports = class ResolverFactory extends Tapable { constructor() { super(); this.hooks = { resolveOptions: new HookMap( () => new SyncWaterfallHook(["resolveOptions"]) ), resolver: new HookMap(() => new SyncHook(["resolver", "resolveOptions"])) }; this._pluginCompat.tap("ResolverFactory", options => { let match; match = /^resolve-options (.+)$/.exec(options.name); if (match) { this.hooks.resolveOptions.tap( match[1], options.fn.name || "unnamed compat plugin", options.fn ); return true; } match = /^resolver (.+)$/.exec(options.name); if (match) { this.hooks.resolver.tap( match[1], options.fn.name || "unnamed compat plugin", options.fn ); return true; } }); this.cache1 = new WeakMap(); this.cache2 = new Map(); } get(type, resolveOptions) { const cachedResolver = this.cache1.get(resolveOptions); if (cachedResolver) return cachedResolver(); const ident = `${type}|${JSON.stringify(resolveOptions)}`; const resolver = this.cache2.get(ident); if (resolver) return resolver; const newResolver = this._create(type, resolveOptions); this.cache2.set(ident, newResolver); return newResolver; } _create(type, resolveOptions) { const originalResolveOptions = Object.assign({}, resolveOptions); resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions); const resolver = Factory.createResolver(resolveOptions); if (!resolver) { throw new Error("No resolver created"); } /** @type {Map} */ const childCache = new Map(); resolver.withOptions = options => { const cacheEntry = childCache.get(options); if (cacheEntry !== undefined) return cacheEntry; const mergedOptions = Object.assign({}, originalResolveOptions, options); const resolver = this.get(type, mergedOptions); childCache.set(options, resolver); return resolver; }; this.hooks.resolver.for(type).call(resolver, resolveOptions); return resolver; } }; webpack-4.30.0/lib/RuleSet.js000066400000000000000000000275171345416772700157350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /* : : [] : { resource: { test: , include: , exclude: , }, resource: , -> resource.test test: , -> resource.test include: , -> resource.include exclude: , -> resource.exclude resourceQuery: , compiler: , issuer: , use: "loader", -> use[0].loader loader: <>, -> use[0].loader loaders: <>, -> use options: {}, -> use[0].options, query: {}, -> options parser: {}, use: [ "loader" -> use[x].loader ], use: [ { loader: "loader", options: {} } ], rules: [ ], oneOf: [ ] } : /regExp/ : function(arg) {} : "starting" : [] // or : { and: [] } : { or: [] } : { not: [] } : { test: , include: , exclude: } normalized: { resource: function(), resourceQuery: function(), compiler: function(), issuer: function(), use: [ { loader: string, options: string, : } ], rules: [], oneOf: [], : , } */ "use strict"; const notMatcher = matcher => { return str => { return !matcher(str); }; }; const orMatcher = items => { return str => { for (let i = 0; i < items.length; i++) { if (items[i](str)) return true; } return false; }; }; const andMatcher = items => { return str => { for (let i = 0; i < items.length; i++) { if (!items[i](str)) return false; } return true; }; }; module.exports = class RuleSet { constructor(rules) { this.references = Object.create(null); this.rules = RuleSet.normalizeRules(rules, this.references, "ref-"); } static normalizeRules(rules, refs, ident) { if (Array.isArray(rules)) { return rules.map((rule, idx) => { return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`); }); } else if (rules) { return [RuleSet.normalizeRule(rules, refs, ident)]; } else { return []; } } static normalizeRule(rule, refs, ident) { if (typeof rule === "string") { return { use: [ { loader: rule } ] }; } if (!rule) { throw new Error("Unexcepted null when object was expected as rule"); } if (typeof rule !== "object") { throw new Error( "Unexcepted " + typeof rule + " when object was expected as rule (" + rule + ")" ); } const newRule = {}; let useSource; let resourceSource; let condition; const checkUseSource = newSource => { if (useSource && useSource !== newSource) { throw new Error( RuleSet.buildErrorMessage( rule, new Error( "Rule can only have one result source (provided " + newSource + " and " + useSource + ")" ) ) ); } useSource = newSource; }; const checkResourceSource = newSource => { if (resourceSource && resourceSource !== newSource) { throw new Error( RuleSet.buildErrorMessage( rule, new Error( "Rule can only have one resource source (provided " + newSource + " and " + resourceSource + ")" ) ) ); } resourceSource = newSource; }; if (rule.test || rule.include || rule.exclude) { checkResourceSource("test + include + exclude"); condition = { test: rule.test, include: rule.include, exclude: rule.exclude }; try { newRule.resource = RuleSet.normalizeCondition(condition); } catch (error) { throw new Error(RuleSet.buildErrorMessage(condition, error)); } } if (rule.resource) { checkResourceSource("resource"); try { newRule.resource = RuleSet.normalizeCondition(rule.resource); } catch (error) { throw new Error(RuleSet.buildErrorMessage(rule.resource, error)); } } if (rule.realResource) { try { newRule.realResource = RuleSet.normalizeCondition(rule.realResource); } catch (error) { throw new Error(RuleSet.buildErrorMessage(rule.realResource, error)); } } if (rule.resourceQuery) { try { newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery); } catch (error) { throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error)); } } if (rule.compiler) { try { newRule.compiler = RuleSet.normalizeCondition(rule.compiler); } catch (error) { throw new Error(RuleSet.buildErrorMessage(rule.compiler, error)); } } if (rule.issuer) { try { newRule.issuer = RuleSet.normalizeCondition(rule.issuer); } catch (error) { throw new Error(RuleSet.buildErrorMessage(rule.issuer, error)); } } if (rule.loader && rule.loaders) { throw new Error( RuleSet.buildErrorMessage( rule, new Error( "Provided loader and loaders for rule (use only one of them)" ) ) ); } const loader = rule.loaders || rule.loader; if (typeof loader === "string" && !rule.options && !rule.query) { checkUseSource("loader"); newRule.use = RuleSet.normalizeUse(loader.split("!"), ident); } else if (typeof loader === "string" && (rule.options || rule.query)) { checkUseSource("loader + options/query"); newRule.use = RuleSet.normalizeUse( { loader: loader, options: rule.options, query: rule.query }, ident ); } else if (loader && (rule.options || rule.query)) { throw new Error( RuleSet.buildErrorMessage( rule, new Error( "options/query cannot be used with loaders (use options for each array item)" ) ) ); } else if (loader) { checkUseSource("loaders"); newRule.use = RuleSet.normalizeUse(loader, ident); } else if (rule.options || rule.query) { throw new Error( RuleSet.buildErrorMessage( rule, new Error( "options/query provided without loader (use loader + options)" ) ) ); } if (rule.use) { checkUseSource("use"); newRule.use = RuleSet.normalizeUse(rule.use, ident); } if (rule.rules) { newRule.rules = RuleSet.normalizeRules( rule.rules, refs, `${ident}-rules` ); } if (rule.oneOf) { newRule.oneOf = RuleSet.normalizeRules( rule.oneOf, refs, `${ident}-oneOf` ); } const keys = Object.keys(rule).filter(key => { return ![ "resource", "resourceQuery", "compiler", "test", "include", "exclude", "issuer", "loader", "options", "query", "loaders", "use", "rules", "oneOf" ].includes(key); }); for (const key of keys) { newRule[key] = rule[key]; } if (Array.isArray(newRule.use)) { for (const item of newRule.use) { if (item.ident) { refs[item.ident] = item.options; } } } return newRule; } static buildErrorMessage(condition, error) { const conditionAsText = JSON.stringify( condition, (key, value) => { return value === undefined ? "undefined" : value; }, 2 ); return error.message + " in " + conditionAsText; } static normalizeUse(use, ident) { if (typeof use === "function") { return data => RuleSet.normalizeUse(use(data), ident); } if (Array.isArray(use)) { return use .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`)) .reduce((arr, items) => arr.concat(items), []); } return [RuleSet.normalizeUseItem(use, ident)]; } static normalizeUseItemString(useItemString) { const idx = useItemString.indexOf("?"); if (idx >= 0) { return { loader: useItemString.substr(0, idx), options: useItemString.substr(idx + 1) }; } return { loader: useItemString, options: undefined }; } static normalizeUseItem(item, ident) { if (typeof item === "string") { return RuleSet.normalizeUseItemString(item); } const newItem = {}; if (item.options && item.query) { throw new Error("Provided options and query in use"); } if (!item.loader) { throw new Error("No loader specified"); } newItem.options = item.options || item.query; if (typeof newItem.options === "object" && newItem.options) { if (newItem.options.ident) { newItem.ident = newItem.options.ident; } else { newItem.ident = ident; } } const keys = Object.keys(item).filter(function(key) { return !["options", "query"].includes(key); }); for (const key of keys) { newItem[key] = item[key]; } return newItem; } static normalizeCondition(condition) { if (!condition) throw new Error("Expected condition but got falsy value"); if (typeof condition === "string") { return str => str.indexOf(condition) === 0; } if (typeof condition === "function") { return condition; } if (condition instanceof RegExp) { return condition.test.bind(condition); } if (Array.isArray(condition)) { const items = condition.map(c => RuleSet.normalizeCondition(c)); return orMatcher(items); } if (typeof condition !== "object") { throw Error( "Unexcepted " + typeof condition + " when condition was expected (" + condition + ")" ); } const matchers = []; Object.keys(condition).forEach(key => { const value = condition[key]; switch (key) { case "or": case "include": case "test": if (value) matchers.push(RuleSet.normalizeCondition(value)); break; case "and": if (value) { const items = value.map(c => RuleSet.normalizeCondition(c)); matchers.push(andMatcher(items)); } break; case "not": case "exclude": if (value) { const matcher = RuleSet.normalizeCondition(value); matchers.push(notMatcher(matcher)); } break; default: throw new Error("Unexcepted property " + key + " in condition"); } }); if (matchers.length === 0) { throw new Error("Excepted condition but got " + condition); } if (matchers.length === 1) { return matchers[0]; } return andMatcher(matchers); } exec(data) { const result = []; this._run( data, { rules: this.rules }, result ); return result; } _run(data, rule, result) { // test conditions if (rule.resource && !data.resource) return false; if (rule.realResource && !data.realResource) return false; if (rule.resourceQuery && !data.resourceQuery) return false; if (rule.compiler && !data.compiler) return false; if (rule.issuer && !data.issuer) return false; if (rule.resource && !rule.resource(data.resource)) return false; if (rule.realResource && !rule.realResource(data.realResource)) return false; if (data.issuer && rule.issuer && !rule.issuer(data.issuer)) return false; if ( data.resourceQuery && rule.resourceQuery && !rule.resourceQuery(data.resourceQuery) ) { return false; } if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) { return false; } // apply const keys = Object.keys(rule).filter(key => { return ![ "resource", "realResource", "resourceQuery", "compiler", "issuer", "rules", "oneOf", "use", "enforce" ].includes(key); }); for (const key of keys) { result.push({ type: key, value: rule[key] }); } if (rule.use) { const process = use => { if (typeof use === "function") { process(use(data)); } else if (Array.isArray(use)) { use.forEach(process); } else { result.push({ type: "use", value: use, enforce: rule.enforce }); } }; process(rule.use); } if (rule.rules) { for (let i = 0; i < rule.rules.length; i++) { this._run(data, rule.rules[i], result); } } if (rule.oneOf) { for (let i = 0; i < rule.oneOf.length; i++) { if (this._run(data, rule.oneOf[i], result)) break; } } return true; } findOptionsByIdent(ident) { const options = this.references[ident]; if (!options) { throw new Error("Can't find options with ident '" + ident + "'"); } return options; } }; webpack-4.30.0/lib/RuntimeTemplate.js000066400000000000000000000223761345416772700174670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("./Template"); /** @typedef {import("./Module")} Module */ module.exports = class RuntimeTemplate { constructor(outputOptions, requestShortener) { this.outputOptions = outputOptions || {}; this.requestShortener = requestShortener; } /** * Add a comment * @param {object} options Information content of the comment * @param {string=} options.request request string used originally * @param {string=} options.chunkName name of the chunk referenced * @param {string=} options.chunkReason reason information of the chunk * @param {string=} options.message additional message * @param {string=} options.exportName name of the export * @returns {string} comment */ comment({ request, chunkName, chunkReason, message, exportName }) { let content; if (this.outputOptions.pathinfo) { content = [message, request, chunkName, chunkReason] .filter(Boolean) .map(item => this.requestShortener.shorten(item)) .join(" | "); } else { content = [message, chunkName, chunkReason] .filter(Boolean) .map(item => this.requestShortener.shorten(item)) .join(" | "); } if (!content) return ""; if (this.outputOptions.pathinfo) { return Template.toComment(content) + " "; } else { return Template.toNormalComment(content) + " "; } } throwMissingModuleErrorFunction({ request }) { const err = `Cannot find module '${request}'`; return `function webpackMissingModule() { var e = new Error(${JSON.stringify( err )}); e.code = 'MODULE_NOT_FOUND'; throw e; }`; } missingModule({ request }) { return `!(${this.throwMissingModuleErrorFunction({ request })}())`; } missingModuleStatement({ request }) { return `${this.missingModule({ request })};\n`; } missingModulePromise({ request }) { return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ request })})`; } moduleId({ module, request }) { if (!module) { return this.missingModule({ request }); } if (module.id === null) { throw new Error( `RuntimeTemplate.moduleId(): Module ${module.identifier()} has no id. This should not happen.` ); } return `${this.comment({ request })}${JSON.stringify(module.id)}`; } moduleRaw({ module, request }) { if (!module) { return this.missingModule({ request }); } return `__webpack_require__(${this.moduleId({ module, request })})`; } moduleExports({ module, request }) { return this.moduleRaw({ module, request }); } moduleNamespace({ module, request, strict }) { if (!module) { return this.missingModule({ request }); } const moduleId = this.moduleId({ module, request }); const exportsType = module.buildMeta && module.buildMeta.exportsType; if (exportsType === "namespace") { const rawModule = this.moduleRaw({ module, request }); return rawModule; } else if (exportsType === "named") { return `__webpack_require__.t(${moduleId}, 3)`; } else if (strict) { return `__webpack_require__.t(${moduleId}, 1)`; } else { return `__webpack_require__.t(${moduleId}, 7)`; } } moduleNamespacePromise({ block, module, request, message, strict, weak }) { if (!module) { return this.missingModulePromise({ request }); } if (module.id === null) { throw new Error( `RuntimeTemplate.moduleNamespacePromise(): Module ${module.identifier()} has no id. This should not happen.` ); } const promise = this.blockPromise({ block, message }); let getModuleFunction; let idExpr = JSON.stringify(module.id); const comment = this.comment({ request }); let header = ""; if (weak) { if (idExpr.length > 8) { // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' header += `var id = ${idExpr}; `; idExpr = "id"; } header += `if(!__webpack_require__.m[${idExpr}]) { var e = new Error("Module '" + ${idExpr} + "' is not available (weak dependency)"); e.code = 'MODULE_NOT_FOUND'; throw e; } `; } const moduleId = this.moduleId({ module, request }); const exportsType = module.buildMeta && module.buildMeta.exportsType; if (exportsType === "namespace") { if (header) { const rawModule = this.moduleRaw({ module, request }); getModuleFunction = `function() { ${header}return ${rawModule}; }`; } else { getModuleFunction = `__webpack_require__.bind(null, ${comment}${idExpr})`; } } else if (exportsType === "named") { if (header) { getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 3); }`; } else { getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 3)`; } } else if (strict) { if (header) { getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 1); }`; } else { getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 1)`; } } else { if (header) { getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 7); }`; } else { getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 7)`; } } return `${promise || "Promise.resolve()"}.then(${getModuleFunction})`; } /** * * @param {Object} options options object * @param {boolean=} options.update whether a new variable should be created or the existing one updated * @param {Module} options.module the module * @param {string} options.request the request that should be printed as comment * @param {string} options.importVar name of the import variable * @param {Module} options.originModule module in which the statement is emitted * @returns {string} the import statement */ importStatement({ update, module, request, importVar, originModule }) { if (!module) { return this.missingModuleStatement({ request }); } const moduleId = this.moduleId({ module, request }); const optDeclaration = update ? "" : "var "; const exportsType = module.buildMeta && module.buildMeta.exportsType; let content = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; if (!exportsType && !originModule.buildMeta.strictHarmonyModule) { content += `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/__webpack_require__.n(${importVar});\n`; } if (exportsType === "named") { if (Array.isArray(module.buildMeta.providedExports)) { content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId}, 1);\n`; } else { content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId});\n`; } } return content; } exportFromImport({ module, request, exportName, originModule, asiSafe, isCall, callContext, importVar }) { if (!module) { return this.missingModule({ request }); } const exportsType = module.buildMeta && module.buildMeta.exportsType; if (!exportsType) { if (exportName === "default") { if (!originModule.buildMeta.strictHarmonyModule) { if (isCall) { return `${importVar}_default()`; } else if (asiSafe) { return `(${importVar}_default())`; } else { return `${importVar}_default.a`; } } else { return importVar; } } else if (originModule.buildMeta.strictHarmonyModule) { if (exportName) { return "/* non-default import from non-esm module */undefined"; } else { return `/*#__PURE__*/__webpack_require__.t(${importVar})`; } } } if (exportsType === "named") { if (exportName === "default") { return importVar; } else if (!exportName) { return `${importVar}_namespace`; } } if (exportName) { const used = module.isUsed(exportName); if (!used) { const comment = Template.toNormalComment(`unused export ${exportName}`); return `${comment} undefined`; } const comment = used !== exportName ? Template.toNormalComment(exportName) + " " : ""; const access = `${importVar}[${comment}${JSON.stringify(used)}]`; if (isCall) { if (callContext === false && asiSafe) { return `(0,${access})`; } else if (callContext === false) { return `Object(${access})`; } } return access; } else { return importVar; } } blockPromise({ block, message }) { if (!block || !block.chunkGroup || block.chunkGroup.chunks.length === 0) { const comment = this.comment({ message }); return `Promise.resolve(${comment.trim()})`; } const chunks = block.chunkGroup.chunks.filter( chunk => !chunk.hasRuntime() && chunk.id !== null ); const comment = this.comment({ message, chunkName: block.chunkName, chunkReason: block.chunkReason }); if (chunks.length === 1) { const chunkId = JSON.stringify(chunks[0].id); return `__webpack_require__.e(${comment}${chunkId})`; } else if (chunks.length > 0) { const requireChunkId = chunk => `__webpack_require__.e(${JSON.stringify(chunk.id)})`; return `Promise.all(${comment.trim()}[${chunks .map(requireChunkId) .join(", ")}])`; } else { return `Promise.resolve(${comment.trim()})`; } } onError() { return "__webpack_require__.oe"; } defineEsModuleFlagStatement({ exportsArgument }) { return `__webpack_require__.r(${exportsArgument});\n`; } }; webpack-4.30.0/lib/SetVarMainTemplatePlugin.js000066400000000000000000000033041345416772700212220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); /** @typedef {import("./Compilation")} Compilation */ class SetVarMainTemplatePlugin { /** * @param {string} varExpression the accessor where the library is exported * @param {boolean} copyObject specify copying the exports */ constructor(varExpression, copyObject) { /** @type {string} */ this.varExpression = varExpression; /** @type {boolean} */ this.copyObject = copyObject; } /** * @param {Compilation} compilation the compilation instance * @returns {void} */ apply(compilation) { const { mainTemplate, chunkTemplate } = compilation; const onRenderWithEntry = (source, chunk, hash) => { const varExpression = mainTemplate.getAssetPath(this.varExpression, { hash, chunk }); if (this.copyObject) { return new ConcatSource( `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, source, "))" ); } else { const prefix = `${varExpression} =\n`; return new ConcatSource(prefix, source); } }; for (const template of [mainTemplate, chunkTemplate]) { template.hooks.renderWithEntry.tap( "SetVarMainTemplatePlugin", onRenderWithEntry ); } mainTemplate.hooks.globalHashPaths.tap( "SetVarMainTemplatePlugin", paths => { if (this.varExpression) paths.push(this.varExpression); return paths; } ); mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => { hash.update("set var"); hash.update(`${this.varExpression}`); hash.update(`${this.copyObject}`); }); } } module.exports = SetVarMainTemplatePlugin; webpack-4.30.0/lib/SingleEntryPlugin.js000066400000000000000000000027101345416772700177600ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); /** @typedef {import("./Compiler")} Compiler */ class SingleEntryPlugin { /** * An entry plugin which will handle * creation of the SingleEntryDependency * * @param {string} context context path * @param {string} entry entry path * @param {string} name entry key name */ constructor(context, entry, name) { this.context = context; this.entry = entry; this.name = name; } /** * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap( "SingleEntryPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( SingleEntryDependency, normalModuleFactory ); } ); compiler.hooks.make.tapAsync( "SingleEntryPlugin", (compilation, callback) => { const { entry, name, context } = this; const dep = SingleEntryPlugin.createDependency(entry, name); compilation.addEntry(context, dep, name, callback); } ); } /** * @param {string} entry entry request * @param {string} name entry name * @returns {SingleEntryDependency} the dependency */ static createDependency(entry, name) { const dep = new SingleEntryDependency(entry); dep.loc = { name }; return dep; } } module.exports = SingleEntryPlugin; webpack-4.30.0/lib/SizeFormatHelpers.js000066400000000000000000000010321345416772700177400ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Sean Larkin @thelarkinn */ "use strict"; const SizeFormatHelpers = exports; SizeFormatHelpers.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 / Math.pow(1024, index)).toPrecision(3)} ${ abbreviations[index] }`; }; webpack-4.30.0/lib/SourceMapDevToolModuleOptionsPlugin.js000066400000000000000000000022531345416772700234340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); class SourceMapDevToolModuleOptionsPlugin { constructor(options) { this.options = options; } apply(compilation) { const options = this.options; if (options.module !== false) { compilation.hooks.buildModule.tap( "SourceMapDevToolModuleOptionsPlugin", module => { module.useSourceMap = true; } ); } if (options.lineToLine === true) { compilation.hooks.buildModule.tap( "SourceMapDevToolModuleOptionsPlugin", module => { module.lineToLine = true; } ); } else if (options.lineToLine) { compilation.hooks.buildModule.tap( "SourceMapDevToolModuleOptionsPlugin", module => { if (!module.resource) return; let resourcePath = module.resource; const idx = resourcePath.indexOf("?"); if (idx >= 0) resourcePath = resourcePath.substr(0, idx); module.lineToLine = ModuleFilenameHelpers.matchObject( options.lineToLine, resourcePath ); } ); } } } module.exports = SourceMapDevToolModuleOptionsPlugin; webpack-4.30.0/lib/SourceMapDevToolPlugin.js000066400000000000000000000222371345416772700207160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const { ConcatSource, RawSource } = require("webpack-sources"); const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); const createHash = require("./util/createHash"); const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/SourceMapDevToolPlugin.json"); /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ const basename = name => { if (!name.includes("/")) return name; return name.substr(name.lastIndexOf("/") + 1); }; const assetsCache = new WeakMap(); const getTaskForFile = (file, chunk, options, compilation) => { const asset = compilation.assets[file]; const cache = assetsCache.get(asset); if (cache && cache.file === file) { for (const cachedFile in cache.assets) { compilation.assets[cachedFile] = cache.assets[cachedFile]; if (cachedFile !== file) chunk.files.push(cachedFile); } return; } let source, sourceMap; if (asset.sourceAndMap) { const sourceAndMap = asset.sourceAndMap(options); sourceMap = sourceAndMap.map; source = sourceAndMap.source; } else { sourceMap = asset.map(options); source = asset.source(); } if (sourceMap) { return { chunk, file, asset, source, sourceMap, modules: undefined }; } }; class SourceMapDevToolPlugin { /** * @param {SourceMapDevToolPluginOptions=} options options object */ constructor(options) { if (arguments.length > 1) { throw new Error( "SourceMapDevToolPlugin only takes one argument (pass an options object)" ); } if (!options) options = {}; validateOptions(schema, options, "SourceMap DevTool Plugin"); this.sourceMapFilename = options.filename; /** @type {string | false} */ this.sourceMappingURLComment = options.append === false ? false : options.append || "\n//# sourceMappingURL=[url]"; this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; this.fallbackModuleFilenameTemplate = options.fallbackModuleFilenameTemplate || "webpack://[namespace]/[resourcePath]?[hash]"; this.namespace = options.namespace || ""; this.options = options; } apply(compiler) { const sourceMapFilename = this.sourceMapFilename; const sourceMappingURLComment = this.sourceMappingURLComment; const moduleFilenameTemplate = this.moduleFilenameTemplate; const namespace = this.namespace; const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; const requestShortener = compiler.requestShortener; const options = this.options; options.test = options.test || /\.(m?js|css)($|\?)/i; const matchObject = ModuleFilenameHelpers.matchObject.bind( undefined, options ); compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); compilation.hooks.afterOptimizeChunkAssets.tap( { name: "SourceMapDevToolPlugin", context: true }, (context, chunks) => { const moduleToSourceNameMapping = new Map(); const reportProgress = context && context.reportProgress ? context.reportProgress : () => {}; const files = []; for (const chunk of chunks) { for (const file of chunk.files) { if (matchObject(file)) { files.push({ file, chunk }); } } } reportProgress(0.0); const tasks = []; files.forEach(({ file, chunk }, idx) => { reportProgress( (0.5 * idx) / files.length, file, "generate SourceMap" ); const task = getTaskForFile(file, chunk, options, compilation); if (task) { const modules = task.sourceMap.sources.map(source => { const module = compilation.findModule(source); return module || source; }); for (let idx = 0; idx < modules.length; idx++) { const module = modules[idx]; if (!moduleToSourceNameMapping.get(module)) { moduleToSourceNameMapping.set( module, ModuleFilenameHelpers.createFilename( module, { moduleFilenameTemplate: moduleFilenameTemplate, namespace: namespace }, requestShortener ) ); } } task.modules = modules; tasks.push(task); } }); reportProgress(0.5, "resolve sources"); const usedNamesSet = new Set(moduleToSourceNameMapping.values()); const conflictDetectionSet = new Set(); // all modules in defined order (longest identifier first) const allModules = Array.from(moduleToSourceNameMapping.keys()).sort( (a, b) => { const ai = typeof a === "string" ? a : a.identifier(); const bi = typeof b === "string" ? b : b.identifier(); return ai.length - bi.length; } ); // find modules with conflicting source names for (let idx = 0; idx < allModules.length; idx++) { const module = allModules[idx]; let sourceName = moduleToSourceNameMapping.get(module); let hasName = conflictDetectionSet.has(sourceName); if (!hasName) { conflictDetectionSet.add(sourceName); continue; } // try the fallback name first sourceName = ModuleFilenameHelpers.createFilename( module, { moduleFilenameTemplate: fallbackModuleFilenameTemplate, namespace: namespace }, requestShortener ); hasName = usedNamesSet.has(sourceName); if (!hasName) { moduleToSourceNameMapping.set(module, sourceName); usedNamesSet.add(sourceName); continue; } // elsewise just append stars until we have a valid name while (hasName) { sourceName += "*"; hasName = usedNamesSet.has(sourceName); } moduleToSourceNameMapping.set(module, sourceName); usedNamesSet.add(sourceName); } tasks.forEach((task, index) => { reportProgress( 0.5 + (0.5 * index) / tasks.length, task.file, "attach SourceMap" ); const assets = Object.create(null); const chunk = task.chunk; const file = task.file; const asset = task.asset; const sourceMap = task.sourceMap; const source = task.source; const modules = task.modules; const moduleFilenames = modules.map(m => moduleToSourceNameMapping.get(m) ); sourceMap.sources = moduleFilenames; if (options.noSources) { sourceMap.sourcesContent = undefined; } sourceMap.sourceRoot = options.sourceRoot || ""; sourceMap.file = file; assetsCache.set(asset, { file, assets }); /** @type {string | false} */ let currentSourceMappingURLComment = sourceMappingURLComment; if ( currentSourceMappingURLComment !== false && /\.css($|\?)/i.test(file) ) { currentSourceMappingURLComment = currentSourceMappingURLComment.replace( /^\n\/\/(.*)$/, "\n/*$1*/" ); } const sourceMapString = JSON.stringify(sourceMap); if (sourceMapFilename) { let filename = file; let query = ""; const idx = filename.indexOf("?"); if (idx >= 0) { query = filename.substr(idx); filename = filename.substr(0, idx); } let sourceMapFile = compilation.getPath(sourceMapFilename, { chunk, filename: options.fileContext ? path.relative(options.fileContext, filename) : filename, query, basename: basename(filename), contentHash: createHash("md4") .update(sourceMapString) .digest("hex") }); const sourceMapUrl = options.publicPath ? options.publicPath + sourceMapFile.replace(/\\/g, "/") : path .relative(path.dirname(file), sourceMapFile) .replace(/\\/g, "/"); if (currentSourceMappingURLComment !== false) { assets[file] = compilation.assets[file] = new ConcatSource( new RawSource(source), currentSourceMappingURLComment.replace( /\[url\]/g, sourceMapUrl ) ); } assets[sourceMapFile] = compilation.assets[ sourceMapFile ] = new RawSource(sourceMapString); chunk.files.push(sourceMapFile); } else { if (currentSourceMappingURLComment === false) { throw new Error( "SourceMapDevToolPlugin: append can't be false when no filename is provided" ); } assets[file] = compilation.assets[file] = new ConcatSource( new RawSource(source), currentSourceMappingURLComment .replace(/\[map\]/g, () => sourceMapString) .replace( /\[url\]/g, () => `data:application/json;charset=utf-8;base64,${Buffer.from( sourceMapString, "utf-8" ).toString("base64")}` ) ); } }); reportProgress(1.0); } ); }); } } module.exports = SourceMapDevToolPlugin; webpack-4.30.0/lib/Stats.js000066400000000000000000001144731345416772700154460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequestShortener = require("./RequestShortener"); const SizeFormatHelpers = require("./SizeFormatHelpers"); const formatLocation = require("./formatLocation"); const identifierUtils = require("./util/identifier"); const compareLocations = require("./compareLocations"); const optionsOrFallback = (...args) => { let optionValues = []; optionValues.push(...args); return optionValues.find(optionValue => optionValue !== undefined); }; const compareId = (a, b) => { if (typeof a !== typeof b) { return typeof a < typeof b ? -1 : 1; } if (a < b) return -1; if (a > b) return 1; return 0; }; class Stats { constructor(compilation) { this.compilation = compilation; this.hash = compilation.hash; this.startTime = undefined; this.endTime = undefined; } static filterWarnings(warnings, warningsFilter) { // we dont have anything to filter so all warnings can be shown if (!warningsFilter) { return warnings; } // create a chain of filters // if they return "true" a warning should be suppressed const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => { if (typeof filter === "string") { return warning => warning.includes(filter); } if (filter instanceof RegExp) { return warning => filter.test(warning); } if (typeof filter === "function") { return filter; } throw new Error( `Can only filter warnings with Strings or RegExps. (Given: ${filter})` ); }); return warnings.filter(warning => { return !normalizedWarningsFilters.some(check => check(warning)); }); } formatFilePath(filePath) { const OPTIONS_REGEXP = /^(\s|\S)*!/; return filePath.includes("!") ? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})` : `${filePath}`; } hasWarnings() { return ( this.compilation.warnings.length > 0 || this.compilation.children.some(child => child.getStats().hasWarnings()) ); } hasErrors() { return ( this.compilation.errors.length > 0 || this.compilation.children.some(child => child.getStats().hasErrors()) ); } // remove a prefixed "!" that can be specified to reverse sort order normalizeFieldKey(field) { if (field[0] === "!") { return field.substr(1); } return field; } // if a field is prefixed by a "!" reverse sort order sortOrderRegular(field) { if (field[0] === "!") { return false; } return true; } toJson(options, forToString) { if (typeof options === "boolean" || typeof options === "string") { options = Stats.presetToOptions(options); } else if (!options) { options = {}; } const optionOrLocalFallback = (v, def) => v !== undefined ? v : options.all !== undefined ? options.all : def; const testAgainstGivenOption = item => { if (typeof item === "string") { const regExp = new RegExp( `[\\\\/]${item.replace( // eslint-disable-next-line no-useless-escape /[-[\]{}()*+?.\\^$|]/g, "\\$&" )}([\\\\/]|$|!|\\?)` ); return ident => regExp.test(ident); } if (item && typeof item === "object" && typeof item.test === "function") { return ident => item.test(ident); } if (typeof item === "function") { return item; } if (typeof item === "boolean") { return () => item; } }; const compilation = this.compilation; const context = optionsOrFallback( options.context, compilation.compiler.context ); const requestShortener = compilation.compiler.context === context ? compilation.requestShortener : new RequestShortener(context); const showPerformance = optionOrLocalFallback(options.performance, true); const showHash = optionOrLocalFallback(options.hash, true); const showEnv = optionOrLocalFallback(options.env, false); const showVersion = optionOrLocalFallback(options.version, true); const showTimings = optionOrLocalFallback(options.timings, true); const showBuiltAt = optionOrLocalFallback(options.builtAt, true); const showAssets = optionOrLocalFallback(options.assets, true); const showEntrypoints = optionOrLocalFallback(options.entrypoints, true); const showChunkGroups = optionOrLocalFallback( options.chunkGroups, !forToString ); const showChunks = optionOrLocalFallback(options.chunks, !forToString); const showChunkModules = optionOrLocalFallback(options.chunkModules, true); const showChunkOrigins = optionOrLocalFallback( options.chunkOrigins, !forToString ); const showModules = optionOrLocalFallback(options.modules, true); const showNestedModules = optionOrLocalFallback( options.nestedModules, true ); const showModuleAssets = optionOrLocalFallback( options.moduleAssets, !forToString ); const showDepth = optionOrLocalFallback(options.depth, !forToString); const showCachedModules = optionOrLocalFallback(options.cached, true); const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true); const showReasons = optionOrLocalFallback(options.reasons, !forToString); const showUsedExports = optionOrLocalFallback( options.usedExports, !forToString ); const showProvidedExports = optionOrLocalFallback( options.providedExports, !forToString ); const showOptimizationBailout = optionOrLocalFallback( options.optimizationBailout, !forToString ); const showChildren = optionOrLocalFallback(options.children, true); const showSource = optionOrLocalFallback(options.source, !forToString); const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true); const showErrors = optionOrLocalFallback(options.errors, true); const showErrorDetails = optionOrLocalFallback( options.errorDetails, !forToString ); const showWarnings = optionOrLocalFallback(options.warnings, true); const warningsFilter = optionsOrFallback(options.warningsFilter, null); const showPublicPath = optionOrLocalFallback( options.publicPath, !forToString ); const excludeModules = [] .concat(optionsOrFallback(options.excludeModules, options.exclude, [])) .map(testAgainstGivenOption); const excludeAssets = [] .concat(optionsOrFallback(options.excludeAssets, [])) .map(testAgainstGivenOption); const maxModules = optionsOrFallback( options.maxModules, forToString ? 15 : Infinity ); const sortModules = optionsOrFallback(options.modulesSort, "id"); const sortChunks = optionsOrFallback(options.chunksSort, "id"); const sortAssets = optionsOrFallback(options.assetsSort, ""); const showOutputPath = optionOrLocalFallback( options.outputPath, !forToString ); if (!showCachedModules) { excludeModules.push((ident, module) => !module.built); } const createModuleFilter = () => { let i = 0; return module => { if (excludeModules.length > 0) { const ident = requestShortener.shorten(module.resource); const excluded = excludeModules.some(fn => fn(ident, module)); if (excluded) return false; } const result = i < maxModules; i++; return result; }; }; const createAssetFilter = () => { return asset => { if (excludeAssets.length > 0) { const ident = asset.name; const excluded = excludeAssets.some(fn => fn(ident, asset)); if (excluded) return false; } return showCachedAssets || asset.emitted; }; }; const sortByFieldAndOrder = (fieldKey, a, b) => { if (a[fieldKey] === null && b[fieldKey] === null) return 0; if (a[fieldKey] === null) return 1; if (b[fieldKey] === null) return -1; if (a[fieldKey] === b[fieldKey]) return 0; if (typeof a[fieldKey] !== typeof b[fieldKey]) return typeof a[fieldKey] < typeof b[fieldKey] ? -1 : 1; return a[fieldKey] < b[fieldKey] ? -1 : 1; }; const sortByField = (field, originalArray) => { const originalMap = originalArray.reduce((map, v, i) => { map.set(v, i); return map; }, new Map()); return (a, b) => { if (field) { const fieldKey = this.normalizeFieldKey(field); // if a field is prefixed with a "!" the sort is reversed! const sortIsRegular = this.sortOrderRegular(field); const cmp = sortByFieldAndOrder( fieldKey, sortIsRegular ? a : b, sortIsRegular ? b : a ); if (cmp) return cmp; } return originalMap.get(a) - originalMap.get(b); }; }; const formatError = e => { let text = ""; if (typeof e === "string") { e = { message: e }; } if (e.chunk) { text += `chunk ${e.chunk.name || e.chunk.id}${ e.chunk.hasRuntime() ? " [entry]" : e.chunk.canBeInitial() ? " [initial]" : "" }\n`; } if (e.file) { text += `${e.file}\n`; } if ( e.module && e.module.readableIdentifier && typeof e.module.readableIdentifier === "function" ) { text += this.formatFilePath( e.module.readableIdentifier(requestShortener) ); if (typeof e.loc === "object") { const locInfo = formatLocation(e.loc); if (locInfo) text += ` ${locInfo}`; } text += "\n"; } text += e.message; if (showErrorDetails && e.details) { text += `\n${e.details}`; } if (showErrorDetails && e.missing) { text += e.missing.map(item => `\n[${item}]`).join(""); } if (showModuleTrace && e.origin) { text += `\n @ ${this.formatFilePath( e.origin.readableIdentifier(requestShortener) )}`; if (typeof e.originLoc === "object") { const locInfo = formatLocation(e.originLoc); if (locInfo) text += ` ${locInfo}`; } if (e.dependencies) { for (const dep of e.dependencies) { if (!dep.loc) continue; if (typeof dep.loc === "string") continue; const locInfo = formatLocation(dep.loc); if (!locInfo) continue; text += ` ${locInfo}`; } } let current = e.origin; while (current.issuer) { current = current.issuer; text += `\n @ ${current.readableIdentifier(requestShortener)}`; } } return text; }; const obj = { errors: compilation.errors.map(formatError), warnings: Stats.filterWarnings( compilation.warnings.map(formatError), warningsFilter ) }; //We just hint other renderers since actually omitting //errors/warnings from the JSON would be kind of weird. Object.defineProperty(obj, "_showWarnings", { value: showWarnings, enumerable: false }); Object.defineProperty(obj, "_showErrors", { value: showErrors, enumerable: false }); if (showVersion) { obj.version = require("../package.json").version; } if (showHash) obj.hash = this.hash; if (showTimings && this.startTime && this.endTime) { obj.time = this.endTime - this.startTime; } if (showBuiltAt && this.endTime) { obj.builtAt = this.endTime; } if (showEnv && options._env) { obj.env = options._env; } if (compilation.needAdditionalPass) { obj.needAdditionalPass = true; } if (showPublicPath) { obj.publicPath = this.compilation.mainTemplate.getPublicPath({ hash: this.compilation.hash }); } if (showOutputPath) { obj.outputPath = this.compilation.mainTemplate.outputOptions.path; } if (showAssets) { const assetsByFile = {}; const compilationAssets = Object.keys(compilation.assets).sort(); obj.assetsByChunkName = {}; obj.assets = compilationAssets .map(asset => { const obj = { name: asset, size: compilation.assets[asset].size(), chunks: [], chunkNames: [], // TODO webpack 5: remove .emitted emitted: compilation.assets[asset].emitted || compilation.emittedAssets.has(asset) }; if (showPerformance) { obj.isOverSizeLimit = compilation.assets[asset].isOverSizeLimit; } assetsByFile[asset] = obj; return obj; }) .filter(createAssetFilter()); obj.filteredAssets = compilationAssets.length - obj.assets.length; for (const chunk of compilation.chunks) { for (const asset of chunk.files) { if (assetsByFile[asset]) { for (const id of chunk.ids) { assetsByFile[asset].chunks.push(id); } if (chunk.name) { assetsByFile[asset].chunkNames.push(chunk.name); if (obj.assetsByChunkName[chunk.name]) { obj.assetsByChunkName[chunk.name] = [] .concat(obj.assetsByChunkName[chunk.name]) .concat([asset]); } else { obj.assetsByChunkName[chunk.name] = asset; } } } } } obj.assets.sort(sortByField(sortAssets, obj.assets)); } const fnChunkGroup = groupMap => { const obj = {}; for (const keyValuePair of groupMap) { const name = keyValuePair[0]; const cg = keyValuePair[1]; const children = cg.getChildrenByOrders(); obj[name] = { chunks: cg.chunks.map(c => c.id), assets: cg.chunks.reduce( (array, c) => array.concat(c.files || []), [] ), children: Object.keys(children).reduce((obj, key) => { const groups = children[key]; obj[key] = groups.map(group => ({ name: group.name, chunks: group.chunks.map(c => c.id), assets: group.chunks.reduce( (array, c) => array.concat(c.files || []), [] ) })); return obj; }, Object.create(null)), childAssets: Object.keys(children).reduce((obj, key) => { const groups = children[key]; obj[key] = Array.from( groups.reduce((set, group) => { for (const chunk of group.chunks) { for (const asset of chunk.files) { set.add(asset); } } return set; }, new Set()) ); return obj; }, Object.create(null)) }; if (showPerformance) { obj[name].isOverSizeLimit = cg.isOverSizeLimit; } } return obj; }; if (showEntrypoints) { obj.entrypoints = fnChunkGroup(compilation.entrypoints); } if (showChunkGroups) { obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups); } const fnModule = module => { const path = []; let current = module; while (current.issuer) { path.push((current = current.issuer)); } path.reverse(); const obj = { id: module.id, identifier: module.identifier(), name: module.readableIdentifier(requestShortener), index: module.index, index2: module.index2, size: module.size(), cacheable: module.buildInfo.cacheable, built: !!module.built, optional: module.optional, prefetched: module.prefetched, chunks: Array.from(module.chunksIterable, chunk => chunk.id), issuer: module.issuer && module.issuer.identifier(), issuerId: module.issuer && module.issuer.id, issuerName: module.issuer && module.issuer.readableIdentifier(requestShortener), issuerPath: module.issuer && path.map(module => ({ id: module.id, identifier: module.identifier(), name: module.readableIdentifier(requestShortener), profile: module.profile })), profile: module.profile, failed: !!module.error, errors: module.errors ? module.errors.length : 0, warnings: module.warnings ? module.warnings.length : 0 }; if (showModuleAssets) { obj.assets = Object.keys(module.buildInfo.assets || {}); } if (showReasons) { obj.reasons = module.reasons .sort((a, b) => { if (a.module && !b.module) return -1; if (!a.module && b.module) return 1; if (a.module && b.module) { const cmp = compareId(a.module.id, b.module.id); if (cmp) return cmp; } if (a.dependency && !b.dependency) return -1; if (!a.dependency && b.dependency) return 1; if (a.dependency && b.dependency) { const cmp = compareLocations(a.dependency.loc, b.dependency.loc); if (cmp) return cmp; if (a.dependency.type < b.dependency.type) return -1; if (a.dependency.type > b.dependency.type) return 1; } return 0; }) .map(reason => { const obj = { moduleId: reason.module ? reason.module.id : null, moduleIdentifier: reason.module ? reason.module.identifier() : null, module: reason.module ? reason.module.readableIdentifier(requestShortener) : null, moduleName: reason.module ? reason.module.readableIdentifier(requestShortener) : null, type: reason.dependency ? reason.dependency.type : null, explanation: reason.explanation, userRequest: reason.dependency ? reason.dependency.userRequest : null }; if (reason.dependency) { const locInfo = formatLocation(reason.dependency.loc); if (locInfo) { obj.loc = locInfo; } } return obj; }); } if (showUsedExports) { if (module.used === true) { obj.usedExports = module.usedExports; } else if (module.used === false) { obj.usedExports = false; } } if (showProvidedExports) { obj.providedExports = Array.isArray(module.buildMeta.providedExports) ? module.buildMeta.providedExports : null; } if (showOptimizationBailout) { obj.optimizationBailout = module.optimizationBailout.map(item => { if (typeof item === "function") return item(requestShortener); return item; }); } if (showDepth) { obj.depth = module.depth; } if (showNestedModules) { if (module.modules) { const modules = module.modules; obj.modules = modules .sort(sortByField("depth", modules)) .filter(createModuleFilter()) .map(fnModule); obj.filteredModules = modules.length - obj.modules.length; obj.modules.sort(sortByField(sortModules, obj.modules)); } } if (showSource && module._source) { obj.source = module._source.source(); } return obj; }; if (showChunks) { obj.chunks = compilation.chunks.map(chunk => { const parents = new Set(); const children = new Set(); const siblings = new Set(); const childIdByOrder = chunk.getChildIdsByOrders(); for (const chunkGroup of chunk.groupsIterable) { for (const parentGroup of chunkGroup.parentsIterable) { for (const chunk of parentGroup.chunks) { parents.add(chunk.id); } } for (const childGroup of chunkGroup.childrenIterable) { for (const chunk of childGroup.chunks) { children.add(chunk.id); } } for (const sibling of chunkGroup.chunks) { if (sibling !== chunk) siblings.add(sibling.id); } } const obj = { id: chunk.id, rendered: chunk.rendered, initial: chunk.canBeInitial(), entry: chunk.hasRuntime(), recorded: chunk.recorded, reason: chunk.chunkReason, size: chunk.modulesSize(), names: chunk.name ? [chunk.name] : [], files: chunk.files.slice(), hash: chunk.renderedHash, siblings: Array.from(siblings).sort(compareId), parents: Array.from(parents).sort(compareId), children: Array.from(children).sort(compareId), childrenByOrder: childIdByOrder }; if (showChunkModules) { const modules = chunk.getModules(); obj.modules = modules .slice() .sort(sortByField("depth", modules)) .filter(createModuleFilter()) .map(fnModule); obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length; obj.modules.sort(sortByField(sortModules, obj.modules)); } if (showChunkOrigins) { obj.origins = Array.from(chunk.groupsIterable, g => g.origins) .reduce((a, b) => a.concat(b), []) .map(origin => ({ moduleId: origin.module ? origin.module.id : undefined, module: origin.module ? origin.module.identifier() : "", moduleIdentifier: origin.module ? origin.module.identifier() : "", moduleName: origin.module ? origin.module.readableIdentifier(requestShortener) : "", loc: formatLocation(origin.loc), request: origin.request, reasons: origin.reasons || [] })) .sort((a, b) => { const cmp1 = compareId(a.moduleId, b.moduleId); if (cmp1) return cmp1; const cmp2 = compareId(a.loc, b.loc); if (cmp2) return cmp2; const cmp3 = compareId(a.request, b.request); if (cmp3) return cmp3; return 0; }); } return obj; }); obj.chunks.sort(sortByField(sortChunks, obj.chunks)); } if (showModules) { obj.modules = compilation.modules .slice() .sort(sortByField("depth", compilation.modules)) .filter(createModuleFilter()) .map(fnModule); obj.filteredModules = compilation.modules.length - obj.modules.length; obj.modules.sort(sortByField(sortModules, obj.modules)); } if (showChildren) { obj.children = compilation.children.map((child, idx) => { const childOptions = Stats.getChildOptions(options, idx); const obj = new Stats(child).toJson(childOptions, forToString); delete obj.hash; delete obj.version; if (child.name) { obj.name = identifierUtils.makePathsRelative( context, child.name, compilation.cache ); } return obj; }); } return obj; } toString(options) { if (typeof options === "boolean" || typeof options === "string") { options = Stats.presetToOptions(options); } else if (!options) { options = {}; } const useColors = optionsOrFallback(options.colors, false); const obj = this.toJson(options, true); return Stats.jsonToString(obj, useColors); } static jsonToString(obj, useColors) { const buf = []; const defaultColors = { bold: "\u001b[1m", yellow: "\u001b[1m\u001b[33m", red: "\u001b[1m\u001b[31m", green: "\u001b[1m\u001b[32m", cyan: "\u001b[1m\u001b[36m", magenta: "\u001b[1m\u001b[35m" }; const colors = Object.keys(defaultColors).reduce( (obj, color) => { obj[color] = str => { if (useColors) { buf.push( useColors === true || useColors[color] === undefined ? defaultColors[color] : useColors[color] ); } buf.push(str); if (useColors) { buf.push("\u001b[39m\u001b[22m"); } }; return obj; }, { normal: str => buf.push(str) } ); const coloredTime = time => { let times = [800, 400, 200, 100]; if (obj.time) { times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16]; } if (time < times[3]) colors.normal(`${time}ms`); else if (time < times[2]) colors.bold(`${time}ms`); else if (time < times[1]) colors.green(`${time}ms`); else if (time < times[0]) colors.yellow(`${time}ms`); else colors.red(`${time}ms`); }; const newline = () => buf.push("\n"); const getText = (arr, row, col) => { return arr[row][col].value; }; const table = (array, align, splitter) => { const rows = array.length; const cols = array[0].length; const colSizes = new Array(cols); for (let col = 0; col < cols; col++) { colSizes[col] = 0; } for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { const value = `${getText(array, row, col)}`; if (value.length > colSizes[col]) { colSizes[col] = value.length; } } } for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { const format = array[row][col].color; const value = `${getText(array, row, col)}`; let l = value.length; if (align[col] === "l") { format(value); } for (; l < colSizes[col] && col !== cols - 1; l++) { colors.normal(" "); } if (align[col] === "r") { format(value); } if (col + 1 < cols && colSizes[col] !== 0) { colors.normal(splitter || " "); } } newline(); } }; const getAssetColor = (asset, defaultColor) => { if (asset.isOverSizeLimit) { return colors.yellow; } return defaultColor; }; if (obj.hash) { colors.normal("Hash: "); colors.bold(obj.hash); newline(); } if (obj.version) { colors.normal("Version: webpack "); colors.bold(obj.version); newline(); } if (typeof obj.time === "number") { colors.normal("Time: "); colors.bold(obj.time); colors.normal("ms"); newline(); } if (typeof obj.builtAt === "number") { const builtAtDate = new Date(obj.builtAt); colors.normal("Built at: "); colors.normal( builtAtDate.toLocaleDateString(undefined, { day: "2-digit", month: "2-digit", year: "numeric" }) ); colors.normal(" "); colors.bold(builtAtDate.toLocaleTimeString()); newline(); } if (obj.env) { colors.normal("Environment (--env): "); colors.bold(JSON.stringify(obj.env, null, 2)); newline(); } if (obj.publicPath) { colors.normal("PublicPath: "); colors.bold(obj.publicPath); newline(); } if (obj.assets && obj.assets.length > 0) { const t = [ [ { value: "Asset", color: colors.bold }, { value: "Size", color: colors.bold }, { value: "Chunks", color: colors.bold }, { value: "", color: colors.bold }, { value: "", color: colors.bold }, { value: "Chunk Names", color: colors.bold } ] ]; for (const asset of obj.assets) { t.push([ { value: asset.name, color: getAssetColor(asset, colors.green) }, { value: SizeFormatHelpers.formatSize(asset.size), color: getAssetColor(asset, colors.normal) }, { value: asset.chunks.join(", "), color: colors.bold }, { value: asset.emitted ? "[emitted]" : "", color: colors.green }, { value: asset.isOverSizeLimit ? "[big]" : "", color: getAssetColor(asset, colors.normal) }, { value: asset.chunkNames.join(", "), color: colors.normal } ]); } table(t, "rrrlll"); } if (obj.filteredAssets > 0) { colors.normal(" "); if (obj.assets.length > 0) colors.normal("+ "); colors.normal(obj.filteredAssets); if (obj.assets.length > 0) colors.normal(" hidden"); colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset"); newline(); } const processChunkGroups = (namedGroups, prefix) => { for (const name of Object.keys(namedGroups)) { const cg = namedGroups[name]; colors.normal(`${prefix} `); colors.bold(name); if (cg.isOverSizeLimit) { colors.normal(" "); colors.yellow("[big]"); } colors.normal(" ="); for (const asset of cg.assets) { colors.normal(" "); colors.green(asset); } for (const name of Object.keys(cg.childAssets)) { const assets = cg.childAssets[name]; if (assets && assets.length > 0) { colors.normal(" "); colors.magenta(`(${name}:`); for (const asset of assets) { colors.normal(" "); colors.green(asset); } colors.magenta(")"); } } newline(); } }; if (obj.entrypoints) { processChunkGroups(obj.entrypoints, "Entrypoint"); } if (obj.namedChunkGroups) { let outputChunkGroups = obj.namedChunkGroups; if (obj.entrypoints) { outputChunkGroups = Object.keys(outputChunkGroups) .filter(name => !obj.entrypoints[name]) .reduce((result, name) => { result[name] = obj.namedChunkGroups[name]; return result; }, {}); } processChunkGroups(outputChunkGroups, "Chunk Group"); } const modulesByIdentifier = {}; if (obj.modules) { for (const module of obj.modules) { modulesByIdentifier[`$${module.identifier}`] = module; } } else if (obj.chunks) { for (const chunk of obj.chunks) { if (chunk.modules) { for (const module of chunk.modules) { modulesByIdentifier[`$${module.identifier}`] = module; } } } } const processModuleAttributes = module => { colors.normal(" "); colors.normal(SizeFormatHelpers.formatSize(module.size)); if (module.chunks) { for (const chunk of module.chunks) { colors.normal(" {"); colors.yellow(chunk); colors.normal("}"); } } if (typeof module.depth === "number") { colors.normal(` [depth ${module.depth}]`); } if (module.cacheable === false) { colors.red(" [not cacheable]"); } if (module.optional) { colors.yellow(" [optional]"); } if (module.built) { colors.green(" [built]"); } if (module.assets && module.assets.length) { colors.magenta( ` [${module.assets.length} asset${ module.assets.length === 1 ? "" : "s" }]` ); } if (module.prefetched) { colors.magenta(" [prefetched]"); } if (module.failed) colors.red(" [failed]"); if (module.warnings) { colors.yellow( ` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]` ); } if (module.errors) { colors.red( ` [${module.errors} error${module.errors === 1 ? "" : "s"}]` ); } }; const processModuleContent = (module, prefix) => { if (Array.isArray(module.providedExports)) { colors.normal(prefix); if (module.providedExports.length === 0) { colors.cyan("[no exports]"); } else { colors.cyan(`[exports: ${module.providedExports.join(", ")}]`); } newline(); } if (module.usedExports !== undefined) { if (module.usedExports !== true) { colors.normal(prefix); if (module.usedExports === null) { colors.cyan("[used exports unknown]"); } else if (module.usedExports === false) { colors.cyan("[no exports used]"); } else if ( Array.isArray(module.usedExports) && module.usedExports.length === 0 ) { colors.cyan("[no exports used]"); } else if (Array.isArray(module.usedExports)) { const providedExportsCount = Array.isArray(module.providedExports) ? module.providedExports.length : null; if ( providedExportsCount !== null && providedExportsCount === module.usedExports.length ) { colors.cyan("[all exports used]"); } else { colors.cyan( `[only some exports used: ${module.usedExports.join(", ")}]` ); } } newline(); } } if (Array.isArray(module.optimizationBailout)) { for (const item of module.optimizationBailout) { colors.normal(prefix); colors.yellow(item); newline(); } } if (module.reasons) { for (const reason of module.reasons) { colors.normal(prefix); if (reason.type) { colors.normal(reason.type); colors.normal(" "); } if (reason.userRequest) { colors.cyan(reason.userRequest); colors.normal(" "); } if (reason.moduleId !== null) { colors.normal("["); colors.normal(reason.moduleId); colors.normal("]"); } if (reason.module && reason.module !== reason.moduleId) { colors.normal(" "); colors.magenta(reason.module); } if (reason.loc) { colors.normal(" "); colors.normal(reason.loc); } if (reason.explanation) { colors.normal(" "); colors.cyan(reason.explanation); } newline(); } } if (module.profile) { colors.normal(prefix); let sum = 0; if (module.issuerPath) { for (const m of module.issuerPath) { colors.normal("["); colors.normal(m.id); colors.normal("] "); if (m.profile) { const time = (m.profile.factory || 0) + (m.profile.building || 0); coloredTime(time); sum += time; colors.normal(" "); } colors.normal("-> "); } } for (const key of Object.keys(module.profile)) { colors.normal(`${key}:`); const time = module.profile[key]; coloredTime(time); colors.normal(" "); sum += time; } colors.normal("= "); coloredTime(sum); newline(); } if (module.modules) { processModulesList(module, prefix + "| "); } }; const processModulesList = (obj, prefix) => { if (obj.modules) { let maxModuleId = 0; for (const module of obj.modules) { if (typeof module.id === "number") { if (maxModuleId < module.id) maxModuleId = module.id; } } let contentPrefix = prefix + " "; if (maxModuleId >= 10) contentPrefix += " "; if (maxModuleId >= 100) contentPrefix += " "; if (maxModuleId >= 1000) contentPrefix += " "; for (const module of obj.modules) { colors.normal(prefix); const name = module.name || module.identifier; if (typeof module.id === "string" || typeof module.id === "number") { if (typeof module.id === "number") { if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" "); if (module.id < 100 && maxModuleId >= 100) colors.normal(" "); if (module.id < 10 && maxModuleId >= 10) colors.normal(" "); } else { if (maxModuleId >= 1000) colors.normal(" "); if (maxModuleId >= 100) colors.normal(" "); if (maxModuleId >= 10) colors.normal(" "); } if (name !== module.id) { colors.normal("["); colors.normal(module.id); colors.normal("]"); colors.normal(" "); } else { colors.normal("["); colors.bold(module.id); colors.normal("]"); } } if (name !== module.id) { colors.bold(name); } processModuleAttributes(module); newline(); processModuleContent(module, contentPrefix); } if (obj.filteredModules > 0) { colors.normal(prefix); colors.normal(" "); if (obj.modules.length > 0) colors.normal(" + "); colors.normal(obj.filteredModules); if (obj.modules.length > 0) colors.normal(" hidden"); colors.normal(obj.filteredModules !== 1 ? " modules" : " module"); newline(); } } }; if (obj.chunks) { for (const chunk of obj.chunks) { colors.normal("chunk "); if (chunk.id < 1000) colors.normal(" "); if (chunk.id < 100) colors.normal(" "); if (chunk.id < 10) colors.normal(" "); colors.normal("{"); colors.yellow(chunk.id); colors.normal("} "); colors.green(chunk.files.join(", ")); if (chunk.names && chunk.names.length > 0) { colors.normal(" ("); colors.normal(chunk.names.join(", ")); colors.normal(")"); } colors.normal(" "); colors.normal(SizeFormatHelpers.formatSize(chunk.size)); for (const id of chunk.parents) { colors.normal(" <{"); colors.yellow(id); colors.normal("}>"); } for (const id of chunk.siblings) { colors.normal(" ={"); colors.yellow(id); colors.normal("}="); } for (const id of chunk.children) { colors.normal(" >{"); colors.yellow(id); colors.normal("}<"); } if (chunk.childrenByOrder) { for (const name of Object.keys(chunk.childrenByOrder)) { const children = chunk.childrenByOrder[name]; colors.normal(" "); colors.magenta(`(${name}:`); for (const id of children) { colors.normal(" {"); colors.yellow(id); colors.normal("}"); } colors.magenta(")"); } } if (chunk.entry) { colors.yellow(" [entry]"); } else if (chunk.initial) { colors.yellow(" [initial]"); } if (chunk.rendered) { colors.green(" [rendered]"); } if (chunk.recorded) { colors.green(" [recorded]"); } if (chunk.reason) { colors.yellow(` ${chunk.reason}`); } newline(); if (chunk.origins) { for (const origin of chunk.origins) { colors.normal(" > "); if (origin.reasons && origin.reasons.length) { colors.yellow(origin.reasons.join(" ")); colors.normal(" "); } if (origin.request) { colors.normal(origin.request); colors.normal(" "); } if (origin.module) { colors.normal("["); colors.normal(origin.moduleId); colors.normal("] "); const module = modulesByIdentifier[`$${origin.module}`]; if (module) { colors.bold(module.name); colors.normal(" "); } } if (origin.loc) { colors.normal(origin.loc); } newline(); } } processModulesList(chunk, " "); } } processModulesList(obj, ""); if (obj._showWarnings && obj.warnings) { for (const warning of obj.warnings) { newline(); colors.yellow(`WARNING in ${warning}`); newline(); } } if (obj._showErrors && obj.errors) { for (const error of obj.errors) { newline(); colors.red(`ERROR in ${error}`); newline(); } } if (obj.children) { for (const child of obj.children) { const childString = Stats.jsonToString(child, useColors); if (childString) { if (child.name) { colors.normal("Child "); colors.bold(child.name); colors.normal(":"); } else { colors.normal("Child"); } newline(); buf.push(" "); buf.push(childString.replace(/\n/g, "\n ")); newline(); } } } if (obj.needAdditionalPass) { colors.yellow( "Compilation needs an additional pass and will compile again." ); } while (buf[buf.length - 1] === "\n") { buf.pop(); } return buf.join(""); } static presetToOptions(name) { // Accepted values: none, errors-only, minimal, normal, detailed, verbose // Any other falsy value will behave as 'none', truthy values as 'normal' const pn = (typeof name === "string" && name.toLowerCase()) || name || "none"; switch (pn) { case "none": return { all: false }; case "verbose": return { entrypoints: true, chunkGroups: true, modules: false, chunks: true, chunkModules: true, chunkOrigins: true, depth: true, env: true, reasons: true, usedExports: true, providedExports: true, optimizationBailout: true, errorDetails: true, publicPath: true, exclude: false, maxModules: Infinity }; case "detailed": return { entrypoints: true, chunkGroups: true, chunks: true, chunkModules: false, chunkOrigins: true, depth: true, usedExports: true, providedExports: true, optimizationBailout: true, errorDetails: true, publicPath: true, exclude: false, maxModules: Infinity }; case "minimal": return { all: false, modules: true, maxModules: 0, errors: true, warnings: true }; case "errors-only": return { all: false, errors: true, moduleTrace: true }; default: return {}; } } static getChildOptions(options, idx) { let innerOptions; if (Array.isArray(options.children)) { if (idx < options.children.length) { innerOptions = options.children[idx]; } } else if (typeof options.children === "object" && options.children) { innerOptions = options.children; } if (typeof innerOptions === "boolean" || typeof innerOptions === "string") { innerOptions = Stats.presetToOptions(innerOptions); } if (!innerOptions) { return options; } const childOptions = Object.assign({}, options); delete childOptions.children; // do not inherit children return Object.assign(childOptions, innerOptions); } } module.exports = Stats; webpack-4.30.0/lib/SystemMainTemplatePlugin.js000066400000000000000000000063571345416772700213150ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Joel Denning @joeldenning */ "use strict"; const { ConcatSource } = require("webpack-sources"); const Template = require("./Template"); /** @typedef {import("./Compilation")} Compilation */ /** * @typedef {Object} SystemMainTemplatePluginOptions * @param {string=} name the library name */ class SystemMainTemplatePlugin { /** * @param {SystemMainTemplatePluginOptions} options the plugin options */ constructor(options) { this.name = options.name; } /** * @param {Compilation} compilation the compilation instance * @returns {void} */ apply(compilation) { const { mainTemplate, chunkTemplate } = compilation; const onRenderWithEntry = (source, chunk, hash) => { const externals = chunk.getModules().filter(m => m.external); // The name this bundle should be registered as with System const name = this.name ? `${JSON.stringify(this.name)}, ` : ""; // The array of dependencies that are external to webpack and will be provided by System const systemDependencies = JSON.stringify( externals.map(m => typeof m.request === "object" ? m.request.amd : m.request ) ); // The name of the variable provided by System for exporting const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; // An array of the internal variable names for the webpack externals const externalWebpackNames = externals.map( m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` ); // Declaring variables for the internal variable names for the webpack externals const externalVarDeclarations = externalWebpackNames.length > 0 ? `var ${externalWebpackNames.join(", ")};` : ""; // The system.register format requires an array of setter functions for externals. const setters = externalWebpackNames.length === 0 ? "" : Template.asString([ "setters: [", Template.indent( externalWebpackNames .map(external => Template.asString([ "function(module) {", Template.indent(`${external} = module;`), "}" ]) ) .join(",\n") ), "]," ]); return new ConcatSource( Template.asString([ `System.register(${name}${systemDependencies}, function(${dynamicExport}) {`, Template.indent([ externalVarDeclarations, "return {", Template.indent([ setters, "execute: function() {", Template.indent(`${dynamicExport}(`) ]) ]) ]) + "\n", source, "\n" + Template.asString([ Template.indent([ Template.indent([Template.indent([");"]), "}"]), "};" ]), "})" ]) ); }; for (const template of [mainTemplate, chunkTemplate]) { template.hooks.renderWithEntry.tap( "SystemMainTemplatePlugin", onRenderWithEntry ); } mainTemplate.hooks.globalHashPaths.tap( "SystemMainTemplatePlugin", paths => { if (this.name) { paths.push(this.name); } return paths; } ); mainTemplate.hooks.hash.tap("SystemMainTemplatePlugin", hash => { hash.update("exports system"); if (this.name) { hash.update(this.name); } }); } } module.exports = SystemMainTemplatePlugin; webpack-4.30.0/lib/Template.js000066400000000000000000000177351345416772700161260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /** @typedef {import("./Module")} Module */ /** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./ModuleTemplate")} ModuleTemplate */ /** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ const { ConcatSource } = require("webpack-sources"); const HotUpdateChunk = require("./HotUpdateChunk"); const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; const INDENT_MULTILINE_REGEX = /^\t/gm; const LINE_SEPARATOR_REGEX = /\r?\n/g; const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; const COMMENT_END_REGEX = /\*\//g; const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; /** @typedef {import("webpack-sources").Source} Source */ /** * @typedef {Object} HasId * @property {number | string} id */ /** * @typedef {function(Module, number): boolean} ModuleFilterPredicate */ /** * @param {HasId} a first id object to be sorted * @param {HasId} b second id object to be sorted against * @returns {-1|0|1} the sort value */ const stringifyIdSortPredicate = (a, b) => { const aId = a.id + ""; const bId = b.id + ""; if (aId < bId) return -1; if (aId > bId) return 1; return 0; }; class Template { /** * * @param {Function} fn - a runtime function (.runtime.js) "template" * @returns {string} the updated and normalized function string */ static getFunctionContent(fn) { return fn .toString() .replace(FUNCTION_CONTENT_REGEX, "") .replace(INDENT_MULTILINE_REGEX, "") .replace(LINE_SEPARATOR_REGEX, "\n"); } /** * @param {string} str the string converted to identifier * @returns {string} created identifier */ static toIdentifier(str) { if (typeof str !== "string") return ""; return str .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); } /** * * @param {string} str string to be converted to commented in bundle code * @returns {string} returns a commented version of string */ static toComment(str) { if (!str) return ""; return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; } /** * * @param {string} str string to be converted to "normal comment" * @returns {string} returns a commented version of string */ static toNormalComment(str) { if (!str) return ""; return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; } /** * @param {string} str string path to be normalized * @returns {string} normalized bundle-safe path */ static toPath(str) { if (typeof str !== "string") return ""; return str .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); } // map number to a single character a-z, A-Z or <_ + number> if number is too big /** * * @param {number} n number to convert to ident * @returns {string} returns single character ident */ static numberToIdentifer(n) { // lower case if (n < DELTA_A_TO_Z) { return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); } // upper case if (n < DELTA_A_TO_Z * 2) { return String.fromCharCode( START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z ); } // use multiple letters return ( Template.numberToIdentifer(n % (2 * DELTA_A_TO_Z)) + Template.numberToIdentifer(Math.floor(n / (2 * DELTA_A_TO_Z))) ); } /** * * @param {string | string[]} s string to convert to identity * @returns {string} converted identity */ static indent(s) { if (Array.isArray(s)) { return s.map(Template.indent).join("\n"); } else { const str = s.trimRight(); if (!str) return ""; const ind = str[0] === "\n" ? "" : "\t"; return ind + str.replace(/\n([^\n])/g, "\n\t$1"); } } /** * * @param {string|string[]} s string to create prefix for * @param {string} prefix prefix to compose * @returns {string} returns new prefix string */ static prefix(s, prefix) { const str = Template.asString(s).trim(); if (!str) return ""; const ind = str[0] === "\n" ? "" : prefix; return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); } /** * * @param {string|string[]} str string or string collection * @returns {string} returns a single string from array */ static asString(str) { if (Array.isArray(str)) { return str.join("\n"); } return str; } /** * @typedef {Object} WithId * @property {string|number} id */ /** * @param {WithId[]} modules a collection of modules to get array bounds for * @returns {[number, number] | false} returns the upper and lower array bounds * or false if not every module has a number based id */ static getModulesArrayBounds(modules) { let maxId = -Infinity; let minId = Infinity; for (const module of modules) { if (typeof module.id !== "number") return false; if (maxId < module.id) maxId = /** @type {number} */ (module.id); if (minId > module.id) minId = /** @type {number} */ (module.id); } if (minId < 16 + ("" + minId).length) { // add minId x ',' instead of 'Array(minId).concat(…)' minId = 0; } const objectOverhead = modules .map(module => (module.id + "").length + 2) .reduce((a, b) => a + b, -1); const arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId; return arrayOverhead < objectOverhead ? [minId, maxId] : false; } /** * @param {Chunk} chunk chunk whose modules will be rendered * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules * @param {TODO | TODO[]} dependencyTemplates templates needed for each module to render dependencies * @param {string=} prefix applying prefix strings * @returns {ConcatSource} rendered chunk modules in a Source object */ static renderChunkModules( chunk, filterFn, moduleTemplate, dependencyTemplates, prefix = "" ) { const source = new ConcatSource(); const modules = chunk.getModules().filter(filterFn); let removedModules; if (chunk instanceof HotUpdateChunk) { removedModules = chunk.removedModules; } if ( modules.length === 0 && (!removedModules || removedModules.length === 0) ) { source.add("[]"); return source; } /** @type {{id: string|number, source: Source|string}[]} */ const allModules = modules.map(module => { return { id: module.id, source: moduleTemplate.render(module, dependencyTemplates, { chunk }) }; }); if (removedModules && removedModules.length > 0) { for (const id of removedModules) { allModules.push({ id, source: "false" }); } } const bounds = Template.getModulesArrayBounds(allModules); if (bounds) { // Render a spare array const minId = bounds[0]; const maxId = bounds[1]; if (minId !== 0) { source.add(`Array(${minId}).concat(`); } source.add("[\n"); /** @type {Map} */ const modules = new Map(); for (const module of allModules) { modules.set(module.id, module); } for (let idx = minId; idx <= maxId; idx++) { const module = modules.get(idx); if (idx !== minId) { source.add(",\n"); } source.add(`/* ${idx} */`); if (module) { source.add("\n"); source.add(module.source); } } source.add("\n" + prefix + "]"); if (minId !== 0) { source.add(")"); } } else { // Render an object source.add("{\n"); allModules.sort(stringifyIdSortPredicate).forEach((module, idx) => { if (idx !== 0) { source.add(",\n"); } source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); source.add(module.source); }); source.add(`\n\n${prefix}}`); } return source; } } module.exports = Template; webpack-4.30.0/lib/TemplatedPathPlugin.js000066400000000000000000000123641345416772700202570ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Jason Anderson @diurnalist */ "use strict"; const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi, REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi, REGEXP_MODULEHASH = /\[modulehash(?::(\d+))?\]/gi, REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/gi, REGEXP_NAME = /\[name\]/gi, REGEXP_ID = /\[id\]/gi, REGEXP_MODULEID = /\[moduleid\]/gi, REGEXP_FILE = /\[file\]/gi, REGEXP_QUERY = /\[query\]/gi, REGEXP_FILEBASE = /\[filebase\]/gi; // Using global RegExp for .test is dangerous // We use a normal RegExp instead of .test const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"), REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"), REGEXP_CONTENTHASH_FOR_TEST = new RegExp(REGEXP_CONTENTHASH.source, "i"), REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i"); const withHashLength = (replacer, handlerFn) => { const fn = (match, hashLength, ...args) => { const length = hashLength && parseInt(hashLength, 10); if (length && handlerFn) { return handlerFn(length); } const hash = replacer(match, hashLength, ...args); return length ? hash.slice(0, length) : hash; }; return fn; }; const getReplacer = (value, allowEmpty) => { const fn = (match, ...args) => { // last argument in replacer is the entire input string const input = args[args.length - 1]; if (value === null || value === undefined) { if (!allowEmpty) { throw new Error( `Path variable ${match} not implemented in this context: ${input}` ); } return ""; } else { return `${value}`; } }; return fn; }; const replacePathVariables = (path, data) => { const chunk = data.chunk; const chunkId = chunk && chunk.id; const chunkName = chunk && (chunk.name || chunk.id); const chunkHash = chunk && (chunk.renderedHash || chunk.hash); const chunkHashWithLength = chunk && chunk.hashWithLength; const contentHashType = data.contentHashType; const contentHash = (chunk && chunk.contentHash && chunk.contentHash[contentHashType]) || data.contentHash; const contentHashWithLength = (chunk && chunk.contentHashWithLength && chunk.contentHashWithLength[contentHashType]) || data.contentHashWithLength; const module = data.module; const moduleId = module && module.id; const moduleHash = module && (module.renderedHash || module.hash); const moduleHashWithLength = module && module.hashWithLength; if (typeof path === "function") { path = path(data); } if ( data.noChunkHash && (REGEXP_CHUNKHASH_FOR_TEST.test(path) || REGEXP_CONTENTHASH_FOR_TEST.test(path)) ) { throw new Error( `Cannot use [chunkhash] or [contenthash] for chunk in '${path}' (use [hash] instead)` ); } return ( path .replace( REGEXP_HASH, withHashLength(getReplacer(data.hash), data.hashWithLength) ) .replace( REGEXP_CHUNKHASH, withHashLength(getReplacer(chunkHash), chunkHashWithLength) ) .replace( REGEXP_CONTENTHASH, withHashLength(getReplacer(contentHash), contentHashWithLength) ) .replace( REGEXP_MODULEHASH, withHashLength(getReplacer(moduleHash), moduleHashWithLength) ) .replace(REGEXP_ID, getReplacer(chunkId)) .replace(REGEXP_MODULEID, getReplacer(moduleId)) .replace(REGEXP_NAME, getReplacer(chunkName)) .replace(REGEXP_FILE, getReplacer(data.filename)) .replace(REGEXP_FILEBASE, getReplacer(data.basename)) // query is optional, it's OK if it's in a path but there's nothing to replace it with .replace(REGEXP_QUERY, getReplacer(data.query, true)) ); }; class TemplatedPathPlugin { apply(compiler) { compiler.hooks.compilation.tap("TemplatedPathPlugin", compilation => { const mainTemplate = compilation.mainTemplate; mainTemplate.hooks.assetPath.tap( "TemplatedPathPlugin", replacePathVariables ); mainTemplate.hooks.globalHash.tap( "TemplatedPathPlugin", (chunk, paths) => { const outputOptions = mainTemplate.outputOptions; const publicPath = outputOptions.publicPath || ""; const filename = outputOptions.filename || ""; const chunkFilename = outputOptions.chunkFilename || outputOptions.filename; if ( REGEXP_HASH_FOR_TEST.test(publicPath) || REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || REGEXP_CONTENTHASH_FOR_TEST.test(publicPath) || REGEXP_NAME_FOR_TEST.test(publicPath) ) return true; if (REGEXP_HASH_FOR_TEST.test(filename)) return true; if (REGEXP_HASH_FOR_TEST.test(chunkFilename)) return true; if (REGEXP_HASH_FOR_TEST.test(paths.join("|"))) return true; } ); mainTemplate.hooks.hashForChunk.tap( "TemplatedPathPlugin", (hash, chunk) => { const outputOptions = mainTemplate.outputOptions; const chunkFilename = outputOptions.chunkFilename || outputOptions.filename; if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) { hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); } if (REGEXP_CONTENTHASH_FOR_TEST.test(chunkFilename)) { hash.update( JSON.stringify( chunk.getChunkMaps(true).contentHash.javascript || {} ) ); } if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) { hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); } } ); }); } } module.exports = TemplatedPathPlugin; webpack-4.30.0/lib/UmdMainTemplatePlugin.js000066400000000000000000000211141345416772700205420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource, OriginalSource } = require("webpack-sources"); const Template = require("./Template"); /** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ /** @typedef {import("./Compilation")} Compilation */ /** * @param {string[]} accessor the accessor to convert to path * @returns {string} the path */ const accessorToObjectAccess = accessor => { return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); }; /** * @param {string=} base the path prefix * @param {string|string[]} accessor the accessor * @param {string=} joinWith the element separator * @returns {string} the path */ const accessorAccess = (base, accessor, joinWith = ", ") => { const accessors = Array.isArray(accessor) ? accessor : [accessor]; return accessors .map((_, idx) => { const a = base ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); if (idx === accessors.length - 1) return a; if (idx === 0 && base === undefined) return `${a} = typeof ${a} === "object" ? ${a} : {}`; return `${a} = ${a} || {}`; }) .join(joinWith); }; /** @typedef {string | string[] | LibraryCustomUmdObject} UmdMainTemplatePluginName */ /** * @typedef {Object} AuxiliaryCommentObject * @property {string} root * @property {string} commonjs * @property {string} commonjs2 * @property {string} amd */ /** * @typedef {Object} UmdMainTemplatePluginOption * @property {boolean=} optionalAmdExternalAsGlobal * @property {boolean} namedDefine * @property {string | AuxiliaryCommentObject} auxiliaryComment */ class UmdMainTemplatePlugin { /** * @param {UmdMainTemplatePluginName} name the name of the UMD library * @param {UmdMainTemplatePluginOption} options the plugin option */ constructor(name, options) { if (typeof name === "object" && !Array.isArray(name)) { this.name = name.root || name.amd || name.commonjs; this.names = name; } else { this.name = name; this.names = { commonjs: name, root: name, amd: name }; } this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; this.namedDefine = options.namedDefine; this.auxiliaryComment = options.auxiliaryComment; } /** * @param {Compilation} compilation the compilation instance * @returns {void} */ apply(compilation) { const { mainTemplate, chunkTemplate, runtimeTemplate } = compilation; const onRenderWithEntry = (source, chunk, hash) => { let externals = chunk .getModules() .filter( m => m.external && (m.externalType === "umd" || m.externalType === "umd2") ); const optionalExternals = []; let requiredExternals = []; if (this.optionalAmdExternalAsGlobal) { for (const m of externals) { if (m.optional) { optionalExternals.push(m); } else { requiredExternals.push(m); } } externals = requiredExternals.concat(optionalExternals); } else { requiredExternals = externals; } const replaceKeys = str => { return mainTemplate.getAssetPath(str, { hash, chunk }); }; const externalsDepsArray = modules => { return `[${replaceKeys( modules .map(m => JSON.stringify( typeof m.request === "object" ? m.request.amd : m.request ) ) .join(", ") )}]`; }; const externalsRootArray = modules => { return replaceKeys( modules .map(m => { let request = m.request; if (typeof request === "object") request = request.root; return `root${accessorToObjectAccess([].concat(request))}`; }) .join(", ") ); }; const externalsRequireArray = type => { return replaceKeys( externals .map(m => { let expr; let request = m.request; if (typeof request === "object") { request = request[type]; } if (request === undefined) { throw new Error( "Missing external configuration for type:" + type ); } if (Array.isArray(request)) { expr = `require(${JSON.stringify( request[0] )})${accessorToObjectAccess(request.slice(1))}`; } else { expr = `require(${JSON.stringify(request)})`; } if (m.optional) { expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; } return expr; }) .join(", ") ); }; const externalsArguments = modules => { return modules .map( m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` ) .join(", "); }; const libraryName = library => { return JSON.stringify(replaceKeys([].concat(library).pop())); }; let amdFactory; if (optionalExternals.length > 0) { const wrapperArguments = externalsArguments(requiredExternals); const factoryArguments = requiredExternals.length > 0 ? externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) : externalsRootArray(optionalExternals); amdFactory = `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + ` return factory(${factoryArguments});\n` + " }"; } else { amdFactory = "factory"; } const auxiliaryComment = this.auxiliaryComment; const getAuxilaryComment = type => { if (auxiliaryComment) { if (typeof auxiliaryComment === "string") return "\t//" + auxiliaryComment + "\n"; if (auxiliaryComment[type]) return "\t//" + auxiliaryComment[type] + "\n"; } return ""; }; return new ConcatSource( new OriginalSource( "(function webpackUniversalModuleDefinition(root, factory) {\n" + getAuxilaryComment("commonjs2") + " if(typeof exports === 'object' && typeof module === 'object')\n" + " module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" + getAuxilaryComment("amd") + " else if(typeof define === 'function' && define.amd)\n" + (requiredExternals.length > 0 ? this.names.amd && this.namedDefine === true ? " define(" + libraryName(this.names.amd) + ", " + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" : " define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" : this.names.amd && this.namedDefine === true ? " define(" + libraryName(this.names.amd) + ", [], " + amdFactory + ");\n" : " define([], " + amdFactory + ");\n") + (this.names.root || this.names.commonjs ? getAuxilaryComment("commonjs") + " else if(typeof exports === 'object')\n" + " exports[" + libraryName(this.names.commonjs || this.names.root) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" + getAuxilaryComment("root") + " else\n" + " " + replaceKeys( accessorAccess("root", this.names.root || this.names.commonjs) ) + " = factory(" + externalsRootArray(externals) + ");\n" : " else {\n" + (externals.length > 0 ? " var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" : " var a = factory();\n") + " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + " }\n") + `})(${ runtimeTemplate.outputOptions.globalObject }, function(${externalsArguments(externals)}) {\nreturn `, "webpack/universalModuleDefinition" ), source, ";\n})" ); }; for (const template of [mainTemplate, chunkTemplate]) { template.hooks.renderWithEntry.tap( "UmdMainTemplatePlugin", onRenderWithEntry ); } mainTemplate.hooks.globalHashPaths.tap("UmdMainTemplatePlugin", paths => { if (this.names.root) paths = paths.concat(this.names.root); if (this.names.amd) paths = paths.concat(this.names.amd); if (this.names.commonjs) paths = paths.concat(this.names.commonjs); return paths; }); mainTemplate.hooks.hash.tap("UmdMainTemplatePlugin", hash => { hash.update("umd"); hash.update(`${this.names.root}`); hash.update(`${this.names.amd}`); hash.update(`${this.names.commonjs}`); }); } } module.exports = UmdMainTemplatePlugin; webpack-4.30.0/lib/UnsupportedFeatureWarning.js000066400000000000000000000014511345416772700215310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); /** @typedef {import("./Module")} Module */ /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ class UnsupportedFeatureWarning extends WebpackError { /** * @param {Module} module module relevant to warning * @param {string} message description of warning * @param {DependencyLocation} loc location start and end positions of the module */ constructor(module, message, loc) { super(message); this.name = "UnsupportedFeatureWarning"; this.module = module; this.loc = loc; this.hideStack = true; Error.captureStackTrace(this, this.constructor); } } module.exports = UnsupportedFeatureWarning; webpack-4.30.0/lib/UseStrictPlugin.js000066400000000000000000000031051345416772700174410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./dependencies/ConstDependency"); /** @typedef {import("./Compiler")} Compiler */ class UseStrictPlugin { /** * @param {Compiler} compiler Webpack Compiler * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap( "UseStrictPlugin", (compilation, { normalModuleFactory }) => { const handler = parser => { parser.hooks.program.tap("UseStrictPlugin", ast => { const firstNode = ast.body[0]; if ( firstNode && firstNode.type === "ExpressionStatement" && firstNode.expression.type === "Literal" && firstNode.expression.value === "use strict" ) { // Remove "use strict" expression. It will be added later by the renderer again. // This is necessary in order to not break the strict mode when webpack prepends code. // @see https://github.com/webpack/webpack/issues/1970 const dep = new ConstDependency("", firstNode.range); dep.loc = firstNode.loc; parser.state.current.addDependency(dep); parser.state.module.buildInfo.strict = true; } }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("UseStrictPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("UseStrictPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("UseStrictPlugin", handler); } ); } } module.exports = UseStrictPlugin; webpack-4.30.0/lib/WarnCaseSensitiveModulesPlugin.js000066400000000000000000000017701345416772700224500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning"); class WarnCaseSensitiveModulesPlugin { apply(compiler) { compiler.hooks.compilation.tap( "WarnCaseSensitiveModulesPlugin", compilation => { compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { const moduleWithoutCase = new Map(); for (const module of compilation.modules) { const identifier = module.identifier().toLowerCase(); const array = moduleWithoutCase.get(identifier); if (array) { array.push(module); } else { moduleWithoutCase.set(identifier, [module]); } } for (const pair of moduleWithoutCase) { const array = pair[1]; if (array.length > 1) { compilation.warnings.push(new CaseSensitiveModulesWarning(array)); } } }); } ); } } module.exports = WarnCaseSensitiveModulesPlugin; webpack-4.30.0/lib/WarnNoModeSetPlugin.js000066400000000000000000000006071345416772700202050ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NoModeWarning = require("./NoModeWarning"); class WarnNoModeSetPlugin { apply(compiler) { compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { compilation.warnings.push(new NoModeWarning()); }); } } module.exports = WarnNoModeSetPlugin; webpack-4.30.0/lib/WatchIgnorePlugin.js000066400000000000000000000044771345416772700177430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/WatchIgnorePlugin.json"); /** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ class IgnoringWatchFileSystem { constructor(wfs, paths) { this.wfs = wfs; this.paths = paths; } watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { const ignored = path => this.paths.some(p => p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 ); const notIgnored = path => !ignored(path); const ignoredFiles = files.filter(ignored); const ignoredDirs = dirs.filter(ignored); const watcher = this.wfs.watch( files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, options, ( err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps, removedFiles ) => { if (err) return callback(err); for (const path of ignoredFiles) { fileTimestamps.set(path, 1); } for (const path of ignoredDirs) { dirTimestamps.set(path, 1); } callback( err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps, removedFiles ); }, callbackUndelayed ); return { close: () => watcher.close(), pause: () => watcher.pause(), getContextTimestamps: () => { const dirTimestamps = watcher.getContextTimestamps(); for (const path of ignoredDirs) { dirTimestamps.set(path, 1); } return dirTimestamps; }, getFileTimestamps: () => { const fileTimestamps = watcher.getFileTimestamps(); for (const path of ignoredFiles) { fileTimestamps.set(path, 1); } return fileTimestamps; } }; } } class WatchIgnorePlugin { /** * @param {WatchIgnorePluginOptions} paths list of paths */ constructor(paths) { validateOptions(schema, paths, "Watch Ignore Plugin"); this.paths = paths; } apply(compiler) { compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { compiler.watchFileSystem = new IgnoringWatchFileSystem( compiler.watchFileSystem, this.paths ); }); } } module.exports = WatchIgnorePlugin; webpack-4.30.0/lib/Watching.js000066400000000000000000000111141345416772700161000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Stats = require("./Stats"); class Watching { constructor(compiler, watchOptions, handler) { this.startTime = null; this.invalid = false; this.handler = handler; this.callbacks = []; this.closed = false; if (typeof watchOptions === "number") { this.watchOptions = { aggregateTimeout: watchOptions }; } else if (watchOptions && typeof watchOptions === "object") { this.watchOptions = Object.assign({}, watchOptions); } else { this.watchOptions = {}; } this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200; this.compiler = compiler; this.running = true; this.compiler.readRecords(err => { if (err) return this._done(err); this._go(); }); } _go() { this.startTime = Date.now(); this.running = true; this.invalid = false; this.compiler.hooks.watchRun.callAsync(this.compiler, err => { if (err) return this._done(err); const onCompiled = (err, compilation) => { if (err) return this._done(err); if (this.invalid) return this._done(); if (this.compiler.hooks.shouldEmit.call(compilation) === false) { return this._done(null, compilation); } this.compiler.emitAssets(compilation, err => { if (err) return this._done(err); if (this.invalid) return this._done(); this.compiler.emitRecords(err => { if (err) return this._done(err); if (compilation.hooks.needAdditionalPass.call()) { compilation.needAdditionalPass = true; const stats = new Stats(compilation); stats.startTime = this.startTime; stats.endTime = Date.now(); this.compiler.hooks.done.callAsync(stats, err => { if (err) return this._done(err); this.compiler.hooks.additionalPass.callAsync(err => { if (err) return this._done(err); this.compiler.compile(onCompiled); }); }); return; } return this._done(null, compilation); }); }); }; this.compiler.compile(onCompiled); }); } _getStats(compilation) { const stats = new Stats(compilation); stats.startTime = this.startTime; stats.endTime = Date.now(); return stats; } _done(err, compilation) { this.running = false; if (this.invalid) return this._go(); const stats = compilation ? this._getStats(compilation) : null; if (err) { this.compiler.hooks.failed.call(err); this.handler(err, stats); return; } this.compiler.hooks.done.callAsync(stats, () => { this.handler(null, stats); if (!this.closed) { this.watch( Array.from(compilation.fileDependencies), Array.from(compilation.contextDependencies), Array.from(compilation.missingDependencies) ); } for (const cb of this.callbacks) cb(); this.callbacks.length = 0; }); } watch(files, dirs, missing) { this.pausedWatcher = null; this.watcher = this.compiler.watchFileSystem.watch( files, dirs, missing, this.startTime, this.watchOptions, ( err, filesModified, contextModified, missingModified, fileTimestamps, contextTimestamps, removedFiles ) => { this.pausedWatcher = this.watcher; this.watcher = null; if (err) { return this.handler(err); } this.compiler.fileTimestamps = fileTimestamps; this.compiler.contextTimestamps = contextTimestamps; this.compiler.removedFiles = removedFiles; this._invalidate(); }, (fileName, changeTime) => { this.compiler.hooks.invalid.call(fileName, changeTime); } ); } invalidate(callback) { if (callback) { this.callbacks.push(callback); } if (this.watcher) { this.compiler.fileTimestamps = this.watcher.getFileTimestamps(); this.compiler.contextTimestamps = this.watcher.getContextTimestamps(); } return this._invalidate(); } _invalidate() { if (this.watcher) { this.pausedWatcher = this.watcher; this.watcher.pause(); this.watcher = null; } if (this.running) { this.invalid = true; return false; } else { this._go(); } } close(callback) { const finalCallback = () => { this.compiler.hooks.watchClose.call(); this.compiler.running = false; this.compiler.watchMode = false; if (callback !== undefined) callback(); }; this.closed = true; if (this.watcher) { this.watcher.close(); this.watcher = null; } if (this.pausedWatcher) { this.pausedWatcher.close(); this.pausedWatcher = null; } if (this.running) { this.invalid = true; this._done = finalCallback; } else { finalCallback(); } } } module.exports = Watching; webpack-4.30.0/lib/WebpackError.js000066400000000000000000000012241345416772700167230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Jarid Margolin @jaridmargolin */ "use strict"; const inspect = require("util").inspect.custom; class WebpackError extends Error { /** * Creates an instance of WebpackError. * @param {string=} message error message */ constructor(message) { super(message); this.details = undefined; this.missing = undefined; this.origin = undefined; this.dependencies = undefined; this.module = undefined; Error.captureStackTrace(this, this.constructor); } [inspect]() { return this.stack + (this.details ? `\n${this.details}` : ""); } } module.exports = WebpackError; webpack-4.30.0/lib/WebpackOptionsApply.js000066400000000000000000000445211345416772700203020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const OptionsApply = require("./OptionsApply"); const JavascriptModulesPlugin = require("./JavascriptModulesPlugin"); const JsonModulesPlugin = require("./JsonModulesPlugin"); const WebAssemblyModulesPlugin = require("./wasm/WebAssemblyModulesPlugin"); const LoaderTargetPlugin = require("./LoaderTargetPlugin"); const FunctionModulePlugin = require("./FunctionModulePlugin"); const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin"); const SourceMapDevToolPlugin = require("./SourceMapDevToolPlugin"); const EvalSourceMapDevToolPlugin = require("./EvalSourceMapDevToolPlugin"); const EntryOptionPlugin = require("./EntryOptionPlugin"); const RecordIdsPlugin = require("./RecordIdsPlugin"); const APIPlugin = require("./APIPlugin"); const ConstPlugin = require("./ConstPlugin"); const NodeStuffPlugin = require("./NodeStuffPlugin"); const CompatibilityPlugin = require("./CompatibilityPlugin"); const TemplatedPathPlugin = require("./TemplatedPathPlugin"); const WarnCaseSensitiveModulesPlugin = require("./WarnCaseSensitiveModulesPlugin"); const UseStrictPlugin = require("./UseStrictPlugin"); const LoaderPlugin = require("./dependencies/LoaderPlugin"); const CommonJsPlugin = require("./dependencies/CommonJsPlugin"); const HarmonyModulesPlugin = require("./dependencies/HarmonyModulesPlugin"); const SystemPlugin = require("./dependencies/SystemPlugin"); const ImportPlugin = require("./dependencies/ImportPlugin"); const RequireContextPlugin = require("./dependencies/RequireContextPlugin"); const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin"); const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin"); /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ /** @typedef {import("./Compiler")} Compiler */ class WebpackOptionsApply extends OptionsApply { constructor() { super(); } /** * @param {WebpackOptions} options options object * @param {Compiler} compiler compiler object * @returns {WebpackOptions} options object */ process(options, compiler) { let ExternalsPlugin; compiler.outputPath = options.output.path; compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; compiler.recordsOutputPath = options.recordsOutputPath || options.recordsPath; compiler.name = options.name; // TODO webpack 5 refactor this to MultiCompiler.setDependencies() with a WeakMap // @ts-ignore TODO compiler.dependencies = options.dependencies; if (typeof options.target === "string") { let JsonpTemplatePlugin; let FetchCompileWasmTemplatePlugin; let ReadFileCompileWasmTemplatePlugin; let NodeSourcePlugin; let NodeTargetPlugin; let NodeTemplatePlugin; switch (options.target) { case "web": JsonpTemplatePlugin = require("./web/JsonpTemplatePlugin"); FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); new JsonpTemplatePlugin().apply(compiler); new FetchCompileWasmTemplatePlugin({ mangleImports: options.optimization.mangleWasmImports }).apply(compiler); new FunctionModulePlugin().apply(compiler); new NodeSourcePlugin(options.node).apply(compiler); new LoaderTargetPlugin(options.target).apply(compiler); break; case "webworker": { let WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); new WebWorkerTemplatePlugin().apply(compiler); new FetchCompileWasmTemplatePlugin({ mangleImports: options.optimization.mangleWasmImports }).apply(compiler); new FunctionModulePlugin().apply(compiler); new NodeSourcePlugin(options.node).apply(compiler); new LoaderTargetPlugin(options.target).apply(compiler); break; } case "node": case "async-node": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); ReadFileCompileWasmTemplatePlugin = require("./node/ReadFileCompileWasmTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); new NodeTemplatePlugin({ asyncChunkLoading: options.target === "async-node" }).apply(compiler); new ReadFileCompileWasmTemplatePlugin({ mangleImports: options.optimization.mangleWasmImports }).apply(compiler); new FunctionModulePlugin().apply(compiler); new NodeTargetPlugin().apply(compiler); new LoaderTargetPlugin("node").apply(compiler); break; case "node-webkit": JsonpTemplatePlugin = require("./web/JsonpTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); new JsonpTemplatePlugin().apply(compiler); new FunctionModulePlugin().apply(compiler); new NodeTargetPlugin().apply(compiler); new ExternalsPlugin("commonjs", "nw.gui").apply(compiler); new LoaderTargetPlugin(options.target).apply(compiler); break; case "electron-main": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); new NodeTemplatePlugin({ asyncChunkLoading: true }).apply(compiler); new FunctionModulePlugin().apply(compiler); new NodeTargetPlugin().apply(compiler); new ExternalsPlugin("commonjs", [ "app", "auto-updater", "browser-window", "clipboard", "content-tracing", "crash-reporter", "dialog", "electron", "global-shortcut", "ipc", "ipc-main", "menu", "menu-item", "native-image", "original-fs", "power-monitor", "power-save-blocker", "protocol", "screen", "session", "shell", "tray", "web-contents" ]).apply(compiler); new LoaderTargetPlugin(options.target).apply(compiler); break; case "electron-renderer": JsonpTemplatePlugin = require("./web/JsonpTemplatePlugin"); FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); new JsonpTemplatePlugin().apply(compiler); new FetchCompileWasmTemplatePlugin({ mangleImports: options.optimization.mangleWasmImports }).apply(compiler); new FunctionModulePlugin().apply(compiler); new NodeTargetPlugin().apply(compiler); new ExternalsPlugin("commonjs", [ "clipboard", "crash-reporter", "desktop-capturer", "electron", "ipc", "ipc-renderer", "native-image", "original-fs", "remote", "screen", "shell", "web-frame" ]).apply(compiler); new LoaderTargetPlugin(options.target).apply(compiler); break; default: throw new Error("Unsupported target '" + options.target + "'."); } } // @ts-ignore This is always true, which is good this way else if (options.target !== false) { options.target(compiler); } else { throw new Error("Unsupported target '" + options.target + "'."); } if (options.output.library || options.output.libraryTarget !== "var") { const LibraryTemplatePlugin = require("./LibraryTemplatePlugin"); new LibraryTemplatePlugin( options.output.library, options.output.libraryTarget, options.output.umdNamedDefine, options.output.auxiliaryComment || "", options.output.libraryExport ).apply(compiler); } if (options.externals) { ExternalsPlugin = require("./ExternalsPlugin"); new ExternalsPlugin( options.output.libraryTarget, options.externals ).apply(compiler); } let noSources; let legacy; let modern; let comment; if ( options.devtool && (options.devtool.includes("sourcemap") || options.devtool.includes("source-map")) ) { const hidden = options.devtool.includes("hidden"); const inline = options.devtool.includes("inline"); const evalWrapped = options.devtool.includes("eval"); const cheap = options.devtool.includes("cheap"); const moduleMaps = options.devtool.includes("module"); noSources = options.devtool.includes("nosources"); legacy = options.devtool.includes("@"); modern = options.devtool.includes("#"); comment = legacy && modern ? "\n/*\n//@ source" + "MappingURL=[url]\n//# source" + "MappingURL=[url]\n*/" : legacy ? "\n/*\n//@ source" + "MappingURL=[url]\n*/" : modern ? "\n//# source" + "MappingURL=[url]" : null; const Plugin = evalWrapped ? EvalSourceMapDevToolPlugin : SourceMapDevToolPlugin; new Plugin({ filename: inline ? null : options.output.sourceMapFilename, moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, fallbackModuleFilenameTemplate: options.output.devtoolFallbackModuleFilenameTemplate, append: hidden ? false : comment, module: moduleMaps ? true : cheap ? false : true, columns: cheap ? false : true, lineToLine: options.output.devtoolLineToLine, noSources: noSources, namespace: options.output.devtoolNamespace }).apply(compiler); } else if (options.devtool && options.devtool.includes("eval")) { legacy = options.devtool.includes("@"); modern = options.devtool.includes("#"); comment = legacy && modern ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" : legacy ? "\n//@ sourceURL=[url]" : modern ? "\n//# sourceURL=[url]" : null; new EvalDevToolModulePlugin({ sourceUrlComment: comment, moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, namespace: options.output.devtoolNamespace }).apply(compiler); } new JavascriptModulesPlugin().apply(compiler); new JsonModulesPlugin().apply(compiler); new WebAssemblyModulesPlugin({ mangleImports: options.optimization.mangleWasmImports }).apply(compiler); new EntryOptionPlugin().apply(compiler); compiler.hooks.entryOption.call(options.context, options.entry); new CompatibilityPlugin().apply(compiler); new HarmonyModulesPlugin(options.module).apply(compiler); if (options.amd !== false) { const AMDPlugin = require("./dependencies/AMDPlugin"); const RequireJsStuffPlugin = require("./RequireJsStuffPlugin"); new AMDPlugin(options.module, options.amd || {}).apply(compiler); new RequireJsStuffPlugin().apply(compiler); } new CommonJsPlugin(options.module).apply(compiler); new LoaderPlugin().apply(compiler); new NodeStuffPlugin(options.node).apply(compiler); new APIPlugin().apply(compiler); new ConstPlugin().apply(compiler); new UseStrictPlugin().apply(compiler); new RequireIncludePlugin().apply(compiler); new RequireEnsurePlugin().apply(compiler); new RequireContextPlugin( options.resolve.modules, options.resolve.extensions, options.resolve.mainFiles ).apply(compiler); new ImportPlugin(options.module).apply(compiler); new SystemPlugin(options.module).apply(compiler); if (typeof options.mode !== "string") { const WarnNoModeSetPlugin = require("./WarnNoModeSetPlugin"); new WarnNoModeSetPlugin().apply(compiler); } const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin"); new EnsureChunkConditionsPlugin().apply(compiler); if (options.optimization.removeAvailableModules) { const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin"); new RemoveParentModulesPlugin().apply(compiler); } if (options.optimization.removeEmptyChunks) { const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin"); new RemoveEmptyChunksPlugin().apply(compiler); } if (options.optimization.mergeDuplicateChunks) { const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin"); new MergeDuplicateChunksPlugin().apply(compiler); } if (options.optimization.flagIncludedChunks) { const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin"); new FlagIncludedChunksPlugin().apply(compiler); } if (options.optimization.sideEffects) { const SideEffectsFlagPlugin = require("./optimize/SideEffectsFlagPlugin"); new SideEffectsFlagPlugin().apply(compiler); } if (options.optimization.providedExports) { const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin"); new FlagDependencyExportsPlugin().apply(compiler); } if (options.optimization.usedExports) { const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin"); new FlagDependencyUsagePlugin().apply(compiler); } if (options.optimization.concatenateModules) { const ModuleConcatenationPlugin = require("./optimize/ModuleConcatenationPlugin"); new ModuleConcatenationPlugin().apply(compiler); } if (options.optimization.splitChunks) { const SplitChunksPlugin = require("./optimize/SplitChunksPlugin"); new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); } if (options.optimization.runtimeChunk) { const RuntimeChunkPlugin = require("./optimize/RuntimeChunkPlugin"); new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); } if (options.optimization.noEmitOnErrors) { const NoEmitOnErrorsPlugin = require("./NoEmitOnErrorsPlugin"); new NoEmitOnErrorsPlugin().apply(compiler); } if (options.optimization.checkWasmTypes) { const WasmFinalizeExportsPlugin = require("./wasm/WasmFinalizeExportsPlugin"); new WasmFinalizeExportsPlugin().apply(compiler); } let moduleIds = options.optimization.moduleIds; if (moduleIds === undefined) { // TODO webpack 5 remove all these options if (options.optimization.occurrenceOrder) { moduleIds = "size"; } if (options.optimization.namedModules) { moduleIds = "named"; } if (options.optimization.hashedModuleIds) { moduleIds = "hashed"; } if (moduleIds === undefined) { moduleIds = "natural"; } } if (moduleIds) { const NamedModulesPlugin = require("./NamedModulesPlugin"); const HashedModuleIdsPlugin = require("./HashedModuleIdsPlugin"); const OccurrenceModuleOrderPlugin = require("./optimize/OccurrenceModuleOrderPlugin"); switch (moduleIds) { case "natural": // TODO webpack 5: see hint in Compilation.sortModules break; case "named": new NamedModulesPlugin().apply(compiler); break; case "hashed": new HashedModuleIdsPlugin().apply(compiler); break; case "size": new OccurrenceModuleOrderPlugin({ prioritiseInitial: true }).apply(compiler); break; case "total-size": new OccurrenceModuleOrderPlugin({ prioritiseInitial: false }).apply(compiler); break; default: throw new Error( `webpack bug: moduleIds: ${moduleIds} is not implemented` ); } } let chunkIds = options.optimization.chunkIds; if (chunkIds === undefined) { // TODO webpack 5 remove all these options if (options.optimization.occurrenceOrder) { // This looks weird but it's for backward-compat // This bug already existed before adding this feature chunkIds = "total-size"; } if (options.optimization.namedChunks) { chunkIds = "named"; } if (chunkIds === undefined) { chunkIds = "natural"; } } if (chunkIds) { const NaturalChunkOrderPlugin = require("./optimize/NaturalChunkOrderPlugin"); const NamedChunksPlugin = require("./NamedChunksPlugin"); const OccurrenceChunkOrderPlugin = require("./optimize/OccurrenceChunkOrderPlugin"); switch (chunkIds) { case "natural": new NaturalChunkOrderPlugin().apply(compiler); break; case "named": // TODO webapck 5: for backward-compat this need to have OccurrenceChunkOrderPlugin too // The NamedChunksPlugin doesn't give every chunk a name // This should be fixed, and the OccurrenceChunkOrderPlugin should be removed here. new OccurrenceChunkOrderPlugin({ prioritiseInitial: false }).apply(compiler); new NamedChunksPlugin().apply(compiler); break; case "size": new OccurrenceChunkOrderPlugin({ prioritiseInitial: true }).apply(compiler); break; case "total-size": new OccurrenceChunkOrderPlugin({ prioritiseInitial: false }).apply(compiler); break; default: throw new Error( `webpack bug: chunkIds: ${chunkIds} is not implemented` ); } } if (options.optimization.nodeEnv) { const DefinePlugin = require("./DefinePlugin"); new DefinePlugin({ "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) }).apply(compiler); } if (options.optimization.minimize) { for (const minimizer of options.optimization.minimizer) { if (typeof minimizer === "function") { minimizer.call(compiler, compiler); } else { minimizer.apply(compiler); } } } if (options.performance) { const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin"); new SizeLimitsPlugin(options.performance).apply(compiler); } new TemplatedPathPlugin().apply(compiler); new RecordIdsPlugin({ portableIds: options.optimization.portableRecords }).apply(compiler); new WarnCaseSensitiveModulesPlugin().apply(compiler); if (options.cache) { const CachePlugin = require("./CachePlugin"); new CachePlugin( typeof options.cache === "object" ? options.cache : null ).apply(compiler); } compiler.hooks.afterPlugins.call(compiler); if (!compiler.inputFileSystem) { throw new Error("No input filesystem provided"); } compiler.resolverFactory.hooks.resolveOptions .for("normal") .tap("WebpackOptionsApply", resolveOptions => { return Object.assign( { fileSystem: compiler.inputFileSystem }, options.resolve, resolveOptions ); }); compiler.resolverFactory.hooks.resolveOptions .for("context") .tap("WebpackOptionsApply", resolveOptions => { return Object.assign( { fileSystem: compiler.inputFileSystem, resolveToContext: true }, options.resolve, resolveOptions ); }); compiler.resolverFactory.hooks.resolveOptions .for("loader") .tap("WebpackOptionsApply", resolveOptions => { return Object.assign( { fileSystem: compiler.inputFileSystem }, options.resolveLoader, resolveOptions ); }); compiler.hooks.afterResolvers.call(compiler); return options; } } module.exports = WebpackOptionsApply; webpack-4.30.0/lib/WebpackOptionsDefaulter.js000066400000000000000000000266251345416772700211350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const OptionsDefaulter = require("./OptionsDefaulter"); const Template = require("./Template"); const isProductionLikeMode = options => { return options.mode === "production" || !options.mode; }; const isWebLikeTarget = options => { return options.target === "web" || options.target === "webworker"; }; const getDevtoolNamespace = library => { // if options.output.library is a string if (Array.isArray(library)) { return library.join("."); } else if (typeof library === "object") { return getDevtoolNamespace(library.root); } return library || ""; }; class WebpackOptionsDefaulter extends OptionsDefaulter { constructor() { super(); this.set("entry", "./src"); this.set("devtool", "make", options => options.mode === "development" ? "eval" : false ); this.set("cache", "make", options => options.mode === "development"); this.set("context", process.cwd()); this.set("target", "web"); this.set("module", "call", value => Object.assign({}, value)); this.set("module.unknownContextRequest", "."); this.set("module.unknownContextRegExp", false); this.set("module.unknownContextRecursive", true); this.set("module.unknownContextCritical", true); this.set("module.exprContextRequest", "."); this.set("module.exprContextRegExp", false); this.set("module.exprContextRecursive", true); this.set("module.exprContextCritical", true); this.set("module.wrappedContextRegExp", /.*/); this.set("module.wrappedContextRecursive", true); this.set("module.wrappedContextCritical", false); this.set("module.strictExportPresence", false); this.set("module.strictThisContextOnImports", false); this.set("module.unsafeCache", "make", options => !!options.cache); this.set("module.rules", []); this.set("module.defaultRules", "make", options => [ { type: "javascript/auto", resolve: {} }, { test: /\.mjs$/i, type: "javascript/esm", resolve: { mainFields: options.target === "web" || options.target === "webworker" || options.target === "electron-renderer" ? ["browser", "main"] : ["main"] } }, { test: /\.json$/i, type: "json" }, { test: /\.wasm$/i, type: "webassembly/experimental" } ]); this.set("output", "call", (value, options) => { if (typeof value === "string") { return { filename: value }; } else if (typeof value !== "object") { return {}; } else { return Object.assign({}, value); } }); this.set("output.filename", "[name].js"); this.set("output.chunkFilename", "make", options => { const filename = options.output.filename; if (typeof filename !== "function") { const hasName = filename.includes("[name]"); const hasId = filename.includes("[id]"); const hasChunkHash = filename.includes("[chunkhash]"); // Anything changing depending on chunk is fine if (hasChunkHash || hasName || hasId) return filename; // Elsewise prefix "[id]." in front of the basename to make it changing return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); } return "[id].js"; }); this.set("output.webassemblyModuleFilename", "[modulehash].module.wasm"); this.set("output.library", ""); this.set("output.hotUpdateFunction", "make", options => { return Template.toIdentifier( "webpackHotUpdate" + Template.toIdentifier(options.output.library) ); }); this.set("output.jsonpFunction", "make", options => { return Template.toIdentifier( "webpackJsonp" + Template.toIdentifier(options.output.library) ); }); this.set("output.chunkCallbackName", "make", options => { return Template.toIdentifier( "webpackChunk" + Template.toIdentifier(options.output.library) ); }); this.set("output.globalObject", "make", options => { switch (options.target) { case "web": case "electron-renderer": case "node-webkit": return "window"; case "webworker": return "self"; case "node": case "async-node": case "electron-main": return "global"; default: return "self"; } }); this.set("output.devtoolNamespace", "make", options => { return getDevtoolNamespace(options.output.library); }); this.set("output.libraryTarget", "var"); this.set("output.path", path.join(process.cwd(), "dist")); this.set( "output.pathinfo", "make", options => options.mode === "development" ); this.set("output.sourceMapFilename", "[file].map[query]"); this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js"); this.set("output.hotUpdateMainFilename", "[hash].hot-update.json"); this.set("output.crossOriginLoading", false); this.set("output.jsonpScriptType", false); this.set("output.chunkLoadTimeout", 120000); this.set("output.hashFunction", "md4"); this.set("output.hashDigest", "hex"); this.set("output.hashDigestLength", 20); this.set("output.devtoolLineToLine", false); this.set("output.strictModuleExceptionHandling", false); this.set("node", "call", value => { if (typeof value === "boolean") { return value; } else { return Object.assign({}, value); } }); this.set("node.console", false); this.set("node.process", true); this.set("node.global", true); this.set("node.Buffer", true); this.set("node.setImmediate", true); this.set("node.__filename", "mock"); this.set("node.__dirname", "mock"); this.set("performance", "call", (value, options) => { if (value === false) return false; if ( value === undefined && (!isProductionLikeMode(options) || !isWebLikeTarget(options)) ) return false; return Object.assign({}, value); }); this.set("performance.maxAssetSize", 250000); this.set("performance.maxEntrypointSize", 250000); this.set("performance.hints", "make", options => isProductionLikeMode(options) ? "warning" : false ); this.set("optimization", "call", value => Object.assign({}, value)); this.set("optimization.removeAvailableModules", true); this.set("optimization.removeEmptyChunks", true); this.set("optimization.mergeDuplicateChunks", true); this.set("optimization.flagIncludedChunks", "make", options => isProductionLikeMode(options) ); // TODO webpack 5 add `moduleIds: "named"` default for development // TODO webpack 5 add `moduleIds: "size"` default for production // TODO webpack 5 remove optimization.occurrenceOrder this.set("optimization.occurrenceOrder", "make", options => isProductionLikeMode(options) ); this.set("optimization.sideEffects", "make", options => isProductionLikeMode(options) ); this.set("optimization.providedExports", true); this.set("optimization.usedExports", "make", options => isProductionLikeMode(options) ); this.set("optimization.concatenateModules", "make", options => isProductionLikeMode(options) ); this.set("optimization.splitChunks", {}); this.set("optimization.splitChunks.hidePathInfo", "make", options => { return isProductionLikeMode(options); }); this.set("optimization.splitChunks.chunks", "async"); this.set("optimization.splitChunks.minSize", "make", options => { return isProductionLikeMode(options) ? 30000 : 10000; }); this.set("optimization.splitChunks.minChunks", 1); this.set("optimization.splitChunks.maxAsyncRequests", "make", options => { return isProductionLikeMode(options) ? 5 : Infinity; }); this.set("optimization.splitChunks.automaticNameDelimiter", "~"); this.set("optimization.splitChunks.maxInitialRequests", "make", options => { return isProductionLikeMode(options) ? 3 : Infinity; }); this.set("optimization.splitChunks.name", true); this.set("optimization.splitChunks.cacheGroups", {}); this.set("optimization.splitChunks.cacheGroups.default", { automaticNamePrefix: "", reuseExistingChunk: true, minChunks: 2, priority: -20 }); this.set("optimization.splitChunks.cacheGroups.vendors", { automaticNamePrefix: "vendors", test: /[\\/]node_modules[\\/]/, priority: -10 }); this.set("optimization.runtimeChunk", "call", value => { if (value === "single") { return { name: "runtime" }; } if (value === true || value === "multiple") { return { name: entrypoint => `runtime~${entrypoint.name}` }; } return value; }); this.set("optimization.noEmitOnErrors", "make", options => isProductionLikeMode(options) ); this.set("optimization.checkWasmTypes", "make", options => isProductionLikeMode(options) ); this.set("optimization.mangleWasmImports", false); // TODO webpack 5 remove optimization.namedModules this.set( "optimization.namedModules", "make", options => options.mode === "development" ); this.set("optimization.hashedModuleIds", false); // TODO webpack 5 add `chunkIds: "named"` default for development // TODO webpack 5 add `chunkIds: "size"` default for production // TODO webpack 5 remove optimization.namedChunks this.set( "optimization.namedChunks", "make", options => options.mode === "development" ); this.set( "optimization.portableRecords", "make", options => !!( options.recordsInputPath || options.recordsOutputPath || options.recordsPath ) ); this.set("optimization.minimize", "make", options => isProductionLikeMode(options) ); this.set("optimization.minimizer", "make", options => [ { apply: compiler => { // Lazy load the Terser plugin const TerserPlugin = require("terser-webpack-plugin"); const SourceMapDevToolPlugin = require("./SourceMapDevToolPlugin"); new TerserPlugin({ cache: true, parallel: true, sourceMap: (options.devtool && /source-?map/.test(options.devtool)) || (options.plugins && options.plugins.some(p => p instanceof SourceMapDevToolPlugin)) }).apply(compiler); } } ]); this.set("optimization.nodeEnv", "make", options => { // TODO: In webpack 5, it should return `false` when mode is `none` return options.mode || "production"; }); this.set("resolve", "call", value => Object.assign({}, value)); this.set("resolve.unsafeCache", true); this.set("resolve.modules", ["node_modules"]); this.set("resolve.extensions", [".wasm", ".mjs", ".js", ".json"]); this.set("resolve.mainFiles", ["index"]); this.set("resolve.aliasFields", "make", options => { if ( options.target === "web" || options.target === "webworker" || options.target === "electron-renderer" ) { return ["browser"]; } else { return []; } }); this.set("resolve.mainFields", "make", options => { if ( options.target === "web" || options.target === "webworker" || options.target === "electron-renderer" ) { return ["browser", "module", "main"]; } else { return ["module", "main"]; } }); this.set("resolve.cacheWithContext", "make", options => { return ( Array.isArray(options.resolve.plugins) && options.resolve.plugins.length > 0 ); }); this.set("resolveLoader", "call", value => Object.assign({}, value)); this.set("resolveLoader.unsafeCache", true); this.set("resolveLoader.mainFields", ["loader", "main"]); this.set("resolveLoader.extensions", [".js", ".json"]); this.set("resolveLoader.mainFiles", ["index"]); this.set("resolveLoader.cacheWithContext", "make", options => { return ( Array.isArray(options.resolveLoader.plugins) && options.resolveLoader.plugins.length > 0 ); }); } } module.exports = WebpackOptionsDefaulter; webpack-4.30.0/lib/WebpackOptionsValidationError.js000066400000000000000000000232301345416772700223130ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Gajus Kuizinas @gajus */ "use strict"; const WebpackError = require("./WebpackError"); const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); const getSchemaPart = (path, parents, additionalPath) => { parents = parents || 0; path = path.split("/"); path = path.slice(0, path.length - parents); if (additionalPath) { additionalPath = additionalPath.split("/"); path = path.concat(additionalPath); } let schemaPart = webpackOptionsSchema; for (let i = 1; i < path.length; i++) { const inner = schemaPart[path[i]]; if (inner) schemaPart = inner; } return schemaPart; }; const getSchemaPartText = (schemaPart, additionalPath) => { if (additionalPath) { for (let i = 0; i < additionalPath.length; i++) { const inner = schemaPart[additionalPath[i]]; if (inner) schemaPart = inner; } } while (schemaPart.$ref) { schemaPart = getSchemaPart(schemaPart.$ref); } let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart); if (schemaPart.description) { schemaText += `\n-> ${schemaPart.description}`; } return schemaText; }; const getSchemaPartDescription = schemaPart => { while (schemaPart.$ref) { schemaPart = getSchemaPart(schemaPart.$ref); } if (schemaPart.description) { return `\n-> ${schemaPart.description}`; } return ""; }; const filterChildren = children => { return children.filter( err => err.keyword !== "anyOf" && err.keyword !== "allOf" && err.keyword !== "oneOf" ); }; const indent = (str, prefix, firstLine) => { if (firstLine) { return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); } else { return str.replace(/\n(?!$)/g, `\n${prefix}`); } }; class WebpackOptionsValidationError extends WebpackError { constructor(validationErrors) { super( "Invalid configuration object. " + "Webpack has been initialised using a configuration object that does not match the API schema.\n" + validationErrors .map( err => " - " + indent( WebpackOptionsValidationError.formatValidationError(err), " ", false ) ) .join("\n") ); this.name = "WebpackOptionsValidationError"; this.validationErrors = validationErrors; Error.captureStackTrace(this, this.constructor); } static formatSchema(schema, prevSchemas) { prevSchemas = prevSchemas || []; const formatInnerSchema = (innerSchema, addSelf) => { if (!addSelf) { return WebpackOptionsValidationError.formatSchema( innerSchema, prevSchemas ); } if (prevSchemas.includes(innerSchema)) { return "(recursive)"; } return WebpackOptionsValidationError.formatSchema( innerSchema, prevSchemas.concat(schema) ); }; if (schema.type === "string") { if (schema.minLength === 1) { return "non-empty string"; } if (schema.minLength > 1) { return `string (min length ${schema.minLength})`; } return "string"; } if (schema.type === "boolean") { return "boolean"; } if (schema.type === "number") { return "number"; } if (schema.type === "object") { if (schema.properties) { const required = schema.required || []; return `object { ${Object.keys(schema.properties) .map(property => { if (!required.includes(property)) return property + "?"; return property; }) .concat(schema.additionalProperties ? ["…"] : []) .join(", ")} }`; } if (schema.additionalProperties) { return `object { : ${formatInnerSchema( schema.additionalProperties )} }`; } return "object"; } if (schema.type === "array") { return `[${formatInnerSchema(schema.items)}]`; } switch (schema.instanceof) { case "Function": return "function"; case "RegExp": return "RegExp"; } if (schema.$ref) { return formatInnerSchema(getSchemaPart(schema.$ref), true); } if (schema.allOf) { return schema.allOf.map(formatInnerSchema).join(" & "); } if (schema.oneOf) { return schema.oneOf.map(formatInnerSchema).join(" | "); } if (schema.anyOf) { return schema.anyOf.map(formatInnerSchema).join(" | "); } if (schema.enum) { return schema.enum.map(item => JSON.stringify(item)).join(" | "); } return JSON.stringify(schema, null, 2); } static formatValidationError(err) { const dataPath = `configuration${err.dataPath}`; if (err.keyword === "additionalProperties") { const baseMessage = `${dataPath} has an unknown property '${ err.params.additionalProperty }'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`; if (!err.dataPath) { switch (err.params.additionalProperty) { case "debug": return ( `${baseMessage}\n` + "The 'debug' property was removed in webpack 2.0.0.\n" + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + "plugins: [\n" + " new webpack.LoaderOptionsPlugin({\n" + " debug: true\n" + " })\n" + "]" ); } return ( `${baseMessage}\n` + "For typos: please correct them.\n" + "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + " plugins: [\n" + " new webpack.LoaderOptionsPlugin({\n" + " // test: /\\.xxx$/, // may apply this only for some modules\n" + " options: {\n" + ` ${err.params.additionalProperty}: …\n` + " }\n" + " })\n" + " ]" ); } return baseMessage; } else if (err.keyword === "oneOf" || err.keyword === "anyOf") { if (err.children && err.children.length > 0) { if (err.schema.length === 1) { const lastChild = err.children[err.children.length - 1]; const remainingChildren = err.children.slice( 0, err.children.length - 1 ); return WebpackOptionsValidationError.formatValidationError( Object.assign({}, lastChild, { children: remainingChildren, parentSchema: Object.assign( {}, err.parentSchema, lastChild.parentSchema ) }) ); } return ( `${dataPath} should be one of these:\n${getSchemaPartText( err.parentSchema )}\n` + `Details:\n${filterChildren(err.children) .map( err => " * " + indent( WebpackOptionsValidationError.formatValidationError(err), " ", false ) ) .join("\n")}` ); } return `${dataPath} should be one of these:\n${getSchemaPartText( err.parentSchema )}`; } else if (err.keyword === "enum") { if ( err.parentSchema && err.parentSchema.enum && err.parentSchema.enum.length === 1 ) { return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`; } return `${dataPath} should be one of these:\n${getSchemaPartText( err.parentSchema )}`; } else if (err.keyword === "allOf") { return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`; } else if (err.keyword === "type") { switch (err.params.type) { case "object": return `${dataPath} should be an object.${getSchemaPartDescription( err.parentSchema )}`; case "string": return `${dataPath} should be a string.${getSchemaPartDescription( err.parentSchema )}`; case "boolean": return `${dataPath} should be a boolean.${getSchemaPartDescription( err.parentSchema )}`; case "number": return `${dataPath} should be a number.${getSchemaPartDescription( err.parentSchema )}`; case "array": return `${dataPath} should be an array:\n${getSchemaPartText( err.parentSchema )}`; } return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText( err.parentSchema )}`; } else if (err.keyword === "instanceof") { return `${dataPath} should be an instance of ${getSchemaPartText( err.parentSchema )}`; } else if (err.keyword === "required") { const missingProperty = err.params.missingProperty.replace(/^\./, ""); return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText( err.parentSchema, ["properties", missingProperty] )}`; } else if (err.keyword === "minimum") { return `${dataPath} ${err.message}.${getSchemaPartDescription( err.parentSchema )}`; } else if (err.keyword === "uniqueItems") { return `${dataPath} should not contain the item '${ err.data[err.params.i] }' twice.${getSchemaPartDescription(err.parentSchema)}`; } else if ( err.keyword === "minLength" || err.keyword === "minItems" || err.keyword === "minProperties" ) { if (err.params.limit === 1) { return `${dataPath} should not be empty.${getSchemaPartDescription( err.parentSchema )}`; } else { return `${dataPath} ${err.message}${getSchemaPartDescription( err.parentSchema )}`; } } else if (err.keyword === "absolutePath") { const baseMessage = `${dataPath}: ${ err.message }${getSchemaPartDescription(err.parentSchema)}`; if (dataPath === "configuration.output.filename") { return ( `${baseMessage}\n` + "Please use output.path to specify absolute path and output.filename for the file name." ); } return baseMessage; } else { return `${dataPath} ${err.message} (${JSON.stringify( err, null, 2 )}).\n${getSchemaPartText(err.parentSchema)}`; } } } module.exports = WebpackOptionsValidationError; webpack-4.30.0/lib/compareLocations.js000066400000000000000000000024441345416772700176440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ // TODO webpack 5 remove string type from a and b /** * Compare two locations * @param {string|DependencyLocation} a A location node * @param {string|DependencyLocation} b A location node * @returns {-1|0|1} sorting comparator value */ module.exports = (a, b) => { if (typeof a === "string") { if (typeof b === "string") { if (a < b) return -1; if (a > b) return 1; return 0; } else if (typeof b === "object") { return 1; } else { return 0; } } else if (typeof a === "object") { if (typeof b === "string") { return -1; } else if (typeof b === "object") { if ("start" in a && "start" in b) { const ap = a.start; const bp = b.start; if (ap.line < bp.line) return -1; if (ap.line > bp.line) return 1; if (ap.column < bp.column) return -1; if (ap.column > bp.column) return 1; } if ("name" in a && "name" in b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; } if ("index" in a && "index" in b) { if (a.index < b.index) return -1; if (a.index > b.index) return 1; } return 0; } else { return 0; } } }; webpack-4.30.0/lib/debug/000077500000000000000000000000001345416772700150665ustar00rootroot00000000000000webpack-4.30.0/lib/debug/ProfilingPlugin.js000066400000000000000000000230061345416772700205350ustar00rootroot00000000000000const fs = require("fs"); const path = require("path"); const mkdirp = require("mkdirp"); const { Tracer } = require("chrome-trace-event"); const validateOptions = require("schema-utils"); const schema = require("../../schemas/plugins/debug/ProfilingPlugin.json"); /** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ let inspector = undefined; try { // eslint-disable-next-line node/no-unsupported-features/node-builtins inspector = require("inspector"); } catch (e) { console.log("Unable to CPU profile in < node 8.0"); } class Profiler { constructor(inspector) { this.session = undefined; this.inspector = inspector; } hasSession() { return this.session !== undefined; } startProfiling() { if (this.inspector === undefined) { return Promise.resolve(); } try { this.session = new inspector.Session(); this.session.connect(); } catch (_) { this.session = undefined; return Promise.resolve(); } return Promise.all([ this.sendCommand("Profiler.setSamplingInterval", { interval: 100 }), this.sendCommand("Profiler.enable"), this.sendCommand("Profiler.start") ]); } sendCommand(method, params) { if (this.hasSession()) { return new Promise((res, rej) => { return this.session.post(method, params, (err, params) => { if (err !== null) { rej(err); } else { res(params); } }); }); } else { return Promise.resolve(); } } destroy() { if (this.hasSession()) { this.session.disconnect(); } return Promise.resolve(); } stopProfiling() { return this.sendCommand("Profiler.stop"); } } /** * @typedef {Object} Trace * @description an object that wraps Tracer and Profiler with a counter * @property {Tracer} trace instance of Tracer * @property {number} counter Counter * @property {Profiler} profiler instance of Profiler * @property {Function} end the end function */ /** * @param {string} outputPath The location where to write the log. * @returns {Trace} The trace object */ const createTrace = outputPath => { const trace = new Tracer({ noStream: true }); const profiler = new Profiler(inspector); if (/\/|\\/.test(outputPath)) { const dirPath = path.dirname(outputPath); mkdirp.sync(dirPath); } const fsStream = fs.createWriteStream(outputPath); let counter = 0; trace.pipe(fsStream); // These are critical events that need to be inserted so that tools like // chrome dev tools can load the profile. trace.instantEvent({ name: "TracingStartedInPage", id: ++counter, cat: ["disabled-by-default-devtools.timeline"], args: { data: { sessionId: "-1", page: "0xfff", frames: [ { frame: "0xfff", url: "webpack", name: "" } ] } } }); trace.instantEvent({ name: "TracingStartedInBrowser", id: ++counter, cat: ["disabled-by-default-devtools.timeline"], args: { data: { sessionId: "-1" } } }); return { trace, counter, profiler, end: callback => { // Wait until the write stream finishes. fsStream.on("finish", () => { callback(); }); // Tear down the readable trace stream. trace.push(null); } }; }; const pluginName = "ProfilingPlugin"; class ProfilingPlugin { /** * @param {ProfilingPluginOptions=} opts options object */ constructor(opts) { validateOptions(schema, opts || {}, "Profiling plugin"); opts = opts || {}; this.outputPath = opts.outputPath || "events.json"; } apply(compiler) { const tracer = createTrace(this.outputPath); tracer.profiler.startProfiling(); // Compiler Hooks Object.keys(compiler.hooks).forEach(hookName => { compiler.hooks[hookName].intercept( makeInterceptorFor("Compiler", tracer)(hookName) ); }); Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { compiler.resolverFactory.hooks[hookName].intercept( makeInterceptorFor("Resolver", tracer)(hookName) ); }); compiler.hooks.compilation.tap( pluginName, (compilation, { normalModuleFactory, contextModuleFactory }) => { interceptAllHooksFor(compilation, tracer, "Compilation"); interceptAllHooksFor( normalModuleFactory, tracer, "Normal Module Factory" ); interceptAllHooksFor( contextModuleFactory, tracer, "Context Module Factory" ); interceptAllParserHooks(normalModuleFactory, tracer); interceptTemplateInstancesFrom(compilation, tracer); } ); // We need to write out the CPU profile when we are all done. compiler.hooks.done.tapAsync( { name: pluginName, stage: Infinity }, (stats, callback) => { tracer.profiler.stopProfiling().then(parsedResults => { if (parsedResults === undefined) { tracer.profiler.destroy(); tracer.trace.flush(); tracer.end(callback); return; } const cpuStartTime = parsedResults.profile.startTime; const cpuEndTime = parsedResults.profile.endTime; tracer.trace.completeEvent({ name: "TaskQueueManager::ProcessTaskFromWorkQueue", id: ++tracer.counter, cat: ["toplevel"], ts: cpuStartTime, args: { src_file: "../../ipc/ipc_moji_bootstrap.cc", src_func: "Accept" } }); tracer.trace.completeEvent({ name: "EvaluateScript", id: ++tracer.counter, cat: ["devtools.timeline"], ts: cpuStartTime, dur: cpuEndTime - cpuStartTime, args: { data: { url: "webpack", lineNumber: 1, columnNumber: 1, frame: "0xFFF" } } }); tracer.trace.instantEvent({ name: "CpuProfile", id: ++tracer.counter, cat: ["disabled-by-default-devtools.timeline"], ts: cpuEndTime, args: { data: { cpuProfile: parsedResults.profile } } }); tracer.profiler.destroy(); tracer.trace.flush(); tracer.end(callback); }); } ); } } const interceptTemplateInstancesFrom = (compilation, tracer) => { const { mainTemplate, chunkTemplate, hotUpdateChunkTemplate, moduleTemplates } = compilation; const { javascript, webassembly } = moduleTemplates; [ { instance: mainTemplate, name: "MainTemplate" }, { instance: chunkTemplate, name: "ChunkTemplate" }, { instance: hotUpdateChunkTemplate, name: "HotUpdateChunkTemplate" }, { instance: javascript, name: "JavaScriptModuleTemplate" }, { instance: webassembly, name: "WebAssemblyModuleTemplate" } ].forEach(templateObject => { Object.keys(templateObject.instance.hooks).forEach(hookName => { templateObject.instance.hooks[hookName].intercept( makeInterceptorFor(templateObject.name, tracer)(hookName) ); }); }); }; const interceptAllHooksFor = (instance, tracer, logLabel) => { if (Reflect.has(instance, "hooks")) { Object.keys(instance.hooks).forEach(hookName => { instance.hooks[hookName].intercept( makeInterceptorFor(logLabel, tracer)(hookName) ); }); } }; const interceptAllParserHooks = (moduleFactory, tracer) => { const moduleTypes = [ "javascript/auto", "javascript/dynamic", "javascript/esm", "json", "webassembly/experimental" ]; moduleTypes.forEach(moduleType => { moduleFactory.hooks.parser .for(moduleType) .tap("ProfilingPlugin", (parser, parserOpts) => { interceptAllHooksFor(parser, tracer, "Parser"); }); }); }; const makeInterceptorFor = (instance, tracer) => hookName => ({ register: ({ name, type, context, fn }) => { const newFn = makeNewProfiledTapFn(hookName, tracer, { name, type, fn }); return { name, type, context, fn: newFn }; } }); // TODO improve typing /** @typedef {(...args: TODO[]) => void | Promise} PluginFunction */ /** * @param {string} hookName Name of the hook to profile. * @param {Trace} tracer The trace object. * @param {object} options Options for the profiled fn. * @param {string} options.name Plugin name * @param {string} options.type Plugin type (sync | async | promise) * @param {PluginFunction} options.fn Plugin function * @returns {PluginFunction} Chainable hooked function. */ const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { const defaultCategory = ["blink.user_timing"]; switch (type) { case "promise": return (...args) => { const id = ++tracer.counter; tracer.trace.begin({ name, id, cat: defaultCategory }); const promise = /** @type {Promise<*>} */ (fn(...args)); return promise.then(r => { tracer.trace.end({ name, id, cat: defaultCategory }); return r; }); }; case "async": return (...args) => { const id = ++tracer.counter; tracer.trace.begin({ name, id, cat: defaultCategory }); fn(...args, (...r) => { const callback = args.pop(); tracer.trace.end({ name, id, cat: defaultCategory }); callback(...r); }); }; case "sync": return (...args) => { const id = ++tracer.counter; // Do not instrument ourself due to the CPU // profile needing to be the last event in the trace. if (name === pluginName) { return fn(...args); } tracer.trace.begin({ name, id, cat: defaultCategory }); let r; try { r = fn(...args); } catch (error) { tracer.trace.end({ name, id, cat: defaultCategory }); throw error; } tracer.trace.end({ name, id, cat: defaultCategory }); return r; }; default: break; } }; module.exports = ProfilingPlugin; module.exports.Profiler = Profiler; webpack-4.30.0/lib/dependencies/000077500000000000000000000000001345416772700164265ustar00rootroot00000000000000webpack-4.30.0/lib/dependencies/AMDDefineDependency.js000066400000000000000000000123651345416772700225060ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class AMDDefineDependency extends NullDependency { constructor(range, arrayRange, functionRange, objectRange, namedModule) { super(); this.range = range; this.arrayRange = arrayRange; this.functionRange = functionRange; this.objectRange = objectRange; this.namedModule = namedModule; this.localModule = null; } get type() { return "amd define"; } } AMDDefineDependency.Template = class AMDDefineDependencyTemplate { get definitions() { return { f: [ "var __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], o: ["", "!(module.exports = #)"], of: [ "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], af: [ "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], ao: ["", "!(#, module.exports = #)"], aof: [ "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], lf: [ "var XXX, XXXmodule;", "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))" ], lo: ["var XXX;", "!(XXX = #)"], lof: [ "var XXX, XXXfactory, XXXmodule;", "!(XXXfactory = (#), (XXXmodule = { id: YYY, exports: {}, loaded: false }), XXX = (typeof XXXfactory === 'function' ? (XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)) : XXXfactory), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports))" ], laf: [ "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;", "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = ((#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))" ], lao: ["var XXX;", "!(#, XXX = #)"], laof: [ "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_FACTORY__, XXX;", `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), XXX = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__))` ] }; } apply(dependency, source) { const branch = this.branch(dependency); const defAndText = this.definitions[branch]; const definitions = defAndText[0]; const text = defAndText[1]; this.replace(dependency, source, definitions, text); } localModuleVar(dependency) { return ( dependency.localModule && dependency.localModule.used && dependency.localModule.variableName() ); } branch(dependency) { const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; const arrayRange = dependency.arrayRange ? "a" : ""; const objectRange = dependency.objectRange ? "o" : ""; const functionRange = dependency.functionRange ? "f" : ""; return localModuleVar + arrayRange + objectRange + functionRange; } replace(dependency, source, definition, text) { const localModuleVar = this.localModuleVar(dependency); if (localModuleVar) { text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); definition = definition.replace( /XXX/g, localModuleVar.replace(/\$/g, "$$$$") ); } if (dependency.namedModule) { text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); } const texts = text.split("#"); if (definition) source.insert(0, definition); let current = dependency.range[0]; if (dependency.arrayRange) { source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); current = dependency.arrayRange[1]; } if (dependency.objectRange) { source.replace(current, dependency.objectRange[0] - 1, texts.shift()); current = dependency.objectRange[1]; } else if (dependency.functionRange) { source.replace(current, dependency.functionRange[0] - 1, texts.shift()); current = dependency.functionRange[1]; } source.replace(current, dependency.range[1] - 1, texts.shift()); if (texts.length > 0) throw new Error("Implementation error"); } }; module.exports = AMDDefineDependency; webpack-4.30.0/lib/dependencies/AMDDefineDependencyParserPlugin.js000066400000000000000000000221021345416772700250300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const AMDRequireItemDependency = require("./AMDRequireItemDependency"); const AMDRequireContextDependency = require("./AMDRequireContextDependency"); const ConstDependency = require("./ConstDependency"); const AMDDefineDependency = require("./AMDDefineDependency"); const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); const LocalModuleDependency = require("./LocalModuleDependency"); const ContextDependencyHelpers = require("./ContextDependencyHelpers"); const LocalModulesHelpers = require("./LocalModulesHelpers"); const isBoundFunctionExpression = expr => { if (expr.type !== "CallExpression") return false; if (expr.callee.type !== "MemberExpression") return false; if (expr.callee.computed) return false; if (expr.callee.object.type !== "FunctionExpression") return false; if (expr.callee.property.type !== "Identifier") return false; if (expr.callee.property.name !== "bind") return false; return true; }; const isUnboundFunctionExpression = expr => { if (expr.type === "FunctionExpression") return true; if (expr.type === "ArrowFunctionExpression") return true; return false; }; const isCallable = expr => { if (isUnboundFunctionExpression(expr)) return true; if (isBoundFunctionExpression(expr)) return true; return false; }; class AMDDefineDependencyParserPlugin { constructor(options) { this.options = options; } apply(parser) { parser.hooks.call .for("define") .tap( "AMDDefineDependencyParserPlugin", this.processCallDefine.bind(this, parser) ); } processArray(parser, expr, param, identifiers, namedModule) { if (param.isArray()) { param.items.forEach((param, idx) => { if ( param.isString() && ["require", "module", "exports"].includes(param.string) ) identifiers[idx] = param.string; const result = this.processItem(parser, expr, param, namedModule); if (result === undefined) { this.processContext(parser, expr, param); } }); return true; } else if (param.isConstArray()) { const deps = []; param.array.forEach((request, idx) => { let dep; let localModule; if (request === "require") { identifiers[idx] = request; dep = "__webpack_require__"; } else if (["exports", "module"].includes(request)) { identifiers[idx] = request; dep = request; } else if ( (localModule = LocalModulesHelpers.getLocalModule( parser.state, request )) ) { dep = new LocalModuleDependency(localModule, undefined, false); dep.loc = expr.loc; parser.state.current.addDependency(dep); } else { dep = this.newRequireItemDependency(request); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); } deps.push(dep); }); const dep = this.newRequireArrayDependency(deps, param.range); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } } processItem(parser, expr, param, namedModule) { if (param.isConditional()) { param.options.forEach(param => { const result = this.processItem(parser, expr, param); if (result === undefined) { this.processContext(parser, expr, param); } }); return true; } else if (param.isString()) { let dep, localModule; if (param.string === "require") { dep = new ConstDependency("__webpack_require__", param.range); } else if (["require", "exports", "module"].includes(param.string)) { dep = new ConstDependency(param.string, param.range); } else if ( (localModule = LocalModulesHelpers.getLocalModule( parser.state, param.string, namedModule )) ) { dep = new LocalModuleDependency(localModule, param.range, false); } else { dep = this.newRequireItemDependency(param.string, param.range); } dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } } processContext(parser, expr, param) { const dep = ContextDependencyHelpers.create( AMDRequireContextDependency, param.range, param, expr, this.options, {}, parser ); if (!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } processCallDefine(parser, expr) { let array, fn, obj, namedModule; switch (expr.arguments.length) { case 1: if (isCallable(expr.arguments[0])) { // define(f() {…}) fn = expr.arguments[0]; } else if (expr.arguments[0].type === "ObjectExpression") { // define({…}) obj = expr.arguments[0]; } else { // define(expr) // unclear if function or object obj = fn = expr.arguments[0]; } break; case 2: if (expr.arguments[0].type === "Literal") { namedModule = expr.arguments[0].value; // define("…", …) if (isCallable(expr.arguments[1])) { // define("…", f() {…}) fn = expr.arguments[1]; } else if (expr.arguments[1].type === "ObjectExpression") { // define("…", {…}) obj = expr.arguments[1]; } else { // define("…", expr) // unclear if function or object obj = fn = expr.arguments[1]; } } else { array = expr.arguments[0]; if (isCallable(expr.arguments[1])) { // define([…], f() {}) fn = expr.arguments[1]; } else if (expr.arguments[1].type === "ObjectExpression") { // define([…], {…}) obj = expr.arguments[1]; } else { // define([…], expr) // unclear if function or object obj = fn = expr.arguments[1]; } } break; case 3: // define("…", […], f() {…}) namedModule = expr.arguments[0].value; array = expr.arguments[1]; if (isCallable(expr.arguments[2])) { // define("…", […], f() {}) fn = expr.arguments[2]; } else if (expr.arguments[2].type === "ObjectExpression") { // define("…", […], {…}) obj = expr.arguments[2]; } else { // define("…", […], expr) // unclear if function or object obj = fn = expr.arguments[2]; } break; default: return; } let fnParams = null; let fnParamsOffset = 0; if (fn) { if (isUnboundFunctionExpression(fn)) { fnParams = fn.params; } else if (isBoundFunctionExpression(fn)) { fnParams = fn.callee.object.params; fnParamsOffset = fn.arguments.length - 1; if (fnParamsOffset < 0) { fnParamsOffset = 0; } } } let fnRenames = parser.scope.renames.createChild(); if (array) { const identifiers = {}; const param = parser.evaluateExpression(array); const result = this.processArray( parser, expr, param, identifiers, namedModule ); if (!result) return; if (fnParams) { fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { if (identifiers[idx]) { fnRenames.set(param.name, identifiers[idx]); return false; } return true; }); } } else { const identifiers = ["require", "exports", "module"]; if (fnParams) { fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { if (identifiers[idx]) { fnRenames.set(param.name, identifiers[idx]); return false; } return true; }); } } let inTry; if (fn && isUnboundFunctionExpression(fn)) { inTry = parser.scope.inTry; parser.inScope(fnParams, () => { parser.scope.renames = fnRenames; parser.scope.inTry = inTry; if (fn.body.type === "BlockStatement") { parser.walkStatement(fn.body); } else { parser.walkExpression(fn.body); } }); } else if (fn && isBoundFunctionExpression(fn)) { inTry = parser.scope.inTry; parser.inScope( fn.callee.object.params.filter( i => !["require", "module", "exports"].includes(i.name) ), () => { parser.scope.renames = fnRenames; parser.scope.inTry = inTry; if (fn.callee.object.body.type === "BlockStatement") { parser.walkStatement(fn.callee.object.body); } else { parser.walkExpression(fn.callee.object.body); } } ); if (fn.arguments) { parser.walkExpressions(fn.arguments); } } else if (fn || obj) { parser.walkExpression(fn || obj); } const dep = this.newDefineDependency( expr.range, array ? array.range : null, fn ? fn.range : null, obj ? obj.range : null, namedModule ? namedModule : null ); dep.loc = expr.loc; if (namedModule) { dep.localModule = LocalModulesHelpers.addLocalModule( parser.state, namedModule ); } parser.state.current.addDependency(dep); return true; } newDefineDependency( range, arrayRange, functionRange, objectRange, namedModule ) { return new AMDDefineDependency( range, arrayRange, functionRange, objectRange, namedModule ); } newRequireArrayDependency(depsArray, range) { return new AMDRequireArrayDependency(depsArray, range); } newRequireItemDependency(request, range) { return new AMDRequireItemDependency(request, range); } } module.exports = AMDDefineDependencyParserPlugin; webpack-4.30.0/lib/dependencies/AMDPlugin.js000066400000000000000000000152061345416772700205500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const AMDRequireDependency = require("./AMDRequireDependency"); const AMDRequireItemDependency = require("./AMDRequireItemDependency"); const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); const AMDRequireContextDependency = require("./AMDRequireContextDependency"); const AMDDefineDependency = require("./AMDDefineDependency"); const UnsupportedDependency = require("./UnsupportedDependency"); const LocalModuleDependency = require("./LocalModuleDependency"); const NullFactory = require("../NullFactory"); const AMDRequireDependenciesBlockParserPlugin = require("./AMDRequireDependenciesBlockParserPlugin"); const AMDDefineDependencyParserPlugin = require("./AMDDefineDependencyParserPlugin"); const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin"); const ParserHelpers = require("../ParserHelpers"); class AMDPlugin { constructor(options, amdOptions) { this.amdOptions = amdOptions; this.options = options; } apply(compiler) { const options = this.options; const amdOptions = this.amdOptions; compiler.hooks.compilation.tap( "AMDPlugin", (compilation, { contextModuleFactory, normalModuleFactory }) => { compilation.dependencyFactories.set( AMDRequireDependency, new NullFactory() ); compilation.dependencyTemplates.set( AMDRequireDependency, new AMDRequireDependency.Template() ); compilation.dependencyFactories.set( AMDRequireItemDependency, normalModuleFactory ); compilation.dependencyTemplates.set( AMDRequireItemDependency, new AMDRequireItemDependency.Template() ); compilation.dependencyFactories.set( AMDRequireArrayDependency, new NullFactory() ); compilation.dependencyTemplates.set( AMDRequireArrayDependency, new AMDRequireArrayDependency.Template() ); compilation.dependencyFactories.set( AMDRequireContextDependency, contextModuleFactory ); compilation.dependencyTemplates.set( AMDRequireContextDependency, new AMDRequireContextDependency.Template() ); compilation.dependencyFactories.set( AMDDefineDependency, new NullFactory() ); compilation.dependencyTemplates.set( AMDDefineDependency, new AMDDefineDependency.Template() ); compilation.dependencyFactories.set( UnsupportedDependency, new NullFactory() ); compilation.dependencyTemplates.set( UnsupportedDependency, new UnsupportedDependency.Template() ); compilation.dependencyFactories.set( LocalModuleDependency, new NullFactory() ); compilation.dependencyTemplates.set( LocalModuleDependency, new LocalModuleDependency.Template() ); const handler = (parser, parserOptions) => { if (parserOptions.amd !== undefined && !parserOptions.amd) return; const setExpressionToModule = (outerExpr, module) => { parser.hooks.expression.for(outerExpr).tap("AMDPlugin", expr => { const dep = new AMDRequireItemDependency(module, expr.range); dep.userRequest = outerExpr; dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; }); }; new AMDRequireDependenciesBlockParserPlugin(options).apply(parser); new AMDDefineDependencyParserPlugin(options).apply(parser); setExpressionToModule("require.amd", "!!webpack amd options"); setExpressionToModule("define.amd", "!!webpack amd options"); setExpressionToModule("define", "!!webpack amd define"); parser.hooks.expression .for("__webpack_amd_options__") .tap("AMDPlugin", () => parser.state.current.addVariable( "__webpack_amd_options__", JSON.stringify(amdOptions) ) ); parser.hooks.evaluateTypeof .for("define.amd") .tap( "AMDPlugin", ParserHelpers.evaluateToString(typeof amdOptions) ); parser.hooks.evaluateTypeof .for("require.amd") .tap( "AMDPlugin", ParserHelpers.evaluateToString(typeof amdOptions) ); parser.hooks.evaluateIdentifier .for("define.amd") .tap( "AMDPlugin", ParserHelpers.evaluateToIdentifier("define.amd", true) ); parser.hooks.evaluateIdentifier .for("require.amd") .tap( "AMDPlugin", ParserHelpers.evaluateToIdentifier("require.amd", true) ); parser.hooks.typeof .for("define") .tap( "AMDPlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("function") ) ); parser.hooks.evaluateTypeof .for("define") .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); parser.hooks.canRename .for("define") .tap("AMDPlugin", ParserHelpers.approve); parser.hooks.rename.for("define").tap("AMDPlugin", expr => { const dep = new AMDRequireItemDependency( "!!webpack amd define", expr.range ); dep.userRequest = "define"; dep.loc = expr.loc; parser.state.current.addDependency(dep); return false; }); parser.hooks.typeof .for("require") .tap( "AMDPlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("function") ) ); parser.hooks.evaluateTypeof .for("require") .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("AMDPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("AMDPlugin", handler); } ); compiler.hooks.afterResolvers.tap("AMDPlugin", () => { compiler.resolverFactory.hooks.resolver .for("normal") .tap("AMDPlugin", resolver => { new AliasPlugin( "described-resolve", { name: "amdefine", alias: path.join( __dirname, "..", "..", "buildin", "amd-define.js" ) }, "resolve" ).apply(resolver); new AliasPlugin( "described-resolve", { name: "webpack amd options", alias: path.join( __dirname, "..", "..", "buildin", "amd-options.js" ) }, "resolve" ).apply(resolver); new AliasPlugin( "described-resolve", { name: "webpack amd define", alias: path.join( __dirname, "..", "..", "buildin", "amd-define.js" ) }, "resolve" ).apply(resolver); }); }); } } module.exports = AMDPlugin; webpack-4.30.0/lib/dependencies/AMDRequireArrayDependency.js000066400000000000000000000020751345416772700237240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); class AMDRequireArrayDependency extends Dependency { constructor(depsArray, range) { super(); this.depsArray = depsArray; this.range = range; } get type() { return "amd require array"; } } AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate { apply(dep, source, runtime) { const content = this.getContent(dep, runtime); source.replace(dep.range[0], dep.range[1] - 1, content); } getContent(dep, runtime) { const requires = dep.depsArray.map(dependency => { return this.contentForDependency(dependency, runtime); }); return `[${requires.join(", ")}]`; } contentForDependency(dep, runtime) { if (typeof dep === "string") { return dep; } if (dep.localModule) { return dep.localModule.variableName(); } else { return runtime.moduleExports({ module: dep.module, request: dep.request }); } } }; module.exports = AMDRequireArrayDependency; webpack-4.30.0/lib/dependencies/AMDRequireContextDependency.js000066400000000000000000000010371345416772700242670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); class AMDRequireContextDependency extends ContextDependency { constructor(options, range, valueRange) { super(options); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } } AMDRequireContextDependency.Template = require("./ContextDependencyTemplateAsRequireCall"); module.exports = AMDRequireContextDependency; webpack-4.30.0/lib/dependencies/AMDRequireDependenciesBlock.js000066400000000000000000000023721345416772700242100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); const AMDRequireDependency = require("./AMDRequireDependency"); module.exports = class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { constructor( expr, arrayRange, functionRange, errorCallbackRange, module, loc, request ) { super(null, module, loc, request); this.expr = expr; this.outerRange = expr.range; this.arrayRange = arrayRange; this.functionBindThis = false; this.functionRange = functionRange; this.errorCallbackBindThis = false; this.errorCallbackRange = errorCallbackRange; this.bindThis = true; if (arrayRange && functionRange && errorCallbackRange) { this.range = [arrayRange[0], errorCallbackRange[1]]; } else if (arrayRange && functionRange) { this.range = [arrayRange[0], functionRange[1]]; } else if (arrayRange) { this.range = arrayRange; } else if (functionRange) { this.range = functionRange; } else { this.range = expr.range; } const dep = this.newRequireDependency(); dep.loc = loc; this.addDependency(dep); } newRequireDependency() { return new AMDRequireDependency(this); } }; webpack-4.30.0/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js000066400000000000000000000161771345416772700265540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const AMDRequireItemDependency = require("./AMDRequireItemDependency"); const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); const AMDRequireContextDependency = require("./AMDRequireContextDependency"); const AMDRequireDependenciesBlock = require("./AMDRequireDependenciesBlock"); const UnsupportedDependency = require("./UnsupportedDependency"); const LocalModuleDependency = require("./LocalModuleDependency"); const ContextDependencyHelpers = require("./ContextDependencyHelpers"); const LocalModulesHelpers = require("./LocalModulesHelpers"); const ConstDependency = require("./ConstDependency"); const getFunctionExpression = require("./getFunctionExpression"); const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); class AMDRequireDependenciesBlockParserPlugin { constructor(options) { this.options = options; } processFunctionArgument(parser, expression) { let bindThis = true; const fnData = getFunctionExpression(expression); if (fnData) { parser.inScope( fnData.fn.params.filter(i => { return !["require", "module", "exports"].includes(i.name); }), () => { if (fnData.fn.body.type === "BlockStatement") { parser.walkStatement(fnData.fn.body); } else { parser.walkExpression(fnData.fn.body); } } ); parser.walkExpressions(fnData.expressions); if (fnData.needThis === false) { bindThis = false; } } else { parser.walkExpression(expression); } return bindThis; } apply(parser) { parser.hooks.call .for("require") .tap( "AMDRequireDependenciesBlockParserPlugin", this.processCallRequire.bind(this, parser) ); } processArray(parser, expr, param) { if (param.isArray()) { for (const p of param.items) { const result = this.processItem(parser, expr, p); if (result === undefined) { this.processContext(parser, expr, p); } } return true; } else if (param.isConstArray()) { const deps = []; for (const request of param.array) { let dep, localModule; if (request === "require") { dep = "__webpack_require__"; } else if (["exports", "module"].includes(request)) { dep = request; } else if ( (localModule = LocalModulesHelpers.getLocalModule( parser.state, request )) ) { dep = new LocalModuleDependency(localModule, undefined, false); dep.loc = expr.loc; parser.state.current.addDependency(dep); } else { dep = this.newRequireItemDependency(request); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); } deps.push(dep); } const dep = this.newRequireArrayDependency(deps, param.range); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } } processItem(parser, expr, param) { if (param.isConditional()) { for (const p of param.options) { const result = this.processItem(parser, expr, p); if (result === undefined) { this.processContext(parser, expr, p); } } return true; } else if (param.isString()) { let dep, localModule; if (param.string === "require") { dep = new ConstDependency("__webpack_require__", param.string); } else if (param.string === "module") { dep = new ConstDependency( parser.state.module.buildInfo.moduleArgument, param.range ); } else if (param.string === "exports") { dep = new ConstDependency( parser.state.module.buildInfo.exportsArgument, param.range ); } else if ( (localModule = LocalModulesHelpers.getLocalModule( parser.state, param.string )) ) { dep = new LocalModuleDependency(localModule, param.range, false); } else { dep = this.newRequireItemDependency(param.string, param.range); } dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } } processContext(parser, expr, param) { const dep = ContextDependencyHelpers.create( AMDRequireContextDependency, param.range, param, expr, this.options, {}, parser ); if (!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } processArrayForRequestString(param) { if (param.isArray()) { const result = param.items.map(item => this.processItemForRequestString(item) ); if (result.every(Boolean)) return result.join(" "); } else if (param.isConstArray()) { return param.array.join(" "); } } processItemForRequestString(param) { if (param.isConditional()) { const result = param.options.map(item => this.processItemForRequestString(item) ); if (result.every(Boolean)) return result.join("|"); } else if (param.isString()) { return param.string; } } processCallRequire(parser, expr) { let param; let dep; let result; const old = parser.state.current; if (expr.arguments.length >= 1) { param = parser.evaluateExpression(expr.arguments[0]); dep = this.newRequireDependenciesBlock( expr, param.range, expr.arguments.length > 1 ? expr.arguments[1].range : null, expr.arguments.length > 2 ? expr.arguments[2].range : null, parser.state.module, expr.loc, this.processArrayForRequestString(param) ); parser.state.current = dep; } if (expr.arguments.length === 1) { parser.inScope([], () => { result = this.processArray(parser, expr, param); }); parser.state.current = old; if (!result) return; parser.state.current.addBlock(dep); return true; } if (expr.arguments.length === 2 || expr.arguments.length === 3) { try { parser.inScope([], () => { result = this.processArray(parser, expr, param); }); if (!result) { dep = new UnsupportedDependency("unsupported", expr.range); old.addDependency(dep); if (parser.state.module) { parser.state.module.errors.push( new UnsupportedFeatureWarning( parser.state.module, "Cannot statically analyse 'require(…, …)' in line " + expr.loc.start.line, expr.loc ) ); } dep = null; return true; } dep.functionBindThis = this.processFunctionArgument( parser, expr.arguments[1] ); if (expr.arguments.length === 3) { dep.errorCallbackBindThis = this.processFunctionArgument( parser, expr.arguments[2] ); } } finally { parser.state.current = old; if (dep) parser.state.current.addBlock(dep); } return true; } } newRequireDependenciesBlock( expr, arrayRange, functionRange, errorCallbackRange, module, loc, request ) { return new AMDRequireDependenciesBlock( expr, arrayRange, functionRange, errorCallbackRange, module, loc, request ); } newRequireItemDependency(request, range) { return new AMDRequireItemDependency(request, range); } newRequireArrayDependency(depsArray, range) { return new AMDRequireArrayDependency(depsArray, range); } } module.exports = AMDRequireDependenciesBlockParserPlugin; webpack-4.30.0/lib/dependencies/AMDRequireDependency.js000066400000000000000000000063231345416772700227250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class AMDRequireDependency extends NullDependency { constructor(block) { super(); this.block = block; } } AMDRequireDependency.Template = class AMDRequireDependencyTemplate { apply(dep, source, runtime) { const depBlock = dep.block; const promise = runtime.blockPromise({ block: depBlock, message: "AMD require" }); // has array range but no function range if (depBlock.arrayRange && !depBlock.functionRange) { const startBlock = `${promise}.then(function() {`; const endBlock = `;}).catch(${runtime.onError()})`; source.replace( depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock ); source.replace( depBlock.arrayRange[1], depBlock.outerRange[1] - 1, endBlock ); return; } // has function range but no array range if (depBlock.functionRange && !depBlock.arrayRange) { const startBlock = `${promise}.then((`; const endBlock = `).bind(exports, __webpack_require__, exports, module)).catch(${runtime.onError()})`; source.replace( depBlock.outerRange[0], depBlock.functionRange[0] - 1, startBlock ); source.replace( depBlock.functionRange[1], depBlock.outerRange[1] - 1, endBlock ); return; } // has array range, function range, and errorCallbackRange if ( depBlock.arrayRange && depBlock.functionRange && depBlock.errorCallbackRange ) { const startBlock = `${promise}.then(function() { `; const errorRangeBlock = `}${ depBlock.functionBindThis ? ".bind(this)" : "" }).catch(`; const endBlock = `${ depBlock.errorCallbackBindThis ? ".bind(this)" : "" })`; source.replace( depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock ); source.insert( depBlock.arrayRange[0] + 0.9, "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " ); source.replace( depBlock.arrayRange[1], depBlock.functionRange[0] - 1, "; (" ); source.insert( depBlock.functionRange[1], ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" ); source.replace( depBlock.functionRange[1], depBlock.errorCallbackRange[0] - 1, errorRangeBlock ); source.replace( depBlock.errorCallbackRange[1], depBlock.outerRange[1] - 1, endBlock ); return; } // has array range, function range, but no errorCallbackRange if (depBlock.arrayRange && depBlock.functionRange) { const startBlock = `${promise}.then(function() { `; const endBlock = `}${ depBlock.functionBindThis ? ".bind(this)" : "" }).catch(${runtime.onError()})`; source.replace( depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock ); source.insert( depBlock.arrayRange[0] + 0.9, "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " ); source.replace( depBlock.arrayRange[1], depBlock.functionRange[0] - 1, "; (" ); source.insert( depBlock.functionRange[1], ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" ); source.replace( depBlock.functionRange[1], depBlock.outerRange[1] - 1, endBlock ); } } }; module.exports = AMDRequireDependency; webpack-4.30.0/lib/dependencies/AMDRequireItemDependency.js000066400000000000000000000010571345416772700235430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); class AMDRequireItemDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "amd require"; } } AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; module.exports = AMDRequireItemDependency; webpack-4.30.0/lib/dependencies/CommonJsPlugin.js000066400000000000000000000115541345416772700216760ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./ConstDependency"); const CommonJsRequireDependency = require("./CommonJsRequireDependency"); const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency"); const RequireResolveDependency = require("./RequireResolveDependency"); const RequireResolveContextDependency = require("./RequireResolveContextDependency"); const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency"); const RequireHeaderDependency = require("./RequireHeaderDependency"); const NullFactory = require("../NullFactory"); const RequireResolveDependencyParserPlugin = require("./RequireResolveDependencyParserPlugin"); const CommonJsRequireDependencyParserPlugin = require("./CommonJsRequireDependencyParserPlugin"); const ParserHelpers = require("../ParserHelpers"); class CommonJsPlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap( "CommonJsPlugin", (compilation, { contextModuleFactory, normalModuleFactory }) => { compilation.dependencyFactories.set( CommonJsRequireDependency, normalModuleFactory ); compilation.dependencyTemplates.set( CommonJsRequireDependency, new CommonJsRequireDependency.Template() ); compilation.dependencyFactories.set( CommonJsRequireContextDependency, contextModuleFactory ); compilation.dependencyTemplates.set( CommonJsRequireContextDependency, new CommonJsRequireContextDependency.Template() ); compilation.dependencyFactories.set( RequireResolveDependency, normalModuleFactory ); compilation.dependencyTemplates.set( RequireResolveDependency, new RequireResolveDependency.Template() ); compilation.dependencyFactories.set( RequireResolveContextDependency, contextModuleFactory ); compilation.dependencyTemplates.set( RequireResolveContextDependency, new RequireResolveContextDependency.Template() ); compilation.dependencyFactories.set( RequireResolveHeaderDependency, new NullFactory() ); compilation.dependencyTemplates.set( RequireResolveHeaderDependency, new RequireResolveHeaderDependency.Template() ); compilation.dependencyFactories.set( RequireHeaderDependency, new NullFactory() ); compilation.dependencyTemplates.set( RequireHeaderDependency, new RequireHeaderDependency.Template() ); const handler = (parser, parserOptions) => { if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) return; const requireExpressions = [ "require", "require.resolve", "require.resolveWeak" ]; for (let expression of requireExpressions) { parser.hooks.typeof .for(expression) .tap( "CommonJsPlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("function") ) ); parser.hooks.evaluateTypeof .for(expression) .tap( "CommonJsPlugin", ParserHelpers.evaluateToString("function") ); parser.hooks.evaluateIdentifier .for(expression) .tap( "CommonJsPlugin", ParserHelpers.evaluateToIdentifier(expression, true) ); } parser.hooks.evaluateTypeof .for("module") .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { // to not leak to global "require", we need to define a local require here. const dep = new ConstDependency("var require;", 0); dep.loc = expr.loc; parser.state.current.addDependency(dep); parser.scope.definitions.add("require"); return true; }); parser.hooks.canRename .for("require") .tap("CommonJsPlugin", () => true); parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { // define the require variable. It's still undefined, but not "not defined". const dep = new ConstDependency("var require;", 0); dep.loc = expr.loc; parser.state.current.addDependency(dep); return false; }); parser.hooks.typeof.for("module").tap("CommonJsPlugin", () => true); parser.hooks.evaluateTypeof .for("exports") .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); new CommonJsRequireDependencyParserPlugin(options).apply(parser); new RequireResolveDependencyParserPlugin(options).apply(parser); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("CommonJsPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("CommonJsPlugin", handler); } ); } } module.exports = CommonJsPlugin; webpack-4.30.0/lib/dependencies/CommonJsRequireContextDependency.js000066400000000000000000000012071345416772700254120ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class CommonJsRequireContextDependency extends ContextDependency { constructor(options, range, valueRange) { super(options); this.range = range; this.valueRange = valueRange; } get type() { return "cjs require context"; } } CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = CommonJsRequireContextDependency; webpack-4.30.0/lib/dependencies/CommonJsRequireDependency.js000066400000000000000000000010351345416772700240440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); class CommonJsRequireDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "cjs require"; } } CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; module.exports = CommonJsRequireDependency; webpack-4.30.0/lib/dependencies/CommonJsRequireDependencyParserPlugin.js000066400000000000000000000077521345416772700264140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const CommonJsRequireDependency = require("./CommonJsRequireDependency"); const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency"); const RequireHeaderDependency = require("./RequireHeaderDependency"); const LocalModuleDependency = require("./LocalModuleDependency"); const ContextDependencyHelpers = require("./ContextDependencyHelpers"); const LocalModulesHelpers = require("./LocalModulesHelpers"); const ParserHelpers = require("../ParserHelpers"); class CommonJsRequireDependencyParserPlugin { constructor(options) { this.options = options; } apply(parser) { const options = this.options; const processItem = (expr, param) => { if (param.isString()) { const dep = new CommonJsRequireDependency(param.string, param.range); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }; const processContext = (expr, param) => { const dep = ContextDependencyHelpers.create( CommonJsRequireContextDependency, expr.range, param, expr, options, {}, parser ); if (!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; }; parser.hooks.expression .for("require.cache") .tap( "CommonJsRequireDependencyParserPlugin", ParserHelpers.toConstantDependencyWithWebpackRequire( parser, "__webpack_require__.c" ) ); parser.hooks.expression .for("require") .tap("CommonJsRequireDependencyParserPlugin", expr => { const dep = new CommonJsRequireContextDependency( { request: options.unknownContextRequest, recursive: options.unknownContextRecursive, regExp: options.unknownContextRegExp, mode: "sync" }, expr.range ); dep.critical = options.unknownContextCritical && "require function is used in a way in which dependencies cannot be statically extracted"; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; }); const createHandler = callNew => expr => { if (expr.arguments.length !== 1) return; let localModule; const param = parser.evaluateExpression(expr.arguments[0]); if (param.isConditional()) { let isExpression = false; const prevLength = parser.state.current.dependencies.length; const dep = new RequireHeaderDependency(expr.callee.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); for (const p of param.options) { const result = processItem(expr, p); if (result === undefined) { isExpression = true; } } if (isExpression) { parser.state.current.dependencies.length = prevLength; } else { return true; } } if ( param.isString() && (localModule = LocalModulesHelpers.getLocalModule( parser.state, param.string )) ) { const dep = new LocalModuleDependency(localModule, expr.range, callNew); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; } else { const result = processItem(expr, param); if (result === undefined) { processContext(expr, param); } else { const dep = new RequireHeaderDependency(expr.callee.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); } return true; } }; parser.hooks.call .for("require") .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); parser.hooks.new .for("require") .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); parser.hooks.call .for("module.require") .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); parser.hooks.new .for("module.require") .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); } } module.exports = CommonJsRequireDependencyParserPlugin; webpack-4.30.0/lib/dependencies/ConstDependency.js000066400000000000000000000014111345416772700220460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class ConstDependency extends NullDependency { constructor(expression, range, requireWebpackRequire) { super(); this.expression = expression; this.range = range; this.requireWebpackRequire = requireWebpackRequire; } updateHash(hash) { hash.update(this.range + ""); hash.update(this.expression + ""); } } ConstDependency.Template = class ConstDependencyTemplate { apply(dep, source) { if (typeof dep.range === "number") { source.insert(dep.range, dep.expression); return; } source.replace(dep.range[0], dep.range[1] - 1, dep.expression); } }; module.exports = ConstDependency; webpack-4.30.0/lib/dependencies/ContextDependency.js000066400000000000000000000035031345416772700224100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); const CriticalDependencyWarning = require("./CriticalDependencyWarning"); const regExpToString = r => (r ? r + "" : ""); class ContextDependency extends Dependency { // options: { request, recursive, regExp, include, exclude, mode, chunkName, groupOptions } constructor(options) { super(); this.options = options; this.userRequest = this.options.request; /** @type {false | string} */ this.critical = false; this.hadGlobalOrStickyRegExp = false; if (this.options.regExp.global || this.options.regExp.sticky) { this.options.regExp = null; this.hadGlobalOrStickyRegExp = true; } } getResourceIdentifier() { return ( `context${this.options.request} ${this.options.recursive} ` + `${regExpToString(this.options.regExp)} ${regExpToString( this.options.include )} ${regExpToString(this.options.exclude)} ` + `${this.options.mode} ${this.options.chunkName} ` + `${JSON.stringify(this.options.groupOptions)}` ); } getWarnings() { let warnings = super.getWarnings() || []; if (this.critical) { warnings.push(new CriticalDependencyWarning(this.critical)); } if (this.hadGlobalOrStickyRegExp) { warnings.push( new CriticalDependencyWarning( "Contexts can't use RegExps with the 'g' or 'y' flags." ) ); } return warnings; } } // TODO remove in webpack 5 Object.defineProperty(ContextDependency.prototype, "async", { configurable: false, get() { throw new Error( "ContextDependency.async was removed. Use ContextDependency.options.mode instead." ); }, set() { throw new Error( "ContextDependency.async was removed. Pass options.mode to constructor instead" ); } }); module.exports = ContextDependency; webpack-4.30.0/lib/dependencies/ContextDependencyHelpers.js000066400000000000000000000130221345416772700237300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependencyHelpers = exports; /** * Escapes regular expression metacharacters * @param {string} str String to quote * @returns {string} Escaped string */ const quotemeta = str => { return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); }; const splitContextFromPrefix = prefix => { const idx = prefix.lastIndexOf("/"); let context = "."; if (idx >= 0) { context = prefix.substr(0, idx); prefix = `.${prefix.substr(idx)}`; } return { context, prefix }; }; const splitQueryFromPostfix = postfix => { const idx = postfix.indexOf("?"); let query = ""; if (idx >= 0) { query = postfix.substr(idx); postfix = postfix.substr(0, idx); } return { postfix, query }; }; ContextDependencyHelpers.create = ( Dep, range, param, expr, options, contextOptions, // when parser is not passed in, expressions won't be walked parser = null ) => { if (param.isTemplateString()) { let prefixRaw = param.quasis[0].string; let postfixRaw = param.quasis.length > 1 ? param.quasis[param.quasis.length - 1].string : ""; const valueRange = param.range; const { context, prefix } = splitContextFromPrefix(prefixRaw); const { postfix, query } = splitQueryFromPostfix(postfixRaw); // When there are more than two quasis, the generated RegExp can be more precise // We join the quasis with the expression regexp const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); const innerRegExp = options.wrappedContextRegExp.source + innerQuasis .map(q => quotemeta(q.string) + options.wrappedContextRegExp.source) .join(""); // Example: `./context/pre${e}inner${e}inner2${e}post?query` // context: "./context" // prefix: "./pre" // innerQuasis: [BEE("inner"), BEE("inner2")] // (BEE = BasicEvaluatedExpression) // postfix: "post" // query: "?query" // regExp: /^\.\/pre.*inner.*inner2.*post$/ const regExp = new RegExp( `^${quotemeta(prefix)}${innerRegExp}${quotemeta(postfix)}$` ); const dep = new Dep( Object.assign( { request: context + query, recursive: options.wrappedContextRecursive, regExp, mode: "sync" }, contextOptions ), range, valueRange ); dep.loc = expr.loc; const replaces = []; param.parts.forEach((part, i) => { if (i % 2 === 0) { // Quasis or merged quasi let range = part.range; let value = part.string; if (param.templateStringKind === "cooked") { value = JSON.stringify(value); value = value.slice(1, value.length - 1); } if (i === 0) { // prefix value = prefix; range = [param.range[0], part.range[1]]; value = (param.templateStringKind === "cooked" ? "`" : "String.raw`") + value; } else if (i === param.parts.length - 1) { // postfix value = postfix; range = [part.range[0], param.range[1]]; value = value + "`"; } else if ( part.expression && part.expression.type === "TemplateElement" && part.expression.value.raw === value ) { // Shortcut when it's a single quasi and doesn't need to be replaced return; } replaces.push({ range, value }); } else { // Expression if (parser) { parser.walkExpression(part.expression); } } }); dep.replaces = replaces; dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression"; return dep; } else if ( param.isWrapped() && ((param.prefix && param.prefix.isString()) || (param.postfix && param.postfix.isString())) ) { let prefixRaw = param.prefix && param.prefix.isString() ? param.prefix.string : ""; let postfixRaw = param.postfix && param.postfix.isString() ? param.postfix.string : ""; const prefixRange = param.prefix && param.prefix.isString() ? param.prefix.range : null; const postfixRange = param.postfix && param.postfix.isString() ? param.postfix.range : null; const valueRange = param.range; const { context, prefix } = splitContextFromPrefix(prefixRaw); const { postfix, query } = splitQueryFromPostfix(postfixRaw); const regExp = new RegExp( `^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta( postfix )}$` ); const dep = new Dep( Object.assign( { request: context + query, recursive: options.wrappedContextRecursive, regExp, mode: "sync" }, contextOptions ), range, valueRange ); dep.loc = expr.loc; const replaces = []; if (prefixRange) { replaces.push({ range: prefixRange, value: JSON.stringify(prefix) }); } if (postfixRange) { replaces.push({ range: postfixRange, value: JSON.stringify(postfix) }); } dep.replaces = replaces; dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression"; if (parser && param.wrappedInnerExpressions) { for (const part of param.wrappedInnerExpressions) { if (part.expression) parser.walkExpression(part.expression); } } return dep; } else { const dep = new Dep( Object.assign( { request: options.exprContextRequest, recursive: options.exprContextRecursive, regExp: options.exprContextRegExp, mode: "sync" }, contextOptions ), range, param.range ); dep.loc = expr.loc; dep.critical = options.exprContextCritical && "the request of a dependency is an expression"; if (parser) { parser.walkExpression(param.expression); } return dep; } }; webpack-4.30.0/lib/dependencies/ContextDependencyTemplateAsId.js000066400000000000000000000021121345416772700246400ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ContextDependencyTemplateAsId { apply(dep, source, runtime) { const moduleExports = runtime.moduleExports({ module: dep.module, request: dep.request }); if (dep.module) { if (dep.valueRange) { if (Array.isArray(dep.replaces)) { for (let i = 0; i < dep.replaces.length; i++) { const rep = dep.replaces[i]; source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); // TODO webpack 5 remove `prepend` it's no longer used source.replace( dep.range[0], dep.valueRange[0] - 1, `${moduleExports}.resolve(${ typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" }` ); } else { source.replace( dep.range[0], dep.range[1] - 1, `${moduleExports}.resolve` ); } } else { source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } } } module.exports = ContextDependencyTemplateAsId; webpack-4.30.0/lib/dependencies/ContextDependencyTemplateAsRequireCall.js000066400000000000000000000020621345416772700265200ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ContextDependencyTemplateAsRequireCall { apply(dep, source, runtime) { const moduleExports = runtime.moduleExports({ module: dep.module, request: dep.request }); if (dep.module) { if (dep.valueRange) { if (Array.isArray(dep.replaces)) { for (let i = 0; i < dep.replaces.length; i++) { const rep = dep.replaces[i]; source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); // TODO webpack 5 remove `prepend` it's no longer used source.replace( dep.range[0], dep.valueRange[0] - 1, `${moduleExports}(${ typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" }` ); } else { source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } } else { source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } } } module.exports = ContextDependencyTemplateAsRequireCall; webpack-4.30.0/lib/dependencies/ContextElementDependency.js000066400000000000000000000006671345416772700237320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class ContextElementDependency extends ModuleDependency { constructor(request, userRequest) { super(request); if (userRequest) { this.userRequest = userRequest; } } get type() { return "context element"; } } module.exports = ContextElementDependency; webpack-4.30.0/lib/dependencies/CriticalDependencyWarning.js000066400000000000000000000007051345416772700240450ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("../WebpackError"); class CriticalDependencyWarning extends WebpackError { constructor(message) { super(); this.name = "CriticalDependencyWarning"; this.message = "Critical dependency: " + message; Error.captureStackTrace(this, this.constructor); } } module.exports = CriticalDependencyWarning; webpack-4.30.0/lib/dependencies/DelegatedExportsDependency.js000066400000000000000000000012431345416772700242260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependencyReference = require("./DependencyReference"); const NullDependency = require("./NullDependency"); class DelegatedExportsDependency extends NullDependency { constructor(originModule, exports) { super(); this.originModule = originModule; this.exports = exports; } get type() { return "delegated exports"; } getReference() { return new DependencyReference(this.originModule, true, false); } getExports() { return { exports: this.exports, dependencies: undefined }; } } module.exports = DelegatedExportsDependency; webpack-4.30.0/lib/dependencies/DelegatedSourceDependency.js000066400000000000000000000005611345416772700240240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class DelegatedSourceDependency extends ModuleDependency { constructor(request) { super(request); } get type() { return "delegated source"; } } module.exports = DelegatedSourceDependency; webpack-4.30.0/lib/dependencies/DependencyReference.js000066400000000000000000000034001345416772700226560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Florent Cailhol @ooflorent */ "use strict"; /** @typedef {import("../Module")} Module */ class DependencyReference { // TODO webpack 5: module must be dynamic, you must pass a function returning a module // This is needed to remove the hack in ConcatenatedModule // The problem is that the `module` in Dependency could be replaced i. e. because of Scope Hoisting /** * * @param {Module} module the referenced module * @param {string[] | boolean} importedNames imported named from the module * @param {boolean=} weak if this is a weak reference * @param {number} order the order information or NaN if don't care */ constructor(module, importedNames, weak = false, order = NaN) { // TODO webpack 5: make it a getter this.module = module; // true: full object // false: only sideeffects/no export // array of strings: the exports with this names this.importedNames = importedNames; this.weak = !!weak; this.order = order; } /** * @param {DependencyReference[]} array an array (will be modified) * @returns {DependencyReference[]} the array again */ static sort(array) { /** @type {WeakMap} */ const originalOrder = new WeakMap(); let i = 0; for (const ref of array) { originalOrder.set(ref, i++); } return array.sort((a, b) => { const aOrder = a.order; const bOrder = b.order; if (isNaN(aOrder)) { if (!isNaN(bOrder)) { return 1; } } else { if (isNaN(bOrder)) { return -1; } if (aOrder !== bOrder) { return aOrder - bOrder; } } const aOrg = originalOrder.get(a); const bOrg = originalOrder.get(b); return aOrg - bOrg; }); } } module.exports = DependencyReference; webpack-4.30.0/lib/dependencies/DllEntryDependency.js000066400000000000000000000006071345416772700225230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); class DllEntryDependency extends Dependency { constructor(dependencies, name) { super(); this.dependencies = dependencies; this.name = name; } get type() { return "dll entry"; } } module.exports = DllEntryDependency; webpack-4.30.0/lib/dependencies/HarmonyAcceptDependency.js000066400000000000000000000022541345416772700235230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); const HarmonyImportDependency = require("./HarmonyImportDependency"); class HarmonyAcceptDependency extends NullDependency { constructor(range, dependencies, hasCallback) { super(); this.range = range; this.dependencies = dependencies; this.hasCallback = hasCallback; } get type() { return "accepted harmony modules"; } } HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate { apply(dep, source, runtime) { const content = dep.dependencies .filter(dependency => HarmonyImportDependency.Template.isImportEmitted(dependency, source) ) .map(dependency => dependency.getImportStatement(true, runtime)) .join(""); if (dep.hasCallback) { source.insert( dep.range[0], `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` ); source.insert( dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" ); return; } source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); } }; module.exports = HarmonyAcceptDependency; webpack-4.30.0/lib/dependencies/HarmonyAcceptImportDependency.js000066400000000000000000000011771345416772700247210ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyImportDependency = require("./HarmonyImportDependency"); class HarmonyAcceptImportDependency extends HarmonyImportDependency { constructor(request, originModule, parserScope) { super(request, originModule, NaN, parserScope); this.weak = true; } get type() { return "harmony accept"; } } HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends HarmonyImportDependency.Template { apply(dep, source, runtime) {} }; module.exports = HarmonyAcceptImportDependency; webpack-4.30.0/lib/dependencies/HarmonyCompatibilityDependency.js000066400000000000000000000014401345416772700251310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class HarmonyCompatibilityDependency extends NullDependency { constructor(originModule) { super(); this.originModule = originModule; } get type() { return "harmony export header"; } } HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate { apply(dep, source, runtime) { const usedExports = dep.originModule.usedExports; if (usedExports !== false && !Array.isArray(usedExports)) { const content = runtime.defineEsModuleFlagStatement({ exportsArgument: dep.originModule.exportsArgument }); source.insert(-10, content); } } }; module.exports = HarmonyCompatibilityDependency; webpack-4.30.0/lib/dependencies/HarmonyDetectionParserPlugin.js000066400000000000000000000052131345416772700245750ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); const HarmonyInitDependency = require("./HarmonyInitDependency"); module.exports = class HarmonyDetectionParserPlugin { apply(parser) { parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { const isStrictHarmony = parser.state.module.type === "javascript/esm"; const isHarmony = isStrictHarmony || ast.body.some( statement => statement.type === "ImportDeclaration" || statement.type === "ExportDefaultDeclaration" || statement.type === "ExportNamedDeclaration" || statement.type === "ExportAllDeclaration" ); if (isHarmony) { const module = parser.state.module; const compatDep = new HarmonyCompatibilityDependency(module); compatDep.loc = { start: { line: -1, column: 0 }, end: { line: -1, column: 0 }, index: -3 }; module.addDependency(compatDep); const initDep = new HarmonyInitDependency(module); initDep.loc = { start: { line: -1, column: 0 }, end: { line: -1, column: 0 }, index: -2 }; module.addDependency(initDep); parser.state.harmonyParserScope = parser.state.harmonyParserScope || {}; parser.scope.isStrict = true; module.buildMeta.exportsType = "namespace"; module.buildInfo.strict = true; module.buildInfo.exportsArgument = "__webpack_exports__"; if (isStrictHarmony) { module.buildMeta.strictHarmonyModule = true; module.buildInfo.moduleArgument = "__webpack_module__"; } } }); const skipInHarmony = () => { const module = parser.state.module; if (module && module.buildMeta && module.buildMeta.exportsType) { return true; } }; const nullInHarmony = () => { const module = parser.state.module; if (module && module.buildMeta && module.buildMeta.exportsType) { return null; } }; const nonHarmonyIdentifiers = ["define", "exports"]; for (const identifer of nonHarmonyIdentifiers) { parser.hooks.evaluateTypeof .for(identifer) .tap("HarmonyDetectionParserPlugin", nullInHarmony); parser.hooks.typeof .for(identifer) .tap("HarmonyDetectionParserPlugin", skipInHarmony); parser.hooks.evaluate .for(identifer) .tap("HarmonyDetectionParserPlugin", nullInHarmony); parser.hooks.expression .for(identifer) .tap("HarmonyDetectionParserPlugin", skipInHarmony); parser.hooks.call .for(identifer) .tap("HarmonyDetectionParserPlugin", skipInHarmony); } } }; webpack-4.30.0/lib/dependencies/HarmonyExportDependencyParserPlugin.js000066400000000000000000000111111345416772700261310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); const ConstDependency = require("./ConstDependency"); module.exports = class HarmonyExportDependencyParserPlugin { constructor(moduleOptions) { this.strictExportPresence = moduleOptions.strictExportPresence; } apply(parser) { parser.hooks.export.tap( "HarmonyExportDependencyParserPlugin", statement => { const dep = new HarmonyExportHeaderDependency( statement.declaration && statement.declaration.range, statement.range ); dep.loc = Object.create(statement.loc); dep.loc.index = -1; parser.state.current.addDependency(dep); return true; } ); parser.hooks.exportImport.tap( "HarmonyExportDependencyParserPlugin", (statement, source) => { parser.state.lastHarmonyImportOrder = (parser.state.lastHarmonyImportOrder || 0) + 1; const clearDep = new ConstDependency("", statement.range); clearDep.loc = Object.create(statement.loc); clearDep.loc.index = -1; parser.state.current.addDependency(clearDep); const sideEffectDep = new HarmonyImportSideEffectDependency( source, parser.state.module, parser.state.lastHarmonyImportOrder, parser.state.harmonyParserScope ); sideEffectDep.loc = Object.create(statement.loc); sideEffectDep.loc.index = -1; parser.state.current.addDependency(sideEffectDep); return true; } ); parser.hooks.exportExpression.tap( "HarmonyExportDependencyParserPlugin", (statement, expr) => { const comments = parser.getComments([ statement.range[0], expr.range[0] ]); const dep = new HarmonyExportExpressionDependency( parser.state.module, expr.range, statement.range, comments .map(c => { switch (c.type) { case "Block": return `/*${c.value}*/`; case "Line": return `//${c.value}\n`; } return ""; }) .join("") ); dep.loc = Object.create(statement.loc); dep.loc.index = -1; parser.state.current.addDependency(dep); return true; } ); parser.hooks.exportDeclaration.tap( "HarmonyExportDependencyParserPlugin", statement => {} ); parser.hooks.exportSpecifier.tap( "HarmonyExportDependencyParserPlugin", (statement, id, name, idx) => { const rename = parser.scope.renames.get(id); let dep; const harmonyNamedExports = (parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set()); harmonyNamedExports.add(name); if (rename === "imported var") { const settings = parser.state.harmonySpecifier.get(id); dep = new HarmonyExportImportedSpecifierDependency( settings.source, parser.state.module, settings.sourceOrder, parser.state.harmonyParserScope, settings.id, name, harmonyNamedExports, null, this.strictExportPresence ); } else { dep = new HarmonyExportSpecifierDependency( parser.state.module, id, name ); } dep.loc = Object.create(statement.loc); dep.loc.index = idx; parser.state.current.addDependency(dep); return true; } ); parser.hooks.exportImportSpecifier.tap( "HarmonyExportDependencyParserPlugin", (statement, source, id, name, idx) => { const harmonyNamedExports = (parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set()); let harmonyStarExports = null; if (name) { harmonyNamedExports.add(name); } else { harmonyStarExports = parser.state.harmonyStarExports = parser.state.harmonyStarExports || []; } const dep = new HarmonyExportImportedSpecifierDependency( source, parser.state.module, parser.state.lastHarmonyImportOrder, parser.state.harmonyParserScope, id, name, harmonyNamedExports, harmonyStarExports && harmonyStarExports.slice(), this.strictExportPresence ); if (harmonyStarExports) { harmonyStarExports.push(dep); } dep.loc = Object.create(statement.loc); dep.loc.index = idx; parser.state.current.addDependency(dep); return true; } ); } }; webpack-4.30.0/lib/dependencies/HarmonyExportExpressionDependency.js000066400000000000000000000026031345416772700256630ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class HarmonyExportExpressionDependency extends NullDependency { constructor(originModule, range, rangeStatement, prefix) { super(); this.originModule = originModule; this.range = range; this.rangeStatement = rangeStatement; this.prefix = prefix; } get type() { return "harmony export expression"; } getExports() { return { exports: ["default"], dependencies: undefined }; } } HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate { apply(dep, source) { const used = dep.originModule.isUsed("default"); const content = this.getContent(dep.originModule, used); if (dep.range) { source.replace( dep.rangeStatement[0], dep.range[0] - 1, content + "(" + dep.prefix ); source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); return; } source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); } getContent(module, used) { const exportsName = module.exportsArgument; if (used) { return `/* harmony default export */ ${exportsName}[${JSON.stringify( used )}] = `; } return "/* unused harmony default export */ var _unused_webpack_default_export = "; } }; module.exports = HarmonyExportExpressionDependency; webpack-4.30.0/lib/dependencies/HarmonyExportHeaderDependency.js000066400000000000000000000013301345416772700247100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class HarmonyExportHeaderDependency extends NullDependency { constructor(range, rangeStatement) { super(); this.range = range; this.rangeStatement = rangeStatement; } get type() { return "harmony export header"; } } HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate { apply(dep, source) { const content = ""; const replaceUntil = dep.range ? dep.range[0] - 1 : dep.rangeStatement[1] - 1; source.replace(dep.rangeStatement[0], replaceUntil, content); } }; module.exports = HarmonyExportHeaderDependency; webpack-4.30.0/lib/dependencies/HarmonyExportImportedSpecifierDependency.js000066400000000000000000000375751345416772700271610ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependencyReference = require("./DependencyReference"); const HarmonyImportDependency = require("./HarmonyImportDependency"); const Template = require("../Template"); const HarmonyLinkingError = require("../HarmonyLinkingError"); /** @typedef {import("../Module")} Module */ /** @typedef {"missing"|"unused"|"empty-star"|"reexport-non-harmony-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-non-harmony-default-strict"|"reexport-fake-namespace-object"|"rexport-non-harmony-undefined"|"safe-reexport"|"checked-reexport"|"dynamic-reexport"} ExportModeType */ /** @type {Map} */ const EMPTY_MAP = new Map(); class ExportMode { /** * @param {ExportModeType} type type of the mode */ constructor(type) { /** @type {ExportModeType} */ this.type = type; /** @type {string|null} */ this.name = null; /** @type {Map} */ this.map = EMPTY_MAP; /** @type {Module|null} */ this.module = null; /** @type {string|null} */ this.userRequest = null; } } const EMPTY_STAR_MODE = new ExportMode("empty-star"); class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { constructor( request, originModule, sourceOrder, parserScope, id, name, activeExports, otherStarExports, strictExportPresence ) { super(request, originModule, sourceOrder, parserScope); this.id = id; this.name = name; this.activeExports = activeExports; this.otherStarExports = otherStarExports; this.strictExportPresence = strictExportPresence; } get type() { return "harmony export imported specifier"; } getMode(ignoreUnused) { const name = this.name; const id = this.id; const used = this.originModule.isUsed(name); const importedModule = this._module; if (!importedModule) { const mode = new ExportMode("missing"); mode.userRequest = this.userRequest; return mode; } if ( !ignoreUnused && (name ? !used : this.originModule.usedExports === false) ) { const mode = new ExportMode("unused"); mode.name = name || "*"; return mode; } const strictHarmonyModule = this.originModule.buildMeta.strictHarmonyModule; if (name && id === "default" && importedModule.buildMeta) { if (!importedModule.buildMeta.exportsType) { const mode = new ExportMode( strictHarmonyModule ? "reexport-non-harmony-default-strict" : "reexport-non-harmony-default" ); mode.name = name; mode.module = importedModule; return mode; } else if (importedModule.buildMeta.exportsType === "named") { const mode = new ExportMode("reexport-named-default"); mode.name = name; mode.module = importedModule; return mode; } } const isNotAHarmonyModule = importedModule.buildMeta && !importedModule.buildMeta.exportsType; if (name) { let mode; if (id) { // export { name as name } if (isNotAHarmonyModule && strictHarmonyModule) { mode = new ExportMode("rexport-non-harmony-undefined"); mode.name = name; } else { mode = new ExportMode("safe-reexport"); mode.map = new Map([[name, id]]); } } else { // export { * as name } if (isNotAHarmonyModule && strictHarmonyModule) { mode = new ExportMode("reexport-fake-namespace-object"); mode.name = name; } else { mode = new ExportMode("reexport-namespace-object"); mode.name = name; } } mode.module = importedModule; return mode; } const hasUsedExports = Array.isArray(this.originModule.usedExports); const hasProvidedExports = Array.isArray( importedModule.buildMeta.providedExports ); const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); // export * if (hasUsedExports) { // reexport * with known used exports if (hasProvidedExports) { const map = new Map( this.originModule.usedExports .filter(id => { if (id === "default") return false; if (this.activeExports.has(id)) return false; if (activeFromOtherStarExports.has(id)) return false; if (!importedModule.buildMeta.providedExports.includes(id)) return false; return true; }) .map(item => [item, item]) ); if (map.size === 0) { return EMPTY_STAR_MODE; } const mode = new ExportMode("safe-reexport"); mode.module = importedModule; mode.map = map; return mode; } const map = new Map( this.originModule.usedExports .filter(id => { if (id === "default") return false; if (this.activeExports.has(id)) return false; if (activeFromOtherStarExports.has(id)) return false; return true; }) .map(item => [item, item]) ); if (map.size === 0) { return EMPTY_STAR_MODE; } const mode = new ExportMode("checked-reexport"); mode.module = importedModule; mode.map = map; return mode; } if (hasProvidedExports) { const map = new Map( importedModule.buildMeta.providedExports .filter(id => { if (id === "default") return false; if (this.activeExports.has(id)) return false; if (activeFromOtherStarExports.has(id)) return false; return true; }) .map(item => [item, item]) ); if (map.size === 0) { return EMPTY_STAR_MODE; } const mode = new ExportMode("safe-reexport"); mode.module = importedModule; mode.map = map; return mode; } const mode = new ExportMode("dynamic-reexport"); mode.module = importedModule; return mode; } getReference() { const mode = this.getMode(false); switch (mode.type) { case "missing": case "unused": case "empty-star": return null; case "reexport-non-harmony-default": case "reexport-named-default": return new DependencyReference( mode.module, ["default"], false, this.sourceOrder ); case "reexport-namespace-object": case "reexport-non-harmony-default-strict": case "reexport-fake-namespace-object": case "rexport-non-harmony-undefined": return new DependencyReference( mode.module, true, false, this.sourceOrder ); case "safe-reexport": case "checked-reexport": return new DependencyReference( mode.module, Array.from(mode.map.values()), false, this.sourceOrder ); case "dynamic-reexport": return new DependencyReference( mode.module, true, false, this.sourceOrder ); default: throw new Error(`Unknown mode ${mode.type}`); } } _discoverActiveExportsFromOtherStartExports() { if (!this.otherStarExports) return new Set(); const result = new Set(); // try to learn impossible exports from other star exports with provided exports for (const otherStarExport of this.otherStarExports) { const otherImportedModule = otherStarExport._module; if ( otherImportedModule && Array.isArray(otherImportedModule.buildMeta.providedExports) ) { for (const exportName of otherImportedModule.buildMeta .providedExports) { result.add(exportName); } } } return result; } getExports() { if (this.name) { return { exports: [this.name], dependencies: undefined }; } const importedModule = this.module; if (!importedModule) { // no imported module available return { exports: null, dependencies: undefined }; } if (Array.isArray(importedModule.buildMeta.providedExports)) { return { exports: importedModule.buildMeta.providedExports.filter( id => id !== "default" ), dependencies: [importedModule] }; } if (importedModule.buildMeta.providedExports) { return { exports: true, dependencies: undefined }; } return { exports: null, dependencies: [importedModule] }; } getWarnings() { if ( this.strictExportPresence || this.originModule.buildMeta.strictHarmonyModule ) { return []; } return this._getErrors(); } getErrors() { if ( this.strictExportPresence || this.originModule.buildMeta.strictHarmonyModule ) { return this._getErrors(); } return []; } _getErrors() { const importedModule = this._module; if (!importedModule) { return; } if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { // It's not an harmony module if ( this.originModule.buildMeta.strictHarmonyModule && this.id !== "default" ) { // In strict harmony modules we only support the default export const exportName = this.id ? `the named export '${this.id}'` : "the namespace object"; return [ new HarmonyLinkingError( `Can't reexport ${exportName} from non EcmaScript module (only default export is available)` ) ]; } return; } if (!this.id) { return; } if (importedModule.isProvided(this.id) !== false) { // It's provided or we are not sure return; } // We are sure that it's not provided const idIsNotNameMessage = this.id !== this.name ? ` (reexported as '${this.name}')` : ""; const errorMessage = `"export '${ this.id }'${idIsNotNameMessage} was not found in '${this.userRequest}'`; return [new HarmonyLinkingError(errorMessage)]; } updateHash(hash) { super.updateHash(hash); const hashValue = this.getHashValue(this._module); hash.update(hashValue); } getHashValue(importedModule) { if (!importedModule) { return ""; } const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); const stringifiedProvidedExport = JSON.stringify( importedModule.buildMeta.providedExports ); return ( importedModule.used + stringifiedUsedExport + stringifiedProvidedExport ); } } module.exports = HarmonyExportImportedSpecifierDependency; HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends HarmonyImportDependency.Template { harmonyInit(dep, source, runtime, dependencyTemplates) { super.harmonyInit(dep, source, runtime, dependencyTemplates); const content = this.getContent(dep); source.insert(-1, content); } getHarmonyInitOrder(dep) { if (dep.name) { const used = dep.originModule.isUsed(dep.name); if (!used) return NaN; } else { const importedModule = dep._module; const activeFromOtherStarExports = dep._discoverActiveExportsFromOtherStartExports(); if (Array.isArray(dep.originModule.usedExports)) { // we know which exports are used const unused = dep.originModule.usedExports.every(id => { if (id === "default") return true; if (dep.activeExports.has(id)) return true; if (importedModule.isProvided(id) === false) return true; if (activeFromOtherStarExports.has(id)) return true; return false; }); if (unused) return NaN; } else if ( dep.originModule.usedExports && importedModule && Array.isArray(importedModule.buildMeta.providedExports) ) { // not sure which exports are used, but we know which are provided const unused = importedModule.buildMeta.providedExports.every(id => { if (id === "default") return true; if (dep.activeExports.has(id)) return true; if (activeFromOtherStarExports.has(id)) return true; return false; }); if (unused) return NaN; } } return super.getHarmonyInitOrder(dep); } getContent(dep) { const mode = dep.getMode(false); const module = dep.originModule; const importedModule = dep._module; const importVar = dep.getImportVar(); switch (mode.type) { case "missing": return `throw new Error(${JSON.stringify( `Cannot find module '${mode.userRequest}'` )});\n`; case "unused": return `${Template.toNormalComment( `unused harmony reexport ${mode.name}` )}\n`; case "reexport-non-harmony-default": return ( "/* harmony reexport (default from non-harmony) */ " + this.getReexportStatement( module, module.isUsed(mode.name), importVar, null ) ); case "reexport-named-default": return ( "/* harmony reexport (default from named exports) */ " + this.getReexportStatement( module, module.isUsed(mode.name), importVar, "" ) ); case "reexport-fake-namespace-object": return ( "/* harmony reexport (fake namespace object from non-harmony) */ " + this.getReexportFakeNamespaceObjectStatement( module, module.isUsed(mode.name), importVar ) ); case "rexport-non-harmony-undefined": return ( "/* harmony reexport (non default export from non-harmony) */ " + this.getReexportStatement( module, module.isUsed(mode.name), "undefined", "" ) ); case "reexport-non-harmony-default-strict": return ( "/* harmony reexport (default from non-harmony) */ " + this.getReexportStatement( module, module.isUsed(mode.name), importVar, "" ) ); case "reexport-namespace-object": return ( "/* harmony reexport (module object) */ " + this.getReexportStatement( module, module.isUsed(mode.name), importVar, "" ) ); case "empty-star": return "/* empty/unused harmony star reexport */"; case "safe-reexport": return Array.from(mode.map.entries()) .map(item => { return ( "/* harmony reexport (safe) */ " + this.getReexportStatement( module, module.isUsed(item[0]), importVar, importedModule.isUsed(item[1]) ) + "\n" ); }) .join(""); case "checked-reexport": return Array.from(mode.map.entries()) .map(item => { return ( "/* harmony reexport (checked) */ " + this.getConditionalReexportStatement( module, item[0], importVar, item[1] ) + "\n" ); }) .join(""); case "dynamic-reexport": { const activeExports = new Set([ ...dep.activeExports, ...dep._discoverActiveExportsFromOtherStartExports() ]); let content = "/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + importVar + ") "; // Filter out exports which are defined by other exports // and filter out default export because it cannot be reexported with * if (activeExports.size > 0) { content += "if(" + JSON.stringify(Array.from(activeExports).concat("default")) + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; } else { content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; } const exportsName = dep.originModule.exportsArgument; return ( content + `(function(key) { __webpack_require__.d(${exportsName}, key, function() { return ${importVar}[key]; }) }(__WEBPACK_IMPORT_KEY__));\n` ); } default: throw new Error(`Unknown mode ${mode.type}`); } } getReexportStatement(module, key, name, valueKey) { const exportsName = module.exportsArgument; const returnValue = this.getReturnValue(name, valueKey); return `__webpack_require__.d(${exportsName}, ${JSON.stringify( key )}, function() { return ${returnValue}; });\n`; } getReexportFakeNamespaceObjectStatement(module, key, name) { const exportsName = module.exportsArgument; return `__webpack_require__.d(${exportsName}, ${JSON.stringify( key )}, function() { return __webpack_require__.t(${name}); });\n`; } getConditionalReexportStatement(module, key, name, valueKey) { if (valueKey === false) { return "/* unused export */\n"; } const exportsName = module.exportsArgument; const returnValue = this.getReturnValue(name, valueKey); return `if(__webpack_require__.o(${name}, ${JSON.stringify( valueKey )})) __webpack_require__.d(${exportsName}, ${JSON.stringify( key )}, function() { return ${returnValue}; });\n`; } getReturnValue(name, valueKey) { if (valueKey === null) { return `${name}_default.a`; } if (valueKey === "") { return name; } if (valueKey === false) { return "/* unused export */ undefined"; } return `${name}[${JSON.stringify(valueKey)}]`; } }; webpack-4.30.0/lib/dependencies/HarmonyExportSpecifierDependency.js000066400000000000000000000022561345416772700254410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class HarmonyExportSpecifierDependency extends NullDependency { constructor(originModule, id, name) { super(); this.originModule = originModule; this.id = id; this.name = name; } get type() { return "harmony export specifier"; } getExports() { return { exports: [this.name], dependencies: undefined }; } } HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate { apply(dep, source) {} getHarmonyInitOrder(dep) { return 0; } harmonyInit(dep, source, runtime) { const content = this.getContent(dep); source.insert(-1, content); } getContent(dep) { const used = dep.originModule.isUsed(dep.name); if (!used) { return `/* unused harmony export ${dep.name || "namespace"} */\n`; } const exportsName = dep.originModule.exportsArgument; return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify( used )}, function() { return ${dep.id}; });\n`; } }; module.exports = HarmonyExportSpecifierDependency; webpack-4.30.0/lib/dependencies/HarmonyImportDependency.js000066400000000000000000000052471345416772700236030ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependencyReference = require("./DependencyReference"); const ModuleDependency = require("./ModuleDependency"); const Template = require("../Template"); class HarmonyImportDependency extends ModuleDependency { constructor(request, originModule, sourceOrder, parserScope) { super(request); this.redirectedModule = undefined; this.originModule = originModule; this.sourceOrder = sourceOrder; this.parserScope = parserScope; } get _module() { return this.redirectedModule || this.module; } getReference() { if (!this._module) return null; return new DependencyReference( this._module, false, this.weak, this.sourceOrder ); } getImportVar() { let importVarMap = this.parserScope.importVarMap; if (!importVarMap) this.parserScope.importVarMap = importVarMap = new Map(); let importVar = importVarMap.get(this._module); if (importVar) return importVar; importVar = `${Template.toIdentifier( `${this.userRequest}` )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; importVarMap.set(this._module, importVar); return importVar; } getImportStatement(update, runtime) { return runtime.importStatement({ update, module: this._module, importVar: this.getImportVar(), request: this.request, originModule: this.originModule }); } updateHash(hash) { super.updateHash(hash); const importedModule = this._module; hash.update( (importedModule && (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + "" ); hash.update((importedModule && importedModule.id) + ""); } disconnect() { super.disconnect(); this.redirectedModule = undefined; } } module.exports = HarmonyImportDependency; const importEmittedMap = new WeakMap(); HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { apply(dep, source, runtime) { // no-op } getHarmonyInitOrder(dep) { return dep.sourceOrder; } static isImportEmitted(dep, source) { let sourceInfo = importEmittedMap.get(source); if (!sourceInfo) return false; const key = dep._module || dep.request; return key && sourceInfo.emittedImports.get(key); } harmonyInit(dep, source, runtime, dependencyTemplates) { let sourceInfo = importEmittedMap.get(source); if (!sourceInfo) { importEmittedMap.set( source, (sourceInfo = { emittedImports: new Map() }) ); } const key = dep._module || dep.request; if (key && sourceInfo.emittedImports.get(key)) return; sourceInfo.emittedImports.set(key, true); const content = dep.getImportStatement(false, runtime); source.insert(-1, content); } }; webpack-4.30.0/lib/dependencies/HarmonyImportDependencyParserPlugin.js000066400000000000000000000153161345416772700261350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { SyncBailHook } = require("tapable"); const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency"); const HarmonyAcceptDependency = require("./HarmonyAcceptDependency"); const ConstDependency = require("./ConstDependency"); module.exports = class HarmonyImportDependencyParserPlugin { constructor(moduleOptions) { this.strictExportPresence = moduleOptions.strictExportPresence; this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports; } apply(parser) { parser.hooks.import.tap( "HarmonyImportDependencyParserPlugin", (statement, source) => { parser.state.lastHarmonyImportOrder = (parser.state.lastHarmonyImportOrder || 0) + 1; const clearDep = new ConstDependency("", statement.range); clearDep.loc = statement.loc; parser.state.module.addDependency(clearDep); const sideEffectDep = new HarmonyImportSideEffectDependency( source, parser.state.module, parser.state.lastHarmonyImportOrder, parser.state.harmonyParserScope ); sideEffectDep.loc = statement.loc; parser.state.module.addDependency(sideEffectDep); return true; } ); parser.hooks.importSpecifier.tap( "HarmonyImportDependencyParserPlugin", (statement, source, id, name) => { parser.scope.definitions.delete(name); parser.scope.renames.set(name, "imported var"); if (!parser.state.harmonySpecifier) { parser.state.harmonySpecifier = new Map(); } parser.state.harmonySpecifier.set(name, { source, id, sourceOrder: parser.state.lastHarmonyImportOrder }); return true; } ); parser.hooks.expression .for("imported var") .tap("HarmonyImportDependencyParserPlugin", expr => { const name = expr.name; const settings = parser.state.harmonySpecifier.get(name); const dep = new HarmonyImportSpecifierDependency( settings.source, parser.state.module, settings.sourceOrder, parser.state.harmonyParserScope, settings.id, name, expr.range, this.strictExportPresence ); dep.shorthand = parser.scope.inShorthand; dep.directImport = true; dep.loc = expr.loc; parser.state.module.addDependency(dep); return true; }); parser.hooks.expressionAnyMember .for("imported var") .tap("HarmonyImportDependencyParserPlugin", expr => { const name = expr.object.name; const settings = parser.state.harmonySpecifier.get(name); if (settings.id !== null) return false; const dep = new HarmonyImportSpecifierDependency( settings.source, parser.state.module, settings.sourceOrder, parser.state.harmonyParserScope, expr.property.name || expr.property.value, name, expr.range, this.strictExportPresence ); dep.shorthand = parser.scope.inShorthand; dep.directImport = false; dep.loc = expr.loc; parser.state.module.addDependency(dep); return true; }); if (this.strictThisContextOnImports) { // only in case when we strictly follow the spec we need a special case here parser.hooks.callAnyMember .for("imported var") .tap("HarmonyImportDependencyParserPlugin", expr => { if (expr.callee.type !== "MemberExpression") return; if (expr.callee.object.type !== "Identifier") return; const name = expr.callee.object.name; const settings = parser.state.harmonySpecifier.get(name); if (settings.id !== null) return false; const dep = new HarmonyImportSpecifierDependency( settings.source, parser.state.module, settings.sourceOrder, parser.state.harmonyParserScope, expr.callee.property.name || expr.callee.property.value, name, expr.callee.range, this.strictExportPresence ); dep.shorthand = parser.scope.inShorthand; dep.directImport = false; dep.namespaceObjectAsContext = true; dep.loc = expr.callee.loc; parser.state.module.addDependency(dep); if (expr.arguments) parser.walkExpressions(expr.arguments); return true; }); } parser.hooks.call .for("imported var") .tap("HarmonyImportDependencyParserPlugin", expr => { const args = expr.arguments; const fullExpr = expr; expr = expr.callee; if (expr.type !== "Identifier") return; const name = expr.name; const settings = parser.state.harmonySpecifier.get(name); const dep = new HarmonyImportSpecifierDependency( settings.source, parser.state.module, settings.sourceOrder, parser.state.harmonyParserScope, settings.id, name, expr.range, this.strictExportPresence ); dep.directImport = true; dep.callArgs = args; dep.call = fullExpr; dep.loc = expr.loc; parser.state.module.addDependency(dep); if (args) parser.walkExpressions(args); return true; }); // TODO webpack 5: refactor this, no custom hooks if (!parser.hooks.hotAcceptCallback) { parser.hooks.hotAcceptCallback = new SyncBailHook([ "expression", "requests" ]); } if (!parser.hooks.hotAcceptWithoutCallback) { parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ "expression", "requests" ]); } parser.hooks.hotAcceptCallback.tap( "HarmonyImportDependencyParserPlugin", (expr, requests) => { const harmonyParserScope = parser.state.harmonyParserScope; if (!harmonyParserScope) { // This is not a harmony module, skip it return; } const dependencies = requests.map(request => { const dep = new HarmonyAcceptImportDependency( request, parser.state.module, harmonyParserScope ); dep.loc = expr.loc; parser.state.module.addDependency(dep); return dep; }); if (dependencies.length > 0) { const dep = new HarmonyAcceptDependency( expr.range, dependencies, true ); dep.loc = expr.loc; parser.state.module.addDependency(dep); } } ); parser.hooks.hotAcceptWithoutCallback.tap( "HarmonyImportDependencyParserPlugin", (expr, requests) => { const dependencies = requests.map(request => { const dep = new HarmonyAcceptImportDependency( request, parser.state.module, parser.state.harmonyParserScope ); dep.loc = expr.loc; parser.state.module.addDependency(dep); return dep; }); if (dependencies.length > 0) { const dep = new HarmonyAcceptDependency( expr.range, dependencies, false ); dep.loc = expr.loc; parser.state.module.addDependency(dep); } } ); } }; webpack-4.30.0/lib/dependencies/HarmonyImportSideEffectDependency.js000066400000000000000000000016231345416772700255170ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyImportDependency = require("./HarmonyImportDependency"); class HarmonyImportSideEffectDependency extends HarmonyImportDependency { constructor(request, originModule, sourceOrder, parserScope) { super(request, originModule, sourceOrder, parserScope); } getReference() { if (this._module && this._module.factoryMeta.sideEffectFree) return null; return super.getReference(); } get type() { return "harmony side effect evaluation"; } } HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template { getHarmonyInitOrder(dep) { if (dep._module && dep._module.factoryMeta.sideEffectFree) return NaN; return super.getHarmonyInitOrder(dep); } }; module.exports = HarmonyImportSideEffectDependency; webpack-4.30.0/lib/dependencies/HarmonyImportSpecifierDependency.js000066400000000000000000000077331345416772700254370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependencyReference = require("./DependencyReference"); const HarmonyImportDependency = require("./HarmonyImportDependency"); const HarmonyLinkingError = require("../HarmonyLinkingError"); class HarmonyImportSpecifierDependency extends HarmonyImportDependency { constructor( request, originModule, sourceOrder, parserScope, id, name, range, strictExportPresence ) { super(request, originModule, sourceOrder, parserScope); this.id = id === null ? null : `${id}`; this.redirectedId = undefined; this.name = name; this.range = range; this.strictExportPresence = strictExportPresence; this.namespaceObjectAsContext = false; this.callArgs = undefined; this.call = undefined; this.directImport = undefined; this.shorthand = undefined; } get type() { return "harmony import specifier"; } get _id() { return this.redirectedId || this.id; } getReference() { if (!this._module) return null; return new DependencyReference( this._module, this._id && !this.namespaceObjectAsContext ? [this._id] : true, false, this.sourceOrder ); } getWarnings() { if ( this.strictExportPresence || this.originModule.buildMeta.strictHarmonyModule ) { return []; } return this._getErrors(); } getErrors() { if ( this.strictExportPresence || this.originModule.buildMeta.strictHarmonyModule ) { return this._getErrors(); } return []; } _getErrors() { const importedModule = this._module; if (!importedModule) { return; } if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { // It's not an harmony module if ( this.originModule.buildMeta.strictHarmonyModule && this._id !== "default" ) { // In strict harmony modules we only support the default export const exportName = this._id ? `the named export '${this._id}'` : "the namespace object"; return [ new HarmonyLinkingError( `Can't import ${exportName} from non EcmaScript module (only default export is available)` ) ]; } return; } if (!this._id) { return; } if (importedModule.isProvided(this._id) !== false) { // It's provided or we are not sure return; } // We are sure that it's not provided const idIsNotNameMessage = this._id !== this.name ? ` (imported as '${this.name}')` : ""; const errorMessage = `"export '${ this._id }'${idIsNotNameMessage} was not found in '${this.userRequest}'`; return [new HarmonyLinkingError(errorMessage)]; } // implement this method to allow the occurrence order plugin to count correctly getNumberOfIdOccurrences() { return 0; } updateHash(hash) { super.updateHash(hash); const importedModule = this._module; hash.update((importedModule && this._id) + ""); hash.update( (importedModule && this._id && importedModule.isUsed(this._id)) + "" ); hash.update( (importedModule && (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + "" ); hash.update( (importedModule && importedModule.used + JSON.stringify(importedModule.usedExports)) + "" ); } disconnect() { super.disconnect(); this.redirectedId = undefined; } } HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends HarmonyImportDependency.Template { apply(dep, source, runtime) { super.apply(dep, source, runtime); const content = this.getContent(dep, runtime); source.replace(dep.range[0], dep.range[1] - 1, content); } getContent(dep, runtime) { const exportExpr = runtime.exportFromImport({ module: dep._module, request: dep.request, exportName: dep._id, originModule: dep.originModule, asiSafe: dep.shorthand, isCall: dep.call, callContext: !dep.directImport, importVar: dep.getImportVar() }); return dep.shorthand ? `${dep.name}: ${exportExpr}` : exportExpr; } }; module.exports = HarmonyImportSpecifierDependency; webpack-4.30.0/lib/dependencies/HarmonyInitDependency.js000066400000000000000000000024071345416772700232270ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class HarmonyInitDependency extends NullDependency { constructor(originModule) { super(); this.originModule = originModule; } get type() { return "harmony init"; } } module.exports = HarmonyInitDependency; HarmonyInitDependency.Template = class HarmonyInitDependencyTemplate { apply(dep, source, runtime, dependencyTemplates) { const module = dep.originModule; const list = []; for (const dependency of module.dependencies) { const template = dependencyTemplates.get(dependency.constructor); if ( template && typeof template.harmonyInit === "function" && typeof template.getHarmonyInitOrder === "function" ) { const order = template.getHarmonyInitOrder(dependency); if (!isNaN(order)) { list.push({ order, listOrder: list.length, dependency, template }); } } } list.sort((a, b) => { const x = a.order - b.order; if (x) return x; return a.listOrder - b.listOrder; }); for (const item of list) { item.template.harmonyInit( item.dependency, source, runtime, dependencyTemplates ); } } }; webpack-4.30.0/lib/dependencies/HarmonyModulesPlugin.js000066400000000000000000000111521345416772700231110ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); const HarmonyInitDependency = require("./HarmonyInitDependency"); const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); const HarmonyAcceptDependency = require("./HarmonyAcceptDependency"); const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency"); const NullFactory = require("../NullFactory"); const HarmonyDetectionParserPlugin = require("./HarmonyDetectionParserPlugin"); const HarmonyImportDependencyParserPlugin = require("./HarmonyImportDependencyParserPlugin"); const HarmonyExportDependencyParserPlugin = require("./HarmonyExportDependencyParserPlugin"); const HarmonyTopLevelThisParserPlugin = require("./HarmonyTopLevelThisParserPlugin"); class HarmonyModulesPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.hooks.compilation.tap( "HarmonyModulesPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( HarmonyCompatibilityDependency, new NullFactory() ); compilation.dependencyTemplates.set( HarmonyCompatibilityDependency, new HarmonyCompatibilityDependency.Template() ); compilation.dependencyFactories.set( HarmonyInitDependency, new NullFactory() ); compilation.dependencyTemplates.set( HarmonyInitDependency, new HarmonyInitDependency.Template() ); compilation.dependencyFactories.set( HarmonyImportSideEffectDependency, normalModuleFactory ); compilation.dependencyTemplates.set( HarmonyImportSideEffectDependency, new HarmonyImportSideEffectDependency.Template() ); compilation.dependencyFactories.set( HarmonyImportSpecifierDependency, normalModuleFactory ); compilation.dependencyTemplates.set( HarmonyImportSpecifierDependency, new HarmonyImportSpecifierDependency.Template() ); compilation.dependencyFactories.set( HarmonyExportHeaderDependency, new NullFactory() ); compilation.dependencyTemplates.set( HarmonyExportHeaderDependency, new HarmonyExportHeaderDependency.Template() ); compilation.dependencyFactories.set( HarmonyExportExpressionDependency, new NullFactory() ); compilation.dependencyTemplates.set( HarmonyExportExpressionDependency, new HarmonyExportExpressionDependency.Template() ); compilation.dependencyFactories.set( HarmonyExportSpecifierDependency, new NullFactory() ); compilation.dependencyTemplates.set( HarmonyExportSpecifierDependency, new HarmonyExportSpecifierDependency.Template() ); compilation.dependencyFactories.set( HarmonyExportImportedSpecifierDependency, normalModuleFactory ); compilation.dependencyTemplates.set( HarmonyExportImportedSpecifierDependency, new HarmonyExportImportedSpecifierDependency.Template() ); compilation.dependencyFactories.set( HarmonyAcceptDependency, new NullFactory() ); compilation.dependencyTemplates.set( HarmonyAcceptDependency, new HarmonyAcceptDependency.Template() ); compilation.dependencyFactories.set( HarmonyAcceptImportDependency, normalModuleFactory ); compilation.dependencyTemplates.set( HarmonyAcceptImportDependency, new HarmonyAcceptImportDependency.Template() ); const handler = (parser, parserOptions) => { if (parserOptions.harmony !== undefined && !parserOptions.harmony) return; new HarmonyDetectionParserPlugin().apply(parser); new HarmonyImportDependencyParserPlugin(this.options).apply(parser); new HarmonyExportDependencyParserPlugin(this.options).apply(parser); new HarmonyTopLevelThisParserPlugin().apply(parser); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("HarmonyModulesPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("HarmonyModulesPlugin", handler); } ); } } module.exports = HarmonyModulesPlugin; webpack-4.30.0/lib/dependencies/HarmonyTopLevelThisParserPlugin.js000066400000000000000000000013171345416772700252420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Florent Cailhol @ooflorent */ "use strict"; const ConstDependency = require("./ConstDependency"); class HarmonyTopLevelThisParserPlugin { apply(parser) { parser.hooks.expression .for("this") .tap("HarmonyTopLevelThisParserPlugin", node => { if (!parser.scope.topLevelScope) return; const module = parser.state.module; const isHarmony = !!(module.buildMeta && module.buildMeta.exportsType); if (isHarmony) { const dep = new ConstDependency("undefined", node.range, false); dep.loc = node.loc; parser.state.current.addDependency(dep); } }); } } module.exports = HarmonyTopLevelThisParserPlugin; webpack-4.30.0/lib/dependencies/ImportContextDependency.js000066400000000000000000000011761345416772700236070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class ImportContextDependency extends ContextDependency { constructor(options, range, valueRange) { super(options); this.range = range; this.valueRange = valueRange; } get type() { return `import() context ${this.options.mode}`; } } ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = ImportContextDependency; webpack-4.30.0/lib/dependencies/ImportDependenciesBlock.js000066400000000000000000000011461345416772700235220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); const ImportDependency = require("./ImportDependency"); module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { // TODO webpack 5 reorganize arguments constructor(request, range, groupOptions, module, loc, originModule) { super(groupOptions, module, loc, request); this.range = range; const dep = new ImportDependency(request, originModule, this); dep.loc = loc; this.addDependency(dep); } }; webpack-4.30.0/lib/dependencies/ImportDependency.js000066400000000000000000000014411345416772700222350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class ImportDependency extends ModuleDependency { constructor(request, originModule, block) { super(request); this.originModule = originModule; this.block = block; } get type() { return "import()"; } } ImportDependency.Template = class ImportDependencyTemplate { apply(dep, source, runtime) { const content = runtime.moduleNamespacePromise({ block: dep.block, module: dep.module, request: dep.request, strict: dep.originModule.buildMeta.strictHarmonyModule, message: "import()" }); source.replace(dep.block.range[0], dep.block.range[1] - 1, content); } }; module.exports = ImportDependency; webpack-4.30.0/lib/dependencies/ImportEagerDependency.js000066400000000000000000000014371345416772700232060ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class ImportEagerDependency extends ModuleDependency { constructor(request, originModule, range) { super(request); this.originModule = originModule; this.range = range; } get type() { return "import() eager"; } } ImportEagerDependency.Template = class ImportEagerDependencyTemplate { apply(dep, source, runtime) { const content = runtime.moduleNamespacePromise({ module: dep.module, request: dep.request, strict: dep.originModule.buildMeta.strictHarmonyModule, message: "import() eager" }); source.replace(dep.range[0], dep.range[1] - 1, content); } }; module.exports = ImportEagerDependency; webpack-4.30.0/lib/dependencies/ImportParserPlugin.js000066400000000000000000000161451345416772700226010ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ImportContextDependency = require("./ImportContextDependency"); const ImportWeakDependency = require("./ImportWeakDependency"); const ImportDependenciesBlock = require("./ImportDependenciesBlock"); const ImportEagerDependency = require("./ImportEagerDependency"); const ContextDependencyHelpers = require("./ContextDependencyHelpers"); const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); const CommentCompilationWarning = require("../CommentCompilationWarning"); class ImportParserPlugin { constructor(options) { this.options = options; } apply(parser) { parser.hooks.importCall.tap("ImportParserPlugin", expr => { if (expr.arguments.length !== 1) { throw new Error( "Incorrect number of arguments provided to 'import(module: string) -> Promise'." ); } const param = parser.evaluateExpression(expr.arguments[0]); let chunkName = null; let mode = "lazy"; let include = null; let exclude = null; const groupOptions = {}; const { options: importOptions, errors: commentErrors } = parser.parseCommentOptions(expr.range); if (commentErrors) { for (const e of commentErrors) { const { comment } = e; parser.state.module.warnings.push( new CommentCompilationWarning( `Compilation error while processing magic comment(-s): /*${ comment.value }*/: ${e.message}`, parser.state.module, comment.loc ) ); } } if (importOptions) { if (importOptions.webpackIgnore !== undefined) { if (typeof importOptions.webpackIgnore !== "boolean") { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackIgnore\` expected a boolean, but received: ${ importOptions.webpackIgnore }.`, expr.loc ) ); } else { // Do not instrument `import()` if `webpackIgnore` is `true` if (importOptions.webpackIgnore) { return false; } } } if (importOptions.webpackChunkName !== undefined) { if (typeof importOptions.webpackChunkName !== "string") { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackChunkName\` expected a string, but received: ${ importOptions.webpackChunkName }.`, expr.loc ) ); } else { chunkName = importOptions.webpackChunkName; } } if (importOptions.webpackMode !== undefined) { if (typeof importOptions.webpackMode !== "string") { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackMode\` expected a string, but received: ${ importOptions.webpackMode }.`, expr.loc ) ); } else { mode = importOptions.webpackMode; } } if (importOptions.webpackPrefetch !== undefined) { if (importOptions.webpackPrefetch === true) { groupOptions.prefetchOrder = 0; } else if (typeof importOptions.webpackPrefetch === "number") { groupOptions.prefetchOrder = importOptions.webpackPrefetch; } else { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackPrefetch\` expected true or a number, but received: ${ importOptions.webpackPrefetch }.`, expr.loc ) ); } } if (importOptions.webpackPreload !== undefined) { if (importOptions.webpackPreload === true) { groupOptions.preloadOrder = 0; } else if (typeof importOptions.webpackPreload === "number") { groupOptions.preloadOrder = importOptions.webpackPreload; } else { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackPreload\` expected true or a number, but received: ${ importOptions.webpackPreload }.`, expr.loc ) ); } } if (importOptions.webpackInclude !== undefined) { if ( !importOptions.webpackInclude || importOptions.webpackInclude.constructor.name !== "RegExp" ) { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackInclude\` expected a regular expression, but received: ${ importOptions.webpackInclude }.`, expr.loc ) ); } else { include = new RegExp(importOptions.webpackInclude); } } if (importOptions.webpackExclude !== undefined) { if ( !importOptions.webpackExclude || importOptions.webpackExclude.constructor.name !== "RegExp" ) { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackExclude\` expected a regular expression, but received: ${ importOptions.webpackExclude }.`, expr.loc ) ); } else { exclude = new RegExp(importOptions.webpackExclude); } } } if (param.isString()) { if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, expr.loc ) ); } if (mode === "eager") { const dep = new ImportEagerDependency( param.string, parser.state.module, expr.range ); parser.state.current.addDependency(dep); } else if (mode === "weak") { const dep = new ImportWeakDependency( param.string, parser.state.module, expr.range ); parser.state.current.addDependency(dep); } else { const depBlock = new ImportDependenciesBlock( param.string, expr.range, Object.assign(groupOptions, { name: chunkName }), parser.state.module, expr.loc, parser.state.module ); parser.state.current.addBlock(depBlock); } return true; } else { if ( mode !== "lazy" && mode !== "lazy-once" && mode !== "eager" && mode !== "weak" ) { parser.state.module.warnings.push( new UnsupportedFeatureWarning( parser.state.module, `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, expr.loc ) ); mode = "lazy"; } if (mode === "weak") { mode = "async-weak"; } const dep = ContextDependencyHelpers.create( ImportContextDependency, expr.range, param, expr, this.options, { chunkName, groupOptions, include, exclude, mode, namespaceObject: parser.state.module.buildMeta.strictHarmonyModule ? "strict" : true }, parser ); if (!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }); } } module.exports = ImportParserPlugin; webpack-4.30.0/lib/dependencies/ImportPlugin.js000066400000000000000000000040611345416772700214160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ImportDependency = require("./ImportDependency"); const ImportEagerDependency = require("./ImportEagerDependency"); const ImportWeakDependency = require("./ImportWeakDependency"); const ImportContextDependency = require("./ImportContextDependency"); const ImportParserPlugin = require("./ImportParserPlugin"); class ImportPlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap( "ImportPlugin", (compilation, { contextModuleFactory, normalModuleFactory }) => { compilation.dependencyFactories.set( ImportDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ImportDependency, new ImportDependency.Template() ); compilation.dependencyFactories.set( ImportEagerDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ImportEagerDependency, new ImportEagerDependency.Template() ); compilation.dependencyFactories.set( ImportWeakDependency, normalModuleFactory ); compilation.dependencyTemplates.set( ImportWeakDependency, new ImportWeakDependency.Template() ); compilation.dependencyFactories.set( ImportContextDependency, contextModuleFactory ); compilation.dependencyTemplates.set( ImportContextDependency, new ImportContextDependency.Template() ); const handler = (parser, parserOptions) => { if (parserOptions.import !== undefined && !parserOptions.import) return; new ImportParserPlugin(options).apply(parser); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("ImportPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("ImportPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("ImportPlugin", handler); } ); } } module.exports = ImportPlugin; webpack-4.30.0/lib/dependencies/ImportWeakDependency.js000066400000000000000000000014701345416772700230470ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class ImportWeakDependency extends ModuleDependency { constructor(request, originModule, range) { super(request); this.originModule = originModule; this.range = range; this.weak = true; } get type() { return "import() weak"; } } ImportWeakDependency.Template = class ImportDependencyTemplate { apply(dep, source, runtime) { const content = runtime.moduleNamespacePromise({ module: dep.module, request: dep.request, strict: dep.originModule.buildMeta.strictHarmonyModule, message: "import() weak", weak: true }); source.replace(dep.range[0], dep.range[1] - 1, content); } }; module.exports = ImportWeakDependency; webpack-4.30.0/lib/dependencies/JsonExportsDependency.js000066400000000000000000000007131345416772700232620ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class JsonExportsDependency extends NullDependency { constructor(exports) { super(); this.exports = exports; } get type() { return "json exports"; } getExports() { return { exports: this.exports, dependencies: undefined }; } } module.exports = JsonExportsDependency; webpack-4.30.0/lib/dependencies/LoaderDependency.js000066400000000000000000000006121345416772700221700ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class LoaderDependency extends ModuleDependency { /** * @param {string} request request string */ constructor(request) { super(request); } get type() { return "loader"; } } module.exports = LoaderDependency; webpack-4.30.0/lib/dependencies/LoaderPlugin.js000066400000000000000000000062521345416772700213560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const LoaderDependency = require("./LoaderDependency"); const NormalModule = require("../NormalModule"); /** @typedef {import("../Module")} Module */ /** * @callback LoadModuleCallback * @param {Error=} err error object * @param {string=} source source code * @param {object=} map source map * @param {Module=} module loaded module if successful */ class LoaderPlugin { apply(compiler) { compiler.hooks.compilation.tap( "LoaderPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( LoaderDependency, normalModuleFactory ); } ); compiler.hooks.compilation.tap("LoaderPlugin", compilation => { compilation.hooks.normalModuleLoader.tap( "LoaderPlugin", (loaderContext, module) => { /** * @param {string} request the request string to load the module from * @param {LoadModuleCallback} callback callback returning the loaded module or error * @returns {void} */ loaderContext.loadModule = (request, callback) => { const dep = new LoaderDependency(request); dep.loc = { name: request }; const factory = compilation.dependencyFactories.get( dep.constructor ); if (factory === undefined) { return callback( new Error( `No module factory available for dependency type: ${ dep.constructor.name }` ) ); } compilation.semaphore.release(); compilation.addModuleDependencies( module, [ { factory, dependencies: [dep] } ], true, "lm", true, err => { compilation.semaphore.acquire(() => { if (err) { return callback(err); } if (!dep.module) { return callback(new Error("Cannot load the module")); } // TODO consider removing this in webpack 5 if (dep.module instanceof NormalModule && dep.module.error) { return callback(dep.module.error); } if (!dep.module._source) { throw new Error( "The module created for a LoaderDependency must have a property _source" ); } let source, map; const moduleSource = dep.module._source; if (moduleSource.sourceAndMap) { const sourceAndMap = moduleSource.sourceAndMap(); map = sourceAndMap.map; source = sourceAndMap.source; } else { map = moduleSource.map(); source = moduleSource.source(); } if (dep.module.buildInfo.fileDependencies) { for (const d of dep.module.buildInfo.fileDependencies) { loaderContext.addDependency(d); } } if (dep.module.buildInfo.contextDependencies) { for (const d of dep.module.buildInfo.contextDependencies) { loaderContext.addContextDependency(d); } } return callback(null, source, map, dep.module); }); } ); }; } ); }); } } module.exports = LoaderPlugin; webpack-4.30.0/lib/dependencies/LocalModule.js000066400000000000000000000006211345416772700211630ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class LocalModule { constructor(module, name, idx) { this.module = module; this.name = name; this.idx = idx; this.used = false; } flagUsed() { this.used = true; } variableName() { return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; } } module.exports = LocalModule; webpack-4.30.0/lib/dependencies/LocalModuleDependency.js000066400000000000000000000014001345416772700231560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class LocalModuleDependency extends NullDependency { constructor(localModule, range, callNew) { super(); localModule.flagUsed(); this.localModule = localModule; this.range = range; this.callNew = callNew; } } LocalModuleDependency.Template = class LocalModuleDependencyTemplate { apply(dep, source) { if (!dep.range) return; const moduleInstance = dep.callNew ? `new (function () { return ${dep.localModule.variableName()}; })()` : dep.localModule.variableName(); source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); } }; module.exports = LocalModuleDependency; webpack-4.30.0/lib/dependencies/LocalModulesHelpers.js000066400000000000000000000022521345416772700226730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const LocalModule = require("./LocalModule"); const LocalModulesHelpers = exports; const lookup = (parent, mod) => { if (mod.charAt(0) !== ".") return mod; var path = parent.split("/"); var segs = mod.split("/"); path.pop(); for (let i = 0; i < segs.length; i++) { const seg = segs[i]; if (seg === "..") { path.pop(); } else if (seg !== ".") { path.push(seg); } } return path.join("/"); }; LocalModulesHelpers.addLocalModule = (state, name) => { if (!state.localModules) { state.localModules = []; } const m = new LocalModule(state.module, name, state.localModules.length); state.localModules.push(m); return m; }; LocalModulesHelpers.getLocalModule = (state, name, namedModule) => { if (!state.localModules) return null; if (namedModule) { // resolve dependency name relative to the defining named module name = lookup(namedModule, name); } for (let i = 0; i < state.localModules.length; i++) { if (state.localModules[i].name === name) { return state.localModules[i]; } } return null; }; module.exports = LocalModulesHelpers; webpack-4.30.0/lib/dependencies/ModuleDependency.js000066400000000000000000000007321345416772700222120ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); class ModuleDependency extends Dependency { /** * @param {string} request request path which needs resolving */ constructor(request) { super(); this.request = request; this.userRequest = request; } getResourceIdentifier() { return `module${this.request}`; } } module.exports = ModuleDependency; webpack-4.30.0/lib/dependencies/ModuleDependencyTemplateAsId.js000066400000000000000000000006321345416772700244460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ModuleDependencyTemplateAsId { apply(dep, source, runtime) { if (!dep.range) return; const content = runtime.moduleId({ module: dep.module, request: dep.request }); source.replace(dep.range[0], dep.range[1] - 1, content); } } module.exports = ModuleDependencyTemplateAsId; webpack-4.30.0/lib/dependencies/ModuleDependencyTemplateAsRequireId.js000066400000000000000000000006551345416772700260100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ModuleDependencyTemplateAsRequireId { apply(dep, source, runtime) { if (!dep.range) return; const content = runtime.moduleExports({ module: dep.module, request: dep.request }); source.replace(dep.range[0], dep.range[1] - 1, content); } } module.exports = ModuleDependencyTemplateAsRequireId; webpack-4.30.0/lib/dependencies/ModuleHotAcceptDependency.js000066400000000000000000000010671345416772700240070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); class ModuleHotAcceptDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; this.weak = true; } get type() { return "module.hot.accept"; } } ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; module.exports = ModuleHotAcceptDependency; webpack-4.30.0/lib/dependencies/ModuleHotDeclineDependency.js000066400000000000000000000010731345416772700241500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); class ModuleHotDeclineDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; this.weak = true; } get type() { return "module.hot.decline"; } } ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; module.exports = ModuleHotDeclineDependency; webpack-4.30.0/lib/dependencies/MultiEntryDependency.js000066400000000000000000000011331345416772700230750ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("./SingleEntryDependency")} SingleEntryDependency */ const Dependency = require("../Dependency"); class MultiEntryDependency extends Dependency { /** * @param {SingleEntryDependency[]} dependencies an array of SingleEntryDependencies * @param {string} name entry name */ constructor(dependencies, name) { super(); this.dependencies = dependencies; this.name = name; } get type() { return "multi entry"; } } module.exports = MultiEntryDependency; webpack-4.30.0/lib/dependencies/NullDependency.js000066400000000000000000000005531345416772700217000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); class NullDependency extends Dependency { get type() { return "null"; } updateHash() {} } NullDependency.Template = class NullDependencyTemplate { apply() {} }; module.exports = NullDependency; webpack-4.30.0/lib/dependencies/PrefetchDependency.js000066400000000000000000000005331345416772700225240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class PrefetchDependency extends ModuleDependency { constructor(request) { super(request); } get type() { return "prefetch"; } } module.exports = PrefetchDependency; webpack-4.30.0/lib/dependencies/RequireContextDependency.js000066400000000000000000000010661345416772700237470ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); class RequireContextDependency extends ContextDependency { constructor(options, range) { super(options); this.range = range; } get type() { return "require.context"; } } RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; module.exports = RequireContextDependency; webpack-4.30.0/lib/dependencies/RequireContextDependencyParserPlugin.js000066400000000000000000000027731345416772700263110ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequireContextDependency = require("./RequireContextDependency"); module.exports = class RequireContextDependencyParserPlugin { apply(parser) { parser.hooks.call .for("require.context") .tap("RequireContextDependencyParserPlugin", expr => { let regExp = /^\.\/.*$/; let recursive = true; let mode = "sync"; switch (expr.arguments.length) { case 4: { const modeExpr = parser.evaluateExpression(expr.arguments[3]); if (!modeExpr.isString()) return; mode = modeExpr.string; } // falls through case 3: { const regExpExpr = parser.evaluateExpression(expr.arguments[2]); if (!regExpExpr.isRegExp()) return; regExp = regExpExpr.regExp; } // falls through case 2: { const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); if (!recursiveExpr.isBoolean()) return; recursive = recursiveExpr.bool; } // falls through case 1: { const requestExpr = parser.evaluateExpression(expr.arguments[0]); if (!requestExpr.isString()) return; const dep = new RequireContextDependency( { request: requestExpr.string, recursive, regExp, mode }, expr.range ); dep.loc = expr.loc; dep.optional = parser.scope.inTry; parser.state.current.addDependency(dep); return true; } } }); } }; webpack-4.30.0/lib/dependencies/RequireContextPlugin.js000066400000000000000000000075021345416772700231300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequireContextDependency = require("./RequireContextDependency"); const ContextElementDependency = require("./ContextElementDependency"); const RequireContextDependencyParserPlugin = require("./RequireContextDependencyParserPlugin"); class RequireContextPlugin { constructor(modulesDirectories, extensions, mainFiles) { if (!Array.isArray(modulesDirectories)) { throw new Error("modulesDirectories must be an array"); } if (!Array.isArray(extensions)) { throw new Error("extensions must be an array"); } this.modulesDirectories = modulesDirectories; this.extensions = extensions; this.mainFiles = mainFiles; } apply(compiler) { compiler.hooks.compilation.tap( "RequireContextPlugin", (compilation, { contextModuleFactory, normalModuleFactory }) => { compilation.dependencyFactories.set( RequireContextDependency, contextModuleFactory ); compilation.dependencyTemplates.set( RequireContextDependency, new RequireContextDependency.Template() ); compilation.dependencyFactories.set( ContextElementDependency, normalModuleFactory ); const handler = (parser, parserOptions) => { if ( parserOptions.requireContext !== undefined && !parserOptions.requireContext ) return; new RequireContextDependencyParserPlugin().apply(parser); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("RequireContextPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("RequireContextPlugin", handler); contextModuleFactory.hooks.alternatives.tap( "RequireContextPlugin", items => { if (items.length === 0) return items; return items .map(obj => { return this.extensions .filter(ext => { const l = obj.request.length; return ( l > ext.length && obj.request.substr(l - ext.length, l) === ext ); }) .map(ext => { const l = obj.request.length; return { context: obj.context, request: obj.request.substr(0, l - ext.length) }; }) .concat(obj); }) .reduce((a, b) => a.concat(b), []); } ); contextModuleFactory.hooks.alternatives.tap( "RequireContextPlugin", items => { if (items.length === 0) return items; return items .map(obj => { return this.mainFiles .filter(mainFile => { const l = obj.request.length; return ( l > mainFile.length + 1 && obj.request.substr(l - mainFile.length - 1, l) === "/" + mainFile ); }) .map(mainFile => { const l = obj.request.length; return [ { context: obj.context, request: obj.request.substr(0, l - mainFile.length) }, { context: obj.context, request: obj.request.substr(0, l - mainFile.length - 1) } ]; }) .reduce((a, b) => a.concat(b), []) .concat(obj); }) .reduce((a, b) => a.concat(b), []); } ); contextModuleFactory.hooks.alternatives.tap( "RequireContextPlugin", items => { if (items.length === 0) return items; return items.map(obj => { for (let i = 0; i < this.modulesDirectories.length; i++) { const dir = this.modulesDirectories[i]; const idx = obj.request.indexOf("./" + dir + "/"); if (idx === 0) { obj.request = obj.request.slice(dir.length + 3); break; } } return obj; }); } ); } ); } } module.exports = RequireContextPlugin; webpack-4.30.0/lib/dependencies/RequireEnsureDependenciesBlock.js000066400000000000000000000015401345416772700250440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); const RequireEnsureDependency = require("./RequireEnsureDependency"); module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { constructor( expr, successExpression, errorExpression, chunkName, chunkNameRange, module, loc ) { super(chunkName, module, loc, null); this.expr = expr; const successBodyRange = successExpression && successExpression.body && successExpression.body.range; if (successBodyRange) { this.range = [successBodyRange[0] + 1, successBodyRange[1] - 1]; } this.chunkNameRange = chunkNameRange; const dep = new RequireEnsureDependency(this); dep.loc = loc; this.addDependency(dep); } }; webpack-4.30.0/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js000066400000000000000000000067131345416772700274070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequireEnsureDependenciesBlock = require("./RequireEnsureDependenciesBlock"); const RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); const getFunctionExpression = require("./getFunctionExpression"); module.exports = class RequireEnsureDependenciesBlockParserPlugin { apply(parser) { parser.hooks.call .for("require.ensure") .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { let chunkName = null; let chunkNameRange = null; let errorExpressionArg = null; let errorExpression = null; switch (expr.arguments.length) { case 4: { const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); if (!chunkNameExpr.isString()) return; chunkNameRange = chunkNameExpr.range; chunkName = chunkNameExpr.string; } // falls through case 3: { errorExpressionArg = expr.arguments[2]; errorExpression = getFunctionExpression(errorExpressionArg); if (!errorExpression && !chunkName) { const chunkNameExpr = parser.evaluateExpression( expr.arguments[2] ); if (!chunkNameExpr.isString()) return; chunkNameRange = chunkNameExpr.range; chunkName = chunkNameExpr.string; } } // falls through case 2: { const dependenciesExpr = parser.evaluateExpression( expr.arguments[0] ); const dependenciesItems = dependenciesExpr.isArray() ? dependenciesExpr.items : [dependenciesExpr]; const successExpressionArg = expr.arguments[1]; const successExpression = getFunctionExpression( successExpressionArg ); if (successExpression) { parser.walkExpressions(successExpression.expressions); } if (errorExpression) { parser.walkExpressions(errorExpression.expressions); } const dep = new RequireEnsureDependenciesBlock( expr, successExpression ? successExpression.fn : successExpressionArg, errorExpression ? errorExpression.fn : errorExpressionArg, chunkName, chunkNameRange, parser.state.module, expr.loc ); const old = parser.state.current; parser.state.current = dep; try { let failed = false; parser.inScope([], () => { for (const ee of dependenciesItems) { if (ee.isString()) { const edep = new RequireEnsureItemDependency(ee.string); edep.loc = dep.loc; dep.addDependency(edep); } else { failed = true; } } }); if (failed) { return; } if (successExpression) { if (successExpression.fn.body.type === "BlockStatement") { parser.walkStatement(successExpression.fn.body); } else { parser.walkExpression(successExpression.fn.body); } } old.addBlock(dep); } finally { parser.state.current = old; } if (!successExpression) { parser.walkExpression(successExpressionArg); } if (errorExpression) { if (errorExpression.fn.body.type === "BlockStatement") { parser.walkStatement(errorExpression.fn.body); } else { parser.walkExpression(errorExpression.fn.body); } } else if (errorExpressionArg) { parser.walkExpression(errorExpressionArg); } return true; } } }); } }; webpack-4.30.0/lib/dependencies/RequireEnsureDependency.js000066400000000000000000000026361345416772700235700ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class RequireEnsureDependency extends NullDependency { constructor(block) { super(); this.block = block; } get type() { return "require.ensure"; } } RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate { apply(dep, source, runtime) { const depBlock = dep.block; const promise = runtime.blockPromise({ block: depBlock, message: "require.ensure" }); const errorCallbackExists = depBlock.expr.arguments.length === 4 || (!depBlock.chunkName && depBlock.expr.arguments.length === 3); const startBlock = `${promise}.then((`; const middleBlock = ").bind(null, __webpack_require__)).catch("; const endBlock = `).bind(null, __webpack_require__)).catch(${runtime.onError()})`; source.replace( depBlock.expr.range[0], depBlock.expr.arguments[1].range[0] - 1, startBlock ); if (errorCallbackExists) { source.replace( depBlock.expr.arguments[1].range[1], depBlock.expr.arguments[2].range[0] - 1, middleBlock ); source.replace( depBlock.expr.arguments[2].range[1], depBlock.expr.range[1] - 1, ")" ); } else { source.replace( depBlock.expr.arguments[1].range[1], depBlock.expr.range[1] - 1, endBlock ); } } }; module.exports = RequireEnsureDependency; webpack-4.30.0/lib/dependencies/RequireEnsureItemDependency.js000066400000000000000000000007551345416772700244070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const NullDependency = require("./NullDependency"); class RequireEnsureItemDependency extends ModuleDependency { constructor(request) { super(request); } get type() { return "require.ensure item"; } } RequireEnsureItemDependency.Template = NullDependency.Template; module.exports = RequireEnsureItemDependency; webpack-4.30.0/lib/dependencies/RequireEnsurePlugin.js000066400000000000000000000036721345416772700227510ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); const RequireEnsureDependency = require("./RequireEnsureDependency"); const NullFactory = require("../NullFactory"); const RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDependenciesBlockParserPlugin"); const ParserHelpers = require("../ParserHelpers"); class RequireEnsurePlugin { apply(compiler) { compiler.hooks.compilation.tap( "RequireEnsurePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( RequireEnsureItemDependency, normalModuleFactory ); compilation.dependencyTemplates.set( RequireEnsureItemDependency, new RequireEnsureItemDependency.Template() ); compilation.dependencyFactories.set( RequireEnsureDependency, new NullFactory() ); compilation.dependencyTemplates.set( RequireEnsureDependency, new RequireEnsureDependency.Template() ); const handler = (parser, parserOptions) => { if ( parserOptions.requireEnsure !== undefined && !parserOptions.requireEnsure ) return; new RequireEnsureDependenciesBlockParserPlugin().apply(parser); parser.hooks.evaluateTypeof .for("require.ensure") .tap( "RequireEnsurePlugin", ParserHelpers.evaluateToString("function") ); parser.hooks.typeof .for("require.ensure") .tap( "RequireEnsurePlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("function") ) ); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("RequireEnsurePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("RequireEnsurePlugin", handler); } ); } } module.exports = RequireEnsurePlugin; webpack-4.30.0/lib/dependencies/RequireHeaderDependency.js000066400000000000000000000012521345416772700235100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class RequireHeaderDependency extends NullDependency { constructor(range) { super(); if (!Array.isArray(range)) throw new Error("range must be valid"); this.range = range; } } RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate { apply(dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); } applyAsTemplateArgument(name, dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "require"); } }; module.exports = RequireHeaderDependency; webpack-4.30.0/lib/dependencies/RequireIncludeDependency.js000066400000000000000000000017431345416772700237100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependencyReference = require("./DependencyReference"); const ModuleDependency = require("./ModuleDependency"); const Template = require("../Template"); class RequireIncludeDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } getReference() { if (!this.module) return null; // This doesn't use any export return new DependencyReference(this.module, [], false); } get type() { return "require.include"; } } RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate { apply(dep, source, runtime) { const comment = runtime.outputOptions.pathinfo ? Template.toComment( `require.include ${runtime.requestShortener.shorten(dep.request)}` ) : ""; source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); } }; module.exports = RequireIncludeDependency; webpack-4.30.0/lib/dependencies/RequireIncludeDependencyParserPlugin.js000066400000000000000000000012571345416772700262440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequireIncludeDependency = require("./RequireIncludeDependency"); module.exports = class RequireIncludeDependencyParserPlugin { apply(parser) { parser.hooks.call .for("require.include") .tap("RequireIncludeDependencyParserPlugin", expr => { if (expr.arguments.length !== 1) return; const param = parser.evaluateExpression(expr.arguments[0]); if (!param.isString()) return; const dep = new RequireIncludeDependency(param.string, expr.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; }); } }; webpack-4.30.0/lib/dependencies/RequireIncludePlugin.js000066400000000000000000000031151345416772700230630ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequireIncludeDependency = require("./RequireIncludeDependency"); const RequireIncludeDependencyParserPlugin = require("./RequireIncludeDependencyParserPlugin"); const ParserHelpers = require("../ParserHelpers"); class RequireIncludePlugin { apply(compiler) { compiler.hooks.compilation.tap( "RequireIncludePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( RequireIncludeDependency, normalModuleFactory ); compilation.dependencyTemplates.set( RequireIncludeDependency, new RequireIncludeDependency.Template() ); const handler = (parser, parserOptions) => { if ( parserOptions.requireInclude !== undefined && !parserOptions.requireInclude ) return; new RequireIncludeDependencyParserPlugin().apply(parser); parser.hooks.evaluateTypeof .for("require.include") .tap( "RequireIncludePlugin", ParserHelpers.evaluateToString("function") ); parser.hooks.typeof .for("require.include") .tap( "RequireIncludePlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("function") ) ); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("RequireIncludePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("RequireIncludePlugin", handler); } ); } } module.exports = RequireIncludePlugin; webpack-4.30.0/lib/dependencies/RequireResolveContextDependency.js000066400000000000000000000011511345416772700253020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const ContextDependencyTemplateAsId = require("./ContextDependencyTemplateAsId"); class RequireResolveContextDependency extends ContextDependency { constructor(options, range, valueRange) { super(options); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } } RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; module.exports = RequireResolveContextDependency; webpack-4.30.0/lib/dependencies/RequireResolveDependency.js000066400000000000000000000010161345416772700237350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const ModuleDependencyAsId = require("./ModuleDependencyTemplateAsId"); class RequireResolveDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "require.resolve"; } } RequireResolveDependency.Template = ModuleDependencyAsId; module.exports = RequireResolveDependency; webpack-4.30.0/lib/dependencies/RequireResolveDependencyParserPlugin.js000066400000000000000000000046341345416772700263020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RequireResolveDependency = require("./RequireResolveDependency"); const RequireResolveContextDependency = require("./RequireResolveContextDependency"); const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency"); const ContextDependencyHelpers = require("./ContextDependencyHelpers"); class RequireResolveDependencyParserPlugin { constructor(options) { this.options = options; } apply(parser) { const options = this.options; const process = (expr, weak) => { if (expr.arguments.length !== 1) return; const param = parser.evaluateExpression(expr.arguments[0]); if (param.isConditional()) { for (const option of param.options) { const result = processItem(expr, option, weak); if (result === undefined) { processContext(expr, option, weak); } } const dep = new RequireResolveHeaderDependency(expr.callee.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; } else { const result = processItem(expr, param, weak); if (result === undefined) { processContext(expr, param, weak); } const dep = new RequireResolveHeaderDependency(expr.callee.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; } }; const processItem = (expr, param, weak) => { if (param.isString()) { const dep = new RequireResolveDependency(param.string, param.range); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; dep.weak = weak; parser.state.current.addDependency(dep); return true; } }; const processContext = (expr, param, weak) => { const dep = ContextDependencyHelpers.create( RequireResolveContextDependency, param.range, param, expr, options, { mode: weak ? "weak" : "sync" }, parser ); if (!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; }; parser.hooks.call .for("require.resolve") .tap("RequireResolveDependencyParserPlugin", expr => { return process(expr, false); }); parser.hooks.call .for("require.resolveWeak") .tap("RequireResolveDependencyParserPlugin", expr => { return process(expr, true); }); } } module.exports = RequireResolveDependencyParserPlugin; webpack-4.30.0/lib/dependencies/RequireResolveHeaderDependency.js000066400000000000000000000013221345416772700250460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class RequireResolveHeaderDependency extends NullDependency { constructor(range) { super(); if (!Array.isArray(range)) throw new Error("range must be valid"); this.range = range; } } RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate { apply(dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); } applyAsTemplateArgument(name, dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); } }; module.exports = RequireResolveHeaderDependency; webpack-4.30.0/lib/dependencies/SingleEntryDependency.js000066400000000000000000000006421345416772700232300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class SingleEntryDependency extends ModuleDependency { /** * @param {string} request request path for entry */ constructor(request) { super(request); } get type() { return "single entry"; } } module.exports = SingleEntryDependency; webpack-4.30.0/lib/dependencies/SystemPlugin.js000066400000000000000000000060631345416772700214340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ParserHelpers = require("../ParserHelpers"); const WebpackError = require("../WebpackError"); class SystemPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.hooks.compilation.tap( "SystemPlugin", (compilation, { normalModuleFactory }) => { const handler = (parser, parserOptions) => { if (parserOptions.system !== undefined && !parserOptions.system) return; const shouldWarn = parserOptions.system === undefined; const setNotSupported = name => { parser.hooks.evaluateTypeof .for(name) .tap("SystemPlugin", ParserHelpers.evaluateToString("undefined")); parser.hooks.expression .for(name) .tap( "SystemPlugin", ParserHelpers.expressionIsUnsupported( parser, name + " is not supported by webpack." ) ); }; parser.hooks.typeof .for("System.import") .tap( "SystemPlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("function") ) ); parser.hooks.evaluateTypeof .for("System.import") .tap("SystemPlugin", ParserHelpers.evaluateToString("function")); parser.hooks.typeof .for("System") .tap( "SystemPlugin", ParserHelpers.toConstantDependency( parser, JSON.stringify("object") ) ); parser.hooks.evaluateTypeof .for("System") .tap("SystemPlugin", ParserHelpers.evaluateToString("object")); setNotSupported("System.set"); setNotSupported("System.get"); setNotSupported("System.register"); parser.hooks.expression.for("System").tap("SystemPlugin", () => { const systemPolyfillRequire = ParserHelpers.requireFileAsExpression( parser.state.module.context, require.resolve("../../buildin/system") ); return ParserHelpers.addParsedVariableToModule( parser, "System", systemPolyfillRequire ); }); parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { if (shouldWarn) { parser.state.module.warnings.push( new SystemImportDeprecationWarning( parser.state.module, expr.loc ) ); } return parser.hooks.importCall.call(expr); }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("SystemPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("SystemPlugin", handler); } ); } } class SystemImportDeprecationWarning extends WebpackError { constructor(module, loc) { super( "System.import() is deprecated and will be removed soon. Use import() instead.\n" + "For more info visit https://webpack.js.org/guides/code-splitting/" ); this.name = "SystemImportDeprecationWarning"; this.module = module; this.loc = loc; Error.captureStackTrace(this, this.constructor); } } module.exports = SystemPlugin; webpack-4.30.0/lib/dependencies/UnsupportedDependency.js000066400000000000000000000011661345416772700233170ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); const webpackMissingModule = require("./WebpackMissingModule").module; class UnsupportedDependency extends NullDependency { constructor(request, range) { super(); this.request = request; this.range = range; } } UnsupportedDependency.Template = class UnsupportedDependencyTemplate { apply(dep, source, runtime) { source.replace( dep.range[0], dep.range[1], webpackMissingModule(dep.request) ); } }; module.exports = UnsupportedDependency; webpack-4.30.0/lib/dependencies/WebAssemblyExportImportedDependency.js000066400000000000000000000013671345416772700261150ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependencyReference = require("./DependencyReference"); const ModuleDependency = require("./ModuleDependency"); class WebAssemblyExportImportedDependency extends ModuleDependency { constructor(exportName, request, name, valueType) { super(request); /** @type {string} */ this.exportName = exportName; /** @type {string} */ this.name = name; /** @type {string} */ this.valueType = valueType; } getReference() { if (!this.module) return null; return new DependencyReference(this.module, [this.name], false); } get type() { return "wasm export import"; } } module.exports = WebAssemblyExportImportedDependency; webpack-4.30.0/lib/dependencies/WebAssemblyImportDependency.js000066400000000000000000000030351345416772700243740ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependencyReference = require("./DependencyReference"); const ModuleDependency = require("./ModuleDependency"); const UnsupportedWebAssemblyFeatureError = require("../wasm/UnsupportedWebAssemblyFeatureError"); /** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ class WebAssemblyImportDependency extends ModuleDependency { /** * @param {string} request the request * @param {string} name the imported name * @param {ModuleImportDescription} description the WASM ast node * @param {false | string} onlyDirectImport if only direct imports are allowed */ constructor(request, name, description, onlyDirectImport) { super(request); /** @type {string} */ this.name = name; /** @type {ModuleImportDescription} */ this.description = description; /** @type {false | string} */ this.onlyDirectImport = onlyDirectImport; } getReference() { if (!this.module) return null; return new DependencyReference(this.module, [this.name], false); } getErrors() { if ( this.onlyDirectImport && this.module && !this.module.type.startsWith("webassembly") ) { return [ new UnsupportedWebAssemblyFeatureError( `Import "${this.name}" from "${this.request}" with ${ this.onlyDirectImport } can only be used for direct wasm to wasm dependencies` ) ]; } } get type() { return "wasm import"; } } module.exports = WebAssemblyImportDependency; webpack-4.30.0/lib/dependencies/WebpackMissingModule.js000066400000000000000000000012121345416772700230340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const toErrorCode = err => `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`; exports.module = request => `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`; exports.promise = request => { const errorCode = toErrorCode(`Cannot find module '${request}'`); return `Promise.reject(function webpackMissingModule() { ${errorCode} return e; }())`; }; exports.moduleCode = request => { const errorCode = toErrorCode(`Cannot find module '${request}'`); return `${errorCode} throw e;`; }; webpack-4.30.0/lib/dependencies/getFunctionExpression.js000066400000000000000000000025211345416772700233310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ module.exports = expr => { // if ( expr.type === "FunctionExpression" || expr.type === "ArrowFunctionExpression" ) { return { fn: expr, expressions: [], needThis: false }; } // .bind() if ( expr.type === "CallExpression" && expr.callee.type === "MemberExpression" && expr.callee.object.type === "FunctionExpression" && expr.callee.property.type === "Identifier" && expr.callee.property.name === "bind" && expr.arguments.length === 1 ) { return { fn: expr.callee.object, expressions: [expr.arguments[0]], needThis: undefined }; } // (function(_this) {return })(this) (Coffeescript) if ( expr.type === "CallExpression" && expr.callee.type === "FunctionExpression" && expr.callee.body.type === "BlockStatement" && expr.arguments.length === 1 && expr.arguments[0].type === "ThisExpression" && expr.callee.body.body && expr.callee.body.body.length === 1 && expr.callee.body.body[0].type === "ReturnStatement" && expr.callee.body.body[0].argument && expr.callee.body.body[0].argument.type === "FunctionExpression" ) { return { fn: expr.callee.body.body[0].argument, expressions: [], needThis: true }; } }; webpack-4.30.0/lib/formatLocation.js000066400000000000000000000040151345416772700173170ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("./Dependency").SourcePosition} SourcePosition */ // TODO webpack 5: pos must be SourcePosition /** * @param {SourcePosition|DependencyLocation|string} pos position * @returns {string} formatted position */ const formatPosition = pos => { if (pos === null) return ""; // TODO webpack 5: Simplify this if (typeof pos === "string") return pos; if (typeof pos === "number") return `${pos}`; if (typeof pos === "object") { if ("line" in pos && "column" in pos) { return `${pos.line}:${pos.column}`; } else if ("line" in pos) { return `${pos.line}:?`; } else if ("index" in pos) { // TODO webpack 5 remove this case return `+${pos.index}`; } else { return ""; } } return ""; }; // TODO webpack 5: loc must be DependencyLocation /** * @param {DependencyLocation|SourcePosition|string} loc location * @returns {string} formatted location */ const formatLocation = loc => { if (loc === null) return ""; // TODO webpack 5: Simplify this if (typeof loc === "string") return loc; if (typeof loc === "number") return `${loc}`; if (typeof loc === "object") { if ("start" in loc && loc.start && "end" in loc && loc.end) { if ( typeof loc.start === "object" && typeof loc.start.line === "number" && typeof loc.end === "object" && typeof loc.end.line === "number" && typeof loc.end.column === "number" && loc.start.line === loc.end.line ) { return `${formatPosition(loc.start)}-${loc.end.column}`; } else { return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; } } if ("start" in loc && loc.start) { return formatPosition(loc.start); } if ("name" in loc && "index" in loc) { return `${loc.name}[${loc.index}]`; } if ("name" in loc) { return loc.name; } return formatPosition(loc); } return ""; }; module.exports = formatLocation; webpack-4.30.0/lib/node/000077500000000000000000000000001345416772700147255ustar00rootroot00000000000000webpack-4.30.0/lib/node/NodeChunkTemplatePlugin.js000066400000000000000000000012621345416772700220150ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); class NodeChunkTemplatePlugin { apply(chunkTemplate) { chunkTemplate.hooks.render.tap( "NodeChunkTemplatePlugin", (modules, chunk) => { const source = new ConcatSource(); source.add( `exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = ` ); source.add(modules); source.add(";"); return source; } ); chunkTemplate.hooks.hash.tap("NodeChunkTemplatePlugin", hash => { hash.update("node"); hash.update("3"); }); } } module.exports = NodeChunkTemplatePlugin; webpack-4.30.0/lib/node/NodeEnvironmentPlugin.js000066400000000000000000000016771345416772700215670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NodeWatchFileSystem = require("./NodeWatchFileSystem"); const NodeOutputFileSystem = require("./NodeOutputFileSystem"); const NodeJsInputFileSystem = require("enhanced-resolve/lib/NodeJsInputFileSystem"); const CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem"); class NodeEnvironmentPlugin { apply(compiler) { compiler.inputFileSystem = new CachedInputFileSystem( new NodeJsInputFileSystem(), 60000 ); const inputFileSystem = compiler.inputFileSystem; compiler.outputFileSystem = new NodeOutputFileSystem(); compiler.watchFileSystem = new NodeWatchFileSystem( compiler.inputFileSystem ); compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { if (compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); }); } } module.exports = NodeEnvironmentPlugin; webpack-4.30.0/lib/node/NodeHotUpdateChunkTemplatePlugin.js000066400000000000000000000017321345416772700236350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); class NodeHotUpdateChunkTemplatePlugin { apply(hotUpdateChunkTemplate) { hotUpdateChunkTemplate.hooks.render.tap( "NodeHotUpdateChunkTemplatePlugin", (modulesSource, modules, removedModules, hash, id) => { const source = new ConcatSource(); source.add( "exports.id = " + JSON.stringify(id) + ";\nexports.modules = " ); source.add(modulesSource); source.add(";"); return source; } ); hotUpdateChunkTemplate.hooks.hash.tap( "NodeHotUpdateChunkTemplatePlugin", hash => { hash.update("NodeHotUpdateChunkTemplatePlugin"); hash.update("3"); hash.update( hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" ); hash.update(hotUpdateChunkTemplate.outputOptions.library + ""); } ); } } module.exports = NodeHotUpdateChunkTemplatePlugin; webpack-4.30.0/lib/node/NodeMainTemplate.runtime.js000066400000000000000000000013521345416772700221340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*global installedChunks $hotChunkFilename$ hotAddUpdateChunk $hotMainFilename$ */ module.exports = function() { // eslint-disable-next-line no-unused-vars function hotDownloadUpdateChunk(chunkId) { var chunk = require("./" + $hotChunkFilename$); hotAddUpdateChunk(chunk.id, chunk.modules); } // eslint-disable-next-line no-unused-vars function hotDownloadManifest() { try { var update = require("./" + $hotMainFilename$); } catch (e) { return Promise.resolve(); } return Promise.resolve(update); } //eslint-disable-next-line no-unused-vars function hotDisposeChunk(chunkId) { delete installedChunks[chunkId]; } }; webpack-4.30.0/lib/node/NodeMainTemplateAsync.runtime.js000066400000000000000000000024101345416772700231260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*global installedChunks $hotChunkFilename$ $require$ hotAddUpdateChunk $hotMainFilename$ */ module.exports = function() { // eslint-disable-next-line no-unused-vars function hotDownloadUpdateChunk(chunkId) { var filename = require("path").join(__dirname, $hotChunkFilename$); require("fs").readFile(filename, "utf-8", function(err, content) { if (err) { if ($require$.onError) return $require$.oe(err); throw err; } var chunk = {}; require("vm").runInThisContext( "(function(exports) {" + content + "\n})", { filename: filename } )(chunk); hotAddUpdateChunk(chunk.id, chunk.modules); }); } // eslint-disable-next-line no-unused-vars function hotDownloadManifest() { var filename = require("path").join(__dirname, $hotMainFilename$); return new Promise(function(resolve, reject) { require("fs").readFile(filename, "utf-8", function(err, content) { if (err) return resolve(); try { var update = JSON.parse(content); } catch (e) { return reject(e); } resolve(update); }); }); } // eslint-disable-next-line no-unused-vars function hotDisposeChunk(chunkId) { delete installedChunks[chunkId]; } }; webpack-4.30.0/lib/node/NodeMainTemplatePlugin.js000066400000000000000000000241001345416772700216250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("../Template"); module.exports = class NodeMainTemplatePlugin { constructor(asyncChunkLoading) { this.asyncChunkLoading = asyncChunkLoading; } apply(mainTemplate) { const needChunkOnDemandLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; const asyncChunkLoading = this.asyncChunkLoading; mainTemplate.hooks.localVars.tap( "NodeMainTemplatePlugin", (source, chunk) => { if (needChunkOnDemandLoadingCode(chunk)) { return Template.asString([ source, "", "// object to store loaded chunks", '// "0" means "already loaded"', "var installedChunks = {", Template.indent( chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") ), "};" ]); } return source; } ); mainTemplate.hooks.requireExtensions.tap( "NodeMainTemplatePlugin", (source, chunk) => { if (needChunkOnDemandLoadingCode(chunk)) { return Template.asString([ source, "", "// uncaught error handler for webpack runtime", `${mainTemplate.requireFn}.oe = function(err) {`, Template.indent([ "process.nextTick(function() {", Template.indent( "throw err; // catch this error by using import().catch()" ), "});" ]), "};" ]); } return source; } ); mainTemplate.hooks.requireEnsure.tap( "NodeMainTemplatePlugin", (source, chunk, hash) => { const chunkFilename = mainTemplate.outputOptions.chunkFilename; const chunkMaps = chunk.getChunkMaps(); const insertMoreModules = [ "var moreModules = chunk.modules, chunkIds = chunk.ids;", "for(var moduleId in moreModules) {", Template.indent( mainTemplate.renderAddModule( hash, chunk, "moduleId", "moreModules[moduleId]" ) ), "}" ]; if (asyncChunkLoading) { return Template.asString([ source, "", "// ReadFile + VM.run chunk loading for javascript", "", "var installedChunkData = installedChunks[chunkId];", 'if(installedChunkData !== 0) { // 0 means "already installed".', Template.indent([ '// array of [resolve, reject, promise] means "currently loading"', "if(installedChunkData) {", Template.indent(["promises.push(installedChunkData[2]);"]), "} else {", Template.indent([ "// load the chunk and return promise to it", "var promise = new Promise(function(resolve, reject) {", Template.indent([ "installedChunkData = installedChunks[chunkId] = [resolve, reject];", "var filename = require('path').join(__dirname, " + mainTemplate.getAssetPath( JSON.stringify(`/${chunkFilename}`), { hash: `" + ${mainTemplate.renderCurrentHashCode( hash )} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode( hash, length )} + "`, chunk: { id: '" + chunkId + "', hash: `" + ${JSON.stringify( chunkMaps.hash )}[chunkId] + "`, hashWithLength: length => { const shortChunkHashMap = {}; for (const chunkId of Object.keys(chunkMaps.hash)) { if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[ chunkId ].substr(0, length); } } return `" + ${JSON.stringify( shortChunkHashMap )}[chunkId] + "`; }, contentHash: { javascript: `" + ${JSON.stringify( chunkMaps.contentHash.javascript )}[chunkId] + "` }, contentHashWithLength: { javascript: length => { const shortContentHashMap = {}; const contentHash = chunkMaps.contentHash.javascript; for (const chunkId of Object.keys(contentHash)) { if (typeof contentHash[chunkId] === "string") { shortContentHashMap[chunkId] = contentHash[ chunkId ].substr(0, length); } } return `" + ${JSON.stringify( shortContentHashMap )}[chunkId] + "`; } }, name: `" + (${JSON.stringify( chunkMaps.name )}[chunkId]||chunkId) + "` }, contentHashType: "javascript" } ) + ");", "require('fs').readFile(filename, 'utf-8', function(err, content) {", Template.indent( [ "if(err) return reject(err);", "var chunk = {};", "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + "(chunk, require, require('path').dirname(filename), filename);" ] .concat(insertMoreModules) .concat([ "var callbacks = [];", "for(var i = 0; i < chunkIds.length; i++) {", Template.indent([ "if(installedChunks[chunkIds[i]])", Template.indent([ "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);" ]), "installedChunks[chunkIds[i]] = 0;" ]), "}", "for(i = 0; i < callbacks.length; i++)", Template.indent("callbacks[i]();") ]) ), "});" ]), "});", "promises.push(installedChunkData[2] = promise);" ]), "}" ]), "}" ]); } else { const request = mainTemplate.getAssetPath( JSON.stringify(`./${chunkFilename}`), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: '" + chunkId + "', hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hashWithLength: length => { const shortChunkHashMap = {}; for (const chunkId of Object.keys(chunkMaps.hash)) { if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[ chunkId ].substr(0, length); } } return `" + ${JSON.stringify( shortChunkHashMap )}[chunkId] + "`; }, contentHash: { javascript: `" + ${JSON.stringify( chunkMaps.contentHash.javascript )}[chunkId] + "` }, contentHashWithLength: { javascript: length => { const shortContentHashMap = {}; const contentHash = chunkMaps.contentHash.javascript; for (const chunkId of Object.keys(contentHash)) { if (typeof contentHash[chunkId] === "string") { shortContentHashMap[chunkId] = contentHash[ chunkId ].substr(0, length); } } return `" + ${JSON.stringify( shortContentHashMap )}[chunkId] + "`; } }, name: `" + (${JSON.stringify( chunkMaps.name )}[chunkId]||chunkId) + "` }, contentHashType: "javascript" } ); return Template.asString([ source, "", "// require() chunk loading for javascript", "", '// "0" is the signal for "already loaded"', "if(installedChunks[chunkId] !== 0) {", Template.indent( [`var chunk = require(${request});`] .concat(insertMoreModules) .concat([ "for(var i = 0; i < chunkIds.length; i++)", Template.indent("installedChunks[chunkIds[i]] = 0;") ]) ), "}" ]); } } ); mainTemplate.hooks.hotBootstrap.tap( "NodeMainTemplatePlugin", (source, chunk, hash) => { const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename; const chunkMaps = chunk.getChunkMaps(); const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: '" + chunkId + "', hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hashWithLength: length => { const shortChunkHashMap = {}; for (const chunkId of Object.keys(chunkMaps.hash)) { if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( 0, length ); } } return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`; }, name: `" + (${JSON.stringify( chunkMaps.name )}[chunkId]||chunkId) + "` } } ); const currentHotUpdateMainFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateMainFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` } ); return Template.getFunctionContent( asyncChunkLoading ? require("./NodeMainTemplateAsync.runtime") : require("./NodeMainTemplate.runtime") ) .replace(/\$require\$/g, mainTemplate.requireFn) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename); } ); mainTemplate.hooks.hash.tap("NodeMainTemplatePlugin", hash => { hash.update("node"); hash.update("4"); }); } }; webpack-4.30.0/lib/node/NodeOutputFileSystem.js000066400000000000000000000007671345416772700214100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const fs = require("fs"); const path = require("path"); const mkdirp = require("mkdirp"); class NodeOutputFileSystem { constructor() { this.mkdirp = mkdirp; this.mkdir = fs.mkdir.bind(fs); this.rmdir = fs.rmdir.bind(fs); this.unlink = fs.unlink.bind(fs); this.writeFile = fs.writeFile.bind(fs); this.join = path.join.bind(path); } } module.exports = NodeOutputFileSystem; webpack-4.30.0/lib/node/NodeSourcePlugin.js000066400000000000000000000076061345416772700205210ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin"); const ParserHelpers = require("../ParserHelpers"); const nodeLibsBrowser = require("node-libs-browser"); module.exports = class NodeSourcePlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; if (options === false) { // allow single kill switch to turn off this plugin return; } const getPathToModule = (module, type) => { if (type === true || (type === undefined && nodeLibsBrowser[module])) { if (!nodeLibsBrowser[module]) { throw new Error( `No browser version for node.js core module ${module} available` ); } return nodeLibsBrowser[module]; } else if (type === "mock") { return require.resolve(`node-libs-browser/mock/${module}`); } else if (type === "empty") { return require.resolve("node-libs-browser/mock/empty"); } else { return module; } }; const addExpression = (parser, name, module, type, suffix) => { suffix = suffix || ""; parser.hooks.expression.for(name).tap("NodeSourcePlugin", () => { if ( parser.state.module && parser.state.module.resource === getPathToModule(module, type) ) return; const mockModule = ParserHelpers.requireFileAsExpression( parser.state.module.context, getPathToModule(module, type) ); return ParserHelpers.addParsedVariableToModule( parser, name, mockModule + suffix ); }); }; compiler.hooks.compilation.tap( "NodeSourcePlugin", (compilation, { normalModuleFactory }) => { const handler = (parser, parserOptions) => { if (parserOptions.node === false) return; let localOptions = options; if (parserOptions.node) { localOptions = Object.assign({}, localOptions, parserOptions.node); } if (localOptions.global) { parser.hooks.expression .for("global") .tap("NodeSourcePlugin", () => { const retrieveGlobalModule = ParserHelpers.requireFileAsExpression( parser.state.module.context, require.resolve("../../buildin/global") ); return ParserHelpers.addParsedVariableToModule( parser, "global", retrieveGlobalModule ); }); } if (localOptions.process) { const processType = localOptions.process; addExpression(parser, "process", "process", processType); } if (localOptions.console) { const consoleType = localOptions.console; addExpression(parser, "console", "console", consoleType); } const bufferType = localOptions.Buffer; if (bufferType) { addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); } if (localOptions.setImmediate) { const setImmediateType = localOptions.setImmediate; addExpression( parser, "setImmediate", "timers", setImmediateType, ".setImmediate" ); addExpression( parser, "clearImmediate", "timers", setImmediateType, ".clearImmediate" ); } }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("NodeSourcePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("NodeSourcePlugin", handler); } ); compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => { for (const lib of Object.keys(nodeLibsBrowser)) { if (options[lib] !== false) { compiler.resolverFactory.hooks.resolver .for("normal") .tap("NodeSourcePlugin", resolver => { new AliasPlugin( "described-resolve", { name: lib, onlyModule: true, alias: getPathToModule(lib, options[lib]) }, "resolve" ).apply(resolver); }); } } }); } }; webpack-4.30.0/lib/node/NodeTargetPlugin.js000066400000000000000000000007741345416772700205060ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ExternalsPlugin = require("../ExternalsPlugin"); const builtins = // eslint-disable-next-line node/no-unsupported-features/node-builtins,node/no-deprecated-api require("module").builtinModules || Object.keys(process.binding("natives")); class NodeTargetPlugin { apply(compiler) { new ExternalsPlugin("commonjs", builtins).apply(compiler); } } module.exports = NodeTargetPlugin; webpack-4.30.0/lib/node/NodeTemplatePlugin.js000066400000000000000000000015601345416772700210250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NodeMainTemplatePlugin = require("./NodeMainTemplatePlugin"); const NodeChunkTemplatePlugin = require("./NodeChunkTemplatePlugin"); const NodeHotUpdateChunkTemplatePlugin = require("./NodeHotUpdateChunkTemplatePlugin"); class NodeTemplatePlugin { constructor(options) { options = options || {}; this.asyncChunkLoading = options.asyncChunkLoading; } apply(compiler) { compiler.hooks.thisCompilation.tap("NodeTemplatePlugin", compilation => { new NodeMainTemplatePlugin(this.asyncChunkLoading).apply( compilation.mainTemplate ); new NodeChunkTemplatePlugin().apply(compilation.chunkTemplate); new NodeHotUpdateChunkTemplatePlugin().apply( compilation.hotUpdateChunkTemplate ); }); } } module.exports = NodeTemplatePlugin; webpack-4.30.0/lib/node/NodeWatchFileSystem.js000066400000000000000000000052761345416772700211560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Watchpack = require("watchpack"); const objectToMap = require("../util/objectToMap"); class NodeWatchFileSystem { constructor(inputFileSystem) { this.inputFileSystem = inputFileSystem; this.watcherOptions = { aggregateTimeout: 0 }; this.watcher = new Watchpack(this.watcherOptions); } watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { if (!Array.isArray(files)) { throw new Error("Invalid arguments: 'files'"); } if (!Array.isArray(dirs)) { throw new Error("Invalid arguments: 'dirs'"); } if (!Array.isArray(missing)) { throw new Error("Invalid arguments: 'missing'"); } if (typeof callback !== "function") { throw new Error("Invalid arguments: 'callback'"); } if (typeof startTime !== "number" && startTime) { throw new Error("Invalid arguments: 'startTime'"); } if (typeof options !== "object") { throw new Error("Invalid arguments: 'options'"); } if (typeof callbackUndelayed !== "function" && callbackUndelayed) { throw new Error("Invalid arguments: 'callbackUndelayed'"); } const oldWatcher = this.watcher; this.watcher = new Watchpack(options); if (callbackUndelayed) { this.watcher.once("change", callbackUndelayed); } const cachedFiles = files; const cachedDirs = dirs; this.watcher.once("aggregated", (changes, removals) => { changes = changes.concat(removals); if (this.inputFileSystem && this.inputFileSystem.purge) { this.inputFileSystem.purge(changes); } const times = objectToMap(this.watcher.getTimes()); files = new Set(files); dirs = new Set(dirs); missing = new Set(missing); removals = new Set(removals.filter(file => files.has(file))); callback( null, changes.filter(file => files.has(file)).sort(), changes.filter(file => dirs.has(file)).sort(), changes.filter(file => missing.has(file)).sort(), times, times, removals ); }); this.watcher.watch( cachedFiles.concat(missing), cachedDirs.concat(missing), startTime ); if (oldWatcher) { oldWatcher.close(); } return { close: () => { if (this.watcher) { this.watcher.close(); this.watcher = null; } }, pause: () => { if (this.watcher) { this.watcher.pause(); } }, getFileTimestamps: () => { if (this.watcher) { return objectToMap(this.watcher.getTimes()); } else { return new Map(); } }, getContextTimestamps: () => { if (this.watcher) { return objectToMap(this.watcher.getTimes()); } else { return new Map(); } } }; } } module.exports = NodeWatchFileSystem; webpack-4.30.0/lib/node/ReadFileCompileWasmTemplatePlugin.js000066400000000000000000000026551345416772700237620ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("../Template"); const WasmMainTemplatePlugin = require("../wasm/WasmMainTemplatePlugin"); class ReadFileCompileWasmTemplatePlugin { constructor(options) { this.options = options || {}; } apply(compiler) { compiler.hooks.thisCompilation.tap( "ReadFileCompileWasmTemplatePlugin", compilation => { const generateLoadBinaryCode = path => Template.asString([ "new Promise(function (resolve, reject) {", Template.indent([ "var { readFile } = require('fs');", "var { join } = require('path');", "", "try {", Template.indent([ `readFile(join(__dirname, ${path}), function(err, buffer){`, Template.indent([ "if (err) return reject(err);", "", "// Fake fetch response", "resolve({", Template.indent([ "arrayBuffer() { return Promise.resolve(buffer); }" ]), "});" ]), "});" ]), "} catch (err) { reject(err); }" ]), "})" ]); const plugin = new WasmMainTemplatePlugin( Object.assign( { generateLoadBinaryCode, supportsStreaming: false }, this.options ) ); plugin.apply(compilation.mainTemplate); } ); } } module.exports = ReadFileCompileWasmTemplatePlugin; webpack-4.30.0/lib/optimize/000077500000000000000000000000001345416772700156405ustar00rootroot00000000000000webpack-4.30.0/lib/optimize/AggressiveMergingPlugin.js000066400000000000000000000040301345416772700227620ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class AggressiveMergingPlugin { constructor(options) { if ( (options !== undefined && typeof options !== "object") || Array.isArray(options) ) { throw new Error( "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" ); } this.options = options || {}; } apply(compiler) { const options = this.options; const minSizeReduce = options.minSizeReduce || 1.5; compiler.hooks.thisCompilation.tap( "AggressiveMergingPlugin", compilation => { compilation.hooks.optimizeChunksAdvanced.tap( "AggressiveMergingPlugin", chunks => { let combinations = []; chunks.forEach((a, idx) => { if (a.canBeInitial()) return; for (let i = 0; i < idx; i++) { const b = chunks[i]; if (b.canBeInitial()) continue; combinations.push({ a, b, improvement: undefined }); } }); for (const pair of combinations) { const a = pair.b.size({ chunkOverhead: 0 }); const b = pair.a.size({ chunkOverhead: 0 }); const ab = pair.b.integratedSize(pair.a, { chunkOverhead: 0 }); let newSize; if (ab === false) { pair.improvement = false; return; } else { newSize = ab; } pair.improvement = (a + b) / newSize; } combinations = combinations.filter(pair => { return pair.improvement !== false; }); combinations.sort((a, b) => { return b.improvement - a.improvement; }); const pair = combinations[0]; if (!pair) return; if (pair.improvement < minSizeReduce) return; if (pair.b.integrate(pair.a, "aggressive-merge")) { chunks.splice(chunks.indexOf(pair.a), 1); return true; } } ); } ); } } module.exports = AggressiveMergingPlugin; webpack-4.30.0/lib/optimize/AggressiveSplittingPlugin.js000066400000000000000000000222051345416772700233530ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const identifierUtils = require("../util/identifier"); const { intersect } = require("../util/SetHelpers"); const validateOptions = require("schema-utils"); const schema = require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.json"); /** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ const moveModuleBetween = (oldChunk, newChunk) => { return module => { oldChunk.moveModule(module, newChunk); }; }; const isNotAEntryModule = entryModule => { return module => { return entryModule !== module; }; }; class AggressiveSplittingPlugin { /** * @param {AggressiveSplittingPluginOptions=} options options object */ constructor(options) { if (!options) options = {}; validateOptions(schema, options, "Aggressive Splitting Plugin"); this.options = options; if (typeof this.options.minSize !== "number") { this.options.minSize = 30 * 1024; } if (typeof this.options.maxSize !== "number") { this.options.maxSize = 50 * 1024; } if (typeof this.options.chunkOverhead !== "number") { this.options.chunkOverhead = 0; } if (typeof this.options.entryChunkMultiplicator !== "number") { this.options.entryChunkMultiplicator = 1; } } apply(compiler) { compiler.hooks.thisCompilation.tap( "AggressiveSplittingPlugin", compilation => { let needAdditionalSeal = false; let newSplits; let fromAggressiveSplittingSet; let chunkSplitDataMap; compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { newSplits = []; fromAggressiveSplittingSet = new Set(); chunkSplitDataMap = new Map(); }); compilation.hooks.optimizeChunksAdvanced.tap( "AggressiveSplittingPlugin", chunks => { // Precompute stuff const nameToModuleMap = new Map(); const moduleToNameMap = new Map(); for (const m of compilation.modules) { const name = identifierUtils.makePathsRelative( compiler.context, m.identifier(), compilation.cache ); nameToModuleMap.set(name, m); moduleToNameMap.set(m, name); } // Check used chunk ids const usedIds = new Set(); for (const chunk of chunks) { usedIds.add(chunk.id); } const recordedSplits = (compilation.records && compilation.records.aggressiveSplits) || []; const usedSplits = newSplits ? recordedSplits.concat(newSplits) : recordedSplits; const minSize = this.options.minSize; const maxSize = this.options.maxSize; const applySplit = splitData => { // Cannot split if id is already taken if (splitData.id !== undefined && usedIds.has(splitData.id)) { return false; } // Get module objects from names const selectedModules = splitData.modules.map(name => nameToModuleMap.get(name) ); // Does the modules exist at all? if (!selectedModules.every(Boolean)) return false; // Check if size matches (faster than waiting for hash) const size = selectedModules.reduce( (sum, m) => sum + m.size(), 0 ); if (size !== splitData.size) return false; // get chunks with all modules const selectedChunks = intersect( selectedModules.map(m => new Set(m.chunksIterable)) ); // No relevant chunks found if (selectedChunks.size === 0) return false; // The found chunk is already the split or similar if ( selectedChunks.size === 1 && Array.from(selectedChunks)[0].getNumberOfModules() === selectedModules.length ) { const chunk = Array.from(selectedChunks)[0]; if (fromAggressiveSplittingSet.has(chunk)) return false; fromAggressiveSplittingSet.add(chunk); chunkSplitDataMap.set(chunk, splitData); return true; } // split the chunk into two parts const newChunk = compilation.addChunk(); newChunk.chunkReason = "aggressive splitted"; for (const chunk of selectedChunks) { selectedModules.forEach(moveModuleBetween(chunk, newChunk)); chunk.split(newChunk); chunk.name = null; } fromAggressiveSplittingSet.add(newChunk); chunkSplitDataMap.set(newChunk, splitData); if (splitData.id !== null && splitData.id !== undefined) { newChunk.id = splitData.id; } return true; }; // try to restore to recorded splitting let changed = false; for (let j = 0; j < usedSplits.length; j++) { const splitData = usedSplits[j]; if (applySplit(splitData)) changed = true; } // for any chunk which isn't splitted yet, split it and create a new entry // start with the biggest chunk const sortedChunks = chunks.slice().sort((a, b) => { const diff1 = b.modulesSize() - a.modulesSize(); if (diff1) return diff1; const diff2 = a.getNumberOfModules() - b.getNumberOfModules(); if (diff2) return diff2; const modulesA = Array.from(a.modulesIterable); const modulesB = Array.from(b.modulesIterable); modulesA.sort(); modulesB.sort(); const aI = modulesA[Symbol.iterator](); const bI = modulesB[Symbol.iterator](); // eslint-disable-next-line no-constant-condition while (true) { const aItem = aI.next(); const bItem = bI.next(); if (aItem.done) return 0; const aModuleIdentifier = aItem.value.identifier(); const bModuleIdentifier = bItem.value.identifier(); if (aModuleIdentifier > bModuleIdentifier) return -1; if (aModuleIdentifier < bModuleIdentifier) return 1; } }); for (const chunk of sortedChunks) { if (fromAggressiveSplittingSet.has(chunk)) continue; const size = chunk.modulesSize(); if (size > maxSize && chunk.getNumberOfModules() > 1) { const modules = chunk .getModules() .filter(isNotAEntryModule(chunk.entryModule)) .sort((a, b) => { a = a.identifier(); b = b.identifier(); if (a > b) return 1; if (a < b) return -1; return 0; }); const selectedModules = []; let selectedModulesSize = 0; for (let k = 0; k < modules.length; k++) { const module = modules[k]; const newSize = selectedModulesSize + module.size(); if (newSize > maxSize && selectedModulesSize >= minSize) { break; } selectedModulesSize = newSize; selectedModules.push(module); } if (selectedModules.length === 0) continue; const splitData = { modules: selectedModules .map(m => moduleToNameMap.get(m)) .sort(), size: selectedModulesSize }; if (applySplit(splitData)) { newSplits = (newSplits || []).concat(splitData); changed = true; } } } if (changed) return true; } ); compilation.hooks.recordHash.tap( "AggressiveSplittingPlugin", records => { // 4. save made splittings to records const allSplits = new Set(); const invalidSplits = new Set(); // Check if some splittings are invalid // We remove invalid splittings and try again for (const chunk of compilation.chunks) { const splitData = chunkSplitDataMap.get(chunk); if (splitData !== undefined) { if (splitData.hash && chunk.hash !== splitData.hash) { // Split was successful, but hash doesn't equal // We can throw away the split since it's useless now invalidSplits.add(splitData); } } } if (invalidSplits.size > 0) { records.aggressiveSplits = records.aggressiveSplits.filter( splitData => !invalidSplits.has(splitData) ); needAdditionalSeal = true; } else { // set hash and id values on all (new) splittings for (const chunk of compilation.chunks) { const splitData = chunkSplitDataMap.get(chunk); if (splitData !== undefined) { splitData.hash = chunk.hash; splitData.id = chunk.id; allSplits.add(splitData); // set flag for stats chunk.recorded = true; } } // Also add all unused historial splits (after the used ones) // They can still be used in some future compilation const recordedSplits = compilation.records && compilation.records.aggressiveSplits; if (recordedSplits) { for (const splitData of recordedSplits) { if (!invalidSplits.has(splitData)) allSplits.add(splitData); } } // record all splits records.aggressiveSplits = Array.from(allSplits); needAdditionalSeal = false; } } ); compilation.hooks.needAdditionalSeal.tap( "AggressiveSplittingPlugin", () => { if (needAdditionalSeal) { needAdditionalSeal = false; return true; } } ); } ); } } module.exports = AggressiveSplittingPlugin; webpack-4.30.0/lib/optimize/ChunkModuleIdRangePlugin.js000066400000000000000000000030761345416772700230330ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const sortByIndex = (a, b) => { return a.index - b.index; }; const sortByIndex2 = (a, b) => { return a.index2 - b.index2; }; class ChunkModuleIdRangePlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { const chunk = compilation.chunks.find( chunk => chunk.name === options.name ); if (!chunk) { throw new Error( `ChunkModuleIdRangePlugin: Chunk with name '${ options.name }"' was not found` ); } let chunkModules; if (options.order) { chunkModules = Array.from(chunk.modulesIterable); switch (options.order) { case "index": chunkModules.sort(sortByIndex); break; case "index2": chunkModules.sort(sortByIndex2); break; default: throw new Error( "ChunkModuleIdRangePlugin: unexpected value of order" ); } } else { chunkModules = modules.filter(m => { return m.chunksIterable.has(chunk); }); } let currentId = options.start || 0; for (let i = 0; i < chunkModules.length; i++) { const m = chunkModules[i]; if (m.id === null) { m.id = currentId++; } if (options.end && currentId > options.end) break; } }); }); } } module.exports = ChunkModuleIdRangePlugin; webpack-4.30.0/lib/optimize/ConcatenatedModule.js000066400000000000000000001127671345416772700217520ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("../Module"); const Template = require("../Template"); const Parser = require("../Parser"); const eslintScope = require("eslint-scope"); const { ConcatSource, ReplaceSource } = require("webpack-sources"); const DependencyReference = require("../dependencies/DependencyReference"); const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency"); const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency"); const HarmonyExportSpecifierDependency = require("../dependencies/HarmonyExportSpecifierDependency"); const HarmonyExportExpressionDependency = require("../dependencies/HarmonyExportExpressionDependency"); const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); const createHash = require("../util/createHash"); /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Compilation")} Compilation */ /** @typedef {import("../util/createHash").Hash} Hash */ /** * @typedef {Object} ConcatenationEntry * @property {"concatenated" | "external"} type * @property {Module} module */ const ensureNsObjSource = ( info, moduleToInfoMap, requestShortener, strictHarmonyModule ) => { if (!info.hasNamespaceObject) { info.hasNamespaceObject = true; const name = info.exportMap.get(true); const nsObj = [`var ${name} = {};`, `__webpack_require__.r(${name});`]; for (const exportName of info.module.buildMeta.providedExports) { const finalName = getFinalName( info, exportName, moduleToInfoMap, requestShortener, false, strictHarmonyModule ); nsObj.push( `__webpack_require__.d(${name}, ${JSON.stringify( exportName )}, function() { return ${finalName}; });` ); } info.namespaceObjectSource = nsObj.join("\n") + "\n"; } }; const getExternalImport = ( importedModule, info, exportName, asCall, strictHarmonyModule ) => { const used = importedModule.isUsed(exportName); if (!used) return "/* unused reexport */undefined"; const comment = used !== exportName ? ` ${Template.toNormalComment(exportName)}` : ""; switch (importedModule.buildMeta.exportsType) { case "named": if (exportName === "default") { return info.name; } else if (exportName === true) { info.interopNamespaceObjectUsed = true; return info.interopNamespaceObjectName; } else { break; } case "namespace": if (exportName === true) { return info.name; } else { break; } default: if (strictHarmonyModule) { if (exportName === "default") { return info.name; } else if (exportName === true) { info.interopNamespaceObjectUsed = true; return info.interopNamespaceObjectName; } else { return "/* non-default import from non-esm module */undefined"; } } else { if (exportName === "default") { info.interopDefaultAccessUsed = true; return asCall ? `${info.interopDefaultAccessName}()` : `${info.interopDefaultAccessName}.a`; } else if (exportName === true) { return info.name; } else { break; } } } const reference = `${info.name}[${JSON.stringify(used)}${comment}]`; if (asCall) return `Object(${reference})`; return reference; }; const getFinalName = ( info, exportName, moduleToInfoMap, requestShortener, asCall, strictHarmonyModule, alreadyVisited = new Set() ) => { switch (info.type) { case "concatenated": { const directExport = info.exportMap.get(exportName); if (directExport) { if (exportName === true) { ensureNsObjSource( info, moduleToInfoMap, requestShortener, strictHarmonyModule ); } else if (!info.module.isUsed(exportName)) { return "/* unused export */ undefined"; } if (info.globalExports.has(directExport)) { return directExport; } const name = info.internalNames.get(directExport); if (!name) { throw new Error( `The export "${directExport}" in "${info.module.readableIdentifier( requestShortener )}" has no internal name` ); } return name; } const reexport = info.reexportMap.get(exportName); if (reexport) { if (alreadyVisited.has(reexport)) { throw new Error( `Circular reexports ${Array.from( alreadyVisited, e => `"${e.module.readableIdentifier(requestShortener)}".${ e.exportName }` ).join( " --> " )} -(circular)-> "${reexport.module.readableIdentifier( requestShortener )}".${reexport.exportName}` ); } alreadyVisited.add(reexport); const refInfo = moduleToInfoMap.get(reexport.module); if (refInfo) { // module is in the concatenation return getFinalName( refInfo, reexport.exportName, moduleToInfoMap, requestShortener, asCall, strictHarmonyModule, alreadyVisited ); } } const problem = `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier( requestShortener )}"` + ` (known exports: ${Array.from(info.exportMap.keys()) .filter(name => name !== true) .join(" ")}, ` + `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`; return `${Template.toNormalComment(problem)} undefined`; } case "external": { const importedModule = info.module; return getExternalImport( importedModule, info, exportName, asCall, strictHarmonyModule ); } } }; const addScopeSymbols1 = (s, nameSet, scopeSet) => { let scope = s; while (scope) { if (scopeSet.has(scope)) break; scopeSet.add(scope); for (const variable of scope.variables) { nameSet.add(variable.name); } scope = scope.upper; } }; const addScopeSymbols2 = (s, nameSet, scopeSet1, scopeSet2) => { let scope = s; while (scope) { if (scopeSet1.has(scope)) break; if (scopeSet2.has(scope)) break; scopeSet1.add(scope); for (const variable of scope.variables) { nameSet.add(variable.name); } scope = scope.upper; } }; const getAllReferences = variable => { let set = variable.references; // Look for inner scope variables too (like in class Foo { t() { Foo } }) const identifiers = new Set(variable.identifiers); for (const scope of variable.scope.childScopes) { for (const innerVar of scope.variables) { if (innerVar.identifiers.some(id => identifiers.has(id))) { set = set.concat(innerVar.references); break; } } } return set; }; const getPathInAst = (ast, node) => { if (ast === node) { return []; } const nr = node.range; const enterNode = n => { if (!n) return undefined; const r = n.range; if (r) { if (r[0] <= nr[0] && r[1] >= nr[1]) { const path = getPathInAst(n, node); if (path) { path.push(n); return path; } } } return undefined; }; var i; if (Array.isArray(ast)) { for (i = 0; i < ast.length; i++) { const enterResult = enterNode(ast[i]); if (enterResult !== undefined) return enterResult; } } else if (ast && typeof ast === "object") { const keys = Object.keys(ast); for (i = 0; i < keys.length; i++) { const value = ast[keys[i]]; if (Array.isArray(value)) { const pathResult = getPathInAst(value, node); if (pathResult !== undefined) return pathResult; } else if (value && typeof value === "object") { const enterResult = enterNode(value); if (enterResult !== undefined) return enterResult; } } } }; class ConcatenatedModule extends Module { constructor(rootModule, modules, concatenationList) { super("javascript/esm", null); super.setChunks(rootModule._chunks); // Info from Factory this.rootModule = rootModule; this.factoryMeta = rootModule.factoryMeta; // Info from Compilation this.index = rootModule.index; this.index2 = rootModule.index2; this.depth = rootModule.depth; // Info from Optimization this.used = rootModule.used; this.usedExports = rootModule.usedExports; // Info from Build this.buildInfo = { strict: true, cacheable: modules.every(m => m.buildInfo.cacheable), moduleArgument: rootModule.buildInfo.moduleArgument, exportsArgument: rootModule.buildInfo.exportsArgument, fileDependencies: new Set(), contextDependencies: new Set(), assets: undefined }; this.built = modules.some(m => m.built); this.buildMeta = rootModule.buildMeta; // Caching this._numberOfConcatenatedModules = modules.length; // Graph const modulesSet = new Set(modules); this.reasons = rootModule.reasons.filter( reason => !(reason.dependency instanceof HarmonyImportDependency) || !modulesSet.has(reason.module) ); this.dependencies = []; this.warnings = []; this.errors = []; this._orderedConcatenationList = concatenationList || ConcatenatedModule.createConcatenationList(rootModule, modulesSet, null); for (const info of this._orderedConcatenationList) { if (info.type === "concatenated") { const m = info.module; // populate dependencies for (const d of m.dependencies.filter( dep => !(dep instanceof HarmonyImportDependency) || !modulesSet.has(dep._module) )) { this.dependencies.push(d); } // populate file dependencies if (m.buildInfo.fileDependencies) { for (const file of m.buildInfo.fileDependencies) { this.buildInfo.fileDependencies.add(file); } } // populate context dependencies if (m.buildInfo.contextDependencies) { for (const context of m.buildInfo.contextDependencies) { this.buildInfo.contextDependencies.add(context); } } // populate warnings for (const warning of m.warnings) { this.warnings.push(warning); } // populate errors for (const error of m.errors) { this.errors.push(error); } if (m.buildInfo.assets) { if (this.buildInfo.assets === undefined) { this.buildInfo.assets = Object.create(null); } Object.assign(this.buildInfo.assets, m.buildInfo.assets); } } } this._identifier = this._createIdentifier(); } get modules() { return this._orderedConcatenationList .filter(info => info.type === "concatenated") .map(info => info.module); } identifier() { return this._identifier; } readableIdentifier(requestShortener) { return ( this.rootModule.readableIdentifier(requestShortener) + ` + ${this._numberOfConcatenatedModules - 1} modules` ); } libIdent(options) { return this.rootModule.libIdent(options); } nameForCondition() { return this.rootModule.nameForCondition(); } build(options, compilation, resolver, fs, callback) { throw new Error("Cannot build this module. It should be already built."); } size() { // Guess size from embedded modules return this._orderedConcatenationList.reduce((sum, info) => { switch (info.type) { case "concatenated": return sum + info.module.size(); case "external": return sum + 5; } return sum; }, 0); } /** * @param {Module} rootModule the root of the concatenation * @param {Set} modulesSet a set of modules which should be concatenated * @param {Compilation} compilation the compilation context * @returns {ConcatenationEntry[]} concatenation list */ static createConcatenationList(rootModule, modulesSet, compilation) { const list = []; const set = new Set(); /** * @param {Module} module a module * @returns {(function(): Module)[]} imported modules in order */ const getConcatenatedImports = module => { /** @type {WeakMap} */ const map = new WeakMap(); const references = module.dependencies .filter(dep => dep instanceof HarmonyImportDependency) .map(dep => { const ref = compilation.getDependencyReference(module, dep); if (ref) map.set(ref, dep); return ref; }) .filter(ref => ref); DependencyReference.sort(references); // TODO webpack 5: remove this hack, see also DependencyReference return references.map(ref => { const dep = map.get(ref); return () => compilation.getDependencyReference(module, dep).module; }); }; const enterModule = getModule => { const module = getModule(); if (!module) return; if (set.has(module)) return; set.add(module); if (modulesSet.has(module)) { const imports = getConcatenatedImports(module); imports.forEach(enterModule); list.push({ type: "concatenated", module }); } else { list.push({ type: "external", get module() { // We need to use a getter here, because the module in the dependency // could be replaced by some other process (i. e. also replaced with a // concatenated module) return getModule(); } }); } }; enterModule(() => rootModule); return list; } _createIdentifier() { let orderedConcatenationListIdentifiers = ""; for (let i = 0; i < this._orderedConcatenationList.length; i++) { if (this._orderedConcatenationList[i].type === "concatenated") { orderedConcatenationListIdentifiers += this._orderedConcatenationList[ i ].module.identifier(); orderedConcatenationListIdentifiers += " "; } } const hash = createHash("md4"); hash.update(orderedConcatenationListIdentifiers); return this.rootModule.identifier() + " " + hash.digest("hex"); } source(dependencyTemplates, runtimeTemplate) { const requestShortener = runtimeTemplate.requestShortener; // Metainfo for each module const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => { switch (info.type) { case "concatenated": { const exportMap = new Map(); const reexportMap = new Map(); for (const dep of info.module.dependencies) { if (dep instanceof HarmonyExportSpecifierDependency) { if (!exportMap.has(dep.name)) { exportMap.set(dep.name, dep.id); } } else if (dep instanceof HarmonyExportExpressionDependency) { if (!exportMap.has("default")) { exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); } } else if ( dep instanceof HarmonyExportImportedSpecifierDependency ) { const exportName = dep.name; const importName = dep.id; const importedModule = dep._module; if (exportName && importName) { if (!reexportMap.has(exportName)) { reexportMap.set(exportName, { module: importedModule, exportName: importName, dependency: dep }); } } else if (exportName) { if (!reexportMap.has(exportName)) { reexportMap.set(exportName, { module: importedModule, exportName: true, dependency: dep }); } } else if (importedModule) { for (const name of importedModule.buildMeta.providedExports) { if (dep.activeExports.has(name) || name === "default") { continue; } if (!reexportMap.has(name)) { reexportMap.set(name, { module: importedModule, exportName: name, dependency: dep }); } } } } } return { type: "concatenated", module: info.module, index: idx, ast: undefined, internalSource: undefined, source: undefined, globalScope: undefined, moduleScope: undefined, internalNames: new Map(), globalExports: new Set(), exportMap: exportMap, reexportMap: reexportMap, hasNamespaceObject: false, namespaceObjectSource: null }; } case "external": return { type: "external", module: info.module, index: idx, name: undefined, interopNamespaceObjectUsed: false, interopNamespaceObjectName: undefined, interopDefaultAccessUsed: false, interopDefaultAccessName: undefined }; default: throw new Error(`Unsupported concatenation entry type ${info.type}`); } }); // Create mapping from module to info const moduleToInfoMap = new Map(); for (const m of modulesWithInfo) { moduleToInfoMap.set(m.module, m); } // Configure template decorators for dependencies const innerDependencyTemplates = new Map(dependencyTemplates); innerDependencyTemplates.set( HarmonyImportSpecifierDependency, new HarmonyImportSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyImportSpecifierDependency), moduleToInfoMap ) ); innerDependencyTemplates.set( HarmonyImportSideEffectDependency, new HarmonyImportSideEffectDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyImportSideEffectDependency), moduleToInfoMap ) ); innerDependencyTemplates.set( HarmonyExportSpecifierDependency, new HarmonyExportSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportSpecifierDependency), this.rootModule ) ); innerDependencyTemplates.set( HarmonyExportExpressionDependency, new HarmonyExportExpressionDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportExpressionDependency), this.rootModule ) ); innerDependencyTemplates.set( HarmonyExportImportedSpecifierDependency, new HarmonyExportImportedSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportImportedSpecifierDependency), this.rootModule, moduleToInfoMap ) ); innerDependencyTemplates.set( HarmonyCompatibilityDependency, new HarmonyCompatibilityDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyCompatibilityDependency), this.rootModule, moduleToInfoMap ) ); // Must use full identifier in our cache here to ensure that the source // is updated should our dependencies list change. // TODO webpack 5 refactor innerDependencyTemplates.set( "hash", innerDependencyTemplates.get("hash") + this.identifier() ); // Generate source code and analyse scopes // Prepare a ReplaceSource for the final source for (const info of modulesWithInfo) { if (info.type === "concatenated") { const m = info.module; const source = m.source(innerDependencyTemplates, runtimeTemplate); const code = source.source(); let ast; try { ast = Parser.parse(code, { sourceType: "module" }); } catch (err) { if ( err.loc && typeof err.loc === "object" && typeof err.loc.line === "number" ) { const lineNumber = err.loc.line; const lines = code.split("\n"); err.message += "\n| " + lines .slice(Math.max(0, lineNumber - 3), lineNumber + 2) .join("\n| "); } throw err; } const scopeManager = eslintScope.analyze(ast, { ecmaVersion: 6, sourceType: "module", optimistic: true, ignoreEval: true, impliedStrict: true }); const globalScope = scopeManager.acquire(ast); const moduleScope = globalScope.childScopes[0]; const resultSource = new ReplaceSource(source); info.ast = ast; info.internalSource = source; info.source = resultSource; info.globalScope = globalScope; info.moduleScope = moduleScope; } } // List of all used names to avoid conflicts const allUsedNames = new Set([ "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name "abstract", "arguments", "async", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "eval", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield", "module", "__dirname", "__filename", "exports", "Array", "Date", "eval", "function", "hasOwnProperty", "Infinity", "isFinite", "isNaN", "isPrototypeOf", "length", "Math", "NaN", "name", "Number", "Object", "prototype", "String", "toString", "undefined", "valueOf", "alert", "all", "anchor", "anchors", "area", "assign", "blur", "button", "checkbox", "clearInterval", "clearTimeout", "clientInformation", "close", "closed", "confirm", "constructor", "crypto", "decodeURI", "decodeURIComponent", "defaultStatus", "document", "element", "elements", "embed", "embeds", "encodeURI", "encodeURIComponent", "escape", "event", "fileUpload", "focus", "form", "forms", "frame", "innerHeight", "innerWidth", "layer", "layers", "link", "location", "mimeTypes", "navigate", "navigator", "frames", "frameRate", "hidden", "history", "image", "images", "offscreenBuffering", "open", "opener", "option", "outerHeight", "outerWidth", "packages", "pageXOffset", "pageYOffset", "parent", "parseFloat", "parseInt", "password", "pkcs11", "plugin", "prompt", "propertyIsEnum", "radio", "reset", "screenX", "screenY", "scroll", "secure", "select", "self", "setInterval", "setTimeout", "status", "submit", "taint", "text", "textarea", "top", "unescape", "untaint", "window", "onblur", "onclick", "onerror", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onmouseover", "onload", "onmouseup", "onmousedown", "onsubmit" ]); // Set of already checked scopes const alreadyCheckedScopes = new Set(); // get all global names for (const info of modulesWithInfo) { const superClassExpressions = []; // ignore symbols from moduleScope if (info.moduleScope) { alreadyCheckedScopes.add(info.moduleScope); // The super class expression in class scopes behaves weird // We store ranges of all super class expressions to make // renaming to work correctly for (const childScope of info.moduleScope.childScopes) { if (childScope.type !== "class") continue; if (!childScope.block.superClass) continue; superClassExpressions.push({ range: childScope.block.superClass.range, variables: childScope.variables }); } } // add global symbols if (info.globalScope) { for (const reference of info.globalScope.through) { const name = reference.identifier.name; if ( /^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?(_strict)?__$/.test( name ) ) { for (const expr of superClassExpressions) { if ( expr.range[0] <= reference.identifier.range[0] && expr.range[1] >= reference.identifier.range[1] ) { for (const variable of expr.variables) { allUsedNames.add(variable.name); } } } addScopeSymbols1( reference.from, allUsedNames, alreadyCheckedScopes ); } else { allUsedNames.add(name); } } } // add exported globals if (info.type === "concatenated") { const variables = new Set(); for (const variable of info.moduleScope.variables) { variables.add(variable.name); } for (const [, variable] of info.exportMap) { if (!variables.has(variable)) { info.globalExports.add(variable); } } } } // generate names for symbols for (const info of modulesWithInfo) { switch (info.type) { case "concatenated": { const namespaceObjectName = this.findNewName( "namespaceObject", allUsedNames, null, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(namespaceObjectName); info.internalNames.set(namespaceObjectName, namespaceObjectName); info.exportMap.set(true, namespaceObjectName); for (const variable of info.moduleScope.variables) { const name = variable.name; if (allUsedNames.has(name)) { const references = getAllReferences(variable); const symbolsInReferences = new Set(); const alreadyCheckedInnerScopes = new Set(); for (const ref of references) { addScopeSymbols2( ref.from, symbolsInReferences, alreadyCheckedInnerScopes, alreadyCheckedScopes ); } const newName = this.findNewName( name, allUsedNames, symbolsInReferences, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(newName); info.internalNames.set(name, newName); const source = info.source; const allIdentifiers = new Set( references.map(r => r.identifier).concat(variable.identifiers) ); for (const identifier of allIdentifiers) { const r = identifier.range; const path = getPathInAst(info.ast, identifier); if ( path && path.length > 1 && path[1].type === "Property" && path[1].shorthand ) { source.insert(r[1], `: ${newName}`); } else { source.replace(r[0], r[1] - 1, newName); } } } else { allUsedNames.add(name); info.internalNames.set(name, name); } } break; } case "external": { const externalName = this.findNewName( "", allUsedNames, null, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(externalName); info.name = externalName; if ( info.module.buildMeta.exportsType === "named" || !info.module.buildMeta.exportsType ) { const externalNameInterop = this.findNewName( "namespaceObject", allUsedNames, null, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(externalNameInterop); info.interopNamespaceObjectName = externalNameInterop; } if (!info.module.buildMeta.exportsType) { const externalNameInterop = this.findNewName( "default", allUsedNames, null, info.module.readableIdentifier(requestShortener) ); allUsedNames.add(externalNameInterop); info.interopDefaultAccessName = externalNameInterop; } break; } } } // Find and replace referenced to modules for (const info of modulesWithInfo) { if (info.type === "concatenated") { for (const reference of info.globalScope.through) { const name = reference.identifier.name; const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_strict)?__$/.exec( name ); if (match) { const referencedModule = modulesWithInfo[+match[1]]; let exportName; if (match[2] === "ns") { exportName = true; } else { const exportData = match[2]; exportName = Buffer.from(exportData, "hex").toString("utf-8"); } const asCall = !!match[3]; const strictHarmonyModule = !!match[4]; const finalName = getFinalName( referencedModule, exportName, moduleToInfoMap, requestShortener, asCall, strictHarmonyModule ); const r = reference.identifier.range; const source = info.source; source.replace(r[0], r[1] - 1, finalName); } } } } const result = new ConcatSource(); // add harmony compatibility flag (must be first because of possible circular dependencies) const usedExports = this.rootModule.usedExports; if (usedExports === true || usedExports === null) { result.add( runtimeTemplate.defineEsModuleFlagStatement({ exportsArgument: this.exportsArgument }) ); } // define required namespace objects (must be before evaluation modules) for (const info of modulesWithInfo) { if (info.namespaceObjectSource) { result.add(info.namespaceObjectSource); } } // evaluate modules in order for (const info of modulesWithInfo) { switch (info.type) { case "concatenated": result.add( `\n// CONCATENATED MODULE: ${info.module.readableIdentifier( requestShortener )}\n` ); result.add(info.source); break; case "external": result.add( `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( requestShortener )}\n` ); result.add( `var ${info.name} = __webpack_require__(${JSON.stringify( info.module.id )});\n` ); if (info.interopNamespaceObjectUsed) { if (info.module.buildMeta.exportsType === "named") { result.add( `var ${ info.interopNamespaceObjectName } = /*#__PURE__*/__webpack_require__.t(${info.name}, 2);\n` ); } else if (!info.module.buildMeta.exportsType) { result.add( `var ${ info.interopNamespaceObjectName } = /*#__PURE__*/__webpack_require__.t(${info.name});\n` ); } } if (info.interopDefaultAccessUsed) { result.add( `var ${ info.interopDefaultAccessName } = /*#__PURE__*/__webpack_require__.n(${info.name});\n` ); } break; default: throw new Error(`Unsupported concatenation entry type ${info.type}`); } } return result; } findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { let name = oldName; if (name === "__WEBPACK_MODULE_DEFAULT_EXPORT__") name = ""; // Remove uncool stuff extraInfo = extraInfo.replace( /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, "" ); const splittedInfo = extraInfo.split("/"); while (splittedInfo.length) { name = splittedInfo.pop() + (name ? "_" + name : ""); const nameIdent = Template.toIdentifier(name); if ( !usedNamed1.has(nameIdent) && (!usedNamed2 || !usedNamed2.has(nameIdent)) ) return nameIdent; } let i = 0; let nameWithNumber = Template.toIdentifier(`${name}_${i}`); while ( usedNamed1.has(nameWithNumber) || (usedNamed2 && usedNamed2.has(nameWithNumber)) ) { i++; nameWithNumber = Template.toIdentifier(`${name}_${i}`); } return nameWithNumber; } /** * @param {Hash} hash the hash used to track dependencies * @returns {void} */ updateHash(hash) { for (const info of this._orderedConcatenationList) { switch (info.type) { case "concatenated": info.module.updateHash(hash); break; case "external": hash.update(`${info.module.id}`); break; } } super.updateHash(hash); } } class HarmonyImportSpecifierDependencyConcatenatedTemplate { constructor(originalTemplate, modulesMap) { this.originalTemplate = originalTemplate; this.modulesMap = modulesMap; } getHarmonyInitOrder(dep) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { return this.originalTemplate.getHarmonyInitOrder(dep); } return NaN; } harmonyInit(dep, source, runtimeTemplate, dependencyTemplates) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { this.originalTemplate.harmonyInit( dep, source, runtimeTemplate, dependencyTemplates ); return; } } apply(dep, source, runtime, dependencyTemplates) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); return; } let content; const callFlag = dep.call ? "_call" : ""; const strictFlag = dep.originModule.buildMeta.strictHarmonyModule ? "_strict" : ""; if (dep._id === null) { content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns${strictFlag}__`; } else if (dep.namespaceObjectAsContext) { content = `__WEBPACK_MODULE_REFERENCE__${ info.index }_ns${strictFlag}__[${JSON.stringify(dep._id)}]`; } else { const exportData = Buffer.from(dep._id, "utf-8").toString("hex"); content = `__WEBPACK_MODULE_REFERENCE__${ info.index }_${exportData}${callFlag}${strictFlag}__`; } if (dep.shorthand) { content = dep.name + ": " + content; } source.replace(dep.range[0], dep.range[1] - 1, content); } } class HarmonyImportSideEffectDependencyConcatenatedTemplate { constructor(originalTemplate, modulesMap) { this.originalTemplate = originalTemplate; this.modulesMap = modulesMap; } getHarmonyInitOrder(dep) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { return this.originalTemplate.getHarmonyInitOrder(dep); } return NaN; } harmonyInit(dep, source, runtime, dependencyTemplates) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { this.originalTemplate.harmonyInit( dep, source, runtime, dependencyTemplates ); return; } } apply(dep, source, runtime, dependencyTemplates) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); return; } } } class HarmonyExportSpecifierDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; } getHarmonyInitOrder(dep) { if (dep.originModule === this.rootModule) { return this.originalTemplate.getHarmonyInitOrder(dep); } return NaN; } harmonyInit(dep, source, runtime, dependencyTemplates) { if (dep.originModule === this.rootModule) { this.originalTemplate.harmonyInit( dep, source, runtime, dependencyTemplates ); return; } } apply(dep, source, runtime, dependencyTemplates) { if (dep.originModule === this.rootModule) { this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); } } } class HarmonyExportExpressionDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; } apply(dep, source, runtime, dependencyTemplates) { let content = "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = "; if (dep.originModule === this.rootModule) { const used = dep.originModule.isUsed("default"); const exportsName = dep.originModule.exportsArgument; if (used) content += `${exportsName}[${JSON.stringify(used)}] = `; } if (dep.range) { source.replace( dep.rangeStatement[0], dep.range[0] - 1, content + "(" + dep.prefix ); source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); return; } source.replace( dep.rangeStatement[0], dep.rangeStatement[1] - 1, content + dep.prefix ); } } class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule, modulesMap) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; this.modulesMap = modulesMap; } getExports(dep) { const importModule = dep._module; if (dep.id) { // export { named } from "module" return [ { name: dep.name, id: dep.id, module: importModule } ]; } if (dep.name) { // export * as abc from "module" return [ { name: dep.name, id: true, module: importModule } ]; } // export * from "module" return importModule.buildMeta.providedExports .filter(exp => exp !== "default" && !dep.activeExports.has(exp)) .map(exp => { return { name: exp, id: exp, module: importModule }; }); } getHarmonyInitOrder(dep) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { return this.originalTemplate.getHarmonyInitOrder(dep); } return NaN; } harmonyInit(dep, source, runtime, dependencyTemplates) { const module = dep._module; const info = this.modulesMap.get(module); if (!info) { this.originalTemplate.harmonyInit( dep, source, runtime, dependencyTemplates ); return; } } apply(dep, source, runtime, dependencyTemplates) { if (dep.originModule === this.rootModule) { if (this.modulesMap.get(dep._module)) { const exportDefs = this.getExports(dep); for (const def of exportDefs) { const info = this.modulesMap.get(def.module); const used = dep.originModule.isUsed(def.name); if (!used) { source.insert( -1, `/* unused concated harmony import ${def.name} */\n` ); continue; } let finalName; const strictFlag = dep.originModule.buildMeta.strictHarmonyModule ? "_strict" : ""; if (def.id === true) { finalName = `__WEBPACK_MODULE_REFERENCE__${ info.index }_ns${strictFlag}__`; } else { const exportData = Buffer.from(def.id, "utf-8").toString("hex"); finalName = `__WEBPACK_MODULE_REFERENCE__${ info.index }_${exportData}${strictFlag}__`; } const exportsName = this.rootModule.exportsArgument; const content = `/* concated harmony reexport ${def.name} */` + `__webpack_require__.d(${exportsName}, ` + `${JSON.stringify(used)}, ` + `function() { return ${finalName}; });\n`; source.insert(-1, content); } } else { this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); } } } } class HarmonyCompatibilityDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule, modulesMap) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; this.modulesMap = modulesMap; } apply(dep, source, runtime, dependencyTemplates) { // do nothing } } module.exports = ConcatenatedModule; webpack-4.30.0/lib/optimize/EnsureChunkConditionsPlugin.js000066400000000000000000000040061345416772700236410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const GraphHelpers = require("../GraphHelpers"); class EnsureChunkConditionsPlugin { apply(compiler) { compiler.hooks.compilation.tap( "EnsureChunkConditionsPlugin", compilation => { const handler = chunks => { let changed = false; for (const module of compilation.modules) { if (!module.chunkCondition) continue; const sourceChunks = new Set(); const chunkGroups = new Set(); for (const chunk of module.chunksIterable) { if (!module.chunkCondition(chunk)) { sourceChunks.add(chunk); for (const group of chunk.groupsIterable) { chunkGroups.add(group); } } } if (sourceChunks.size === 0) continue; const targetChunks = new Set(); chunkGroupLoop: for (const chunkGroup of chunkGroups) { // Can module be placed in a chunk of this group? for (const chunk of chunkGroup.chunks) { if (module.chunkCondition(chunk)) { targetChunks.add(chunk); continue chunkGroupLoop; } } // We reached the entrypoint: fail if (chunkGroup.isInitial()) { throw new Error( "Cannot fullfil chunk condition of " + module.identifier() ); } // Try placing in all parents for (const group of chunkGroup.parentsIterable) { chunkGroups.add(group); } } for (const sourceChunk of sourceChunks) { GraphHelpers.disconnectChunkAndModule(sourceChunk, module); } for (const targetChunk of targetChunks) { GraphHelpers.connectChunkAndModule(targetChunk, module); } } if (changed) return true; }; compilation.hooks.optimizeChunksBasic.tap( "EnsureChunkConditionsPlugin", handler ); compilation.hooks.optimizeExtractedChunksBasic.tap( "EnsureChunkConditionsPlugin", handler ); } ); } } module.exports = EnsureChunkConditionsPlugin; webpack-4.30.0/lib/optimize/FlagIncludedChunksPlugin.js000066400000000000000000000062131345416772700230540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class FlagIncludedChunksPlugin { apply(compiler) { compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { compilation.hooks.optimizeChunkIds.tap( "FlagIncludedChunksPlugin", chunks => { // prepare two bit integers for each module // 2^31 is the max number represented as SMI in v8 // we want the bits distributed this way: // the bit 2^31 is pretty rar and only one module should get it // so it has a probability of 1 / modulesCount // the first bit (2^0) is the easiest and every module could get it // if it doesn't get a better bit // from bit 2^n to 2^(n+1) there is a probability of p // so 1 / modulesCount == p^31 // <=> p = sqrt31(1 / modulesCount) // so we use a modulo of 1 / sqrt31(1 / modulesCount) const moduleBits = new WeakMap(); const modulesCount = compilation.modules.length; // precalculate the modulo values for each bit const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); const modulos = Array.from( { length: 31 }, (x, i) => Math.pow(modulo, i) | 0 ); // iterate all modules to generate bit values let i = 0; for (const module of compilation.modules) { let bit = 30; while (i % modulos[bit] !== 0) { bit--; } moduleBits.set(module, 1 << bit); i++; } // interate all chunks to generate bitmaps const chunkModulesHash = new WeakMap(); for (const chunk of chunks) { let hash = 0; for (const module of chunk.modulesIterable) { hash |= moduleBits.get(module); } chunkModulesHash.set(chunk, hash); } for (const chunkA of chunks) { const chunkAHash = chunkModulesHash.get(chunkA); const chunkAModulesCount = chunkA.getNumberOfModules(); if (chunkAModulesCount === 0) continue; let bestModule = undefined; for (const module of chunkA.modulesIterable) { if ( bestModule === undefined || bestModule.getNumberOfChunks() > module.getNumberOfChunks() ) bestModule = module; } loopB: for (const chunkB of bestModule.chunksIterable) { // as we iterate the same iterables twice // skip if we find ourselves if (chunkA === chunkB) continue; const chunkBModulesCount = chunkB.getNumberOfModules(); // ids for empty chunks are not included if (chunkBModulesCount === 0) continue; // instead of swapping A and B just bail // as we loop twice the current A will be B and B then A if (chunkAModulesCount > chunkBModulesCount) continue; // is chunkA in chunkB? // we do a cheap check for the hash value const chunkBHash = chunkModulesHash.get(chunkB); if ((chunkBHash & chunkAHash) !== chunkAHash) continue; // compare all modules for (const m of chunkA.modulesIterable) { if (!chunkB.containsModule(m)) continue loopB; } chunkB.ids.push(chunkA.id); } } } ); }); } } module.exports = FlagIncludedChunksPlugin; webpack-4.30.0/lib/optimize/LimitChunkCountPlugin.js000066400000000000000000000046721345416772700224460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const validateOptions = require("schema-utils"); const schema = require("../../schemas/plugins/optimize/LimitChunkCountPlugin.json"); /** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ class LimitChunkCountPlugin { /** * @param {LimitChunkCountPluginOptions=} options options object */ constructor(options) { if (!options) options = {}; validateOptions(schema, options, "Limit Chunk Count Plugin"); this.options = options; } apply(compiler) { const options = this.options; compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { compilation.hooks.optimizeChunksAdvanced.tap( "LimitChunkCountPlugin", chunks => { const maxChunks = options.maxChunks; if (!maxChunks) return; if (maxChunks < 1) return; if (chunks.length <= maxChunks) return; const orderedChunks = chunks.slice().sort((a, b) => a.compareTo(b)); const sortedExtendedPairCombinations = orderedChunks .reduce((combinations, a, idx) => { // create combination pairs for (let i = 0; i < idx; i++) { const b = orderedChunks[i]; combinations.push([b, a]); } return combinations; }, []) .map(pair => { // extend combination pairs with size and integrated size const a = pair[0].size(options); const b = pair[1].size(options); const ab = pair[0].integratedSize(pair[1], options); return [a + b - ab, ab, pair[0], pair[1], a, b]; }) .filter(extendedPair => { // filter pairs that do not have an integratedSize // meaning they can NOT be integrated! return extendedPair[1] !== false; }) .sort((a, b) => { // sadly javascript does an inplace sort here // sort them by size const diff1 = b[0] - a[0]; if (diff1 !== 0) return diff1; const diff2 = a[1] - b[1]; if (diff2 !== 0) return diff2; const diff3 = a[2].compareTo(b[2]); if (diff3 !== 0) return diff3; return a[3].compareTo(b[3]); }); const pair = sortedExtendedPairCombinations[0]; if (pair && pair[2].integrate(pair[3], "limit")) { chunks.splice(chunks.indexOf(pair[3]), 1); return true; } } ); }); } } module.exports = LimitChunkCountPlugin; webpack-4.30.0/lib/optimize/MergeDuplicateChunksPlugin.js000066400000000000000000000046651345416772700234360ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class MergeDuplicateChunksPlugin { apply(compiler) { compiler.hooks.compilation.tap( "MergeDuplicateChunksPlugin", compilation => { compilation.hooks.optimizeChunksBasic.tap( "MergeDuplicateChunksPlugin", chunks => { // remember already tested chunks for performance const notDuplicates = new Set(); // for each chunk for (const chunk of chunks) { // track a Set of all chunk that could be duplicates let possibleDuplicates; for (const module of chunk.modulesIterable) { if (possibleDuplicates === undefined) { // when possibleDuplicates is not yet set, // create a new Set from chunks of the current module // including only chunks with the same number of modules for (const dup of module.chunksIterable) { if ( dup !== chunk && chunk.getNumberOfModules() === dup.getNumberOfModules() && !notDuplicates.has(dup) ) { // delay allocating the new Set until here, reduce memory pressure if (possibleDuplicates === undefined) { possibleDuplicates = new Set(); } possibleDuplicates.add(dup); } } // when no chunk is possible we can break here if (possibleDuplicates === undefined) break; } else { // validate existing possible duplicates for (const dup of possibleDuplicates) { // remove possible duplicate when module is not contained if (!dup.containsModule(module)) { possibleDuplicates.delete(dup); } } // when all chunks has been removed we can break here if (possibleDuplicates.size === 0) break; } } // when we found duplicates if ( possibleDuplicates !== undefined && possibleDuplicates.size > 0 ) { for (const otherChunk of possibleDuplicates) { if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; // merge them if (chunk.integrate(otherChunk, "duplicate")) { chunks.splice(chunks.indexOf(otherChunk), 1); } } } // don't check already processed chunks twice notDuplicates.add(chunk); } } ); } ); } } module.exports = MergeDuplicateChunksPlugin; webpack-4.30.0/lib/optimize/MinChunkSizePlugin.js000066400000000000000000000050241345416772700217250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const validateOptions = require("schema-utils"); const schema = require("../../schemas/plugins/optimize/MinChunkSizePlugin.json"); /** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ class MinChunkSizePlugin { /** * @param {MinChunkSizePluginOptions} options options object */ constructor(options) { validateOptions(schema, options, "Min Chunk Size Plugin"); this.options = options; } apply(compiler) { const options = this.options; const minChunkSize = options.minChunkSize; compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { compilation.hooks.optimizeChunksAdvanced.tap( "MinChunkSizePlugin", chunks => { const equalOptions = { chunkOverhead: 1, entryChunkMultiplicator: 1 }; const sortedSizeFilteredExtendedPairCombinations = chunks .reduce((combinations, a, idx) => { // create combination pairs for (let i = 0; i < idx; i++) { const b = chunks[i]; combinations.push([b, a]); } return combinations; }, []) .filter(pair => { // check if one of the chunks sizes is smaller than the minChunkSize const p0SmallerThanMinChunkSize = pair[0].size(equalOptions) < minChunkSize; const p1SmallerThanMinChunkSize = pair[1].size(equalOptions) < minChunkSize; return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize; }) .map(pair => { // extend combination pairs with size and integrated size const a = pair[0].size(options); const b = pair[1].size(options); const ab = pair[0].integratedSize(pair[1], options); return [a + b - ab, ab, pair[0], pair[1]]; }) .filter(pair => { // filter pairs that do not have an integratedSize // meaning they can NOT be integrated! return pair[1] !== false; }) .sort((a, b) => { // sadly javascript does an inplace sort here // sort by size const diff = b[0] - a[0]; if (diff !== 0) return diff; return a[1] - b[1]; }); if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; const pair = sortedSizeFilteredExtendedPairCombinations[0]; pair[2].integrate(pair[3], "min-size"); chunks.splice(chunks.indexOf(pair[3]), 1); return true; } ); }); } } module.exports = MinChunkSizePlugin; webpack-4.30.0/lib/optimize/MinMaxSizeWarning.js000066400000000000000000000014631345416772700215540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("../WebpackError"); const SizeFormatHelpers = require("../SizeFormatHelpers"); class MinMaxSizeWarning extends WebpackError { constructor(keys, minSize, maxSize) { let keysMessage = "Fallback cache group"; if (keys) { keysMessage = keys.length > 1 ? `Cache groups ${keys.sort().join(", ")}` : `Cache group ${keys[0]}`; } super( `SplitChunksPlugin\n` + `${keysMessage}\n` + `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + "This seem to be a invalid optimiziation.splitChunks configuration." ); } } module.exports = MinMaxSizeWarning; webpack-4.30.0/lib/optimize/ModuleConcatenationPlugin.js000066400000000000000000000347721345416772700233250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); const ModuleHotAcceptDependency = require("../dependencies/ModuleHotAcceptDependency"); const ModuleHotDeclineDependency = require("../dependencies/ModuleHotDeclineDependency"); const ConcatenatedModule = require("./ConcatenatedModule"); const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); const StackedSetMap = require("../util/StackedSetMap"); const formatBailoutReason = msg => { return "ModuleConcatenation bailout: " + msg; }; class ModuleConcatenationPlugin { constructor(options) { if (typeof options !== "object") options = {}; this.options = options; } apply(compiler) { compiler.hooks.compilation.tap( "ModuleConcatenationPlugin", (compilation, { normalModuleFactory }) => { const handler = (parser, parserOptions) => { parser.hooks.call.for("eval").tap("ModuleConcatenationPlugin", () => { // Because of variable renaming we can't use modules with eval. parser.state.module.buildMeta.moduleConcatenationBailout = "eval()"; }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("ModuleConcatenationPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("ModuleConcatenationPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("ModuleConcatenationPlugin", handler); const bailoutReasonMap = new Map(); const setBailoutReason = (module, reason) => { bailoutReasonMap.set(module, reason); module.optimizationBailout.push( typeof reason === "function" ? rs => formatBailoutReason(reason(rs)) : formatBailoutReason(reason) ); }; const getBailoutReason = (module, requestShortener) => { const reason = bailoutReasonMap.get(module); if (typeof reason === "function") return reason(requestShortener); return reason; }; compilation.hooks.optimizeChunkModules.tap( "ModuleConcatenationPlugin", (allChunks, modules) => { const relevantModules = []; const possibleInners = new Set(); for (const module of modules) { // Only harmony modules are valid for optimization if ( !module.buildMeta || module.buildMeta.exportsType !== "namespace" || !module.dependencies.some( d => d instanceof HarmonyCompatibilityDependency ) ) { setBailoutReason(module, "Module is not an ECMAScript module"); continue; } // Some expressions are not compatible with module concatenation // because they may produce unexpected results. The plugin bails out // if some were detected upfront. if ( module.buildMeta && module.buildMeta.moduleConcatenationBailout ) { setBailoutReason( module, `Module uses ${module.buildMeta.moduleConcatenationBailout}` ); continue; } // Exports must be known (and not dynamic) if (!Array.isArray(module.buildMeta.providedExports)) { setBailoutReason(module, "Module exports are unknown"); continue; } // Using dependency variables is not possible as this wraps the code in a function if (module.variables.length > 0) { setBailoutReason( module, `Module uses injected variables (${module.variables .map(v => v.name) .join(", ")})` ); continue; } // Hot Module Replacement need it's own module to work correctly if ( module.dependencies.some( dep => dep instanceof ModuleHotAcceptDependency || dep instanceof ModuleHotDeclineDependency ) ) { setBailoutReason(module, "Module uses Hot Module Replacement"); continue; } relevantModules.push(module); // Module must not be the entry points if (module.isEntryModule()) { setBailoutReason(module, "Module is an entry point"); continue; } // Module must be in any chunk (we don't want to do useless work) if (module.getNumberOfChunks() === 0) { setBailoutReason(module, "Module is not in any chunk"); continue; } // Module must only be used by Harmony Imports const nonHarmonyReasons = module.reasons.filter( reason => !reason.dependency || !(reason.dependency instanceof HarmonyImportDependency) ); if (nonHarmonyReasons.length > 0) { const importingModules = new Set( nonHarmonyReasons.map(r => r.module).filter(Boolean) ); const importingExplanations = new Set( nonHarmonyReasons.map(r => r.explanation).filter(Boolean) ); const importingModuleTypes = new Map( Array.from(importingModules).map( m => /** @type {[string, Set]} */ ([ m, new Set( nonHarmonyReasons .filter(r => r.module === m) .map(r => r.dependency.type) .sort() ) ]) ) ); setBailoutReason(module, requestShortener => { const names = Array.from(importingModules) .map( m => `${m.readableIdentifier( requestShortener )} (referenced with ${Array.from( importingModuleTypes.get(m) ).join(", ")})` ) .sort(); const explanations = Array.from(importingExplanations).sort(); if (names.length > 0 && explanations.length === 0) { return `Module is referenced from these modules with unsupported syntax: ${names.join( ", " )}`; } else if (names.length === 0 && explanations.length > 0) { return `Module is referenced by: ${explanations.join( ", " )}`; } else if (names.length > 0 && explanations.length > 0) { return `Module is referenced from these modules with unsupported syntax: ${names.join( ", " )} and by: ${explanations.join(", ")}`; } else { return "Module is referenced in a unsupported way"; } }); continue; } possibleInners.add(module); } // sort by depth // modules with lower depth are more likely suited as roots // this improves performance, because modules already selected as inner are skipped relevantModules.sort((a, b) => { return a.depth - b.depth; }); const concatConfigurations = []; const usedAsInner = new Set(); for (const currentRoot of relevantModules) { // when used by another configuration as inner: // the other configuration is better and we can skip this one if (usedAsInner.has(currentRoot)) continue; // create a configuration with the root const currentConfiguration = new ConcatConfiguration(currentRoot); // cache failures to add modules const failureCache = new Map(); // try to add all imports for (const imp of this._getImports(compilation, currentRoot)) { const problem = this._tryToAdd( compilation, currentConfiguration, imp, possibleInners, failureCache ); if (problem) { failureCache.set(imp, problem); currentConfiguration.addWarning(imp, problem); } } if (!currentConfiguration.isEmpty()) { concatConfigurations.push(currentConfiguration); for (const module of currentConfiguration.getModules()) { if (module !== currentConfiguration.rootModule) { usedAsInner.add(module); } } } } // HACK: Sort configurations by length and start with the longest one // to get the biggers groups possible. Used modules are marked with usedModules // TODO: Allow to reuse existing configuration while trying to add dependencies. // This would improve performance. O(n^2) -> O(n) concatConfigurations.sort((a, b) => { return b.modules.size - a.modules.size; }); const usedModules = new Set(); for (const concatConfiguration of concatConfigurations) { if (usedModules.has(concatConfiguration.rootModule)) continue; const modules = concatConfiguration.getModules(); const rootModule = concatConfiguration.rootModule; const newModule = new ConcatenatedModule( rootModule, Array.from(modules), ConcatenatedModule.createConcatenationList( rootModule, modules, compilation ) ); for (const warning of concatConfiguration.getWarningsSorted()) { newModule.optimizationBailout.push(requestShortener => { const reason = getBailoutReason(warning[0], requestShortener); const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; if (warning[0] === warning[1]) { return formatBailoutReason( `Cannot concat with ${warning[0].readableIdentifier( requestShortener )}${reasonWithPrefix}` ); } else { return formatBailoutReason( `Cannot concat with ${warning[0].readableIdentifier( requestShortener )} because of ${warning[1].readableIdentifier( requestShortener )}${reasonWithPrefix}` ); } }); } const chunks = concatConfiguration.rootModule.getChunks(); for (const m of modules) { usedModules.add(m); for (const chunk of chunks) { chunk.removeModule(m); } } for (const chunk of chunks) { chunk.addModule(newModule); newModule.addChunk(chunk); } for (const chunk of allChunks) { if (chunk.entryModule === concatConfiguration.rootModule) { chunk.entryModule = newModule; } } compilation.modules.push(newModule); for (const reason of newModule.reasons) { if (reason.dependency.module === concatConfiguration.rootModule) reason.dependency.module = newModule; if ( reason.dependency.redirectedModule === concatConfiguration.rootModule ) reason.dependency.redirectedModule = newModule; } // TODO: remove when LTS node version contains fixed v8 version // @see https://github.com/webpack/webpack/pull/6613 // Turbofan does not correctly inline for-of loops with polymorphic input arrays. // Work around issue by using a standard for loop and assigning dep.module.reasons for (let i = 0; i < newModule.dependencies.length; i++) { let dep = newModule.dependencies[i]; if (dep.module) { let reasons = dep.module.reasons; for (let j = 0; j < reasons.length; j++) { let reason = reasons[j]; if (reason.dependency === dep) { reason.module = newModule; } } } } } compilation.modules = compilation.modules.filter( m => !usedModules.has(m) ); } ); } ); } _getImports(compilation, module) { return new Set( module.dependencies // Get reference info only for harmony Dependencies .map(dep => { if (!(dep instanceof HarmonyImportDependency)) return null; if (!compilation) return dep.getReference(); return compilation.getDependencyReference(module, dep); }) // Reference is valid and has a module // Dependencies are simple enough to concat them .filter( ref => ref && ref.module && (Array.isArray(ref.importedNames) || Array.isArray(ref.module.buildMeta.providedExports)) ) // Take the imported module .map(ref => ref.module) ); } _tryToAdd(compilation, config, module, possibleModules, failureCache) { const cacheEntry = failureCache.get(module); if (cacheEntry) { return cacheEntry; } // Already added? if (config.has(module)) { return null; } // Not possible to add? if (!possibleModules.has(module)) { failureCache.set(module, module); // cache failures for performance return module; } // module must be in the same chunks if (!config.rootModule.hasEqualsChunks(module)) { failureCache.set(module, module); // cache failures for performance return module; } // Clone config to make experimental changes const testConfig = config.clone(); // Add the module testConfig.add(module); // Every module which depends on the added module must be in the configuration too. for (const reason of module.reasons) { // Modules that are not used can be ignored if ( reason.module.factoryMeta.sideEffectFree && reason.module.used === false ) continue; const problem = this._tryToAdd( compilation, testConfig, reason.module, possibleModules, failureCache ); if (problem) { failureCache.set(module, problem); // cache failures for performance return problem; } } // Commit experimental changes config.set(testConfig); // Eagerly try to add imports too if possible for (const imp of this._getImports(compilation, module)) { const problem = this._tryToAdd( compilation, config, imp, possibleModules, failureCache ); if (problem) { config.addWarning(imp, problem); } } return null; } } class ConcatConfiguration { constructor(rootModule, cloneFrom) { this.rootModule = rootModule; if (cloneFrom) { this.modules = cloneFrom.modules.createChild(5); this.warnings = cloneFrom.warnings.createChild(5); } else { this.modules = new StackedSetMap(); this.modules.add(rootModule); this.warnings = new StackedSetMap(); } } add(module) { this.modules.add(module); } has(module) { return this.modules.has(module); } isEmpty() { return this.modules.size === 1; } addWarning(module, problem) { this.warnings.set(module, problem); } getWarningsSorted() { return new Map( this.warnings.asPairArray().sort((a, b) => { const ai = a[0].identifier(); const bi = b[0].identifier(); if (ai < bi) return -1; if (ai > bi) return 1; return 0; }) ); } getModules() { return this.modules.asSet(); } clone() { return new ConcatConfiguration(this.rootModule, this); } set(config) { this.rootModule = config.rootModule; this.modules = config.modules; this.warnings = config.warnings; } } module.exports = ModuleConcatenationPlugin; webpack-4.30.0/lib/optimize/NaturalChunkOrderPlugin.js000066400000000000000000000021471345416772700227540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {import("../Compiler")} Compiler */ class NaturalChunkOrderPlugin { /** * @param {Compiler} compiler webpack compiler * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap("NaturalChunkOrderPlugin", compilation => { compilation.hooks.optimizeChunkOrder.tap( "NaturalChunkOrderPlugin", chunks => { chunks.sort((chunkA, chunkB) => { const a = chunkA.modulesIterable[Symbol.iterator](); const b = chunkB.modulesIterable[Symbol.iterator](); // eslint-disable-next-line no-constant-condition while (true) { const aItem = a.next(); const bItem = b.next(); if (aItem.done && bItem.done) return 0; if (aItem.done) return -1; if (bItem.done) return 1; const aModuleId = aItem.value.id; const bModuleId = bItem.value.id; if (aModuleId < bModuleId) return -1; if (aModuleId > bModuleId) return 1; } }); } ); }); } } module.exports = NaturalChunkOrderPlugin; webpack-4.30.0/lib/optimize/OccurrenceChunkOrderPlugin.js000066400000000000000000000037771345416772700234500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const validateOptions = require("schema-utils"); const schema = require("../../schemas/plugins/optimize/OccurrenceOrderChunkIdsPlugin.json"); /** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderChunkIdsPlugin").OccurrenceOrderChunkIdsPluginOptions} OccurrenceOrderChunkIdsPluginOptions */ class OccurrenceOrderChunkIdsPlugin { /** * @param {OccurrenceOrderChunkIdsPluginOptions=} options options object */ constructor(options = {}) { validateOptions(schema, options, "Occurrence Order Chunk Ids Plugin"); this.options = options; } apply(compiler) { const prioritiseInitial = this.options.prioritiseInitial; compiler.hooks.compilation.tap( "OccurrenceOrderChunkIdsPlugin", compilation => { compilation.hooks.optimizeChunkOrder.tap( "OccurrenceOrderChunkIdsPlugin", chunks => { const occursInInitialChunksMap = new Map(); const originalOrder = new Map(); let i = 0; for (const c of chunks) { let occurs = 0; for (const chunkGroup of c.groupsIterable) { for (const parent of chunkGroup.parentsIterable) { if (parent.isInitial()) occurs++; } } occursInInitialChunksMap.set(c, occurs); originalOrder.set(c, i++); } chunks.sort((a, b) => { if (prioritiseInitial) { const aEntryOccurs = occursInInitialChunksMap.get(a); const bEntryOccurs = occursInInitialChunksMap.get(b); if (aEntryOccurs > bEntryOccurs) return -1; if (aEntryOccurs < bEntryOccurs) return 1; } const aOccurs = a.getNumberOfGroups(); const bOccurs = b.getNumberOfGroups(); if (aOccurs > bOccurs) return -1; if (aOccurs < bOccurs) return 1; const orgA = originalOrder.get(a); const orgB = originalOrder.get(b); return orgA - orgB; }); } ); } ); } } module.exports = OccurrenceOrderChunkIdsPlugin; webpack-4.30.0/lib/optimize/OccurrenceModuleOrderPlugin.js000066400000000000000000000064101345416772700236100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const validateOptions = require("schema-utils"); const schema = require("../../schemas/plugins/optimize/OccurrenceOrderModuleIdsPlugin.json"); /** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderModuleIdsPlugin").OccurrenceOrderModuleIdsPluginOptions} OccurrenceOrderModuleIdsPluginOptions */ class OccurrenceOrderModuleIdsPlugin { /** * @param {OccurrenceOrderModuleIdsPluginOptions=} options options object */ constructor(options = {}) { validateOptions(schema, options, "Occurrence Order Module Ids Plugin"); this.options = options; } apply(compiler) { const prioritiseInitial = this.options.prioritiseInitial; compiler.hooks.compilation.tap( "OccurrenceOrderModuleIdsPlugin", compilation => { compilation.hooks.optimizeModuleOrder.tap( "OccurrenceOrderModuleIdsPlugin", modules => { const occursInInitialChunksMap = new Map(); const occursInAllChunksMap = new Map(); const initialChunkChunkMap = new Map(); const entryCountMap = new Map(); for (const m of modules) { let initial = 0; let entry = 0; for (const c of m.chunksIterable) { if (c.canBeInitial()) initial++; if (c.entryModule === m) entry++; } initialChunkChunkMap.set(m, initial); entryCountMap.set(m, entry); } const countOccursInEntry = (sum, r) => { if (!r.module) { return sum; } const count = initialChunkChunkMap.get(r.module); if (!count) { return sum; } return sum + count; }; const countOccurs = (sum, r) => { if (!r.module) { return sum; } let factor = 1; if (typeof r.dependency.getNumberOfIdOccurrences === "function") { factor = r.dependency.getNumberOfIdOccurrences(); } if (factor === 0) { return sum; } return sum + factor * r.module.getNumberOfChunks(); }; if (prioritiseInitial) { for (const m of modules) { const result = m.reasons.reduce(countOccursInEntry, 0) + initialChunkChunkMap.get(m) + entryCountMap.get(m); occursInInitialChunksMap.set(m, result); } } const originalOrder = new Map(); let i = 0; for (const m of modules) { const result = m.reasons.reduce(countOccurs, 0) + m.getNumberOfChunks() + entryCountMap.get(m); occursInAllChunksMap.set(m, result); originalOrder.set(m, i++); } modules.sort((a, b) => { if (prioritiseInitial) { const aEntryOccurs = occursInInitialChunksMap.get(a); const bEntryOccurs = occursInInitialChunksMap.get(b); if (aEntryOccurs > bEntryOccurs) return -1; if (aEntryOccurs < bEntryOccurs) return 1; } const aOccurs = occursInAllChunksMap.get(a); const bOccurs = occursInAllChunksMap.get(b); if (aOccurs > bOccurs) return -1; if (aOccurs < bOccurs) return 1; const orgA = originalOrder.get(a); const orgB = originalOrder.get(b); return orgA - orgB; }); } ); } ); } } module.exports = OccurrenceOrderModuleIdsPlugin; webpack-4.30.0/lib/optimize/OccurrenceOrderPlugin.js000066400000000000000000000076351345416772700224540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; // TODO webpack 5 remove this plugin // It has been splitted into separate plugins for modules and chunks class OccurrenceOrderPlugin { constructor(preferEntry) { if (preferEntry !== undefined && typeof preferEntry !== "boolean") { throw new Error( "Argument should be a boolean.\nFor more info on this plugin, see https://webpack.js.org/plugins/" ); } this.preferEntry = preferEntry; } apply(compiler) { const preferEntry = this.preferEntry; compiler.hooks.compilation.tap("OccurrenceOrderPlugin", compilation => { compilation.hooks.optimizeModuleOrder.tap( "OccurrenceOrderPlugin", modules => { const occursInInitialChunksMap = new Map(); const occursInAllChunksMap = new Map(); const initialChunkChunkMap = new Map(); const entryCountMap = new Map(); for (const m of modules) { let initial = 0; let entry = 0; for (const c of m.chunksIterable) { if (c.canBeInitial()) initial++; if (c.entryModule === m) entry++; } initialChunkChunkMap.set(m, initial); entryCountMap.set(m, entry); } const countOccursInEntry = (sum, r) => { if (!r.module) { return sum; } return sum + initialChunkChunkMap.get(r.module); }; const countOccurs = (sum, r) => { if (!r.module) { return sum; } let factor = 1; if (typeof r.dependency.getNumberOfIdOccurrences === "function") { factor = r.dependency.getNumberOfIdOccurrences(); } if (factor === 0) { return sum; } return sum + factor * r.module.getNumberOfChunks(); }; if (preferEntry) { for (const m of modules) { const result = m.reasons.reduce(countOccursInEntry, 0) + initialChunkChunkMap.get(m) + entryCountMap.get(m); occursInInitialChunksMap.set(m, result); } } const originalOrder = new Map(); let i = 0; for (const m of modules) { const result = m.reasons.reduce(countOccurs, 0) + m.getNumberOfChunks() + entryCountMap.get(m); occursInAllChunksMap.set(m, result); originalOrder.set(m, i++); } modules.sort((a, b) => { if (preferEntry) { const aEntryOccurs = occursInInitialChunksMap.get(a); const bEntryOccurs = occursInInitialChunksMap.get(b); if (aEntryOccurs > bEntryOccurs) return -1; if (aEntryOccurs < bEntryOccurs) return 1; } const aOccurs = occursInAllChunksMap.get(a); const bOccurs = occursInAllChunksMap.get(b); if (aOccurs > bOccurs) return -1; if (aOccurs < bOccurs) return 1; const orgA = originalOrder.get(a); const orgB = originalOrder.get(b); return orgA - orgB; }); } ); compilation.hooks.optimizeChunkOrder.tap( "OccurrenceOrderPlugin", chunks => { const occursInInitialChunksMap = new Map(); const originalOrder = new Map(); let i = 0; for (const c of chunks) { let occurs = 0; for (const chunkGroup of c.groupsIterable) { for (const parent of chunkGroup.parentsIterable) { if (parent.isInitial()) occurs++; } } occursInInitialChunksMap.set(c, occurs); originalOrder.set(c, i++); } chunks.sort((a, b) => { const aEntryOccurs = occursInInitialChunksMap.get(a); const bEntryOccurs = occursInInitialChunksMap.get(b); if (aEntryOccurs > bEntryOccurs) return -1; if (aEntryOccurs < bEntryOccurs) return 1; const aOccurs = a.getNumberOfGroups(); const bOccurs = b.getNumberOfGroups(); if (aOccurs > bOccurs) return -1; if (aOccurs < bOccurs) return 1; const orgA = originalOrder.get(a); const orgB = originalOrder.get(b); return orgA - orgB; }); } ); }); } } module.exports = OccurrenceOrderPlugin; webpack-4.30.0/lib/optimize/RemoveEmptyChunksPlugin.js000066400000000000000000000017361345416772700230140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class RemoveEmptyChunksPlugin { apply(compiler) { compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { const handler = chunks => { for (let i = chunks.length - 1; i >= 0; i--) { const chunk = chunks[i]; if ( chunk.isEmpty() && !chunk.hasRuntime() && !chunk.hasEntryModule() ) { chunk.remove("empty"); chunks.splice(i, 1); } } }; compilation.hooks.optimizeChunksBasic.tap( "RemoveEmptyChunksPlugin", handler ); compilation.hooks.optimizeChunksAdvanced.tap( "RemoveEmptyChunksPlugin", handler ); compilation.hooks.optimizeExtractedChunksBasic.tap( "RemoveEmptyChunksPlugin", handler ); compilation.hooks.optimizeExtractedChunksAdvanced.tap( "RemoveEmptyChunksPlugin", handler ); }); } } module.exports = RemoveEmptyChunksPlugin; webpack-4.30.0/lib/optimize/RemoveParentModulesPlugin.js000066400000000000000000000071651345416772700233260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Queue = require("../util/Queue"); const { intersect } = require("../util/SetHelpers"); const getParentChunksWithModule = (currentChunk, module) => { const chunks = []; const stack = new Set(currentChunk.parentsIterable); for (const chunk of stack) { if (chunk.containsModule(module)) { chunks.push(chunk); } else { for (const parent of chunk.parentsIterable) { stack.add(parent); } } } return chunks; }; class RemoveParentModulesPlugin { apply(compiler) { compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { const handler = (chunks, chunkGroups) => { const queue = new Queue(); const availableModulesMap = new WeakMap(); for (const chunkGroup of compilation.entrypoints.values()) { // initialize available modules for chunks without parents availableModulesMap.set(chunkGroup, new Set()); for (const child of chunkGroup.childrenIterable) { queue.enqueue(child); } } while (queue.length > 0) { const chunkGroup = queue.dequeue(); let availableModules = availableModulesMap.get(chunkGroup); let changed = false; for (const parent of chunkGroup.parentsIterable) { const availableModulesInParent = availableModulesMap.get(parent); if (availableModulesInParent !== undefined) { // If we know the available modules in parent: process these if (availableModules === undefined) { // if we have not own info yet: create new entry availableModules = new Set(availableModulesInParent); for (const chunk of parent.chunks) { for (const m of chunk.modulesIterable) { availableModules.add(m); } } availableModulesMap.set(chunkGroup, availableModules); changed = true; } else { for (const m of availableModules) { if ( !parent.containsModule(m) && !availableModulesInParent.has(m) ) { availableModules.delete(m); changed = true; } } } } } if (changed) { // if something changed: enqueue our children for (const child of chunkGroup.childrenIterable) { queue.enqueue(child); } } } // now we have available modules for every chunk for (const chunk of chunks) { const availableModulesSets = Array.from( chunk.groupsIterable, chunkGroup => availableModulesMap.get(chunkGroup) ); if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group const availableModules = availableModulesSets.length === 1 ? availableModulesSets[0] : intersect(availableModulesSets); const numberOfModules = chunk.getNumberOfModules(); const toRemove = new Set(); if (numberOfModules < availableModules.size) { for (const m of chunk.modulesIterable) { if (availableModules.has(m)) { toRemove.add(m); } } } else { for (const m of availableModules) { if (chunk.containsModule(m)) { toRemove.add(m); } } } for (const module of toRemove) { module.rewriteChunkInReasons( chunk, getParentChunksWithModule(chunk, module) ); chunk.removeModule(module); } } }; compilation.hooks.optimizeChunksBasic.tap( "RemoveParentModulesPlugin", handler ); compilation.hooks.optimizeExtractedChunksBasic.tap( "RemoveParentModulesPlugin", handler ); }); } } module.exports = RemoveParentModulesPlugin; webpack-4.30.0/lib/optimize/RuntimeChunkPlugin.js000066400000000000000000000020511345416772700217670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; module.exports = class RuntimeChunkPlugin { constructor(options) { this.options = Object.assign( { name: entrypoint => `runtime~${entrypoint.name}` }, options ); } apply(compiler) { compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { compilation.hooks.optimizeChunksAdvanced.tap("RuntimeChunkPlugin", () => { for (const entrypoint of compilation.entrypoints.values()) { const chunk = entrypoint.getRuntimeChunk(); let name = this.options.name; if (typeof name === "function") { name = name(entrypoint); } if ( chunk.getNumberOfModules() > 0 || !chunk.preventIntegration || chunk.name !== name ) { const newChunk = compilation.addChunk(name); newChunk.preventIntegration = true; entrypoint.unshiftChunk(newChunk); newChunk.addGroup(entrypoint); entrypoint.setRuntimeChunk(newChunk); } } }); }); } }; webpack-4.30.0/lib/optimize/SideEffectsFlagPlugin.js000066400000000000000000000121071345416772700223340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const mm = require("micromatch"); const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency"); const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency"); /** @typedef {import("../Module")} Module */ /** @typedef {import("../Dependency")} Dependency */ /** * @typedef {Object} ExportInModule * @property {Module} module the module * @property {string} exportName the name of the export */ class SideEffectsFlagPlugin { apply(compiler) { compiler.hooks.normalModuleFactory.tap("SideEffectsFlagPlugin", nmf => { nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { const resolveData = data.resourceResolveData; if ( resolveData && resolveData.descriptionFileData && resolveData.relativePath ) { const sideEffects = resolveData.descriptionFileData.sideEffects; const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects( resolveData.relativePath, sideEffects ); if (!hasSideEffects) { module.factoryMeta.sideEffectFree = true; } } return module; }); nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { if (data.settings.sideEffects === false) { module.factoryMeta.sideEffectFree = true; } else if (data.settings.sideEffects === true) { module.factoryMeta.sideEffectFree = false; } }); }); compiler.hooks.compilation.tap("SideEffectsFlagPlugin", compilation => { compilation.hooks.optimizeDependencies.tap( "SideEffectsFlagPlugin", modules => { /** @type {Map>} */ const reexportMaps = new Map(); // Capture reexports of sideEffectFree modules for (const module of modules) { /** @type {Dependency[]} */ const removeDependencies = []; for (const dep of module.dependencies) { if (dep instanceof HarmonyImportSideEffectDependency) { if (dep.module && dep.module.factoryMeta.sideEffectFree) { removeDependencies.push(dep); } } else if ( dep instanceof HarmonyExportImportedSpecifierDependency ) { if (module.factoryMeta.sideEffectFree) { const mode = dep.getMode(true); if (mode.type === "safe-reexport") { let map = reexportMaps.get(module); if (!map) { reexportMaps.set(module, (map = new Map())); } for (const pair of mode.map) { map.set(pair[0], { module: mode.module, exportName: pair[1] }); } } } } } } // Flatten reexports for (const map of reexportMaps.values()) { for (const pair of map) { let mapping = pair[1]; while (mapping) { const innerMap = reexportMaps.get(mapping.module); if (!innerMap) break; const newMapping = innerMap.get(mapping.exportName); if (newMapping) { map.set(pair[0], newMapping); } mapping = newMapping; } } } // Update imports along the reexports from sideEffectFree modules for (const pair of reexportMaps) { const module = pair[0]; const map = pair[1]; let newReasons = undefined; for (let i = 0; i < module.reasons.length; i++) { const reason = module.reasons[i]; const dep = reason.dependency; if ( dep instanceof HarmonyImportSpecifierDependency && !dep.namespaceObjectAsContext ) { const mapping = map.get(dep.id); if (mapping) { dep.redirectedModule = mapping.module; dep.redirectedId = mapping.exportName; mapping.module.addReason( reason.module, dep, reason.explanation ? reason.explanation + " (skipped side-effect-free modules)" : "(skipped side-effect-free modules)" ); // removing the currect reason, by not adding it to the newReasons array // lazily create the newReasons array if (newReasons === undefined) { newReasons = i === 0 ? [] : module.reasons.slice(0, i); } continue; } } if (newReasons !== undefined) newReasons.push(reason); } if (newReasons !== undefined) { module.reasons = newReasons; } } } ); }); } static moduleHasSideEffects(moduleName, flagValue) { switch (typeof flagValue) { case "undefined": return true; case "boolean": return flagValue; case "string": if (process.platform === "win32") { flagValue = flagValue.replace(/\\/g, "/"); } return mm.isMatch(moduleName, flagValue, { matchBase: true }); case "object": return flagValue.some(glob => SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob) ); } } } module.exports = SideEffectsFlagPlugin; webpack-4.30.0/lib/optimize/SplitChunksPlugin.js000066400000000000000000000704261345416772700216350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const crypto = require("crypto"); const SortableSet = require("../util/SortableSet"); const GraphHelpers = require("../GraphHelpers"); const { isSubset } = require("../util/SetHelpers"); const deterministicGrouping = require("../util/deterministicGrouping"); const MinMaxSizeWarning = require("./MinMaxSizeWarning"); const contextify = require("../util/identifier").contextify; /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ /** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ const deterministicGroupingForModules = /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (deterministicGrouping); const hashFilename = name => { return crypto .createHash("md4") .update(name) .digest("hex") .slice(0, 8); }; const sortByIdentifier = (a, b) => { if (a.identifier() > b.identifier()) return 1; if (a.identifier() < b.identifier()) return -1; return 0; }; const getRequests = chunk => { let requests = 0; for (const chunkGroup of chunk.groupsIterable) { requests = Math.max(requests, chunkGroup.chunks.length); } return requests; }; const getModulesSize = modules => { let sum = 0; for (const m of modules) { sum += m.size(); } return sum; }; /** * @template T * @param {Set} a set * @param {Set} b other set * @returns {boolean} true if at least one item of a is in b */ const isOverlap = (a, b) => { for (const item of a) { if (b.has(item)) return true; } return false; }; const compareEntries = (a, b) => { // 1. by priority const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; if (diffPriority) return diffPriority; // 2. by number of chunks const diffCount = a.chunks.size - b.chunks.size; if (diffCount) return diffCount; // 3. by size reduction const aSizeReduce = a.size * (a.chunks.size - 1); const bSizeReduce = b.size * (b.chunks.size - 1); const diffSizeReduce = aSizeReduce - bSizeReduce; if (diffSizeReduce) return diffSizeReduce; // 4. by number of modules (to be able to compare by identifier) const modulesA = a.modules; const modulesB = b.modules; const diff = modulesA.size - modulesB.size; if (diff) return diff; // 5. by module identifiers modulesA.sort(); modulesB.sort(); const aI = modulesA[Symbol.iterator](); const bI = modulesB[Symbol.iterator](); // eslint-disable-next-line no-constant-condition while (true) { const aItem = aI.next(); const bItem = bI.next(); if (aItem.done) return 0; const aModuleIdentifier = aItem.value.identifier(); const bModuleIdentifier = bItem.value.identifier(); if (aModuleIdentifier > bModuleIdentifier) return -1; if (aModuleIdentifier < bModuleIdentifier) return 1; } }; const compareNumbers = (a, b) => a - b; const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); const ALL_CHUNK_FILTER = chunk => true; module.exports = class SplitChunksPlugin { constructor(options) { this.options = SplitChunksPlugin.normalizeOptions(options); } static normalizeOptions(options = {}) { return { chunksFilter: SplitChunksPlugin.normalizeChunksFilter( options.chunks || "all" ), minSize: options.minSize || 0, maxSize: options.maxSize || 0, minChunks: options.minChunks || 1, maxAsyncRequests: options.maxAsyncRequests || 1, maxInitialRequests: options.maxInitialRequests || 1, hidePathInfo: options.hidePathInfo || false, filename: options.filename || undefined, getCacheGroups: SplitChunksPlugin.normalizeCacheGroups({ cacheGroups: options.cacheGroups, name: options.name, automaticNameDelimiter: options.automaticNameDelimiter }), automaticNameDelimiter: options.automaticNameDelimiter, fallbackCacheGroup: SplitChunksPlugin.normalizeFallbackCacheGroup( options.fallbackCacheGroup || {}, options ) }; } static normalizeName({ name, automaticNameDelimiter, automaticNamePrefix }) { if (name === true) { /** @type {WeakMap>} */ const cache = new WeakMap(); const fn = (module, chunks, cacheGroup) => { let cacheEntry = cache.get(chunks); if (cacheEntry === undefined) { cacheEntry = {}; cache.set(chunks, cacheEntry); } else if (cacheGroup in cacheEntry) { return cacheEntry[cacheGroup]; } const names = chunks.map(c => c.name); if (!names.every(Boolean)) { cacheEntry[cacheGroup] = undefined; return; } names.sort(); const prefix = typeof automaticNamePrefix === "string" ? automaticNamePrefix : cacheGroup; const namePrefix = prefix ? prefix + automaticNameDelimiter : ""; let name = namePrefix + names.join(automaticNameDelimiter); // Filenames and paths can't be too long otherwise an // ENAMETOOLONG error is raised. If the generated name if too // long, it is truncated and a hash is appended. The limit has // been set to 100 to prevent `[name].[chunkhash].[ext]` from // generating a 256+ character string. if (name.length > 100) { name = name.slice(0, 100) + automaticNameDelimiter + hashFilename(name); } cacheEntry[cacheGroup] = name; return name; }; return fn; } if (typeof name === "string") { const fn = () => { return name; }; return fn; } if (typeof name === "function") return name; } static normalizeChunksFilter(chunks) { if (chunks === "initial") { return INITIAL_CHUNK_FILTER; } if (chunks === "async") { return ASYNC_CHUNK_FILTER; } if (chunks === "all") { return ALL_CHUNK_FILTER; } if (typeof chunks === "function") return chunks; } static normalizeFallbackCacheGroup( { minSize = undefined, maxSize = undefined, automaticNameDelimiter = undefined }, { minSize: defaultMinSize = undefined, maxSize: defaultMaxSize = undefined, automaticNameDelimiter: defaultAutomaticNameDelimiter = undefined } ) { return { minSize: typeof minSize === "number" ? minSize : defaultMinSize || 0, maxSize: typeof maxSize === "number" ? maxSize : defaultMaxSize || 0, automaticNameDelimiter: automaticNameDelimiter || defaultAutomaticNameDelimiter || "~" }; } static normalizeCacheGroups({ cacheGroups, name, automaticNameDelimiter }) { if (typeof cacheGroups === "function") { // TODO webpack 5 remove this if (cacheGroups.length !== 1) { return module => cacheGroups(module, module.getChunks()); } return cacheGroups; } if (cacheGroups && typeof cacheGroups === "object") { const fn = module => { let results; for (const key of Object.keys(cacheGroups)) { let option = cacheGroups[key]; if (option === false) continue; if (option instanceof RegExp || typeof option === "string") { option = { test: option }; } if (typeof option === "function") { let result = option(module); if (result) { if (results === undefined) results = []; for (const r of Array.isArray(result) ? result : [result]) { const result = Object.assign({ key }, r); if (result.name) result.getName = () => result.name; if (result.chunks) { result.chunksFilter = SplitChunksPlugin.normalizeChunksFilter( result.chunks ); } results.push(result); } } } else if (SplitChunksPlugin.checkTest(option.test, module)) { if (results === undefined) results = []; results.push({ key: key, priority: option.priority, getName: SplitChunksPlugin.normalizeName({ name: option.name || name, automaticNameDelimiter: typeof option.automaticNameDelimiter === "string" ? option.automaticNameDelimiter : automaticNameDelimiter, automaticNamePrefix: option.automaticNamePrefix }) || (() => {}), chunksFilter: SplitChunksPlugin.normalizeChunksFilter( option.chunks ), enforce: option.enforce, minSize: option.minSize, maxSize: option.maxSize, minChunks: option.minChunks, maxAsyncRequests: option.maxAsyncRequests, maxInitialRequests: option.maxInitialRequests, filename: option.filename, reuseExistingChunk: option.reuseExistingChunk }); } } return results; }; return fn; } const fn = () => {}; return fn; } static checkTest(test, module) { if (test === undefined) return true; if (typeof test === "function") { if (test.length !== 1) { return test(module, module.getChunks()); } return test(module); } if (typeof test === "boolean") return test; if (typeof test === "string") { if ( module.nameForCondition && module.nameForCondition().startsWith(test) ) { return true; } for (const chunk of module.chunksIterable) { if (chunk.name && chunk.name.startsWith(test)) { return true; } } return false; } if (test instanceof RegExp) { if (module.nameForCondition && test.test(module.nameForCondition())) { return true; } for (const chunk of module.chunksIterable) { if (chunk.name && test.test(chunk.name)) { return true; } } return false; } return false; } /** * @param {Compiler} compiler webpack compiler * @returns {void} */ apply(compiler) { compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { let alreadyOptimized = false; compilation.hooks.unseal.tap("SplitChunksPlugin", () => { alreadyOptimized = false; }); compilation.hooks.optimizeChunksAdvanced.tap( "SplitChunksPlugin", chunks => { if (alreadyOptimized) return; alreadyOptimized = true; // Give each selected chunk an index (to create strings from chunks) const indexMap = new Map(); let index = 1; for (const chunk of chunks) { indexMap.set(chunk, index++); } const getKey = chunks => { return Array.from(chunks, c => indexMap.get(c)) .sort(compareNumbers) .join(); }; /** @type {Map>} */ const chunkSetsInGraph = new Map(); for (const module of compilation.modules) { const chunksKey = getKey(module.chunksIterable); if (!chunkSetsInGraph.has(chunksKey)) { chunkSetsInGraph.set(chunksKey, new Set(module.chunksIterable)); } } // group these set of chunks by count // to allow to check less sets via isSubset // (only smaller sets can be subset) /** @type {Map>>} */ const chunkSetsByCount = new Map(); for (const chunksSet of chunkSetsInGraph.values()) { const count = chunksSet.size; let array = chunkSetsByCount.get(count); if (array === undefined) { array = []; chunkSetsByCount.set(count, array); } array.push(chunksSet); } // Create a list of possible combinations const combinationsCache = new Map(); // Map[]> const getCombinations = key => { const chunksSet = chunkSetsInGraph.get(key); var array = [chunksSet]; if (chunksSet.size > 1) { for (const [count, setArray] of chunkSetsByCount) { // "equal" is not needed because they would have been merge in the first step if (count < chunksSet.size) { for (const set of setArray) { if (isSubset(chunksSet, set)) { array.push(set); } } } } } return array; }; /** * @typedef {Object} SelectedChunksResult * @property {Chunk[]} chunks the list of chunks * @property {string} key a key of the list */ /** * @typedef {function(Chunk): boolean} ChunkFilterFunction */ /** @type {WeakMap, WeakMap>} */ const selectedChunksCacheByChunksSet = new WeakMap(); /** * get list and key by applying the filter function to the list * It is cached for performance reasons * @param {Set} chunks list of chunks * @param {ChunkFilterFunction} chunkFilter filter function for chunks * @returns {SelectedChunksResult} list and key */ const getSelectedChunks = (chunks, chunkFilter) => { let entry = selectedChunksCacheByChunksSet.get(chunks); if (entry === undefined) { entry = new WeakMap(); selectedChunksCacheByChunksSet.set(chunks, entry); } /** @type {SelectedChunksResult} */ let entry2 = entry.get(chunkFilter); if (entry2 === undefined) { /** @type {Chunk[]} */ const selectedChunks = []; for (const chunk of chunks) { if (chunkFilter(chunk)) selectedChunks.push(chunk); } entry2 = { chunks: selectedChunks, key: getKey(selectedChunks) }; entry.set(chunkFilter, entry2); } return entry2; }; /** * @typedef {Object} ChunksInfoItem * @property {SortableSet} modules * @property {TODO} cacheGroup * @property {string} name * @property {boolean} validateSize * @property {number} size * @property {Set} chunks * @property {Set} reuseableChunks * @property {Set} chunksKeys */ // Map a list of chunks to a list of modules // For the key the chunk "index" is used, the value is a SortableSet of modules /** @type {Map} */ const chunksInfoMap = new Map(); /** * @param {TODO} cacheGroup the current cache group * @param {Chunk[]} selectedChunks chunks selected for this module * @param {string} selectedChunksKey a key of selectedChunks * @param {Module} module the current module * @returns {void} */ const addModuleToChunksInfoMap = ( cacheGroup, selectedChunks, selectedChunksKey, module ) => { // Break if minimum number of chunks is not reached if (selectedChunks.length < cacheGroup.minChunks) return; // Determine name for split chunk const name = cacheGroup.getName( module, selectedChunks, cacheGroup.key ); // Create key for maps // When it has a name we use the name as key // Elsewise we create the key from chunks and cache group key // This automatically merges equal names const key = cacheGroup.key + (name ? ` name:${name}` : ` chunks:${selectedChunksKey}`); // Add module to maps let info = chunksInfoMap.get(key); if (info === undefined) { chunksInfoMap.set( key, (info = { modules: new SortableSet(undefined, sortByIdentifier), cacheGroup, name, validateSize: cacheGroup.minSize > 0, size: 0, chunks: new Set(), reuseableChunks: new Set(), chunksKeys: new Set() }) ); } info.modules.add(module); if (info.validateSize) { info.size += module.size(); } if (!info.chunksKeys.has(selectedChunksKey)) { info.chunksKeys.add(selectedChunksKey); for (const chunk of selectedChunks) { info.chunks.add(chunk); } } }; // Walk through all modules for (const module of compilation.modules) { // Get cache group let cacheGroups = this.options.getCacheGroups(module); if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { continue; } // Prepare some values const chunksKey = getKey(module.chunksIterable); let combs = combinationsCache.get(chunksKey); if (combs === undefined) { combs = getCombinations(chunksKey); combinationsCache.set(chunksKey, combs); } for (const cacheGroupSource of cacheGroups) { const cacheGroup = { key: cacheGroupSource.key, priority: cacheGroupSource.priority || 0, chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter, minSize: cacheGroupSource.minSize !== undefined ? cacheGroupSource.minSize : cacheGroupSource.enforce ? 0 : this.options.minSize, minSizeForMaxSize: cacheGroupSource.minSize !== undefined ? cacheGroupSource.minSize : this.options.minSize, maxSize: cacheGroupSource.maxSize !== undefined ? cacheGroupSource.maxSize : cacheGroupSource.enforce ? 0 : this.options.maxSize, minChunks: cacheGroupSource.minChunks !== undefined ? cacheGroupSource.minChunks : cacheGroupSource.enforce ? 1 : this.options.minChunks, maxAsyncRequests: cacheGroupSource.maxAsyncRequests !== undefined ? cacheGroupSource.maxAsyncRequests : cacheGroupSource.enforce ? Infinity : this.options.maxAsyncRequests, maxInitialRequests: cacheGroupSource.maxInitialRequests !== undefined ? cacheGroupSource.maxInitialRequests : cacheGroupSource.enforce ? Infinity : this.options.maxInitialRequests, getName: cacheGroupSource.getName !== undefined ? cacheGroupSource.getName : this.options.getName, filename: cacheGroupSource.filename !== undefined ? cacheGroupSource.filename : this.options.filename, automaticNameDelimiter: cacheGroupSource.automaticNameDelimiter !== undefined ? cacheGroupSource.automaticNameDelimiter : this.options.automaticNameDelimiter, reuseExistingChunk: cacheGroupSource.reuseExistingChunk }; // For all combination of chunk selection for (const chunkCombination of combs) { // Break if minimum number of chunks is not reached if (chunkCombination.size < cacheGroup.minChunks) continue; // Select chunks by configuration const { chunks: selectedChunks, key: selectedChunksKey } = getSelectedChunks( chunkCombination, cacheGroup.chunksFilter ); addModuleToChunksInfoMap( cacheGroup, selectedChunks, selectedChunksKey, module ); } } } // Filter items were size < minSize for (const pair of chunksInfoMap) { const info = pair[1]; if (info.validateSize && info.size < info.cacheGroup.minSize) { chunksInfoMap.delete(pair[0]); } } /** @type {Map} */ const maxSizeQueueMap = new Map(); while (chunksInfoMap.size > 0) { // Find best matching entry let bestEntryKey; let bestEntry; for (const pair of chunksInfoMap) { const key = pair[0]; const info = pair[1]; if (bestEntry === undefined) { bestEntry = info; bestEntryKey = key; } else if (compareEntries(bestEntry, info) < 0) { bestEntry = info; bestEntryKey = key; } } const item = bestEntry; chunksInfoMap.delete(bestEntryKey); let chunkName = item.name; // Variable for the new chunk (lazy created) /** @type {Chunk} */ let newChunk; // When no chunk name, check if we can reuse a chunk instead of creating a new one let isReused = false; if (item.cacheGroup.reuseExistingChunk) { outer: for (const chunk of item.chunks) { if (chunk.getNumberOfModules() !== item.modules.size) continue; if (chunk.hasEntryModule()) continue; for (const module of item.modules) { if (!chunk.containsModule(module)) continue outer; } if (!newChunk || !newChunk.name) { newChunk = chunk; } else if ( chunk.name && chunk.name.length < newChunk.name.length ) { newChunk = chunk; } else if ( chunk.name && chunk.name.length === newChunk.name.length && chunk.name < newChunk.name ) { newChunk = chunk; } chunkName = undefined; isReused = true; } } // Check if maxRequests condition can be fulfilled const usedChunks = Array.from(item.chunks).filter(chunk => { // skip if we address ourself return ( (!chunkName || chunk.name !== chunkName) && chunk !== newChunk ); }); // Skip when no chunk selected if (usedChunks.length === 0) continue; let validChunks = usedChunks; if ( Number.isFinite(item.cacheGroup.maxInitialRequests) || Number.isFinite(item.cacheGroup.maxAsyncRequests) ) { validChunks = validChunks.filter(chunk => { // respect max requests when not enforced const maxRequests = chunk.isOnlyInitial() ? item.cacheGroup.maxInitialRequests : chunk.canBeInitial() ? Math.min( item.cacheGroup.maxInitialRequests, item.cacheGroup.maxAsyncRequests ) : item.cacheGroup.maxAsyncRequests; return ( !isFinite(maxRequests) || getRequests(chunk) < maxRequests ); }); } validChunks = validChunks.filter(chunk => { for (const module of item.modules) { if (chunk.containsModule(module)) return true; } return false; }); if (validChunks.length < usedChunks.length) { if (validChunks.length >= item.cacheGroup.minChunks) { for (const module of item.modules) { addModuleToChunksInfoMap( item.cacheGroup, validChunks, getKey(validChunks), module ); } } continue; } // Create the new chunk if not reusing one if (!isReused) { newChunk = compilation.addChunk(chunkName); } // Walk through all chunks for (const chunk of usedChunks) { // Add graph connections for splitted chunk chunk.split(newChunk); } // Add a note to the chunk newChunk.chunkReason = isReused ? "reused as split chunk" : "split chunk"; if (item.cacheGroup.key) { newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; } if (chunkName) { newChunk.chunkReason += ` (name: ${chunkName})`; // If the chosen name is already an entry point we remove the entry point const entrypoint = compilation.entrypoints.get(chunkName); if (entrypoint) { compilation.entrypoints.delete(chunkName); entrypoint.remove(); newChunk.entryModule = undefined; } } if (item.cacheGroup.filename) { if (!newChunk.isOnlyInitial()) { throw new Error( "SplitChunksPlugin: You are trying to set a filename for a chunk which is (also) loaded on demand. " + "The runtime can only handle loading of chunks which match the chunkFilename schema. " + "Using a custom filename would fail at runtime. " + `(cache group: ${item.cacheGroup.key})` ); } newChunk.filenameTemplate = item.cacheGroup.filename; } if (!isReused) { // Add all modules to the new chunk for (const module of item.modules) { if (typeof module.chunkCondition === "function") { if (!module.chunkCondition(newChunk)) continue; } // Add module to new chunk GraphHelpers.connectChunkAndModule(newChunk, module); // Remove module from used chunks for (const chunk of usedChunks) { chunk.removeModule(module); module.rewriteChunkInReasons(chunk, [newChunk]); } } } else { // Remove all modules from used chunks for (const module of item.modules) { for (const chunk of usedChunks) { chunk.removeModule(module); module.rewriteChunkInReasons(chunk, [newChunk]); } } } if (item.cacheGroup.maxSize > 0) { const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); maxSizeQueueMap.set(newChunk, { minSize: Math.max( oldMaxSizeSettings ? oldMaxSizeSettings.minSize : 0, item.cacheGroup.minSizeForMaxSize ), maxSize: Math.min( oldMaxSizeSettings ? oldMaxSizeSettings.maxSize : Infinity, item.cacheGroup.maxSize ), automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, keys: oldMaxSizeSettings ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) : [item.cacheGroup.key] }); } // remove all modules from other entries and update size for (const [key, info] of chunksInfoMap) { if (isOverlap(info.chunks, item.chunks)) { if (info.validateSize) { // update modules and total size // may remove it from the map when < minSize const oldSize = info.modules.size; for (const module of item.modules) { info.modules.delete(module); } if (info.modules.size === 0) { chunksInfoMap.delete(key); continue; } if (info.modules.size !== oldSize) { info.size = getModulesSize(info.modules); if (info.size < info.cacheGroup.minSize) { chunksInfoMap.delete(key); } } } else { // only update the modules for (const module of item.modules) { info.modules.delete(module); } if (info.modules.size === 0) { chunksInfoMap.delete(key); } } } } } const incorrectMinMaxSizeSet = new Set(); // Make sure that maxSize is fulfilled for (const chunk of compilation.chunks.slice()) { const { minSize, maxSize, automaticNameDelimiter, keys } = maxSizeQueueMap.get(chunk) || this.options.fallbackCacheGroup; if (!maxSize) continue; if (minSize > maxSize) { const warningKey = `${keys && keys.join()} ${minSize} ${maxSize}`; if (!incorrectMinMaxSizeSet.has(warningKey)) { incorrectMinMaxSizeSet.add(warningKey); compilation.warnings.push( new MinMaxSizeWarning(keys, minSize, maxSize) ); } } const results = deterministicGroupingForModules({ maxSize: Math.max(minSize, maxSize), minSize, items: chunk.modulesIterable, getKey(module) { const ident = contextify( compilation.options.context, module.identifier() ); const name = module.nameForCondition ? contextify( compilation.options.context, module.nameForCondition() ) : ident.replace(/^.*!|\?[^?!]*$/g, ""); const fullKey = name + automaticNameDelimiter + hashFilename(ident); return fullKey.replace(/[\\/?]/g, "_"); }, getSize(module) { return module.size(); } }); results.sort((a, b) => { if (a.key < b.key) return -1; if (a.key > b.key) return 1; return 0; }); for (let i = 0; i < results.length; i++) { const group = results[i]; const key = this.options.hidePathInfo ? hashFilename(group.key) : group.key; let name = chunk.name ? chunk.name + automaticNameDelimiter + key : null; if (name && name.length > 100) { name = name.slice(0, 100) + automaticNameDelimiter + hashFilename(name); } let newPart; if (i !== results.length - 1) { newPart = compilation.addChunk(name); chunk.split(newPart); newPart.chunkReason = chunk.chunkReason; // Add all modules to the new chunk for (const module of group.items) { if (typeof module.chunkCondition === "function") { if (!module.chunkCondition(newPart)) continue; } // Add module to new chunk GraphHelpers.connectChunkAndModule(newPart, module); // Remove module from used chunks chunk.removeModule(module); module.rewriteChunkInReasons(chunk, [newPart]); } } else { // change the chunk to be a part newPart = chunk; chunk.name = name; } } } } ); }); } }; webpack-4.30.0/lib/performance/000077500000000000000000000000001345416772700163015ustar00rootroot00000000000000webpack-4.30.0/lib/performance/AssetsOverSizeLimitWarning.js000066400000000000000000000015051345416772700241160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Sean Larkin @thelarkinn */ "use strict"; const WebpackError = require("../WebpackError"); const SizeFormatHelpers = require("../SizeFormatHelpers"); module.exports = class AssetsOverSizeLimitWarning extends WebpackError { constructor(assetsOverSizeLimit, assetLimit) { const assetLists = assetsOverSizeLimit .map( asset => `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})` ) .join(""); super(`asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize( assetLimit )}). This can impact web performance. Assets: ${assetLists}`); this.name = "AssetsOverSizeLimitWarning"; this.assets = assetsOverSizeLimit; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/performance/EntrypointsOverSizeLimitWarning.js000066400000000000000000000017101345416772700252100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Sean Larkin @thelarkinn */ "use strict"; const WebpackError = require("../WebpackError"); const SizeFormatHelpers = require("../SizeFormatHelpers"); module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { constructor(entrypoints, entrypointLimit) { const entrypointList = entrypoints .map( entrypoint => `\n ${entrypoint.name} (${SizeFormatHelpers.formatSize( entrypoint.size )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` ) .join(""); super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${SizeFormatHelpers.formatSize( entrypointLimit )}). This can impact web performance. Entrypoints:${entrypointList}\n`); this.name = "EntrypointsOverSizeLimitWarning"; this.entrypoints = entrypoints; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/performance/NoAsyncChunksWarning.js000066400000000000000000000011431345416772700227120ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Sean Larkin @thelarkinn */ "use strict"; const WebpackError = require("../WebpackError"); module.exports = class NoAsyncChunksWarning extends WebpackError { constructor() { super( "webpack performance recommendations: \n" + "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + "For more info visit https://webpack.js.org/guides/code-splitting/" ); this.name = "NoAsyncChunksWarning"; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/performance/SizeLimitsPlugin.js000066400000000000000000000054701345416772700221200ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Sean Larkin @thelarkinn */ "use strict"; const EntrypointsOverSizeLimitWarning = require("./EntrypointsOverSizeLimitWarning"); const AssetsOverSizeLimitWarning = require("./AssetsOverSizeLimitWarning"); const NoAsyncChunksWarning = require("./NoAsyncChunksWarning"); module.exports = class SizeLimitsPlugin { constructor(options) { this.hints = options.hints; this.maxAssetSize = options.maxAssetSize; this.maxEntrypointSize = options.maxEntrypointSize; this.assetFilter = options.assetFilter; } apply(compiler) { const entrypointSizeLimit = this.maxEntrypointSize; const assetSizeLimit = this.maxAssetSize; const hints = this.hints; const assetFilter = this.assetFilter || (asset => !asset.endsWith(".map")); compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { const warnings = []; const getEntrypointSize = entrypoint => entrypoint.getFiles().reduce((currentSize, file) => { if (assetFilter(file) && compilation.assets[file]) { return currentSize + compilation.assets[file].size(); } return currentSize; }, 0); const assetsOverSizeLimit = []; for (const assetName of Object.keys(compilation.assets)) { if (!assetFilter(assetName)) { continue; } const asset = compilation.assets[assetName]; const size = asset.size(); if (size > assetSizeLimit) { assetsOverSizeLimit.push({ name: assetName, size: size }); asset.isOverSizeLimit = true; } } const entrypointsOverLimit = []; for (const pair of compilation.entrypoints) { const name = pair[0]; const entry = pair[1]; const size = getEntrypointSize(entry); if (size > entrypointSizeLimit) { entrypointsOverLimit.push({ name: name, size: size, files: entry.getFiles().filter(assetFilter) }); entry.isOverSizeLimit = true; } } if (hints) { // 1. Individual Chunk: Size < 250kb // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb // 3. No Async Chunks // if !1, then 2, if !2 return if (assetsOverSizeLimit.length > 0) { warnings.push( new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) ); } if (entrypointsOverLimit.length > 0) { warnings.push( new EntrypointsOverSizeLimitWarning( entrypointsOverLimit, entrypointSizeLimit ) ); } if (warnings.length > 0) { const hasAsyncChunks = compilation.chunks.filter(chunk => !chunk.canBeInitial()).length > 0; if (!hasAsyncChunks) { warnings.push(new NoAsyncChunksWarning()); } if (hints === "error") { compilation.errors.push(...warnings); } else { compilation.warnings.push(...warnings); } } } }); } }; webpack-4.30.0/lib/util/000077500000000000000000000000001345416772700147555ustar00rootroot00000000000000webpack-4.30.0/lib/util/Queue.js000066400000000000000000000016541345416772700164050ustar00rootroot00000000000000"use strict"; /** * @template T */ class Queue { /** * @param {Iterable=} items The initial elements. */ constructor(items) { /** @private @type {Set} */ this.set = new Set(items); /** @private @type {Iterator} */ this.iterator = this.set[Symbol.iterator](); } /** * Returns the number of elements in this queue. * @returns {number} The number of elements in this queue. */ get length() { return this.set.size; } /** * Appends the specified element to this queue. * @param {T} item The element to add. * @returns {void} */ enqueue(item) { this.set.add(item); } /** * Retrieves and removes the head of this queue. * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. */ dequeue() { const result = this.iterator.next(); if (result.done) return undefined; this.set.delete(result.value); return result.value; } } module.exports = Queue; webpack-4.30.0/lib/util/Semaphore.js000066400000000000000000000017571345416772700172500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class Semaphore { /** * Creates an instance of Semaphore. * * @param {number} available the amount available number of "tasks" * in the Semaphore */ constructor(available) { this.available = available; /** @type {(function(): void)[]} */ this.waiters = []; /** @private */ this._continue = this._continue.bind(this); } /** * @param {function(): void} callback function block to capture and run * @returns {void} */ acquire(callback) { if (this.available > 0) { this.available--; callback(); } else { this.waiters.push(callback); } } release() { this.available++; if (this.waiters.length > 0) { process.nextTick(this._continue); } } _continue() { if (this.available > 0) { if (this.waiters.length > 0) { this.available--; const callback = this.waiters.pop(); callback(); } } } } module.exports = Semaphore; webpack-4.30.0/lib/util/SetHelpers.js000066400000000000000000000025411345416772700173730ustar00rootroot00000000000000"use strict"; /** * intersect creates Set containing the intersection of elements between all sets * @param {Set[]} sets an array of sets being checked for shared elements * @returns {Set} returns a new Set containing the intersecting items */ const intersect = sets => { if (sets.length === 0) return new Set(); if (sets.length === 1) return new Set(sets[0]); let minSize = Infinity; let minIndex = -1; for (let i = 0; i < sets.length; i++) { const size = sets[i].size; if (size < minSize) { minIndex = i; minSize = size; } } const current = new Set(sets[minIndex]); for (let i = 0; i < sets.length; i++) { if (i === minIndex) continue; const set = sets[i]; for (const item of current) { if (!set.has(item)) { current.delete(item); } } } return current; }; /** * Checks if a set is the subset of another set * @param {Set} bigSet a Set which contains the original elements to compare against * @param {Set} smallSet the set whos elements might be contained inside of bigSet * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet */ const isSubset = (bigSet, smallSet) => { if (bigSet.size < smallSet.size) return false; for (const item of smallSet) { if (!bigSet.has(item)) return false; } return true; }; exports.intersect = intersect; exports.isSubset = isSubset; webpack-4.30.0/lib/util/SortableSet.js000066400000000000000000000062451345416772700175510ustar00rootroot00000000000000"use strict"; /** * A subset of Set that offers sorting functionality * @template T item type in set * @extends {Set} */ class SortableSet extends Set { /** * Create a new sortable set * @param {Iterable=} initialIterable The initial iterable value * @typedef {function(T, T): number} SortFunction * @param {SortFunction=} defaultSort Default sorting function */ constructor(initialIterable, defaultSort) { super(initialIterable); /** @private @type {function(T, T): number}} */ this._sortFn = defaultSort; /** @private @type {function(T, T): number} | null} */ this._lastActiveSortFn = null; /** @private @type {Map | undefined} */ this._cache = undefined; /** @private @type {Map | undefined} */ this._cacheOrderIndependent = undefined; } /** * @param {T} value value to add to set * @returns {this} returns itself */ add(value) { this._lastActiveSortFn = null; this._invalidateCache(); this._invalidateOrderedCache(); super.add(value); return this; } /** * @param {T} value value to delete * @returns {boolean} true if value existed in set, false otherwise */ delete(value) { this._invalidateCache(); this._invalidateOrderedCache(); return super.delete(value); } /** * @returns {void} */ clear() { this._invalidateCache(); this._invalidateOrderedCache(); return super.clear(); } /** * Sort with a comparer function * @param {SortFunction} sortFn Sorting comparer function * @returns {void} */ sortWith(sortFn) { if (this.size <= 1 || sortFn === this._lastActiveSortFn) { // already sorted - nothing to do return; } const sortedArray = Array.from(this).sort(sortFn); super.clear(); for (let i = 0; i < sortedArray.length; i += 1) { super.add(sortedArray[i]); } this._lastActiveSortFn = sortFn; this._invalidateCache(); } sort() { this.sortWith(this._sortFn); } /** * Get data from cache * @param {function(SortableSet): T[]} fn function to calculate value * @returns {T[]} returns result of fn(this), cached until set changes */ getFromCache(fn) { if (this._cache === undefined) { this._cache = new Map(); } else { const data = this._cache.get(fn); if (data !== undefined) { return data; } } const newData = fn(this); this._cache.set(fn, newData); return newData; } /** * @param {function(SortableSet): string|number|T[]} fn function to calculate value * @returns {any} returns result of fn(this), cached until set changes */ getFromUnorderedCache(fn) { if (this._cacheOrderIndependent === undefined) { this._cacheOrderIndependent = new Map(); } else { const data = this._cacheOrderIndependent.get(fn); if (data !== undefined) { return data; } } const newData = fn(this); this._cacheOrderIndependent.set(fn, newData); return newData; } /** * @private * @returns {void} */ _invalidateCache() { if (this._cache !== undefined) { this._cache.clear(); } } /** * @private * @returns {void} */ _invalidateOrderedCache() { if (this._cacheOrderIndependent !== undefined) { this._cacheOrderIndependent.clear(); } } } module.exports = SortableSet; webpack-4.30.0/lib/util/StackedSetMap.js000066400000000000000000000054511345416772700200100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const util = require("util"); const TOMBSTONE = {}; const UNDEFINED_MARKER = {}; class StackedSetMap { constructor(parentStack) { this.stack = parentStack === undefined ? [] : parentStack.slice(); this.map = new Map(); this.stack.push(this.map); } add(item) { this.map.set(item, true); } set(item, value) { this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); } delete(item) { if (this.stack.length > 1) { this.map.set(item, TOMBSTONE); } else { this.map.delete(item); } } has(item) { const topValue = this.map.get(item); if (topValue !== undefined) return topValue !== TOMBSTONE; if (this.stack.length > 1) { for (var i = this.stack.length - 2; i >= 0; i--) { const value = this.stack[i].get(item); if (value !== undefined) { this.map.set(item, value); return value !== TOMBSTONE; } } this.map.set(item, TOMBSTONE); } return false; } get(item) { const topValue = this.map.get(item); if (topValue !== undefined) { return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER ? undefined : topValue; } if (this.stack.length > 1) { for (var i = this.stack.length - 2; i >= 0; i--) { const value = this.stack[i].get(item); if (value !== undefined) { this.map.set(item, value); return value === TOMBSTONE || value === UNDEFINED_MARKER ? undefined : value; } } this.map.set(item, TOMBSTONE); } return undefined; } _compress() { if (this.stack.length === 1) return; this.map = new Map(); for (const data of this.stack) { for (const pair of data) { if (pair[1] === TOMBSTONE) { this.map.delete(pair[0]); } else { this.map.set(pair[0], pair[1]); } } } this.stack = [this.map]; } asArray() { this._compress(); return Array.from(this.map.entries(), pair => pair[0]); } asSet() { return new Set(this.asArray()); } asPairArray() { this._compress(); return Array.from(this.map.entries(), pair => /** @type {[TODO, TODO]} */ (pair[1] === UNDEFINED_MARKER ? [pair[0], undefined] : pair) ); } asMap() { return new Map(this.asPairArray()); } get size() { this._compress(); return this.map.size; } createChild() { return new StackedSetMap(this.stack); } get length() { throw new Error("This is no longer an Array"); } set length(value) { throw new Error("This is no longer an Array"); } } // TODO remove in webpack 5 StackedSetMap.prototype.push = util.deprecate( /** * @deprecated * @this {StackedSetMap} * @param {any} item Item to add * @returns {void} */ function(item) { this.add(item); }, "This is no longer an Array: Use add instead." ); module.exports = StackedSetMap; webpack-4.30.0/lib/util/TrackingSet.js000066400000000000000000000010311345416772700175240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; module.exports = class TrackingSet { constructor(set) { this.set = set; this.set2 = new Set(); this.stack = set.stack; } add(item) { this.set2.add(item); return this.set.add(item); } delete(item) { this.set2.delete(item); return this.set.delete(item); } has(item) { return this.set.has(item); } createChild() { return this.set.createChild(); } getAddedItems() { return this.set2; } }; webpack-4.30.0/lib/util/cachedMerge.js000066400000000000000000000021061345416772700175010ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const mergeCache = new WeakMap(); /** * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. * @example * // performs Object.assign(first, second), stores the result in WeakMap and returns result * cachedMerge({a: 1}, {a: 2}) * {a: 2} * // when same arguments passed, gets the result from WeakMap and returns it. * cachedMerge({a: 1}, {a: 2}) * {a: 2} * @param {object} first first object * @param {object} second second object * @returns {object} merged object of first and second object */ const cachedMerge = (first, second) => { let innerCache = mergeCache.get(first); if (innerCache === undefined) { innerCache = new WeakMap(); mergeCache.set(first, innerCache); } const prevMerge = innerCache.get(second); if (prevMerge !== undefined) return prevMerge; const newMerge = Object.assign({}, first, second); innerCache.set(second, newMerge); return newMerge; }; module.exports = cachedMerge; webpack-4.30.0/lib/util/createHash.js000066400000000000000000000036541345416772700173720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; /** @typedef {{new(): Hash}} HashConstructor */ /** * @typedef {Object} Hash * @property {function(string|Buffer, string=): Hash} update * @property {function(string): string} digest */ const BULK_SIZE = 1000; /** * @implements {Hash} */ class BulkUpdateDecorator { constructor(hash) { this.hash = hash; this.buffer = ""; } update(data, inputEncoding) { if ( inputEncoding !== undefined || typeof data !== "string" || data.length > BULK_SIZE ) { if (this.buffer.length > 0) { this.hash.update(this.buffer); this.buffer = ""; } this.hash.update(data, inputEncoding); } else { this.buffer += data; if (this.buffer.length > BULK_SIZE) { this.hash.update(this.buffer); this.buffer = ""; } } return this; } digest(encoding) { if (this.buffer.length > 0) { this.hash.update(this.buffer); } var digestResult = this.hash.digest(encoding); return typeof digestResult === "string" ? digestResult : digestResult.toString(); } } /* istanbul ignore next */ class DebugHash { constructor() { this.string = ""; } update(data, inputEncoding) { if (typeof data !== "string") data = data.toString("utf-8"); this.string += data; return this; } digest(encoding) { return this.string.replace(/[^a-z0-9]+/gi, m => Buffer.from(m).toString("hex") ); } } /** * Creates a hash by name or function * @param {string | HashConstructor} algorithm the algorithm name or a constructor creating a hash * @returns {Hash} the hash */ module.exports = algorithm => { if (typeof algorithm === "function") { return new BulkUpdateDecorator(new algorithm()); } switch (algorithm) { // TODO add non-cryptographic algorithm here case "debug": return new DebugHash(); default: return new BulkUpdateDecorator(require("crypto").createHash(algorithm)); } }; webpack-4.30.0/lib/util/deterministicGrouping.js000066400000000000000000000160051345416772700216730ustar00rootroot00000000000000"use strict"; // Simulations show these probabilities for a single change // 93.1% that one group is invalidated // 4.8% that two groups are invalidated // 1.1% that 3 groups are invalidated // 0.1% that 4 or more groups are invalidated // // And these for removing/adding 10 lexically adjacent files // 64.5% that one group is invalidated // 24.8% that two groups are invalidated // 7.8% that 3 groups are invalidated // 2.7% that 4 or more groups are invalidated // // And these for removing/adding 3 random files // 0% that one group is invalidated // 3.7% that two groups are invalidated // 80.8% that 3 groups are invalidated // 12.3% that 4 groups are invalidated // 3.2% that 5 or more groups are invalidated /** * * @param {string} a key * @param {string} b key * @returns {number} the similarity as number */ const similarity = (a, b) => { const l = Math.min(a.length, b.length); let dist = 0; for (let i = 0; i < l; i++) { const ca = a.charCodeAt(i); const cb = b.charCodeAt(i); dist += Math.max(0, 10 - Math.abs(ca - cb)); } return dist; }; /** * @param {string} a key * @param {string} b key * @returns {string} the common part and a single char for the difference */ const getName = (a, b) => { const l = Math.min(a.length, b.length); let r = ""; for (let i = 0; i < l; i++) { const ca = a.charAt(i); const cb = b.charAt(i); r += ca; if (ca === cb) { continue; } return r; } return a; }; /** * @template T */ class Node { /** * @param {T} item item * @param {string} key key * @param {number} size size */ constructor(item, key, size) { this.item = item; this.key = key; this.size = size; } } /** * @template T */ class Group { /** * @param {Node[]} nodes nodes * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) */ constructor(nodes, similarities) { this.nodes = nodes; this.similarities = similarities; this.size = nodes.reduce((size, node) => size + node.size, 0); /** @type {string} */ this.key = undefined; } } /** * @template T * @typedef {Object} GroupedItems * @property {string} key * @property {T[]} items * @property {number} size */ /** * @template T * @typedef {Object} Options * @property {number} maxSize maximum size of a group * @property {number} minSize minimum size of a group (preferred over maximum size) * @property {Iterable} items a list of items * @property {function(T): number} getSize function to get size of an item * @property {function(T): string} getKey function to get the key of an item */ /** * @template T * @param {Options} options options object * @returns {GroupedItems[]} grouped items */ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { /** @type {Group[]} */ const result = []; const nodes = Array.from( items, item => new Node(item, getKey(item), getSize(item)) ); /** @type {Node[]} */ const initialNodes = []; // lexically ordering of keys nodes.sort((a, b) => { if (a.key < b.key) return -1; if (a.key > b.key) return 1; return 0; }); // return nodes bigger than maxSize directly as group for (const node of nodes) { if (node.size >= maxSize) { result.push(new Group([node], [])); } else { initialNodes.push(node); } } if (initialNodes.length > 0) { // calculate similarities between lexically adjacent nodes /** @type {number[]} */ const similarities = []; for (let i = 1; i < initialNodes.length; i++) { const a = initialNodes[i - 1]; const b = initialNodes[i]; similarities.push(similarity(a.key, b.key)); } const initialGroup = new Group(initialNodes, similarities); if (initialGroup.size < minSize) { // We hit an edgecase where the working set is already smaller than minSize // We merge it with the smallest result node to keep minSize intact if (result.length > 0) { const smallestGroup = result.reduce((min, group) => min.size > group.size ? group : min ); for (const node of initialGroup.nodes) smallestGroup.nodes.push(node); smallestGroup.nodes.sort((a, b) => { if (a.key < b.key) return -1; if (a.key > b.key) return 1; return 0; }); } else { // There are no other nodes // We use all nodes and have to accept that it's smaller than minSize result.push(initialGroup); } } else { const queue = [initialGroup]; while (queue.length) { const group = queue.pop(); // only groups bigger than maxSize need to be splitted if (group.size < maxSize) { result.push(group); continue; } // find unsplittable area from left and right // going minSize from left and right // at least one node need to be included otherwise we get stuck let left = 0; let leftSize = 0; while (leftSize <= minSize) { leftSize += group.nodes[left].size; left++; } let right = group.nodes.length - 1; let rightSize = 0; while (rightSize <= minSize) { rightSize += group.nodes[right].size; right--; } if (left - 1 > right) { // can't split group while holding minSize // because minSize is preferred of maxSize we return // the group here even while it's too big // To avoid this make sure maxSize > minSize * 3 result.push(group); continue; } if (left <= right) { // when there is a area between left and right // we look for best split point // we split at the minimum similarity // here key space is separated the most let best = left - 1; let bestSimilarity = group.similarities[best]; for (let i = left; i <= right; i++) { const similarity = group.similarities[i]; if (similarity < bestSimilarity) { best = i; bestSimilarity = similarity; } } left = best + 1; right = best; } // create two new groups for left and right area // and queue them up const rightNodes = [group.nodes[right + 1]]; /** @type {number[]} */ const rightSimilaries = []; for (let i = right + 2; i < group.nodes.length; i++) { rightSimilaries.push(group.similarities[i - 1]); rightNodes.push(group.nodes[i]); } queue.push(new Group(rightNodes, rightSimilaries)); const leftNodes = [group.nodes[0]]; /** @type {number[]} */ const leftSimilaries = []; for (let i = 1; i < left; i++) { leftSimilaries.push(group.similarities[i - 1]); leftNodes.push(group.nodes[i]); } queue.push(new Group(leftNodes, leftSimilaries)); } } } // lexically ordering result.sort((a, b) => { if (a.nodes[0].key < b.nodes[0].key) return -1; if (a.nodes[0].key > b.nodes[0].key) return 1; return 0; }); // give every group a name for (let i = 0; i < result.length; i++) { const group = result[i]; const first = group.nodes[0]; const last = group.nodes[group.nodes.length - 1]; let name = getName(first.key, last.key); group.key = name; } // return the results return result.map(group => { /** @type {GroupedItems} */ return { key: group.key, items: group.nodes.map(node => node.item), size: group.size }; }); }; webpack-4.30.0/lib/util/identifier.js000066400000000000000000000054441345416772700174440ustar00rootroot00000000000000"use strict"; const path = require("path"); /** * @typedef {Object} MakeRelativePathsCache * @property {Map>=} relativePaths */ /** * * @param {string} maybeAbsolutePath path to check * @returns {boolean} returns true if path is "Absolute Path"-like */ const looksLikeAbsolutePath = maybeAbsolutePath => { if (/^\/.*\/$/.test(maybeAbsolutePath)) { // this 'path' is actually a regexp generated by dynamic requires. // Don't treat it as an absolute path. return false; } return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath); }; /** * * @param {string} p path to normalize * @returns {string} normalized version of path */ const normalizePathSeparator = p => p.replace(/\\/g, "/"); /** * * @param {string} context context for relative path * @param {string} identifier identifier for path * @returns {string} a converted relative path */ const _makePathsRelative = (context, identifier) => { return identifier .split(/([|! ])/) .map(str => looksLikeAbsolutePath(str) ? normalizePathSeparator(path.relative(context, str)) : str ) .join(""); }; /** * * @param {string} context context used to create relative path * @param {string} identifier identifier used to create relative path * @param {MakeRelativePathsCache=} cache the cache object being set * @returns {string} the returned relative path */ exports.makePathsRelative = (context, identifier, cache) => { if (!cache) return _makePathsRelative(context, identifier); const relativePaths = cache.relativePaths || (cache.relativePaths = new Map()); let cachedResult; let contextCache = relativePaths.get(context); if (contextCache === undefined) { relativePaths.set(context, (contextCache = new Map())); } else { cachedResult = contextCache.get(identifier); } if (cachedResult !== undefined) { return cachedResult; } else { const relativePath = _makePathsRelative(context, identifier); contextCache.set(identifier, relativePath); return relativePath; } }; /** * @param {string} context absolute context path * @param {string} request any request string may containing absolute paths, query string, etc. * @returns {string} a new request string avoiding absolute paths when possible */ exports.contextify = (context, request) => { return request .split("!") .map(r => { const splitPath = r.split("?", 2); if (/^[a-zA-Z]:\\/.test(splitPath[0])) { splitPath[0] = path.win32.relative(context, splitPath[0]); if (!/^[a-zA-Z]:\\/.test(splitPath[0])) { splitPath[0] = splitPath[0].replace(/\\/g, "/"); } } if (/^\//.test(splitPath[0])) { splitPath[0] = path.posix.relative(context, splitPath[0]); } if (!/^(\.\.\/|\/|[a-zA-Z]:\\)/.test(splitPath[0])) { splitPath[0] = "./" + splitPath[0]; } return splitPath.join("?"); }) .join("!"); }; webpack-4.30.0/lib/util/objectToMap.js000066400000000000000000000006271345416772700175270ustar00rootroot00000000000000/** * convert an object into its 2D array equivalent to be turned * into an ES6 map * * @param {object} obj - any object type that works with Object.keys() * @returns {Map} an ES6 Map of KV pairs */ module.exports = function objectToMap(obj) { return new Map( Object.keys(obj).map(key => { /** @type {[string, string]} */ const pair = [key, obj[key]]; return pair; }) ); }; webpack-4.30.0/lib/validateSchema.js000066400000000000000000000030661345416772700172550ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Gajus Kuizinas @gajus */ "use strict"; const Ajv = require("ajv"); const ajv = new Ajv({ errorDataPath: "configuration", allErrors: true, verbose: true }); require("ajv-keywords")(ajv, ["instanceof"]); require("../schemas/ajv.absolutePath")(ajv); const validateSchema = (schema, options) => { if (Array.isArray(options)) { const errors = options.map(options => validateObject(schema, options)); errors.forEach((list, idx) => { const applyPrefix = err => { err.dataPath = `[${idx}]${err.dataPath}`; if (err.children) { err.children.forEach(applyPrefix); } }; list.forEach(applyPrefix); }); return errors.reduce((arr, items) => { return arr.concat(items); }, []); } else { return validateObject(schema, options); } }; const validateObject = (schema, options) => { const validate = ajv.compile(schema); const valid = validate(options); return valid ? [] : filterErrors(validate.errors); }; const filterErrors = errors => { let newErrors = []; for (const err of errors) { const dataPath = err.dataPath; let children = []; newErrors = newErrors.filter(oldError => { if (oldError.dataPath.includes(dataPath)) { if (oldError.children) { children = children.concat(oldError.children.slice(0)); } oldError.children = undefined; children.push(oldError); return false; } return true; }); if (children.length) { err.children = children; } newErrors.push(err); } return newErrors; }; module.exports = validateSchema; webpack-4.30.0/lib/wasm/000077500000000000000000000000001345416772700147475ustar00rootroot00000000000000webpack-4.30.0/lib/wasm/UnsupportedWebAssemblyFeatureError.js000066400000000000000000000006671345416772700243320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const WebpackError = require("../WebpackError"); module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { /** @param {string} message Error message */ constructor(message) { super(message); this.name = "UnsupportedWebAssemblyFeatureError"; this.hideStack = true; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/wasm/WasmFinalizeExportsPlugin.js000066400000000000000000000040161345416772700224430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const UnsupportedWebAssemblyFeatureError = require("./UnsupportedWebAssemblyFeatureError"); class WasmFinalizeExportsPlugin { apply(compiler) { compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => { compilation.hooks.finishModules.tap( "WasmFinalizeExportsPlugin", modules => { for (const module of modules) { // 1. if a WebAssembly module if (module.type.startsWith("webassembly") === true) { const jsIncompatibleExports = module.buildMeta.jsIncompatibleExports; if (jsIncompatibleExports === undefined) { continue; } for (const reason of module.reasons) { // 2. is referenced by a non-WebAssembly module if (reason.module.type.startsWith("webassembly") === false) { const ref = compilation.getDependencyReference( reason.module, reason.dependency ); if (!ref) continue; const importedNames = ref.importedNames; if (Array.isArray(importedNames)) { importedNames.forEach(name => { // 3. and uses a func with an incompatible JS signature if ( Object.prototype.hasOwnProperty.call( jsIncompatibleExports, name ) ) { // 4. error /** @type {any} */ const error = new UnsupportedWebAssemblyFeatureError( `Export "${name}" with ${ jsIncompatibleExports[name] } can only be used for direct wasm to wasm dependencies` ); error.module = module; error.origin = reason.module; error.originLoc = reason.dependency.loc; error.dependencies = [reason.dependency]; compilation.errors.push(error); } }); } } } } } } ); }); } } module.exports = WasmFinalizeExportsPlugin; webpack-4.30.0/lib/wasm/WasmMainTemplatePlugin.js000066400000000000000000000240361345416772700217010ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("../Template"); const WebAssemblyUtils = require("./WebAssemblyUtils"); /** @typedef {import("../Module")} Module */ /** @typedef {import("../MainTemplate")} MainTemplate */ // Get all wasm modules const getAllWasmModules = chunk => { const wasmModules = chunk.getAllAsyncChunks(); const array = []; for (const chunk of wasmModules) { for (const m of chunk.modulesIterable) { if (m.type.startsWith("webassembly")) { array.push(m); } } } return array; }; /** * generates the import object function for a module * @param {Module} module the module * @param {boolean} mangle mangle imports * @returns {string} source code */ const generateImportObject = (module, mangle) => { const waitForInstances = new Map(); const properties = []; const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( module, mangle ); for (const usedDep of usedWasmDependencies) { const dep = usedDep.dependency; const importedModule = dep.module; const exportName = dep.name; const usedName = importedModule && importedModule.isUsed(exportName); const description = dep.description; const direct = dep.onlyDirectImport; const module = usedDep.module; const name = usedDep.name; if (direct) { const instanceVar = `m${waitForInstances.size}`; waitForInstances.set(instanceVar, importedModule.id); properties.push({ module, name, value: `${instanceVar}[${JSON.stringify(usedName)}]` }); } else { const params = description.signature.params.map( (param, k) => "p" + k + param.valtype ); const mod = `installedModules[${JSON.stringify(importedModule.id)}]`; const func = `${mod}.exports[${JSON.stringify(usedName)}]`; properties.push({ module, name, value: Template.asString([ (importedModule.type.startsWith("webassembly") ? `${mod} ? ${func} : ` : "") + `function(${params}) {`, Template.indent([`return ${func}(${params});`]), "}" ]) }); } } let importObject; if (mangle) { importObject = [ "return {", Template.indent([ properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") ]), "};" ]; } else { const propertiesByModule = new Map(); for (const p of properties) { let list = propertiesByModule.get(p.module); if (list === undefined) { propertiesByModule.set(p.module, (list = [])); } list.push(p); } importObject = [ "return {", Template.indent([ Array.from(propertiesByModule, ([module, list]) => { return Template.asString([ `${JSON.stringify(module)}: {`, Template.indent([ list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") ]), "}" ]); }).join(",\n") ]), "};" ]; } if (waitForInstances.size === 1) { const moduleId = Array.from(waitForInstances.values())[0]; const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; const variable = Array.from(waitForInstances.keys())[0]; return Template.asString([ `${JSON.stringify(module.id)}: function() {`, Template.indent([ `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, Template.indent(importObject), "});" ]), "}," ]); } else if (waitForInstances.size > 0) { const promises = Array.from( waitForInstances.values(), id => `installedWasmModules[${JSON.stringify(id)}]` ).join(", "); const variables = Array.from( waitForInstances.keys(), (name, i) => `${name} = array[${i}]` ).join(", "); return Template.asString([ `${JSON.stringify(module.id)}: function() {`, Template.indent([ `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, Template.indent([`var ${variables};`, ...importObject]), "});" ]), "}," ]); } else { return Template.asString([ `${JSON.stringify(module.id)}: function() {`, Template.indent(importObject), "}," ]); } }; class WasmMainTemplatePlugin { constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) { this.generateLoadBinaryCode = generateLoadBinaryCode; this.supportsStreaming = supportsStreaming; this.mangleImports = mangleImports; } /** * @param {MainTemplate} mainTemplate main template * @returns {void} */ apply(mainTemplate) { mainTemplate.hooks.localVars.tap( "WasmMainTemplatePlugin", (source, chunk) => { const wasmModules = getAllWasmModules(chunk); if (wasmModules.length === 0) return source; const importObjects = wasmModules.map(module => { return generateImportObject(module, this.mangleImports); }); return Template.asString([ source, "", "// object to store loaded and loading wasm modules", "var installedWasmModules = {};", "", // This function is used to delay reading the installed wasm module promises // by a microtask. Sorting them doesn't help because there are egdecases where // sorting is not possible (modules splitted into different chunks). // So we not even trying and solve this by a microtask delay. "function promiseResolve() { return Promise.resolve(); }", "", "var wasmImportObjects = {", Template.indent(importObjects), "};" ]); } ); mainTemplate.hooks.requireEnsure.tap( "WasmMainTemplatePlugin", (source, chunk, hash) => { const webassemblyModuleFilename = mainTemplate.outputOptions.webassemblyModuleFilename; const chunkModuleMaps = chunk.getChunkModuleMaps(m => m.type.startsWith("webassembly") ); if (Object.keys(chunkModuleMaps.id).length === 0) return source; const wasmModuleSrcPath = mainTemplate.getAssetPath( JSON.stringify(webassemblyModuleFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, module: { id: '" + wasmModuleId + "', hash: `" + ${JSON.stringify( chunkModuleMaps.hash )}[wasmModuleId] + "`, hashWithLength(length) { const shortChunkHashMap = Object.create(null); for (const wasmModuleId of Object.keys(chunkModuleMaps.hash)) { if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") { shortChunkHashMap[wasmModuleId] = chunkModuleMaps.hash[ wasmModuleId ].substr(0, length); } } return `" + ${JSON.stringify( shortChunkHashMap )}[wasmModuleId] + "`; } } } ); const createImportObject = content => this.mangleImports ? `{ ${JSON.stringify( WebAssemblyUtils.MANGLED_MODULE )}: ${content} }` : content; return Template.asString([ source, "", "// Fetch + compile chunk loading for webassembly", "", `var wasmModules = ${JSON.stringify( chunkModuleMaps.id )}[chunkId] || [];`, "", "wasmModules.forEach(function(wasmModuleId) {", Template.indent([ "var installedWasmModuleData = installedWasmModules[wasmModuleId];", "", '// a Promise means "currently loading" or "already loaded".', "if(installedWasmModuleData)", Template.indent(["promises.push(installedWasmModuleData);"]), "else {", Template.indent([ `var importObject = wasmImportObjects[wasmModuleId]();`, `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, "var promise;", this.supportsStreaming ? Template.asString([ "if(importObject instanceof Promise && typeof WebAssembly.compileStreaming === 'function') {", Template.indent([ "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", Template.indent([ `return WebAssembly.instantiate(items[0], ${createImportObject( "items[1]" )});` ]), "});" ]), "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", Template.indent([ `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( "importObject" )});` ]) ]) : Template.asString([ "if(importObject instanceof Promise) {", Template.indent([ "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", "promise = Promise.all([", Template.indent([ "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", "importObject" ]), "]).then(function(items) {", Template.indent([ `return WebAssembly.instantiate(items[0], ${createImportObject( "items[1]" )});` ]), "});" ]) ]), "} else {", Template.indent([ "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", "promise = bytesPromise.then(function(bytes) {", Template.indent([ `return WebAssembly.instantiate(bytes, ${createImportObject( "importObject" )});` ]), "});" ]), "}", "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", Template.indent([ `return ${ mainTemplate.requireFn }.w[wasmModuleId] = (res.instance || res).exports;` ]), "}));" ]), "}" ]), "});" ]); } ); mainTemplate.hooks.requireExtensions.tap( "WasmMainTemplatePlugin", (source, chunk) => { if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) { return source; } return Template.asString([ source, "", "// object with all WebAssembly.instance exports", `${mainTemplate.requireFn}.w = {};` ]); } ); mainTemplate.hooks.hash.tap("WasmMainTemplatePlugin", hash => { hash.update("WasmMainTemplatePlugin"); hash.update("2"); }); } } module.exports = WasmMainTemplatePlugin; webpack-4.30.0/lib/wasm/WebAssemblyGenerator.js000066400000000000000000000266661345416772700214110ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Generator = require("../Generator"); const Template = require("../Template"); const WebAssemblyUtils = require("./WebAssemblyUtils"); const { RawSource } = require("webpack-sources"); const { editWithAST, addWithAST } = require("@webassemblyjs/wasm-edit"); const { decode } = require("@webassemblyjs/wasm-parser"); const t = require("@webassemblyjs/ast"); const { moduleContextFromModuleAST } = require("@webassemblyjs/helper-module-context"); const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); /** @typedef {import("../Module")} Module */ /** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ /** @typedef {import("../NormalModule")} NormalModule */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ /** * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform */ /** * @template T * @param {Function[]} fns transforms * @returns {Function} composed transform */ const compose = (...fns) => { return fns.reduce( (prevFn, nextFn) => { return value => nextFn(prevFn(value)); }, value => value ); }; // TODO replace with @callback /** * Removes the start instruction * * @param {Object} state - unused state * @returns {ArrayBufferTransform} transform */ const removeStartFunc = state => bin => { return editWithAST(state.ast, bin, { Start(path) { path.remove(); } }); }; /** * Get imported globals * * @param {Object} ast - Module's AST * @returns {Array} - nodes */ const getImportedGlobals = ast => { const importedGlobals = []; t.traverse(ast, { ModuleImport({ node }) { if (t.isGlobalType(node.descr) === true) { importedGlobals.push(node); } } }); return importedGlobals; }; const getCountImportedFunc = ast => { let count = 0; t.traverse(ast, { ModuleImport({ node }) { if (t.isFuncImportDescr(node.descr) === true) { count++; } } }); return count; }; /** * Get next type index * * @param {Object} ast - Module's AST * @returns {t.Index} - index */ const getNextTypeIndex = ast => { const typeSectionMetadata = t.getSectionMetadata(ast, "type"); if (typeSectionMetadata === undefined) { return t.indexLiteral(0); } return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); }; /** * Get next func index * * The Func section metadata provide informations for implemented funcs * in order to have the correct index we shift the index by number of external * functions. * * @param {Object} ast - Module's AST * @param {Number} countImportedFunc - number of imported funcs * @returns {t.Index} - index */ const getNextFuncIndex = (ast, countImportedFunc) => { const funcSectionMetadata = t.getSectionMetadata(ast, "func"); if (funcSectionMetadata === undefined) { return t.indexLiteral(0 + countImportedFunc); } const vectorOfSize = funcSectionMetadata.vectorOfSize.value; return t.indexLiteral(vectorOfSize + countImportedFunc); }; /** * Create a init instruction for a global * @param {t.GlobalType} globalType the global type * @returns {t.Instruction} init expression */ const createDefaultInitForGlobal = globalType => { if (globalType.valtype[0] === "i") { // create NumberLiteral global initializer return t.objectInstruction("const", globalType.valtype, [ t.numberLiteralFromRaw(66) ]); } else if (globalType.valtype[0] === "f") { // create FloatLiteral global initializer return t.objectInstruction("const", globalType.valtype, [ t.floatLiteral(66, false, false, "66") ]); } else { throw new Error("unknown type: " + globalType.valtype); } }; /** * Rewrite the import globals: * - removes the ModuleImport instruction * - injects at the same offset a mutable global of the same time * * Since the imported globals are before the other global declarations, our * indices will be preserved. * * Note that globals will become mutable. * * @param {Object} state - unused state * @returns {ArrayBufferTransform} transform */ const rewriteImportedGlobals = state => bin => { const additionalInitCode = state.additionalInitCode; const newGlobals = []; bin = editWithAST(state.ast, bin, { ModuleImport(path) { if (t.isGlobalType(path.node.descr) === true) { const globalType = path.node.descr; globalType.mutability = "var"; const init = [ createDefaultInitForGlobal(globalType), t.instruction("end") ]; newGlobals.push(t.global(globalType, init)); path.remove(); } }, // in order to preserve non-imported global's order we need to re-inject // those as well Global(path) { const { node } = path; const [init] = node.init; if (init.id === "get_global") { node.globalType.mutability = "var"; const initialGlobalidx = init.args[0]; node.init = [ createDefaultInitForGlobal(node.globalType), t.instruction("end") ]; additionalInitCode.push( /** * get_global in global initilizer only work for imported globals. * They have the same indices than the init params, so use the * same index. */ t.instruction("get_local", [initialGlobalidx]), t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) ); } newGlobals.push(node); path.remove(); } }); // Add global declaration instructions return addWithAST(state.ast, bin, newGlobals); }; /** * Rewrite the export names * @param {Object} state state * @param {Object} state.ast Module's ast * @param {Module} state.module Module * @param {Set} state.externalExports Module * @returns {ArrayBufferTransform} transform */ const rewriteExportNames = ({ ast, module, externalExports }) => bin => { return editWithAST(ast, bin, { ModuleExport(path) { const isExternal = externalExports.has(path.node.name); if (isExternal) { path.remove(); return; } const usedName = module.isUsed(path.node.name); if (!usedName) { path.remove(); return; } path.node.name = usedName; } }); }; /** * Mangle import names and modules * @param {Object} state state * @param {Object} state.ast Module's ast * @param {Map} state.usedDependencyMap mappings to mangle names * @returns {ArrayBufferTransform} transform */ const rewriteImports = ({ ast, usedDependencyMap }) => bin => { return editWithAST(ast, bin, { ModuleImport(path) { const result = usedDependencyMap.get( path.node.module + ":" + path.node.name ); if (result !== undefined) { path.node.module = result.module; path.node.name = result.name; } } }); }; /** * Add an init function. * * The init function fills the globals given input arguments. * * @param {Object} state transformation state * @param {Object} state.ast - Module's ast * @param {t.Identifier} state.initFuncId identifier of the init function * @param {t.Index} state.startAtFuncOffset index of the start function * @param {t.ModuleImport[]} state.importedGlobals list of imported globals * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function * @param {t.Index} state.nextFuncIndex index of the next function * @param {t.Index} state.nextTypeIndex index of the next type * @returns {ArrayBufferTransform} transform */ const addInitFunction = ({ ast, initFuncId, startAtFuncOffset, importedGlobals, additionalInitCode, nextFuncIndex, nextTypeIndex }) => bin => { const funcParams = importedGlobals.map(importedGlobal => { // used for debugging const id = t.identifier(`${importedGlobal.module}.${importedGlobal.name}`); return t.funcParam(importedGlobal.descr.valtype, id); }); const funcBody = importedGlobals.reduce((acc, importedGlobal, index) => { const args = [t.indexLiteral(index)]; const body = [ t.instruction("get_local", args), t.instruction("set_global", args) ]; return [...acc, ...body]; }, []); if (typeof startAtFuncOffset === "number") { funcBody.push(t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset))); } for (const instr of additionalInitCode) { funcBody.push(instr); } funcBody.push(t.instruction("end")); const funcResults = []; // Code section const funcSignature = t.signature(funcParams, funcResults); const func = t.func(initFuncId, funcSignature, funcBody); // Type section const functype = t.typeInstruction(undefined, funcSignature); // Func section const funcindex = t.indexInFuncSection(nextTypeIndex); // Export section const moduleExport = t.moduleExport( initFuncId.value, t.moduleExportDescr("Func", nextFuncIndex) ); return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); }; /** * Extract mangle mappings from module * @param {Module} module current module * @param {boolean} mangle mangle imports * @returns {Map} mappings to mangled names */ const getUsedDependencyMap = (module, mangle) => { /** @type {Map} */ const map = new Map(); for (const usedDep of WebAssemblyUtils.getUsedDependencies(module, mangle)) { const dep = usedDep.dependency; const request = dep.request; const exportName = dep.name; map.set(request + ":" + exportName, usedDep); } return map; }; class WebAssemblyGenerator extends Generator { constructor(options) { super(); this.options = options; } /** * @param {NormalModule} module module for which the code should be generated * @param {Map} dependencyTemplates mapping from dependencies to templates * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {string} type which kind of code should be generated * @returns {Source} generated code */ generate(module, dependencyTemplates, runtimeTemplate, type) { let bin = module.originalSource().source(); const initFuncId = t.identifier( Array.isArray(module.usedExports) ? Template.numberToIdentifer(module.usedExports.length) : "__webpack_init__" ); // parse it const ast = decode(bin, { ignoreDataSection: true, ignoreCodeSection: true, ignoreCustomNameSection: true }); const moduleContext = moduleContextFromModuleAST(ast.body[0]); const importedGlobals = getImportedGlobals(ast); const countImportedFunc = getCountImportedFunc(ast); const startAtFuncOffset = moduleContext.getStart(); const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); const nextTypeIndex = getNextTypeIndex(ast); const usedDependencyMap = getUsedDependencyMap( module, this.options.mangleImports ); const externalExports = new Set( module.dependencies .filter(d => d instanceof WebAssemblyExportImportedDependency) .map(d => { const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ (d); return wasmDep.exportName; }) ); /** @type {t.Instruction[]} */ const additionalInitCode = []; const transform = compose( rewriteExportNames({ ast, module, externalExports }), removeStartFunc({ ast }), rewriteImportedGlobals({ ast, additionalInitCode }), rewriteImports({ ast, usedDependencyMap }), addInitFunction({ ast, initFuncId, importedGlobals, additionalInitCode, startAtFuncOffset, nextFuncIndex, nextTypeIndex }) ); const newBin = transform(bin); return new RawSource(newBin); } } module.exports = WebAssemblyGenerator; webpack-4.30.0/lib/wasm/WebAssemblyInInitialChunkError.js000066400000000000000000000052721345416772700233340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const WebpackError = require("../WebpackError"); /** @typedef {import("../Module")} Module */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** * @param {Module} module module to get chains from * @param {RequestShortener} requestShortener to make readable identifiers * @returns {string[]} all chains to the module */ const getInitialModuleChains = (module, requestShortener) => { const queue = [ { head: module, message: module.readableIdentifier(requestShortener) } ]; /** @type {Set} */ const results = new Set(); /** @type {Set} */ const incompleteResults = new Set(); /** @type {Set} */ const visitedModules = new Set(); for (const chain of queue) { const { head, message } = chain; let final = true; /** @type {Set} */ const alreadyReferencedModules = new Set(); for (const reason of head.reasons) { const newHead = reason.module; if (newHead) { if (!newHead.getChunks().some(c => c.canBeInitial())) continue; final = false; if (alreadyReferencedModules.has(newHead)) continue; alreadyReferencedModules.add(newHead); const moduleName = newHead.readableIdentifier(requestShortener); const detail = reason.explanation ? ` (${reason.explanation})` : ""; const newMessage = `${moduleName}${detail} --> ${message}`; if (visitedModules.has(newHead)) { incompleteResults.add(`... --> ${newMessage}`); continue; } visitedModules.add(newHead); queue.push({ head: newHead, message: newMessage }); } else { final = false; const newMessage = reason.explanation ? `(${reason.explanation}) --> ${message}` : message; results.add(newMessage); } } if (final) { results.add(message); } } for (const result of incompleteResults) { results.add(result); } return Array.from(results); }; module.exports = class WebAssemblyInInitialChunkError extends WebpackError { /** * @param {Module} module WASM module * @param {RequestShortener} requestShortener request shortener */ constructor(module, requestShortener) { const moduleChains = getInitialModuleChains(module, requestShortener); const message = `WebAssembly module is included in initial chunk. This is not allowed, because WebAssembly download and compilation must happen asynchronous. Add an async splitpoint (i. e. import()) somewhere between your entrypoint and the WebAssembly module: ${moduleChains.map(s => `* ${s}`).join("\n")}`; super(message); this.name = "WebAssemblyInInitialChunkError"; this.hideStack = true; this.module = module; Error.captureStackTrace(this, this.constructor); } }; webpack-4.30.0/lib/wasm/WebAssemblyJavascriptGenerator.js000066400000000000000000000113041345416772700234170ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Generator = require("../Generator"); const Template = require("../Template"); const { RawSource } = require("webpack-sources"); const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); /** @typedef {import("../NormalModule")} NormalModule */ /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ class WebAssemblyJavascriptGenerator extends Generator { /** * @param {NormalModule} module module for which the code should be generated * @param {Map} dependencyTemplates mapping from dependencies to templates * @param {RuntimeTemplate} runtimeTemplate the runtime template * @param {string} type which kind of code should be generated * @returns {Source} generated code */ generate(module, dependencyTemplates, runtimeTemplate, type) { const initIdentifer = Array.isArray(module.usedExports) ? Template.numberToIdentifer(module.usedExports.length) : "__webpack_init__"; let needExportsCopy = false; const importedModules = new Map(); const initParams = []; let index = 0; for (const dep of module.dependencies) { const depAsAny = /** @type {any} */ (dep); if (dep.module) { let importData = importedModules.get(dep.module); if (importData === undefined) { importedModules.set( dep.module, (importData = { importVar: `m${index}`, index, request: "userRequest" in depAsAny ? depAsAny.userRequest : undefined, names: new Set(), reexports: [] }) ); index++; } if (dep instanceof WebAssemblyImportDependency) { importData.names.add(dep.name); if (dep.description.type === "GlobalType") { const exportName = dep.name; const usedName = dep.module && dep.module.isUsed(exportName); if (dep.module) { if (usedName) { initParams.push( runtimeTemplate.exportFromImport({ module: dep.module, request: dep.request, importVar: importData.importVar, originModule: module, exportName: dep.name, asiSafe: true, isCall: false, callContext: null }) ); } } } } if (dep instanceof WebAssemblyExportImportedDependency) { importData.names.add(dep.name); const usedName = module.isUsed(dep.exportName); if (usedName) { const exportProp = `${module.exportsArgument}[${JSON.stringify( usedName )}]`; const defineStatement = Template.asString([ `${exportProp} = ${runtimeTemplate.exportFromImport({ module: dep.module, request: dep.request, importVar: importData.importVar, originModule: module, exportName: dep.name, asiSafe: true, isCall: false, callContext: null })};`, `if(WebAssembly.Global) ${exportProp} = ` + `new WebAssembly.Global({ value: ${JSON.stringify( dep.valueType )} }, ${exportProp});` ]); importData.reexports.push(defineStatement); needExportsCopy = true; } } } } const importsCode = Template.asString( Array.from( importedModules, ([module, { importVar, request, reexports }]) => { const importStatement = runtimeTemplate.importStatement({ module, request, importVar, originModule: module }); return importStatement + reexports.join("\n"); } ) ); // create source const source = new RawSource( [ '"use strict";', "// Instantiate WebAssembly module", "var wasmExports = __webpack_require__.w[module.i];", !Array.isArray(module.usedExports) ? `__webpack_require__.r(${module.exportsArgument});` : "", // this must be before import for circular dependencies "// export exports from WebAssembly module", Array.isArray(module.usedExports) && !needExportsCopy ? `${module.moduleArgument}.exports = wasmExports;` : "for(var name in wasmExports) " + `if(name != ${JSON.stringify(initIdentifer)}) ` + `${module.exportsArgument}[name] = wasmExports[name];`, "// exec imports from WebAssembly module (for esm order)", importsCode, "", "// exec wasm module", `wasmExports[${JSON.stringify(initIdentifer)}](${initParams.join( ", " )})` ].join("\n") ); return source; } } module.exports = WebAssemblyJavascriptGenerator; webpack-4.30.0/lib/wasm/WebAssemblyModulesPlugin.js000066400000000000000000000065071345416772700222420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Generator = require("../Generator"); const WebAssemblyParser = require("./WebAssemblyParser"); const WebAssemblyGenerator = require("./WebAssemblyGenerator"); const WebAssemblyJavascriptGenerator = require("./WebAssemblyJavascriptGenerator"); const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); const WebAssemblyInInitialChunkError = require("./WebAssemblyInInitialChunkError"); /** @typedef {import("../Compiler")} Compiler */ class WebAssemblyModulesPlugin { constructor(options) { this.options = options; } /** * @param {Compiler} compiler compiler * @returns {void} */ apply(compiler) { compiler.hooks.compilation.tap( "WebAssemblyModulesPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( WebAssemblyImportDependency, normalModuleFactory ); compilation.dependencyFactories.set( WebAssemblyExportImportedDependency, normalModuleFactory ); normalModuleFactory.hooks.createParser .for("webassembly/experimental") .tap("WebAssemblyModulesPlugin", () => { return new WebAssemblyParser(); }); normalModuleFactory.hooks.createGenerator .for("webassembly/experimental") .tap("WebAssemblyModulesPlugin", () => { return Generator.byType({ javascript: new WebAssemblyJavascriptGenerator(), webassembly: new WebAssemblyGenerator(this.options) }); }); compilation.chunkTemplate.hooks.renderManifest.tap( "WebAssemblyModulesPlugin", (result, options) => { const chunk = options.chunk; const outputOptions = options.outputOptions; const moduleTemplates = options.moduleTemplates; const dependencyTemplates = options.dependencyTemplates; for (const module of chunk.modulesIterable) { if (module.type && module.type.startsWith("webassembly")) { const filenameTemplate = outputOptions.webassemblyModuleFilename; result.push({ render: () => this.renderWebAssembly( module, moduleTemplates.webassembly, dependencyTemplates ), filenameTemplate, pathOptions: { module }, identifier: `webassemblyModule${module.id}`, hash: module.hash }); } } return result; } ); compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { const initialWasmModules = new Set(); for (const chunk of compilation.chunks) { if (chunk.canBeInitial()) { for (const module of chunk.modulesIterable) { if (module.type.startsWith("webassembly")) { initialWasmModules.add(module); } } } } for (const module of initialWasmModules) { compilation.errors.push( new WebAssemblyInInitialChunkError( module, compilation.requestShortener ) ); } }); } ); } renderWebAssembly(module, moduleTemplate, dependencyTemplates) { return moduleTemplate.render(module, dependencyTemplates, {}); } } module.exports = WebAssemblyModulesPlugin; webpack-4.30.0/lib/wasm/WebAssemblyParser.js000066400000000000000000000107121345416772700207000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const t = require("@webassemblyjs/ast"); const { decode } = require("@webassemblyjs/wasm-parser"); const { moduleContextFromModuleAST } = require("@webassemblyjs/helper-module-context"); const { Tapable } = require("tapable"); const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); /** @typedef {import("../Module")} Module */ const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); /** * @param {t.Signature} signature the func signature * @returns {null | string} the type incompatible with js types */ const getJsIncompatibleType = signature => { for (const param of signature.params) { if (!JS_COMPAT_TYPES.has(param.valtype)) { return `${param.valtype} as parameter`; } } for (const type of signature.results) { if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; } return null; }; /** * TODO why are there two different Signature types? * @param {t.FuncSignature} signature the func signature * @returns {null | string} the type incompatible with js types */ const getJsIncompatibleTypeOfFuncSignature = signature => { for (const param of signature.args) { if (!JS_COMPAT_TYPES.has(param)) { return `${param} as parameter`; } } for (const type of signature.result) { if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; } return null; }; const decoderOpts = { ignoreCodeSection: true, ignoreDataSection: true, // this will avoid having to lookup with identifiers in the ModuleContext ignoreCustomNameSection: true }; class WebAssemblyParser extends Tapable { constructor(options) { super(); this.hooks = {}; this.options = options; } parse(binary, state) { // flag it as ESM state.module.buildMeta.exportsType = "namespace"; // parse it const program = decode(binary, decoderOpts); const module = program.body[0]; const moduleContext = moduleContextFromModuleAST(module); // extract imports and exports const exports = (state.module.buildMeta.providedExports = []); const jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = []); const importedGlobals = []; t.traverse(module, { ModuleExport({ node }) { const descriptor = node.descr; if (descriptor.exportType === "Func") { const funcidx = descriptor.id.value; /** @type {t.FuncSignature} */ const funcSignature = moduleContext.getFunction(funcidx); const incompatibleType = getJsIncompatibleTypeOfFuncSignature( funcSignature ); if (incompatibleType) { jsIncompatibleExports[node.name] = incompatibleType; } } exports.push(node.name); if (node.descr && node.descr.exportType === "Global") { const refNode = importedGlobals[node.descr.id.value]; if (refNode) { const dep = new WebAssemblyExportImportedDependency( node.name, refNode.module, refNode.name, refNode.descr.valtype ); state.module.addDependency(dep); } } }, Global({ node }) { const init = node.init[0]; let importNode = null; if (init.id === "get_global") { const globalIdx = init.args[0].value; if (globalIdx < importedGlobals.length) { importNode = importedGlobals[globalIdx]; } } importedGlobals.push(importNode); }, ModuleImport({ node }) { /** @type {false | string} */ let onlyDirectImport = false; if (t.isMemory(node.descr) === true) { onlyDirectImport = "Memory"; } else if (t.isTable(node.descr) === true) { onlyDirectImport = "Table"; } else if (t.isFuncImportDescr(node.descr) === true) { const incompatibleType = getJsIncompatibleType(node.descr.signature); if (incompatibleType) { onlyDirectImport = `Non-JS-compatible Func Sigurature (${incompatibleType})`; } } else if (t.isGlobalType(node.descr) === true) { const type = node.descr.valtype; if (!JS_COMPAT_TYPES.has(type)) { onlyDirectImport = `Non-JS-compatible Global Type (${type})`; } } const dep = new WebAssemblyImportDependency( node.module, node.name, node.descr, onlyDirectImport ); state.module.addDependency(dep); if (t.isGlobalType(node.descr)) { importedGlobals.push(node); } } }); return state; } } module.exports = WebAssemblyParser; webpack-4.30.0/lib/wasm/WebAssemblyUtils.js000066400000000000000000000031631345416772700205460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("../Template"); const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); /** @typedef {import("../Module")} Module */ /** @typedef {Object} UsedWasmDependency * @property {WebAssemblyImportDependency} dependency the dependency * @property {string} name the export name * @property {string} module the module name */ const MANGLED_MODULE = "a"; /** * @param {Module} module the module * @param {boolean} mangle mangle module and export names * @returns {UsedWasmDependency[]} used dependencies and (mangled) name */ const getUsedDependencies = (module, mangle) => { /** @type {UsedWasmDependency[]} */ const array = []; let importIndex = 0; for (const dep of module.dependencies) { if (dep instanceof WebAssemblyImportDependency) { if (dep.description.type === "GlobalType" || dep.module === null) { continue; } const exportName = dep.name; // TODO add the following 3 lines when removing of ModuleExport is possible // const importedModule = dep.module; // const usedName = importedModule && importedModule.isUsed(exportName); // if (usedName !== false) { if (mangle) { array.push({ dependency: dep, name: Template.numberToIdentifer(importIndex++), module: MANGLED_MODULE }); } else { array.push({ dependency: dep, name: exportName, module: dep.request }); } } } return array; }; exports.getUsedDependencies = getUsedDependencies; exports.MANGLED_MODULE = MANGLED_MODULE; webpack-4.30.0/lib/web/000077500000000000000000000000001345416772700145555ustar00rootroot00000000000000webpack-4.30.0/lib/web/FetchCompileWasmTemplatePlugin.js000066400000000000000000000014731345416772700231650ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WasmMainTemplatePlugin = require("../wasm/WasmMainTemplatePlugin"); class FetchCompileWasmTemplatePlugin { constructor(options) { this.options = options || {}; } apply(compiler) { compiler.hooks.thisCompilation.tap( "FetchCompileWasmTemplatePlugin", compilation => { const mainTemplate = compilation.mainTemplate; const generateLoadBinaryCode = path => `fetch(${mainTemplate.requireFn}.p + ${path})`; const plugin = new WasmMainTemplatePlugin( Object.assign( { generateLoadBinaryCode, supportsStreaming: true }, this.options ) ); plugin.apply(mainTemplate); } ); } } module.exports = FetchCompileWasmTemplatePlugin; webpack-4.30.0/lib/web/JsonpChunkTemplatePlugin.js000066400000000000000000000040161345416772700220510ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); /** @typedef {import("../ChunkTemplate")} ChunkTemplate */ const getEntryInfo = chunk => { return [chunk.entryModule].filter(Boolean).map(m => [m.id].concat( Array.from(chunk.groupsIterable)[0] .chunks.filter(c => c !== chunk) .map(c => c.id) ) ); }; class JsonpChunkTemplatePlugin { /** * @param {ChunkTemplate} chunkTemplate the chunk template * @returns {void} */ apply(chunkTemplate) { chunkTemplate.hooks.render.tap( "JsonpChunkTemplatePlugin", (modules, chunk) => { const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction; const globalObject = chunkTemplate.outputOptions.globalObject; const source = new ConcatSource(); const prefetchChunks = chunk.getChildIdsByOrders().prefetch; source.add( `(${globalObject}[${JSON.stringify( jsonpFunction )}] = ${globalObject}[${JSON.stringify( jsonpFunction )}] || []).push([${JSON.stringify(chunk.ids)},` ); source.add(modules); const entries = getEntryInfo(chunk); if (entries.length > 0) { source.add(`,${JSON.stringify(entries)}`); } else if (prefetchChunks && prefetchChunks.length) { source.add(`,0`); } if (prefetchChunks && prefetchChunks.length) { source.add(`,${JSON.stringify(prefetchChunks)}`); } source.add("])"); return source; } ); chunkTemplate.hooks.hash.tap("JsonpChunkTemplatePlugin", hash => { hash.update("JsonpChunkTemplatePlugin"); hash.update("4"); hash.update(`${chunkTemplate.outputOptions.jsonpFunction}`); hash.update(`${chunkTemplate.outputOptions.globalObject}`); }); chunkTemplate.hooks.hashForChunk.tap( "JsonpChunkTemplatePlugin", (hash, chunk) => { hash.update(JSON.stringify(getEntryInfo(chunk))); hash.update(JSON.stringify(chunk.getChildIdsByOrders().prefetch) || ""); } ); } } module.exports = JsonpChunkTemplatePlugin; webpack-4.30.0/lib/web/JsonpExportMainTemplatePlugin.js000066400000000000000000000021331345416772700230650ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); class JsonpExportMainTemplatePlugin { /** * @param {string} name jsonp function name */ constructor(name) { this.name = name; } apply(compilation) { const { mainTemplate, chunkTemplate } = compilation; const onRenderWithEntry = (source, chunk, hash) => { const name = mainTemplate.getAssetPath(this.name || "", { hash, chunk }); return new ConcatSource(`${name}(`, source, ");"); }; for (const template of [mainTemplate, chunkTemplate]) { template.hooks.renderWithEntry.tap( "JsonpExportMainTemplatePlugin", onRenderWithEntry ); } mainTemplate.hooks.globalHashPaths.tap( "JsonpExportMainTemplatePlugin", paths => { if (this.name) paths.push(this.name); return paths; } ); mainTemplate.hooks.hash.tap("JsonpExportMainTemplatePlugin", hash => { hash.update("jsonp export"); hash.update(`${this.name}`); }); } } module.exports = JsonpExportMainTemplatePlugin; webpack-4.30.0/lib/web/JsonpHotUpdateChunkTemplatePlugin.js000066400000000000000000000020011345416772700236570ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); class JsonpHotUpdateChunkTemplatePlugin { apply(hotUpdateChunkTemplate) { hotUpdateChunkTemplate.hooks.render.tap( "JsonpHotUpdateChunkTemplatePlugin", (modulesSource, modules, removedModules, hash, id) => { const source = new ConcatSource(); source.add( `${ hotUpdateChunkTemplate.outputOptions.hotUpdateFunction }(${JSON.stringify(id)},` ); source.add(modulesSource); source.add(")"); return source; } ); hotUpdateChunkTemplate.hooks.hash.tap( "JsonpHotUpdateChunkTemplatePlugin", hash => { hash.update("JsonpHotUpdateChunkTemplatePlugin"); hash.update("3"); hash.update( `${hotUpdateChunkTemplate.outputOptions.hotUpdateFunction}` ); hash.update(`${hotUpdateChunkTemplate.outputOptions.library}`); } ); } } module.exports = JsonpHotUpdateChunkTemplatePlugin; webpack-4.30.0/lib/web/JsonpMainTemplate.runtime.js000066400000000000000000000040171345416772700221710ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals hotAddUpdateChunk parentHotUpdateCallback document XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ $crossOriginLoading$ */ module.exports = function() { // eslint-disable-next-line no-unused-vars function webpackHotUpdateCallback(chunkId, moreModules) { hotAddUpdateChunk(chunkId, moreModules); if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } //$semicolon // eslint-disable-next-line no-unused-vars function hotDownloadUpdateChunk(chunkId) { var script = document.createElement("script"); script.charset = "utf-8"; script.src = $require$.p + $hotChunkFilename$; if ($crossOriginLoading$) script.crossOrigin = $crossOriginLoading$; document.head.appendChild(script); } // eslint-disable-next-line no-unused-vars function hotDownloadManifest(requestTimeout) { requestTimeout = requestTimeout || 10000; return new Promise(function(resolve, reject) { if (typeof XMLHttpRequest === "undefined") { return reject(new Error("No browser support")); } try { var request = new XMLHttpRequest(); var requestPath = $require$.p + $hotMainFilename$; request.open("GET", requestPath, true); request.timeout = requestTimeout; request.send(null); } catch (err) { return reject(err); } request.onreadystatechange = function() { if (request.readyState !== 4) return; if (request.status === 0) { // timeout reject( new Error("Manifest request to " + requestPath + " timed out.") ); } else if (request.status === 404) { // no update available resolve(); } else if (request.status !== 200 && request.status !== 304) { // other failure reject(new Error("Manifest request to " + requestPath + " failed.")); } else { // success try { var update = JSON.parse(request.responseText); } catch (e) { reject(e); return; } resolve(update); } }; }); } }; webpack-4.30.0/lib/web/JsonpMainTemplatePlugin.js000066400000000000000000000432671345416772700217000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { SyncWaterfallHook } = require("tapable"); const Template = require("../Template"); class JsonpMainTemplatePlugin { apply(mainTemplate) { const needChunkOnDemandLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; const needChunkLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.chunks.length > 1) return true; if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; const needEntryDeferringCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.chunks.length > 1) return true; } return false; }; const needPrefetchingCode = chunk => { const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch; return allPrefetchChunks && Object.keys(allPrefetchChunks).length; }; // TODO webpack 5, no adding to .hooks, use WeakMap and static methods ["jsonpScript", "linkPreload", "linkPrefetch"].forEach(hook => { if (!mainTemplate.hooks[hook]) { mainTemplate.hooks[hook] = new SyncWaterfallHook([ "source", "chunk", "hash" ]); } }); const getScriptSrcPath = (hash, chunk, chunkIdExpression) => { const chunkFilename = mainTemplate.outputOptions.chunkFilename; const chunkMaps = chunk.getChunkMaps(); return mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: `" + ${chunkIdExpression} + "`, hash: `" + ${JSON.stringify( chunkMaps.hash )}[${chunkIdExpression}] + "`, hashWithLength(length) { const shortChunkHashMap = Object.create(null); for (const chunkId of Object.keys(chunkMaps.hash)) { if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( 0, length ); } } return `" + ${JSON.stringify( shortChunkHashMap )}[${chunkIdExpression}] + "`; }, name: `" + (${JSON.stringify( chunkMaps.name )}[${chunkIdExpression}]||${chunkIdExpression}) + "`, contentHash: { javascript: `" + ${JSON.stringify( chunkMaps.contentHash.javascript )}[${chunkIdExpression}] + "` }, contentHashWithLength: { javascript: length => { const shortContentHashMap = {}; const contentHash = chunkMaps.contentHash.javascript; for (const chunkId of Object.keys(contentHash)) { if (typeof contentHash[chunkId] === "string") { shortContentHashMap[chunkId] = contentHash[chunkId].substr( 0, length ); } } return `" + ${JSON.stringify( shortContentHashMap )}[${chunkIdExpression}] + "`; } } }, contentHashType: "javascript" }); }; mainTemplate.hooks.localVars.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const extraCode = []; if (needChunkLoadingCode(chunk)) { extraCode.push( "", "// object to store loaded and loading chunks", "// undefined = chunk not loaded, null = chunk preloaded/prefetched", "// Promise = chunk loading, 0 = chunk loaded", "var installedChunks = {", Template.indent( chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") ), "};", "", needEntryDeferringCode(chunk) ? "var deferredModules = [];" : "" ); } if (needChunkOnDemandLoadingCode(chunk)) { extraCode.push( "", "// script path function", "function jsonpScriptSrc(chunkId) {", Template.indent([ `return ${mainTemplate.requireFn}.p + ${getScriptSrcPath( hash, chunk, "chunkId" )}` ]), "}" ); } if (extraCode.length === 0) return source; return Template.asString([source, ...extraCode]); } ); mainTemplate.hooks.jsonpScript.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout; const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; return Template.asString([ "var script = document.createElement('script');", "var onScriptComplete;", jsonpScriptType ? `script.type = ${JSON.stringify(jsonpScriptType)};` : "", "script.charset = 'utf-8';", `script.timeout = ${chunkLoadTimeout / 1000};`, `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", "script.src = jsonpScriptSrc(chunkId);", crossOriginLoading ? Template.asString([ "if (script.src.indexOf(window.location.origin + '/') !== 0) {", Template.indent( `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` ), "}" ]) : "", "onScriptComplete = function (event) {", Template.indent([ "// avoid mem leaks in IE.", "script.onerror = script.onload = null;", "clearTimeout(timeout);", "var chunk = installedChunks[chunkId];", "if(chunk !== 0) {", Template.indent([ "if(chunk) {", Template.indent([ "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", "var realSrc = event && event.target && event.target.src;", "var error = new Error('Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')');", "error.type = errorType;", "error.request = realSrc;", "chunk[1](error);" ]), "}", "installedChunks[chunkId] = undefined;" ]), "}" ]), "};", "var timeout = setTimeout(function(){", Template.indent([ "onScriptComplete({ type: 'timeout', target: script });" ]), `}, ${chunkLoadTimeout});`, "script.onerror = script.onload = onScriptComplete;" ]); } ); mainTemplate.hooks.linkPreload.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; return Template.asString([ "var link = document.createElement('link');", jsonpScriptType ? `link.type = ${JSON.stringify(jsonpScriptType)};` : "", "link.charset = 'utf-8';", `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", 'link.rel = "preload";', 'link.as = "script";', "link.href = jsonpScriptSrc(chunkId);", crossOriginLoading ? Template.asString([ "if (link.href.indexOf(window.location.origin + '/') !== 0) {", Template.indent( `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` ), "}" ]) : "" ]); } ); mainTemplate.hooks.linkPrefetch.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; return Template.asString([ "var link = document.createElement('link');", crossOriginLoading ? `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` : "", `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", 'link.rel = "prefetch";', 'link.as = "script";', "link.href = jsonpScriptSrc(chunkId);" ]); } ); mainTemplate.hooks.requireEnsure.tap( "JsonpMainTemplatePlugin load", (source, chunk, hash) => { return Template.asString([ source, "", "// JSONP chunk loading for javascript", "", "var installedChunkData = installedChunks[chunkId];", 'if(installedChunkData !== 0) { // 0 means "already installed".', Template.indent([ "", '// a Promise means "currently loading".', "if(installedChunkData) {", Template.indent(["promises.push(installedChunkData[2]);"]), "} else {", Template.indent([ "// setup Promise in chunk cache", "var promise = new Promise(function(resolve, reject) {", Template.indent([ "installedChunkData = installedChunks[chunkId] = [resolve, reject];" ]), "});", "promises.push(installedChunkData[2] = promise);", "", "// start chunk loading", mainTemplate.hooks.jsonpScript.call("", chunk, hash), "document.head.appendChild(script);" ]), "}" ]), "}" ]); } ); mainTemplate.hooks.requireEnsure.tap( { name: "JsonpMainTemplatePlugin preload", stage: 10 }, (source, chunk, hash) => { const chunkMap = chunk.getChildIdsByOrdersMap().preload; if (!chunkMap || Object.keys(chunkMap).length === 0) return source; return Template.asString([ source, "", "// chunk preloadng for javascript", "", `var chunkPreloadMap = ${JSON.stringify(chunkMap, null, "\t")};`, "", "var chunkPreloadData = chunkPreloadMap[chunkId];", "if(chunkPreloadData) {", Template.indent([ "chunkPreloadData.forEach(function(chunkId) {", Template.indent([ "if(installedChunks[chunkId] === undefined) {", Template.indent([ "installedChunks[chunkId] = null;", mainTemplate.hooks.linkPreload.call("", chunk, hash), "document.head.appendChild(link);" ]), "}" ]), "});" ]), "}" ]); } ); mainTemplate.hooks.requireExtensions.tap( "JsonpMainTemplatePlugin", (source, chunk) => { if (!needChunkOnDemandLoadingCode(chunk)) return source; return Template.asString([ source, "", "// on error function for async loading", `${ mainTemplate.requireFn }.oe = function(err) { console.error(err); throw err; };` ]); } ); mainTemplate.hooks.bootstrap.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needChunkLoadingCode(chunk)) { const withDefer = needEntryDeferringCode(chunk); const withPrefetch = needPrefetchingCode(chunk); return Template.asString([ source, "", "// install a JSONP callback for chunk loading", "function webpackJsonpCallback(data) {", Template.indent([ "var chunkIds = data[0];", "var moreModules = data[1];", withDefer ? "var executeModules = data[2];" : "", withPrefetch ? "var prefetchChunks = data[3] || [];" : "", '// add "moreModules" to the modules object,', '// then flag all "chunkIds" as loaded and fire callback', "var moduleId, chunkId, i = 0, resolves = [];", "for(;i < chunkIds.length; i++) {", Template.indent([ "chunkId = chunkIds[i];", "if(installedChunks[chunkId]) {", Template.indent("resolves.push(installedChunks[chunkId][0]);"), "}", "installedChunks[chunkId] = 0;" ]), "}", "for(moduleId in moreModules) {", Template.indent([ "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {", Template.indent( mainTemplate.renderAddModule( hash, chunk, "moduleId", "moreModules[moduleId]" ) ), "}" ]), "}", "if(parentJsonpFunction) parentJsonpFunction(data);", withPrefetch ? Template.asString([ "// chunk prefetching for javascript", "prefetchChunks.forEach(function(chunkId) {", Template.indent([ "if(installedChunks[chunkId] === undefined) {", Template.indent([ "installedChunks[chunkId] = null;", mainTemplate.hooks.linkPrefetch.call("", chunk, hash), "document.head.appendChild(link);" ]), "}" ]), "});" ]) : "", "while(resolves.length) {", Template.indent("resolves.shift()();"), "}", withDefer ? Template.asString([ "", "// add entry modules from loaded chunk to deferred list", "deferredModules.push.apply(deferredModules, executeModules || []);", "", "// run deferred modules when all chunks ready", "return checkDeferredModules();" ]) : "" ]), "};", withDefer ? Template.asString([ "function checkDeferredModules() {", Template.indent([ "var result;", "for(var i = 0; i < deferredModules.length; i++) {", Template.indent([ "var deferredModule = deferredModules[i];", "var fulfilled = true;", "for(var j = 1; j < deferredModule.length; j++) {", Template.indent([ "var depId = deferredModule[j];", "if(installedChunks[depId] !== 0) fulfilled = false;" ]), "}", "if(fulfilled) {", Template.indent([ "deferredModules.splice(i--, 1);", "result = " + mainTemplate.requireFn + "(" + mainTemplate.requireFn + ".s = deferredModule[0]);" ]), "}" ]), "}", "return result;" ]), "}" ]) : "" ]); } return source; } ); mainTemplate.hooks.beforeStartup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needChunkLoadingCode(chunk)) { var jsonpFunction = mainTemplate.outputOptions.jsonpFunction; var globalObject = mainTemplate.outputOptions.globalObject; return Template.asString([ `var jsonpArray = ${globalObject}[${JSON.stringify( jsonpFunction )}] = ${globalObject}[${JSON.stringify(jsonpFunction)}] || [];`, "var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);", "jsonpArray.push = webpackJsonpCallback;", "jsonpArray = jsonpArray.slice();", "for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);", "var parentJsonpFunction = oldJsonpFunction;", "", source ]); } return source; } ); mainTemplate.hooks.beforeStartup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const prefetchChunks = chunk.getChildIdsByOrders().prefetch; if ( needChunkLoadingCode(chunk) && prefetchChunks && prefetchChunks.length ) { return Template.asString([ source, `webpackJsonpCallback([[], {}, 0, ${JSON.stringify( prefetchChunks )}]);` ]); } return source; } ); mainTemplate.hooks.startup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needEntryDeferringCode(chunk)) { if (chunk.hasEntryModule()) { const entries = [chunk.entryModule].filter(Boolean).map(m => [m.id].concat( Array.from(chunk.groupsIterable)[0] .chunks.filter(c => c !== chunk) .map(c => c.id) ) ); return Template.asString([ "// add entry module to deferred list", `deferredModules.push(${entries .map(e => JSON.stringify(e)) .join(", ")});`, "// run deferred modules when ready", "return checkDeferredModules();" ]); } else { return Template.asString([ "// run deferred modules from other chunks", "checkDeferredModules();" ]); } } return source; } ); mainTemplate.hooks.hotBootstrap.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const globalObject = mainTemplate.outputOptions.globalObject; const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename; const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: '" + chunkId + "' } } ); const currentHotUpdateMainFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateMainFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` } ); const runtimeSource = Template.getFunctionContent( require("./JsonpMainTemplate.runtime") ) .replace(/\/\/\$semicolon/g, ";") .replace(/\$require\$/g, mainTemplate.requireFn) .replace( /\$crossOriginLoading\$/g, crossOriginLoading ? JSON.stringify(crossOriginLoading) : "null" ) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) .replace(/\$hash\$/g, JSON.stringify(hash)); return `${source} function hotDisposeChunk(chunkId) { delete installedChunks[chunkId]; } var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( hotUpdateFunction )}]; ${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; } ); mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => { hash.update("jsonp"); hash.update("6"); }); } } module.exports = JsonpMainTemplatePlugin; webpack-4.30.0/lib/web/JsonpTemplatePlugin.js000066400000000000000000000013571345416772700210650ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const JsonpMainTemplatePlugin = require("./JsonpMainTemplatePlugin"); const JsonpChunkTemplatePlugin = require("./JsonpChunkTemplatePlugin"); const JsonpHotUpdateChunkTemplatePlugin = require("./JsonpHotUpdateChunkTemplatePlugin"); class JsonpTemplatePlugin { apply(compiler) { compiler.hooks.thisCompilation.tap("JsonpTemplatePlugin", compilation => { new JsonpMainTemplatePlugin().apply(compilation.mainTemplate); new JsonpChunkTemplatePlugin().apply(compilation.chunkTemplate); new JsonpHotUpdateChunkTemplatePlugin().apply( compilation.hotUpdateChunkTemplate ); }); } } module.exports = JsonpTemplatePlugin; webpack-4.30.0/lib/web/WebEnvironmentPlugin.js000066400000000000000000000006211345416772700212330ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class WebEnvironmentPlugin { constructor(inputFileSystem, outputFileSystem) { this.inputFileSystem = inputFileSystem; this.outputFileSystem = outputFileSystem; } apply(compiler) { compiler.outputFileSystem = this.outputFileSystem; } } module.exports = WebEnvironmentPlugin; webpack-4.30.0/lib/webpack.js000066400000000000000000000173331345416772700157610ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Compiler = require("./Compiler"); const MultiCompiler = require("./MultiCompiler"); const NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin"); const WebpackOptionsApply = require("./WebpackOptionsApply"); const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter"); const validateSchema = require("./validateSchema"); const WebpackOptionsValidationError = require("./WebpackOptionsValidationError"); const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); const RemovedPluginError = require("./RemovedPluginError"); const version = require("../package.json").version; /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ /** * @param {WebpackOptions} options options object * @param {function(Error=, Stats=): void=} callback callback * @returns {Compiler | MultiCompiler} the compiler object */ const webpack = (options, callback) => { const webpackOptionsValidationErrors = validateSchema( webpackOptionsSchema, options ); if (webpackOptionsValidationErrors.length) { throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); } let compiler; if (Array.isArray(options)) { compiler = new MultiCompiler(options.map(options => webpack(options))); } else if (typeof options === "object") { options = new WebpackOptionsDefaulter().process(options); compiler = new Compiler(options.context); compiler.options = options; new NodeEnvironmentPlugin().apply(compiler); if (options.plugins && Array.isArray(options.plugins)) { for (const plugin of options.plugins) { if (typeof plugin === "function") { plugin.call(compiler, compiler); } else { plugin.apply(compiler); } } } compiler.hooks.environment.call(); compiler.hooks.afterEnvironment.call(); compiler.options = new WebpackOptionsApply().process(options, compiler); } else { throw new Error("Invalid argument: options"); } if (callback) { if (typeof callback !== "function") { throw new Error("Invalid argument: callback"); } if ( options.watch === true || (Array.isArray(options) && options.some(o => o.watch)) ) { const watchOptions = Array.isArray(options) ? options.map(o => o.watchOptions || {}) : options.watchOptions || {}; return compiler.watch(watchOptions, callback); } compiler.run(callback); } return compiler; }; exports = module.exports = webpack; exports.version = version; webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; webpack.WebpackOptionsApply = WebpackOptionsApply; webpack.Compiler = Compiler; webpack.MultiCompiler = MultiCompiler; webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin; // @ts-ignore Global @this directive is not supported webpack.validate = validateSchema.bind(this, webpackOptionsSchema); webpack.validateSchema = validateSchema; webpack.WebpackOptionsValidationError = WebpackOptionsValidationError; const exportPlugins = (obj, mappings) => { for (const name of Object.keys(mappings)) { Object.defineProperty(obj, name, { configurable: false, enumerable: true, get: mappings[name] }); } }; exportPlugins(exports, { AutomaticPrefetchPlugin: () => require("./AutomaticPrefetchPlugin"), BannerPlugin: () => require("./BannerPlugin"), CachePlugin: () => require("./CachePlugin"), ContextExclusionPlugin: () => require("./ContextExclusionPlugin"), ContextReplacementPlugin: () => require("./ContextReplacementPlugin"), DefinePlugin: () => require("./DefinePlugin"), Dependency: () => require("./Dependency"), DllPlugin: () => require("./DllPlugin"), DllReferencePlugin: () => require("./DllReferencePlugin"), EnvironmentPlugin: () => require("./EnvironmentPlugin"), EvalDevToolModulePlugin: () => require("./EvalDevToolModulePlugin"), EvalSourceMapDevToolPlugin: () => require("./EvalSourceMapDevToolPlugin"), ExtendedAPIPlugin: () => require("./ExtendedAPIPlugin"), ExternalsPlugin: () => require("./ExternalsPlugin"), HashedModuleIdsPlugin: () => require("./HashedModuleIdsPlugin"), HotModuleReplacementPlugin: () => require("./HotModuleReplacementPlugin"), IgnorePlugin: () => require("./IgnorePlugin"), LibraryTemplatePlugin: () => require("./LibraryTemplatePlugin"), LoaderOptionsPlugin: () => require("./LoaderOptionsPlugin"), LoaderTargetPlugin: () => require("./LoaderTargetPlugin"), MemoryOutputFileSystem: () => require("./MemoryOutputFileSystem"), Module: () => require("./Module"), ModuleFilenameHelpers: () => require("./ModuleFilenameHelpers"), NamedChunksPlugin: () => require("./NamedChunksPlugin"), NamedModulesPlugin: () => require("./NamedModulesPlugin"), NoEmitOnErrorsPlugin: () => require("./NoEmitOnErrorsPlugin"), NormalModuleReplacementPlugin: () => require("./NormalModuleReplacementPlugin"), PrefetchPlugin: () => require("./PrefetchPlugin"), ProgressPlugin: () => require("./ProgressPlugin"), ProvidePlugin: () => require("./ProvidePlugin"), SetVarMainTemplatePlugin: () => require("./SetVarMainTemplatePlugin"), SingleEntryPlugin: () => require("./SingleEntryPlugin"), SourceMapDevToolPlugin: () => require("./SourceMapDevToolPlugin"), Stats: () => require("./Stats"), Template: () => require("./Template"), UmdMainTemplatePlugin: () => require("./UmdMainTemplatePlugin"), WatchIgnorePlugin: () => require("./WatchIgnorePlugin") }); exportPlugins((exports.dependencies = {}), { DependencyReference: () => require("./dependencies/DependencyReference") }); exportPlugins((exports.optimize = {}), { AggressiveMergingPlugin: () => require("./optimize/AggressiveMergingPlugin"), AggressiveSplittingPlugin: () => require("./optimize/AggressiveSplittingPlugin"), ChunkModuleIdRangePlugin: () => require("./optimize/ChunkModuleIdRangePlugin"), LimitChunkCountPlugin: () => require("./optimize/LimitChunkCountPlugin"), MinChunkSizePlugin: () => require("./optimize/MinChunkSizePlugin"), ModuleConcatenationPlugin: () => require("./optimize/ModuleConcatenationPlugin"), OccurrenceOrderPlugin: () => require("./optimize/OccurrenceOrderPlugin"), OccurrenceModuleOrderPlugin: () => require("./optimize/OccurrenceModuleOrderPlugin"), OccurrenceChunkOrderPlugin: () => require("./optimize/OccurrenceChunkOrderPlugin"), RuntimeChunkPlugin: () => require("./optimize/RuntimeChunkPlugin"), SideEffectsFlagPlugin: () => require("./optimize/SideEffectsFlagPlugin"), SplitChunksPlugin: () => require("./optimize/SplitChunksPlugin") }); exportPlugins((exports.web = {}), { FetchCompileWasmTemplatePlugin: () => require("./web/FetchCompileWasmTemplatePlugin"), JsonpTemplatePlugin: () => require("./web/JsonpTemplatePlugin") }); exportPlugins((exports.webworker = {}), { WebWorkerTemplatePlugin: () => require("./webworker/WebWorkerTemplatePlugin") }); exportPlugins((exports.node = {}), { NodeTemplatePlugin: () => require("./node/NodeTemplatePlugin"), ReadFileCompileWasmTemplatePlugin: () => require("./node/ReadFileCompileWasmTemplatePlugin") }); exportPlugins((exports.debug = {}), { ProfilingPlugin: () => require("./debug/ProfilingPlugin") }); exportPlugins((exports.util = {}), { createHash: () => require("./util/createHash") }); const defineMissingPluginError = (namespace, pluginName, errorMessage) => { Object.defineProperty(namespace, pluginName, { configurable: false, enumerable: true, get() { throw new RemovedPluginError(errorMessage); } }); }; // TODO remove in webpack 5 defineMissingPluginError( exports.optimize, "UglifyJsPlugin", "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." ); // TODO remove in webpack 5 defineMissingPluginError( exports.optimize, "CommonsChunkPlugin", "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." ); webpack-4.30.0/lib/webpack.web.js000066400000000000000000000016561345416772700165360ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Compiler = require("./Compiler"); const WebEnvironmentPlugin = require("./web/WebEnvironmentPlugin"); const WebpackOptionsApply = require("./WebpackOptionsApply"); const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter"); const webpack = (options, callback) => { new WebpackOptionsDefaulter().process(options); const compiler = new Compiler(); compiler.options = new WebpackOptionsApply().process(options, compiler); new WebEnvironmentPlugin( options.inputFileSystem, options.outputFileSystem ).apply(compiler); if (callback) { compiler.run(callback); } return compiler; }; module.exports = webpack; webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; webpack.WebpackOptionsApply = WebpackOptionsApply; webpack.Compiler = Compiler; webpack.WebEnvironmentPlugin = WebEnvironmentPlugin; webpack-4.30.0/lib/webworker/000077500000000000000000000000001345416772700160075ustar00rootroot00000000000000webpack-4.30.0/lib/webworker/WebWorkerChunkTemplatePlugin.js000066400000000000000000000017751345416772700241320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); class WebWorkerChunkTemplatePlugin { apply(chunkTemplate) { chunkTemplate.hooks.render.tap( "WebWorkerChunkTemplatePlugin", (modules, chunk) => { const chunkCallbackName = chunkTemplate.outputOptions.chunkCallbackName; const globalObject = chunkTemplate.outputOptions.globalObject; const source = new ConcatSource(); source.add( `${globalObject}[${JSON.stringify( chunkCallbackName )}](${JSON.stringify(chunk.ids)},` ); source.add(modules); source.add(")"); return source; } ); chunkTemplate.hooks.hash.tap("WebWorkerChunkTemplatePlugin", hash => { hash.update("webworker"); hash.update("3"); hash.update(`${chunkTemplate.outputOptions.chunkCallbackName}`); hash.update(`${chunkTemplate.outputOptions.globalObject}`); }); } } module.exports = WebWorkerChunkTemplatePlugin; webpack-4.30.0/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js000066400000000000000000000022731345416772700257420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { ConcatSource } = require("webpack-sources"); class WebWorkerHotUpdateChunkTemplatePlugin { apply(hotUpdateChunkTemplate) { hotUpdateChunkTemplate.hooks.render.tap( "WebWorkerHotUpdateChunkTemplatePlugin", (modulesSource, modules, removedModules, hash, id) => { const hotUpdateFunction = hotUpdateChunkTemplate.outputOptions.hotUpdateFunction; const globalObject = hotUpdateChunkTemplate.outputOptions.globalObject; const source = new ConcatSource(); source.add( `${globalObject}[${JSON.stringify( hotUpdateFunction )}](${JSON.stringify(id)},` ); source.add(modulesSource); source.add(")"); return source; } ); hotUpdateChunkTemplate.hooks.hash.tap( "WebWorkerHotUpdateChunkTemplatePlugin", hash => { hash.update("WebWorkerHotUpdateChunkTemplatePlugin"); hash.update("3"); hash.update( hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" ); hash.update(hotUpdateChunkTemplate.outputOptions.globalObject + ""); } ); } } module.exports = WebWorkerHotUpdateChunkTemplatePlugin; webpack-4.30.0/lib/webworker/WebWorkerMainTemplate.runtime.js000066400000000000000000000037171345416772700242470ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals installedChunks hotAddUpdateChunk parentHotUpdateCallback importScripts XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ */ module.exports = function() { // eslint-disable-next-line no-unused-vars function webpackHotUpdateCallback(chunkId, moreModules) { hotAddUpdateChunk(chunkId, moreModules); if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } //$semicolon // eslint-disable-next-line no-unused-vars function hotDownloadUpdateChunk(chunkId) { importScripts($require$.p + $hotChunkFilename$); } // eslint-disable-next-line no-unused-vars function hotDownloadManifest(requestTimeout) { requestTimeout = requestTimeout || 10000; return new Promise(function(resolve, reject) { if (typeof XMLHttpRequest === "undefined") { return reject(new Error("No browser support")); } try { var request = new XMLHttpRequest(); var requestPath = $require$.p + $hotMainFilename$; request.open("GET", requestPath, true); request.timeout = requestTimeout; request.send(null); } catch (err) { return reject(err); } request.onreadystatechange = function() { if (request.readyState !== 4) return; if (request.status === 0) { // timeout reject( new Error("Manifest request to " + requestPath + " timed out.") ); } else if (request.status === 404) { // no update available resolve(); } else if (request.status !== 200 && request.status !== 304) { // other failure reject(new Error("Manifest request to " + requestPath + " failed.")); } else { // success try { var update = JSON.parse(request.responseText); } catch (e) { reject(e); return; } resolve(update); } }; }); } //eslint-disable-next-line no-unused-vars function hotDisposeChunk(chunkId) { delete installedChunks[chunkId]; } }; webpack-4.30.0/lib/webworker/WebWorkerMainTemplatePlugin.js000066400000000000000000000134611345416772700237410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("../Template"); class WebWorkerMainTemplatePlugin { apply(mainTemplate) { const needChunkOnDemandLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; mainTemplate.hooks.localVars.tap( "WebWorkerMainTemplatePlugin", (source, chunk) => { if (needChunkOnDemandLoadingCode(chunk)) { return Template.asString([ source, "", "// object to store loaded chunks", '// "1" means "already loaded"', "var installedChunks = {", Template.indent( chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n") ), "};" ]); } return source; } ); mainTemplate.hooks.requireEnsure.tap( "WebWorkerMainTemplatePlugin", (_, chunk, hash) => { const chunkFilename = mainTemplate.outputOptions.chunkFilename; const chunkMaps = chunk.getChunkMaps(); return Template.asString([ "promises.push(Promise.resolve().then(function() {", Template.indent([ '// "1" is the signal for "already loaded"', "if(!installedChunks[chunkId]) {", Template.indent([ "importScripts(" + mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode( hash, length )} + "`, chunk: { id: '" + chunkId + "', hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hashWithLength(length) { const shortChunkHashMap = Object.create(null); for (const chunkId of Object.keys(chunkMaps.hash)) { if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[ chunkId ].substr(0, length); } } return `" + ${JSON.stringify( shortChunkHashMap )}[chunkId] + "`; }, contentHash: { javascript: `" + ${JSON.stringify( chunkMaps.contentHash.javascript )}[chunkId] + "` }, contentHashWithLength: { javascript: length => { const shortContentHashMap = {}; const contentHash = chunkMaps.contentHash.javascript; for (const chunkId of Object.keys(contentHash)) { if (typeof contentHash[chunkId] === "string") { shortContentHashMap[chunkId] = contentHash[ chunkId ].substr(0, length); } } return `" + ${JSON.stringify( shortContentHashMap )}[chunkId] + "`; } }, name: `" + (${JSON.stringify( chunkMaps.name )}[chunkId]||chunkId) + "` }, contentHashType: "javascript" }) + ");" ]), "}" ]), "}));" ]); } ); mainTemplate.hooks.bootstrap.tap( "WebWorkerMainTemplatePlugin", (source, chunk, hash) => { if (needChunkOnDemandLoadingCode(chunk)) { const chunkCallbackName = mainTemplate.outputOptions.chunkCallbackName; const globalObject = mainTemplate.outputOptions.globalObject; return Template.asString([ source, `${globalObject}[${JSON.stringify( chunkCallbackName )}] = function webpackChunkCallback(chunkIds, moreModules) {`, Template.indent([ "for(var moduleId in moreModules) {", Template.indent( mainTemplate.renderAddModule( hash, chunk, "moduleId", "moreModules[moduleId]" ) ), "}", "while(chunkIds.length)", Template.indent("installedChunks[chunkIds.pop()] = 1;") ]), "};" ]); } return source; } ); mainTemplate.hooks.hotBootstrap.tap( "WebWorkerMainTemplatePlugin", (source, chunk, hash) => { const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename; const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; const globalObject = mainTemplate.outputOptions.globalObject; const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: '" + chunkId + "' } } ); const currentHotUpdateMainFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateMainFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` } ); return ( source + "\n" + `var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( hotUpdateFunction )}];\n` + `${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ` + Template.getFunctionContent( require("./WebWorkerMainTemplate.runtime") ) .replace(/\/\/\$semicolon/g, ";") .replace(/\$require\$/g, mainTemplate.requireFn) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) .replace(/\$hash\$/g, JSON.stringify(hash)) ); } ); mainTemplate.hooks.hash.tap("WebWorkerMainTemplatePlugin", hash => { hash.update("webworker"); hash.update("4"); }); } } module.exports = WebWorkerMainTemplatePlugin; webpack-4.30.0/lib/webworker/WebWorkerTemplatePlugin.js000066400000000000000000000014561345416772700231350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebWorkerMainTemplatePlugin = require("./WebWorkerMainTemplatePlugin"); const WebWorkerChunkTemplatePlugin = require("./WebWorkerChunkTemplatePlugin"); const WebWorkerHotUpdateChunkTemplatePlugin = require("./WebWorkerHotUpdateChunkTemplatePlugin"); class WebWorkerTemplatePlugin { apply(compiler) { compiler.hooks.thisCompilation.tap( "WebWorkerTemplatePlugin", compilation => { new WebWorkerMainTemplatePlugin().apply(compilation.mainTemplate); new WebWorkerChunkTemplatePlugin().apply(compilation.chunkTemplate); new WebWorkerHotUpdateChunkTemplatePlugin().apply( compilation.hotUpdateChunkTemplate ); } ); } } module.exports = WebWorkerTemplatePlugin; webpack-4.30.0/open-bot.yaml000066400000000000000000000436561345416772700156570ustar00rootroot00000000000000bot: "webpack-bot" rules: # Add ci-ok, ci-not-ok labels depending on travis status # comment to point the user to the results # comment in case of success - filters: open: true pull_request: mergeable: true status_1: context: "continuous-integration/travis-ci/pr" status_2: context: "continuous-integration/appveyor/pr" ensure_1: value: "{{status_1.state}}" equals: "success" ensure_2: value: "{{status_2.state}}" equals: "success" actions: label: add: "PR: CI-ok" remove: "PR: CI-not-ok" comment: identifier: "ci-result" message: |- Thank you for your pull request! The most important CI builds succeeded, we’ll review the pull request soon. - filters: open: true pull_request: mergeable: true status_1: context: "continuous-integration/travis-ci/pr" status_2: context: "continuous-integration/appveyor/pr" any: ensure_1: value: "{{status_1.state}}" equals: "failure" ensure_2: value: "{{status_2.state}}" equals: "failure" not: any: ensure_3: value: "{{status_1.state}}" equals: "pending" ensure_4: value: "{{status_2.state}}" equals: "pending" actions: label: add: "PR: CI-not-ok" remove: "PR: CI-ok" set: id: report_ci value: yep # Report specific error message if jest for basic tests fails - filters: ensure: value: "{{report_ci}}" equals: yep commit: true status: context: "continuous-integration/travis-ci/pr" travis_job: state: "failed" allow_failure: false config: env: JOB_PART=basic fetch: travis_job.log string_cleanup: id: logResult value: "{{{fetch}}}" remove: - ".\\[2K.\\[1G|.\\[999D.\\[K" - "^[\\s\\S]+?\\$ yarn travis:\\$JOB_PART.*\n" - "\\$ node --max-old-space-size=4096.*\n" - ".+rimraf coverage" - "yarn run.+\n" - "\\(node:\\d+\\) (\\[DEP0005\\]|DeprecationWarning).+\n" - "\\$ yarn (cover|test):.+\n" - "Ran all test suites.\n[\\s\\S]*" - "error Command failed with exit code \\d+.\n" - "info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n" - "Force exiting Jest\n\nHave you considered.+" - "=============================== Coverage summary ===============================[\\s\\S]+?================================================================================" - " *PASS *test/.*\n" - "^\\s+\n|\\s+$" string_cleanup_1: id: firstError value: "{{{logResult}}}" remove: - "\n\n( ●| FAIL)[\\s\\S]*" - "Test Suites:[\\s\\S]*" - "\\s+$" string_cleanup_2: id: remainingErrors value: "{{{logResult}}}" remove: - "^[\\s\\S]+?(?=\n\n( ●| FAIL)|$)" - "^\n+" - "Test Suites:[\\s\\S]*" - "\\s+$" string_cleanup_3: id: summary value: "{{{logResult}}}" remove: - "^[\\s\\S]+?(?=Test Suites:)" - "\\s+$" actions: comment: identifier: "ci-result" message: |- The basic integration tests failed. @{{commit.author.login}} Please review the following output log for errors: ```text {{{firstError}}} ``` {{#if remainingErrors}}
Show remaining errors ```text {{{remainingErrors}}} ```
{{/if}} ```text {{{summary}}} ``` See [complete report here]({{status.target_url}}). set: id: report_ci value: nope # Report specific error message if jest for integration tests fails - filters: ensure: value: "{{report_ci}}" equals: yep commit: true status: context: "continuous-integration/travis-ci/pr" travis_job: state: "failed" allow_failure: false config: env: JOB_PART=integration fetch: travis_job.log string_cleanup: id: logResult value: "{{{fetch}}}" remove: - ".\\[2K.\\[1G|.\\[999D.\\[K" - "^[\\s\\S]+?\\$ yarn travis:\\$JOB_PART.*\n" - "\\$ node --max-old-space-size=4096.*\n" - ".+rimraf coverage" - "yarn run.+\n" - "\\(node:\\d+\\) (\\[DEP0005\\]|DeprecationWarning).+\n" - "\\$ yarn (cover|test):.+\n" - "The command \"yarn travis:\\$JOB_PART\" exited[\\s\\S]*" - "Ran all test suites.+\n" - "error Command failed with exit code \\d+.\n" - "info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n" - "Force exiting Jest\n\nHave you considered.+" - "=============================== Coverage summary ===============================[\\s\\S]+?================================================================================" - " *PASS *test/.*\n" - "^\\s+\n|\\s+$" string_cleanup_1: id: firstError value: "{{{logResult}}}" remove: - "\n\n( ●| FAIL)[\\s\\S]*" - "Test Suites:[\\s\\S]*" - "\\s+$" string_cleanup_2: id: remainingErrors value: "{{{logResult}}}" remove: - "^[\\s\\S]+?(?=\n\n( ●| FAIL)|$)" - "^\n+" - "Test Suites:[\\s\\S]*" - "\\s+$" string_cleanup_3: id: summary value: "{{{logResult}}}" remove: - "^[\\s\\S]+?(?=Test Suites:)" - "\\s+$" actions: comment: identifier: "ci-result" message: |- The basic integration tests succeeded, but the full suite failed. @{{commit.author.login}} Please review the following output log for errors: ```text {{{firstError}}} ``` {{#if remainingErrors}}
Show remaining errors ```text {{{remainingErrors}}} ```
{{/if}} ```text {{{summary}}} ``` See [complete report here]({{status.target_url}}). set: id: report_ci value: nope # Report specific error message if jest for unit tests or liniting fails - filters: ensure: value: "{{report_ci}}" equals: yep commit: true status: context: "continuous-integration/travis-ci/pr" travis_job: state: "failed" allow_failure: false config: env: JOB_PART=lint-unit fetch: travis_job.log string_cleanup: id: logResult value: "{{{fetch}}}" remove: - ".\\[2K.\\[1G|.\\[999D.\\[K" - "^[\\s\\S]+?\\$ yarn travis:\\$JOB_PART.*\n" - "\\$ node --max-old-space-size=4096.*\n" - ".+rimraf coverage" - "yarn run.+\n" - "\\(node:\\d+\\) (\\[DEP0005\\]|DeprecationWarning).+\n" - "\\$ yarn (unit|lint).+\n" - "The command \"yarn travis:\\$JOB_PART\" exited[\\s\\S]*" - "Ran all test suites.+\n" - "error Command failed with exit code \\d+.\n" - "info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n" - "Force exiting Jest\n\nHave you considered.+" - "=============================== Coverage summary ===============================[\\s\\S]+?================================================================================" - " *PASS *test/.*\n" - "^\\s+\n|\\s+$" actions: comment: identifier: "ci-result" message: |- The integration tests look fine, but there are code style issues or unit test failures in the Pull Request. @{{commit.author.login}} Please review the following output log for errors: ``` text {{{logResult}}} ``` If the unit tests are outdated, you can choose to delete them and add integration tests instead. That would be great. See [complete report here]({{status.target_url}}). set: id: report_ci value: nope # Report a general error message - filters: ensure: value: "{{report_ci}}" equals: yep commit: true status_1: context: "continuous-integration/travis-ci/pr" status_2: context: "continuous-integration/appveyor/pr" actions: comment: identifier: "ci-result" message: |- @{{commit.author.login}} The most important CI builds failed. This way your PR can't be merged. Please take a look at the CI results from [travis]({{status_1.target_url}}) ({{status_1.state}}) and [appveyor]({{status_2.target_url}}) ({{status_2.state}}) and fix these issues. # Add tests-needed label depending on codecov status # comment to point the user writing test cases # comment in case of success - filters: open: true pull_request: mergeable: true status: context: "codecov/patch/integration" ensure: value: "{{status.state}}" equals: "success" label: "PR: tests-needed" actions: label: remove: "PR: tests-needed" comment: identifier: "tests-result" message: |- The minimum test ratio has been reached. Thanks! - filters: open: true pull_request: mergeable: true status: context: "codecov/patch/integration" ensure: value: "{{status.state}}" equals: "failure" actions: label: add: "PR: tests-needed" - filters: open: true pull_request: mergeable: true status: context: "codecov/patch/integration" ensure: value: "{{status.state}}" equals: "failure" age: value: "{{status.created_at}}" minimum: 1h permission: "read|none" actions: comment: identifier: "tests-result" message: |- It looks like this Pull Request doesn't include [enough test cases]({{status.target_url}}) (based on Code Coverage analysis of the PR diff). A PR need to be covered by tests if you add a new feature (we want to make sure that your feature is working) or if you fix a bug (we want to make sure that we don't run into a regression in future). @{{issue.user.login}} Please check if this is appliable to your PR and if you can add more test cases. Read the [test readme](https://github.com/webpack/webpack/blob/master/test/README.md) for details how to write test cases. # add conflict label to pull requests with conflict # on conflict all result labels are removed - filters: open: true pull_request: mergeable: false actions: label: add: "PR: conflict" remove: - "PR: tests-needed" - "PR: CI-ok" - "PR: CI-not-ok" - filters: open: true pull_request: mergeable: true actions: label: remove: "PR: conflict" # add unreviewed, reviewed, review-outdated labels # comment to ping reviewer # comment on new PR - filters: open: true in_order: commit: true review: state: APPROVED|CHANGES_REQUESTED ensure: value: "{{review.state}}" equals: APPROVED permission: user: "{{review.user.login}}" actions: label: add: "PR: reviewed-approved" remove: - "PR: review-outdated" - "PR: unreviewed" - "PR: reviewed" - filters: open: true in_order: commit: true review: state: APPROVED|CHANGES_REQUESTED permission: user: "{{review.user.login}}" ensure: value: "{{review.state}}" equals: CHANGES_REQUESTED actions: label: add: "PR: reviewed-changes-requested" remove: - "PR: review-outdated" - "PR: unreviewed" - "PR: reviewed" - filters: open: true in_order: review: state: APPROVED|CHANGES_REQUESTED commit: true permission: user: "{{review.user.login}}" not: label: "review-outdated" ensure: value: "{{commit.author.login}}" notEquals: "{{review.user.login}}" actions: label: add: "PR: review-outdated" remove: - "PR: reviewed-approved" - "PR: reviewed-changes-requested" - "PR: unreviewed" - "PR: reviewed" comment: identifier: "review-outdated" message: |- @{{commit.author.login}} Thanks for your update. I labeled the Pull Request so reviewers will review it again. @{{review.user.login}} Please review the new changes. - filters: open: true commit: true not: review: state: APPROVED|CHANGES_REQUESTED actions: label: "PR: unreviewed" # add non-master and next label to pull request to other branch - filters: pull_request: base_ref: "^master$" actions: label: remove: "PR: non-master" - filters: pull_request: base_ref: "^next$" actions: label: add: "PR: next" remove: "PR: non-master" - filters: pull_request: base_ref: "^(?!master$)(?!next$)" actions: label: add: "PR: non-master" remove: "PR: next" # add non-master label to pull request to other branch - filters: open: true age: minimum: 1d maximum: 1w pull_request: head_ref: "^master$" permission: "read|none" actions: comment: identifier: "head-master" edit: true message: |- Hi @{{pull_request.user.login}}. Just a little hint from a friendly bot about the best practice when submitting pull requests: > Don't submit pull request from your own `master` branch. It's recommended to create a feature branch for the PR. *You don't have to change it for this PR, just make sure to follow this hint the next time you submit a PR.* # add "Send a PR" label when somebody with write permission say it - filters: open: true comment: "[Ss]end a [Pp][Rr]" permission: user: "{{comment.actor.login}}" actions: label: "Send a PR" # Move issue task - filters: open: true comment: "\\s*@webpack-bot\\s+move\\s+(?:to\\s+)?([a-z0-9_\\-\\.]+/[a-z0-9_\\-\\.]+)\\s*([\\s\\S]*)$" not: comment_1: matching: "moved\\-by\\-bot" author: "." permission: user: "{{comment.actor.login}}" actions: new_issue: target: "{{{comment_match.[1]}}}" body: |- {{{issue.body}}} --- This issue was moved from {{owner}}/{{repo}}#{{issue.number}} by @{{comment.actor.login}}. Original issue was by @{{issue.user.login}}. {{{comment_match.[2]}}} comment: identifier: moved-by-bot message: |- I've moved it to {{comment_match.[1]}}. close: true # mark inactive issues with inactive label # close them when no activity after warning - filters: issue: true open: true not: label: inactive ensure: value: "{{issue.reactions.[+1]}}" range: "< 10" last_action_age: 26w # half a year actions: comment: identifer: inactive-warning message: |- **This issue had no activity for at least half a year.** It's subject to automatic issue closing if there is no activity in the next 15 days. label: inactive - filters: open: true label: inactive last_action_age: maximum: 26w # half a year actions: label: remove: - inactive - filters: open: true label: inactive last_action_age: minimum: 15d includeBotActions: true actions: close: true comment: identifer: inactive-close message: |- Issue was closed because of inactivity. If you think this is still a valid issue, please file a new issue with additional information. # Add action actions box to each pull request - filters: pull_request: true open: true not: comment: matching: admin-actions author: webpack-bot actions: comment: identifier: admin-actions message: |- *For maintainers only:* * [ ] This need to be documented (issue in webpack/webpack.js.org will be filed when merged) # When a pull request need to be documented, create an issue in webpack/webpack.js.org when merged - filters: pull_request: merged: true comment: author: webpack-bot matching: "\\* \\[x\\] " not: comment_1: author: webpack-bot matching: admin-action-document-executed actions: new_issue: target: webpack/webpack.js.org title: "Document webpack change: {{{pull_request.title}}}" body: |- *A pull request by @{{pull_request.user.login}} was merged and maintainers requested a documentation change.* See pull request: {{{pull_request.html_url}}} --- {{{pull_request.body}}} comment: identifier: admin-action-document-executed message: |- I've created an issue to document this in webpack/webpack.js.org. # Check open issues and pull requests every day - filters: open: true actions: schedule: 1d webpack-4.30.0/package.json000066400000000000000000000170271345416772700155270ustar00rootroot00000000000000{ "name": "webpack", "version": "4.30.0", "author": "Tobias Koppers @sokra", "description": "Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.", "license": "MIT", "dependencies": { "@webassemblyjs/ast": "1.8.5", "@webassemblyjs/helper-module-context": "1.8.5", "@webassemblyjs/wasm-edit": "1.8.5", "@webassemblyjs/wasm-parser": "1.8.5", "acorn": "^6.0.5", "acorn-dynamic-import": "^4.0.0", "ajv": "^6.1.0", "ajv-keywords": "^3.1.0", "chrome-trace-event": "^1.0.0", "enhanced-resolve": "^4.1.0", "eslint-scope": "^4.0.0", "json-parse-better-errors": "^1.0.2", "loader-runner": "^2.3.0", "loader-utils": "^1.1.0", "memory-fs": "~0.4.1", "micromatch": "^3.1.8", "mkdirp": "~0.5.0", "neo-async": "^2.5.0", "node-libs-browser": "^2.0.0", "schema-utils": "^1.0.0", "tapable": "^1.1.0", "terser-webpack-plugin": "^1.1.0", "watchpack": "^1.5.0", "webpack-sources": "^1.3.0" }, "devDependencies": { "@types/node": "^10.12.21", "@types/tapable": "^1.0.1", "@types/webpack-sources": "^0.1.4", "@yarnpkg/lockfile": "^1.1.0", "benchmark": "^2.1.1", "bundle-loader": "~0.5.0", "coffee-loader": "^0.9.0", "coffeescript": "^2.3.2", "coveralls": "^3.0.2", "css-loader": "^2.1.0", "es6-promise-polyfill": "^1.1.1", "eslint": "^5.8.0", "eslint-config-prettier": "^4.0.0", "eslint-plugin-jest": "^22.2.2", "eslint-plugin-node": "^8.0.0", "eslint-plugin-prettier": "^3.0.0", "express": "~4.16.4", "file-loader": "^3.0.1", "glob": "^7.1.3", "husky": "^1.1.3", "i18n-webpack-plugin": "^1.0.0", "istanbul": "^0.4.5", "jade": "^1.11.0", "jade-loader": "~0.8.0", "jest": "24.1.0", "jest-junit": "^6.2.1", "json-loader": "^0.5.7", "json-schema-to-typescript": "^6.0.1", "less": "^3.9.0", "less-loader": "^4.0.3", "lint-staged": "^8.0.4", "lodash": "^4.17.4", "prettier": "^1.14.3", "pug": "^2.0.3", "pug-loader": "^2.4.0", "raw-loader": "^1.0.0", "react": "^16.8.0", "react-dom": "^16.8.0", "rimraf": "^2.6.2", "script-loader": "~0.7.0", "simple-git": "^1.65.0", "style-loader": "^0.23.1", "typescript": "^3.0.0-rc", "url-loader": "^1.1.2", "val-loader": "^1.0.2", "vm-browserify": "~1.1.0", "wast-loader": "^1.5.5", "webpack-dev-middleware": "^3.5.1", "worker-loader": "^2.0.0", "xxhashjs": "^0.2.1" }, "engines": { "node": ">=6.11.5" }, "repository": { "type": "git", "url": "https://github.com/webpack/webpack.git" }, "homepage": "https://github.com/webpack/webpack", "main": "lib/webpack.js", "web": "lib/webpack.web.js", "bin": "./bin/webpack.js", "files": [ "lib/", "bin/", "buildin/", "declarations/", "hot/", "web_modules/", "schemas/", "SECURITY.md" ], "scripts": { "setup": "node ./setup/setup.js", "test": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest", "test:update-snapshots": "yarn jest -u", "test:integration": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"/test/*.test.js\"", "test:basic": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"/te{st/TestCasesNormal,st/StatsTestCases,st/ConfigTestCases}.test.js\"", "test:unit": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"/test/*.unittest.js\"", "travis:integration": "yarn cover:init && yarn cover:integration --ci $JEST", "travis:basic": "yarn test:basic --ci $JEST", "travis:lint-unit": "yarn lint && yarn cover:init && yarn cover:unit --ci $JEST", "travis:benchmark": "yarn benchmark --ci", "appveyor:integration": "yarn cover:init && yarn cover:integration --ci %JEST%", "appveyor:unit": "yarn cover:init && yarn cover:unit --ci %JEST%", "appveyor:benchmark": "yarn benchmark --ci", "build:examples": "cd examples && node buildAll.js", "pretest": "yarn lint", "prelint": "yarn setup", "lint": "yarn code-lint && yarn jest-lint && yarn type-lint && yarn special-lint", "code-lint": "eslint --cache \"{setup,lib,bin,hot,buildin,benchmark,tooling,schemas}/**/*.js\" \"test/*.js\" \"test/{configCases,watchCases,statsCases,hotCases}/**/webpack.config.js\" \"examples/**/webpack.config.js\"", "type-lint": "tsc --pretty", "special-lint": "node tooling/inherit-types && node tooling/format-schemas && node tooling/compile-to-definitions", "special-lint-fix": "node tooling/inherit-types --write --override && node tooling/format-schemas --write && node tooling/compile-to-definitions --write", "fix": "yarn code-lint --fix && yarn special-lint-fix", "pretty": "prettier --loglevel warn --write \"*.{ts,js,json,yml,yaml}\" \"{setup,lib,bin,hot,buildin,benchmark,tooling,schemas}/**/*.{js,json}\" \"test/*.js\" \"test/{configCases,watchCases,statsCases,hotCases}/**/webpack.config.js\" \"examples/**/webpack.config.js\"", "jest-lint": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --testMatch \"/test/*.lint.js\" --no-verbose", "benchmark": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"/test/*.benchmark.js\" --runInBand", "cover": "yarn cover:init && yarn cover:all && yarn cover:report", "cover:init": "rimraf coverage", "cover:all": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --coverage", "cover:integration": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --testMatch \"/test/*.test.js\" --coverage", "cover:unit": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --testMatch \"/test/*.unittest.js\" --coverage", "cover:report": "istanbul report" }, "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.js|{lib,setup,bin,hot,buildin,tooling,schemas}/**/*.js|test/*.js|{test,examples}/**/webpack.config.js}": [ "eslint --cache" ] }, "jest": { "forceExit": true, "setupFilesAfterEnv": [ "/test/setupTestFramework.js" ], "testMatch": [ "/test/*.test.js", "/test/*.unittest.js" ], "watchPathIgnorePatterns": [ "/.git", "/node_modules", "/test/js", "/test/browsertest/js", "/test/fixtures/temp-cache-fixture", "/test/fixtures/temp-", "/benchmark", "/examples/*/dist", "/coverage", "/.eslintcache" ], "modulePathIgnorePatterns": [ "/.git", "/node_modules/webpack/node_modules", "/test/js", "/test/browsertest/js", "/test/fixtures/temp-cache-fixture", "/test/fixtures/temp-", "/benchmark", "/examples/*/dist", "/coverage", "/.eslintcache" ], "transformIgnorePatterns": [ "" ], "coverageDirectory": "/coverage", "coveragePathIgnorePatterns": [ "\\.runtime\\.js$", "/test", "/schemas", "/node_modules" ], "testEnvironment": "node", "coverageReporters": [ "json" ] } } webpack-4.30.0/schemas/000077500000000000000000000000001345416772700146555ustar00rootroot00000000000000webpack-4.30.0/schemas/WebpackOptions.json000066400000000000000000002057521345416772700205130ustar00rootroot00000000000000{ "definitions": { "ArrayOfStringOrStringArrayValues": { "type": "array", "items": { "description": "string or array of strings", "anyOf": [ { "type": "string", "minLength": 1 }, { "type": "array", "items": { "description": "A non-empty string", "type": "string", "minLength": 1 } } ] } }, "ArrayOfStringValues": { "type": "array", "items": { "description": "A non-empty string", "type": "string", "minLength": 1 } }, "Entry": { "anyOf": [ { "$ref": "#/definitions/EntryDynamic" }, { "$ref": "#/definitions/EntryStatic" } ] }, "EntryDynamic": { "description": "A Function returning an entry object, an entry string, an entry array or a promise to these things.", "instanceof": "Function", "tsType": "(() => EntryStatic | Promise)" }, "EntryItem": { "oneOf": [ { "description": "An entry point without name. The string is resolved to a module which is loaded upon startup.", "type": "string", "minLength": 1 }, { "description": "An entry point without name. All modules are loaded upon startup. The last one is exported.", "anyOf": [ { "$ref": "#/definitions/NonEmptyArrayOfUniqueStringValues" } ] } ] }, "EntryObject": { "description": "Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.", "type": "object", "additionalProperties": { "description": "An entry point with name", "oneOf": [ { "description": "The string is resolved to a module which is loaded upon startup.", "type": "string", "minLength": 1 }, { "description": "All modules are loaded upon startup. The last one is exported.", "anyOf": [ { "$ref": "#/definitions/NonEmptyArrayOfUniqueStringValues" } ] } ] }, "minProperties": 1 }, "EntryStatic": { "oneOf": [ { "$ref": "#/definitions/EntryObject" }, { "$ref": "#/definitions/EntryItem" } ] }, "ExternalItem": { "anyOf": [ { "description": "An exact matched dependency becomes external. The same string is used as external dependency.", "type": "string" }, { "description": "If an dependency matches exactly a property of the object, the property value is used as dependency.", "type": "object", "additionalProperties": { "description": "The dependency used for the external", "anyOf": [ { "type": "string" }, { "type": "object" }, { "$ref": "#/definitions/ArrayOfStringValues" }, { "type": "boolean" } ] } }, { "description": "Every matched dependency becomes external.", "instanceof": "RegExp", "tsType": "RegExp" } ] }, "Externals": { "anyOf": [ { "description": "`function(context, request, callback(err, result))` The function is called on each dependency.", "instanceof": "Function", "tsType": "((context: string, request: string, callback: (err?: Error, result?: string) => void) => void)" }, { "$ref": "#/definitions/ExternalItem" }, { "type": "array", "items": { "description": "External configuration", "anyOf": [ { "description": "`function(context, request, callback(err, result))` The function is called on each dependency.", "instanceof": "Function", "tsType": "((context: string, request: string, callback: (err?: Error, result?: string) => void) => void)" }, { "$ref": "#/definitions/ExternalItem" } ] } } ] }, "FilterItemTypes": { "anyOf": [ { "instanceof": "RegExp", "tsType": "RegExp" }, { "type": "string" }, { "instanceof": "Function", "tsType": "Function" } ] }, "FilterTypes": { "anyOf": [ { "$ref": "#/definitions/FilterItemTypes" }, { "type": "array", "items": { "description": "Rule to filter", "anyOf": [ { "$ref": "#/definitions/FilterItemTypes" } ] } } ] }, "LibraryCustomUmdObject": { "type": "object", "additionalProperties": false, "properties": { "amd": { "description": "Name of the exposed AMD library in the UMD", "type": "string" }, "commonjs": { "description": "Name of the exposed commonjs export in the UMD", "type": "string" }, "root": { "description": "Name of the property exposed globally by a UMD library", "anyOf": [ { "type": "string" }, { "$ref": "#/definitions/ArrayOfStringValues" } ] } } }, "ModuleOptions": { "type": "object", "additionalProperties": false, "properties": { "defaultRules": { "description": "An array of rules applied by default for modules.", "anyOf": [ { "$ref": "#/definitions/RuleSetRules" } ] }, "exprContextCritical": { "description": "Enable warnings for full dynamic dependencies", "type": "boolean" }, "exprContextRecursive": { "description": "Enable recursive directory lookup for full dynamic dependencies", "type": "boolean" }, "exprContextRegExp": { "description": "Sets the default regular expression for full dynamic dependencies", "anyOf": [ { "type": "boolean" }, { "instanceof": "RegExp", "tsType": "RegExp" } ] }, "exprContextRequest": { "description": "Set the default request for full dynamic dependencies", "type": "string" }, "noParse": { "description": "Don't parse files matching. It's matched against the full resolved request.", "anyOf": [ { "type": "array", "items": { "description": "A regular expression, when matched the module is not parsed", "instanceof": "RegExp", "tsType": "RegExp" }, "minItems": 1 }, { "instanceof": "RegExp", "tsType": "RegExp" }, { "instanceof": "Function", "tsType": "Function" }, { "type": "array", "items": { "description": "An absolute path, when the module starts with this path it is not parsed", "type": "string", "absolutePath": true }, "minItems": 1 }, { "type": "string", "absolutePath": true } ] }, "rules": { "description": "An array of rules applied for modules.", "anyOf": [ { "$ref": "#/definitions/RuleSetRules" } ] }, "strictExportPresence": { "description": "Emit errors instead of warnings when imported names don't exist in imported module", "type": "boolean" }, "strictThisContextOnImports": { "description": "Handle the this context correctly according to the spec for namespace objects", "type": "boolean" }, "unknownContextCritical": { "description": "Enable warnings when using the require function in a not statically analyse-able way", "type": "boolean" }, "unknownContextRecursive": { "description": "Enable recursive directory lookup when using the require function in a not statically analyse-able way", "type": "boolean" }, "unknownContextRegExp": { "description": "Sets the regular expression when using the require function in a not statically analyse-able way", "anyOf": [ { "type": "boolean" }, { "instanceof": "RegExp", "tsType": "RegExp" } ] }, "unknownContextRequest": { "description": "Sets the request when using the require function in a not statically analyse-able way", "type": "string" }, "unsafeCache": { "description": "Cache the resolving of module requests", "anyOf": [ { "type": "boolean" }, { "instanceof": "Function", "tsType": "Function" } ] }, "wrappedContextCritical": { "description": "Enable warnings for partial dynamic dependencies", "type": "boolean" }, "wrappedContextRecursive": { "description": "Enable recursive directory lookup for partial dynamic dependencies", "type": "boolean" }, "wrappedContextRegExp": { "description": "Set the inner regular expression for partial dynamic dependencies", "instanceof": "RegExp", "tsType": "RegExp" } } }, "NodeOptions": { "type": "object", "additionalProperties": { "description": "Include a polyfill for the node.js module", "enum": [false, true, "mock", "empty"] }, "properties": { "Buffer": { "description": "Include a polyfill for the 'Buffer' variable", "enum": [false, true, "mock"] }, "__dirname": { "description": "Include a polyfill for the '__dirname' variable", "enum": [false, true, "mock"] }, "__filename": { "description": "Include a polyfill for the '__filename' variable", "enum": [false, true, "mock"] }, "console": { "description": "Include a polyfill for the 'console' variable", "enum": [false, true, "mock"] }, "global": { "description": "Include a polyfill for the 'global' variable", "type": "boolean" }, "process": { "description": "Include a polyfill for the 'process' variable", "enum": [false, true, "mock"] } } }, "NonEmptyArrayOfUniqueStringValues": { "type": "array", "items": { "description": "A non-empty string", "type": "string", "minLength": 1 }, "minItems": 1, "uniqueItems": true }, "OptimizationOptions": { "description": "Enables/Disables integrated optimizations", "type": "object", "additionalProperties": false, "properties": { "checkWasmTypes": { "description": "Check for incompatible wasm types when importing/exporting from/to ESM", "type": "boolean" }, "chunkIds": { "description": "Define the algorithm to choose chunk ids (named: readable ids for better debugging, size: numeric ids focused on minimal initial download size, total-size: numeric ids focused on minimal total download size, false: no algorithm used, as custom one can be provided via plugin)", "enum": ["natural", "named", "size", "total-size", false] }, "concatenateModules": { "description": "Concatenate modules when possible to generate less modules, more efficient code and enable more optimizations by the minimizer", "type": "boolean" }, "flagIncludedChunks": { "description": "Also flag chunks as loaded which contain a subset of the modules", "type": "boolean" }, "hashedModuleIds": { "description": "Use hashed module id instead module identifiers for better long term caching (deprecated, used moduleIds: hashed instead)", "type": "boolean" }, "mangleWasmImports": { "description": "Reduce size of WASM by changing imports to shorter strings.", "type": "boolean" }, "mergeDuplicateChunks": { "description": "Merge chunks which contain the same modules", "type": "boolean" }, "minimize": { "description": "Enable minimizing the output. Uses optimization.minimizer.", "type": "boolean" }, "minimizer": { "description": "Minimizer(s) to use for minimizing the output", "type": "array", "items": { "description": "Plugin of type object or instanceof Function", "anyOf": [ { "$ref": "#/definitions/WebpackPluginInstance" }, { "$ref": "#/definitions/WebpackPluginFunction" } ] } }, "moduleIds": { "description": "Define the algorithm to choose module ids (natural: numeric ids in order of usage, named: readable ids for better debugging, hashed: short hashes as ids for better long term caching, size: numeric ids focused on minimal initial download size, total-size: numeric ids focused on minimal total download size, false: no algorithm used, as custom one can be provided via plugin)", "enum": ["natural", "named", "hashed", "size", "total-size", false] }, "namedChunks": { "description": "Use readable chunk identifiers for better debugging (deprecated, used chunkIds: named instead)", "type": "boolean" }, "namedModules": { "description": "Use readable module identifiers for better debugging (deprecated, used moduleIds: named instead)", "type": "boolean" }, "noEmitOnErrors": { "description": "Avoid emitting assets when errors occur", "type": "boolean" }, "nodeEnv": { "description": "Set process.env.NODE_ENV to a specific value", "anyOf": [ { "enum": [false] }, { "type": "string" } ] }, "occurrenceOrder": { "description": "Figure out a order of modules which results in the smallest initial bundle", "type": "boolean" }, "portableRecords": { "description": "Generate records with relative paths to be able to move the context folder", "type": "boolean" }, "providedExports": { "description": "Figure out which exports are provided by modules to generate more efficient code", "type": "boolean" }, "removeAvailableModules": { "description": "Removes modules from chunks when these modules are already included in all parents", "type": "boolean" }, "removeEmptyChunks": { "description": "Remove chunks which are empty", "type": "boolean" }, "runtimeChunk": { "description": "Create an additional chunk which contains only the webpack runtime and chunk hash maps", "oneOf": [ { "type": "boolean" }, { "enum": ["single", "multiple"] }, { "type": "object", "additionalProperties": false, "properties": { "name": { "description": "The name or name factory for the runtime chunks", "oneOf": [ { "type": "string" }, { "instanceof": "Function", "tsType": "Function" } ] } } } ] }, "sideEffects": { "description": "Skip over modules which are flagged to contain no side effects when exports are not used", "type": "boolean" }, "splitChunks": { "description": "Optimize duplication and caching by splitting chunks by shared modules and cache group", "oneOf": [ { "enum": [false] }, { "$ref": "#/definitions/OptimizationSplitChunksOptions" } ] }, "usedExports": { "description": "Figure out which exports are used by modules to mangle export names, omit unused exports and generate more efficient code", "type": "boolean" } } }, "OptimizationSplitChunksOptions": { "type": "object", "additionalProperties": false, "properties": { "automaticNameDelimiter": { "description": "Sets the name delimiter for created chunks", "type": "string", "minLength": 1 }, "cacheGroups": { "description": "Assign modules to a cache group (modules from different cache groups are tried to keep in separate chunks)", "type": "object", "additionalProperties": { "description": "Configuration for a cache group", "anyOf": [ { "enum": [false] }, { "instanceof": "Function", "tsType": "Function" }, { "type": "string" }, { "instanceof": "RegExp", "tsType": "RegExp" }, { "type": "object", "additionalProperties": false, "properties": { "automaticNameDelimiter": { "description": "Sets the name delimiter for created chunks", "type": "string", "minLength": 1 }, "automaticNamePrefix": { "description": "Sets the name prefix for created chunks", "type": "string" }, "chunks": { "description": "Select chunks for determining cache group content (defaults to \"initial\", \"initial\" and \"all\" requires adding these chunks to the HTML)", "oneOf": [ { "enum": ["initial", "async", "all"] }, { "instanceof": "Function", "tsType": "Function" } ] }, "enforce": { "description": "Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group", "type": "boolean" }, "filename": { "description": "Sets the template for the filename for created chunks (Only works for initial chunks)", "type": "string", "minLength": 1 }, "maxAsyncRequests": { "description": "Maximum number of requests which are accepted for on-demand loading", "type": "number", "minimum": 1 }, "maxInitialRequests": { "description": "Maximum number of initial chunks which are accepted for an entry point", "type": "number", "minimum": 1 }, "maxSize": { "description": "Maximal size hint for the created chunks", "type": "number", "minimum": 0 }, "minChunks": { "description": "Minimum number of times a module has to be duplicated until it's considered for splitting", "type": "number", "minimum": 1 }, "minSize": { "description": "Minimal size for the created chunk", "type": "number", "minimum": 0 }, "name": { "description": "Give chunks for this cache group a name (chunks with equal name are merged)", "oneOf": [ { "type": "boolean" }, { "instanceof": "Function", "tsType": "Function" }, { "type": "string" } ] }, "priority": { "description": "Priority of this cache group", "type": "number" }, "reuseExistingChunk": { "description": "Try to reuse existing chunk (with name) when it has matching modules", "type": "boolean" }, "test": { "description": "Assign modules to a cache group", "oneOf": [ { "instanceof": "Function", "tsType": "Function" }, { "type": "string" }, { "instanceof": "RegExp", "tsType": "RegExp" } ] } } } ] } }, "chunks": { "description": "Select chunks for determining shared modules (defaults to \"async\", \"initial\" and \"all\" requires adding these chunks to the HTML)", "oneOf": [ { "enum": ["initial", "async", "all"] }, { "instanceof": "Function", "tsType": "Function" } ] }, "fallbackCacheGroup": { "description": "Options for modules not selected by any other cache group", "type": "object", "additionalProperties": false, "properties": { "automaticNameDelimiter": { "description": "Sets the name delimiter for created chunks", "type": "string", "minLength": 1 }, "maxSize": { "description": "Maximal size hint for the created chunks", "type": "number", "minimum": 0 }, "minSize": { "description": "Minimal size for the created chunk", "type": "number", "minimum": 0 } } }, "filename": { "description": "Sets the template for the filename for created chunks (Only works for initial chunks)", "type": "string", "minLength": 1 }, "hidePathInfo": { "description": "Prevents exposing path info when creating names for parts splitted by maxSize", "type": "boolean" }, "maxAsyncRequests": { "description": "Maximum number of requests which are accepted for on-demand loading", "type": "number", "minimum": 1 }, "maxInitialRequests": { "description": "Maximum number of initial chunks which are accepted for an entry point", "type": "number", "minimum": 1 }, "maxSize": { "description": "Maximal size hint for the created chunks", "type": "number", "minimum": 0 }, "minChunks": { "description": "Minimum number of times a module has to be duplicated until it's considered for splitting", "type": "number", "minimum": 1 }, "minSize": { "description": "Minimal size for the created chunks", "type": "number", "minimum": 0 }, "name": { "description": "Give chunks created a name (chunks with equal name are merged)", "oneOf": [ { "type": "boolean" }, { "instanceof": "Function", "tsType": "Function" }, { "type": "string" } ] } } }, "OutputOptions": { "type": "object", "additionalProperties": false, "properties": { "auxiliaryComment": { "description": "Add a comment in the UMD wrapper.", "anyOf": [ { "description": "Append the same comment above each import style.", "type": "string" }, { "description": "Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.", "type": "object", "additionalProperties": false, "properties": { "amd": { "description": "Set comment for `amd` section in UMD", "type": "string" }, "commonjs": { "description": "Set comment for `commonjs` (exports) section in UMD", "type": "string" }, "commonjs2": { "description": "Set comment for `commonjs2` (module.exports) section in UMD", "type": "string" }, "root": { "description": "Set comment for `root` (global variable) section in UMD", "type": "string" } } } ] }, "chunkCallbackName": { "description": "The callback function name used by webpack for loading of chunks in WebWorkers.", "type": "string" }, "chunkFilename": { "description": "The filename of non-entry chunks as relative path inside the `output.path` directory.", "type": "string", "absolutePath": false }, "chunkLoadTimeout": { "description": "Number of milliseconds before chunk request expires", "type": "number" }, "crossOriginLoading": { "description": "This option enables cross-origin loading of chunks.", "enum": [false, "anonymous", "use-credentials"] }, "devtoolFallbackModuleFilenameTemplate": { "description": "Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.", "anyOf": [ { "type": "string" }, { "instanceof": "Function", "tsType": "Function" } ] }, "devtoolLineToLine": { "description": "Enable line to line mapped mode for all/specified modules. Line to line mapped mode uses a simple SourceMap where each line of the generated source is mapped to the same line of the original source. It’s a performance optimization. Only use it if your performance need to be better and you are sure that input lines match which generated lines.", "anyOf": [ { "description": "`true` enables it for all modules (not recommended)", "type": "boolean" }, { "description": "An object similar to `module.loaders` enables it for specific files.", "type": "object" } ] }, "devtoolModuleFilenameTemplate": { "description": "Filename template string of function for the sources array in a generated SourceMap.", "anyOf": [ { "type": "string" }, { "instanceof": "Function", "tsType": "Function" } ] }, "devtoolNamespace": { "description": "Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries.", "type": "string" }, "filename": { "description": "Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.", "anyOf": [ { "type": "string", "absolutePath": false }, { "instanceof": "Function", "tsType": "Function" } ] }, "futureEmitAssets": { "description": "Use the future version of asset emitting logic, which is allows freeing memory of assets after emitting. It could break plugins which assume that assets are still readable after emitting. Will be the new default in the next major version.", "type": "boolean" }, "globalObject": { "description": "An expression which is used to address the global object/scope in runtime code", "type": "string", "minLength": 1 }, "hashDigest": { "description": "Digest type used for the hash", "type": "string" }, "hashDigestLength": { "description": "Number of chars which are used for the hash", "type": "number", "minimum": 1 }, "hashFunction": { "description": "Algorithm used for generation the hash (see node.js crypto package)", "anyOf": [ { "type": "string", "minLength": 1 }, { "instanceof": "Function", "tsType": "(new () => import('../lib/util/createHash').Hash)" } ] }, "hashSalt": { "description": "Any string which is added to the hash to salt it", "type": "string", "minLength": 1 }, "hotUpdateChunkFilename": { "description": "The filename of the Hot Update Chunks. They are inside the output.path directory.", "anyOf": [ { "type": "string", "absolutePath": false }, { "instanceof": "Function", "tsType": "Function" } ] }, "hotUpdateFunction": { "description": "The JSONP function used by webpack for async loading of hot update chunks.", "type": "string" }, "hotUpdateMainFilename": { "description": "The filename of the Hot Update Main File. It is inside the `output.path` directory.", "anyOf": [ { "type": "string", "absolutePath": false }, { "instanceof": "Function", "tsType": "Function" } ] }, "jsonpFunction": { "description": "The JSONP function used by webpack for async loading of chunks.", "type": "string" }, "jsonpScriptType": { "description": "This option enables loading async chunks via a custom script type, such as script type=\"module\"", "enum": [false, "text/javascript", "module"] }, "library": { "description": "If set, export the bundle as library. `output.library` is the name.", "anyOf": [ { "type": "string" }, { "type": "array", "items": { "description": "A part of the library name", "type": "string" } }, { "$ref": "#/definitions/LibraryCustomUmdObject" } ] }, "libraryExport": { "description": "Specify which export should be exposed as library", "anyOf": [ { "type": "string" }, { "$ref": "#/definitions/ArrayOfStringValues" } ] }, "libraryTarget": { "description": "Type of library", "enum": [ "var", "assign", "this", "window", "self", "global", "commonjs", "commonjs2", "commonjs-module", "amd", "amd-require", "umd", "umd2", "jsonp", "system" ] }, "path": { "description": "The output directory as **absolute path** (required).", "type": "string", "absolutePath": true }, "pathinfo": { "description": "Include comments with information about the modules.", "type": "boolean" }, "publicPath": { "description": "The `publicPath` specifies the public URL address of the output files when referenced in a browser.", "anyOf": [ { "type": "string" }, { "instanceof": "Function", "tsType": "Function" } ] }, "sourceMapFilename": { "description": "The filename of the SourceMaps for the JavaScript files. They are inside the `output.path` directory.", "type": "string", "absolutePath": false }, "sourcePrefix": { "description": "Prefixes every line of the source in the bundle with this string.", "type": "string" }, "strictModuleExceptionHandling": { "description": "Handles exceptions in module loading correctly at a performance cost.", "type": "boolean" }, "umdNamedDefine": { "description": "If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.", "type": "boolean" }, "webassemblyModuleFilename": { "description": "The filename of WebAssembly modules as relative path inside the `output.path` directory.", "type": "string", "absolutePath": false } } }, "PerformanceOptions": { "type": "object", "additionalProperties": false, "properties": { "assetFilter": { "description": "Filter function to select assets that are checked", "instanceof": "Function", "tsType": "Function" }, "hints": { "description": "Sets the format of the hints: warnings, errors or nothing at all", "enum": [false, "warning", "error"] }, "maxAssetSize": { "description": "Filesize limit (in bytes) when exceeded, that webpack will provide performance hints", "type": "number" }, "maxEntrypointSize": { "description": "Total size of an entry point (in bytes)", "type": "number" } } }, "ResolveOptions": { "type": "object", "additionalProperties": false, "properties": { "alias": { "description": "Redirect module requests", "anyOf": [ { "type": "object", "additionalProperties": { "description": "New request", "type": "string" } }, { "type": "array", "items": { "description": "Alias configuration", "type": "object", "additionalProperties": false, "properties": { "alias": { "description": "New request", "type": "string" }, "name": { "description": "Request to be redirected", "type": "string" }, "onlyModule": { "description": "Redirect only exact matching request", "type": "boolean" } } } } ] }, "aliasFields": { "description": "Fields in the description file (package.json) which are used to redirect requests inside the module", "anyOf": [ { "$ref": "#/definitions/ArrayOfStringOrStringArrayValues" } ] }, "cachePredicate": { "description": "Predicate function to decide which requests should be cached", "instanceof": "Function", "tsType": "Function" }, "cacheWithContext": { "description": "Include the context information in the cache identifier when caching", "type": "boolean" }, "concord": { "description": "Enable concord resolving extras", "type": "boolean" }, "descriptionFiles": { "description": "Filenames used to find a description file", "anyOf": [ { "$ref": "#/definitions/ArrayOfStringValues" } ] }, "enforceExtension": { "description": "Enforce using one of the extensions from the extensions option", "type": "boolean" }, "enforceModuleExtension": { "description": "Enforce using one of the module extensions from the moduleExtensions option", "type": "boolean" }, "extensions": { "description": "Extensions added to the request when trying to find the file", "anyOf": [ { "$ref": "#/definitions/ArrayOfStringValues" } ] }, "fileSystem": { "description": "Filesystem for the resolver" }, "mainFields": { "description": "Field names from the description file (package.json) which are used to find the default entry point", "anyOf": [ { "$ref": "#/definitions/ArrayOfStringOrStringArrayValues" } ] }, "mainFiles": { "description": "Filenames used to find the default entry point if there is no description file or main field", "anyOf": [ { "$ref": "#/definitions/ArrayOfStringValues" } ] }, "moduleExtensions": { "description": "Extensions added to the module request when trying to find the module", "anyOf": [ { "$ref": "#/definitions/ArrayOfStringValues" } ] }, "modules": { "description": "Folder names or directory paths where to find modules", "anyOf": [ { "$ref": "#/definitions/ArrayOfStringValues" } ] }, "plugins": { "description": "Plugins for the resolver", "type": "array", "items": { "description": "Plugin of type object or instanceof Function", "anyOf": [ { "$ref": "#/definitions/WebpackPluginInstance" }, { "$ref": "#/definitions/WebpackPluginFunction" } ] } }, "resolver": { "description": "Custom resolver" }, "symlinks": { "description": "Enable resolving symlinks to the original location", "type": "boolean" }, "unsafeCache": { "description": "Enable caching of successfully resolved requests", "anyOf": [ { "type": "boolean" }, { "type": "object", "additionalProperties": true } ] }, "useSyncFileSystemCalls": { "description": "Use synchronous filesystem calls for the resolver", "type": "boolean" } } }, "RuleSetCondition": { "anyOf": [ { "instanceof": "RegExp", "tsType": "RegExp" }, { "type": "string", "minLength": 1 }, { "instanceof": "Function", "tsType": "((value: string) => boolean)" }, { "$ref": "#/definitions/RuleSetConditions" }, { "type": "object", "additionalProperties": false, "properties": { "and": { "description": "Logical AND", "anyOf": [ { "$ref": "#/definitions/RuleSetConditions" } ] }, "exclude": { "description": "Exclude all modules matching any of these conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditions" } ] }, "include": { "description": "Exclude all modules matching not any of these conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditions" } ] }, "not": { "description": "Logical NOT", "anyOf": [ { "$ref": "#/definitions/RuleSetConditions" } ] }, "or": { "description": "Logical OR", "anyOf": [ { "$ref": "#/definitions/RuleSetConditions" } ] }, "test": { "description": "Exclude all modules matching any of these conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditions" } ] } } } ] }, "RuleSetConditionAbsolute": { "anyOf": [ { "instanceof": "RegExp", "tsType": "RegExp" }, { "type": "string", "absolutePath": true }, { "instanceof": "Function", "tsType": "((value: string) => boolean)" }, { "$ref": "#/definitions/RuleSetConditionsAbsolute" }, { "type": "object", "additionalProperties": false, "properties": { "and": { "description": "Logical AND", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionsAbsolute" } ] }, "exclude": { "description": "Exclude all modules matching any of these conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] }, "include": { "description": "Exclude all modules matching not any of these conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] }, "not": { "description": "Logical NOT", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionsAbsolute" } ] }, "or": { "description": "Logical OR", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionsAbsolute" } ] }, "test": { "description": "Exclude all modules matching any of these conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] } } } ] }, "RuleSetConditionOrConditions": { "description": "One or multiple rule conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetCondition" }, { "$ref": "#/definitions/RuleSetConditions" } ] }, "RuleSetConditionOrConditionsAbsolute": { "description": "One or multiple rule conditions", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionAbsolute" }, { "$ref": "#/definitions/RuleSetConditionsAbsolute" } ] }, "RuleSetConditions": { "type": "array", "items": { "description": "A rule condition", "anyOf": [ { "$ref": "#/definitions/RuleSetCondition" } ] }, "tsType": "RuleSetConditionsRecursive" }, "RuleSetConditionsAbsolute": { "type": "array", "items": { "description": "A rule condition", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionAbsolute" } ] }, "tsType": "RuleSetConditionsAbsoluteRecursive" }, "RuleSetLoader": { "type": "string", "minLength": 1 }, "RuleSetQuery": { "anyOf": [ { "type": "object" }, { "type": "string" } ] }, "RuleSetRule": { "type": "object", "additionalProperties": false, "properties": { "compiler": { "description": "Match the child compiler name", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditions" } ] }, "enforce": { "description": "Enforce this rule as pre or post step", "enum": ["pre", "post"] }, "exclude": { "description": "Shortcut for resource.exclude", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] }, "include": { "description": "Shortcut for resource.include", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] }, "issuer": { "description": "Match the issuer of the module (The module pointing to this module)", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] }, "loader": { "description": "Shortcut for use.loader", "anyOf": [ { "$ref": "#/definitions/RuleSetLoader" }, { "$ref": "#/definitions/RuleSetUse" } ] }, "loaders": { "description": "Shortcut for use.loader", "anyOf": [ { "$ref": "#/definitions/RuleSetUse" } ] }, "oneOf": { "description": "Only execute the first matching rule in this array", "anyOf": [ { "$ref": "#/definitions/RuleSetRules" } ] }, "options": { "description": "Shortcut for use.options", "anyOf": [ { "$ref": "#/definitions/RuleSetQuery" } ] }, "parser": { "description": "Options for parsing", "type": "object", "additionalProperties": true }, "query": { "description": "Shortcut for use.query", "anyOf": [ { "$ref": "#/definitions/RuleSetQuery" } ] }, "resolve": { "description": "Options for the resolver", "type": "object", "anyOf": [ { "$ref": "#/definitions/ResolveOptions" } ] }, "resource": { "description": "Match the resource path of the module", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] }, "resourceQuery": { "description": "Match the resource query of the module", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditions" } ] }, "rules": { "description": "Match and execute these rules when this rule is matched", "anyOf": [ { "$ref": "#/definitions/RuleSetRules" } ] }, "sideEffects": { "description": "Flags a module as with or without side effects", "type": "boolean" }, "test": { "description": "Shortcut for resource.test", "anyOf": [ { "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" } ] }, "type": { "description": "Module type to use for the module", "enum": [ "javascript/auto", "javascript/dynamic", "javascript/esm", "json", "webassembly/experimental" ] }, "use": { "description": "Modifiers applied to the module when rule is matched", "anyOf": [ { "$ref": "#/definitions/RuleSetUse" } ] } } }, "RuleSetRules": { "type": "array", "items": { "description": "A rule", "anyOf": [ { "$ref": "#/definitions/RuleSetRule" } ] } }, "RuleSetUse": { "anyOf": [ { "$ref": "#/definitions/RuleSetUseItem" }, { "instanceof": "Function", "tsType": "Function" }, { "type": "array", "items": { "description": "An use item", "anyOf": [ { "$ref": "#/definitions/RuleSetUseItem" } ] } } ] }, "RuleSetUseItem": { "anyOf": [ { "$ref": "#/definitions/RuleSetLoader" }, { "instanceof": "Function", "tsType": "Function" }, { "type": "object", "additionalProperties": false, "properties": { "ident": { "description": "Unique loader identifier", "type": "string" }, "loader": { "description": "Loader name", "anyOf": [ { "$ref": "#/definitions/RuleSetLoader" } ] }, "options": { "description": "Loader options", "anyOf": [ { "$ref": "#/definitions/RuleSetQuery" } ] }, "query": { "description": "Loader query", "anyOf": [ { "$ref": "#/definitions/RuleSetQuery" } ] } } } ] }, "StatsOptions": { "type": "object", "additionalProperties": false, "properties": { "all": { "description": "fallback value for stats options when an option is not defined (has precedence over local webpack defaults)", "type": "boolean" }, "assets": { "description": "add assets information", "type": "boolean" }, "assetsSort": { "description": "sort the assets by that field", "type": "string" }, "builtAt": { "description": "add built at time information", "type": "boolean" }, "cached": { "description": "add also information about cached (not built) modules", "type": "boolean" }, "cachedAssets": { "description": "Show cached assets (setting this to `false` only shows emitted files)", "type": "boolean" }, "children": { "description": "add children information", "type": "boolean" }, "chunkGroups": { "description": "Display all chunk groups with the corresponding bundles", "type": "boolean" }, "chunkModules": { "description": "add built modules information to chunk information", "type": "boolean" }, "chunkOrigins": { "description": "add the origins of chunks and chunk merging info", "type": "boolean" }, "chunks": { "description": "add chunk information", "type": "boolean" }, "chunksSort": { "description": "sort the chunks by that field", "type": "string" }, "colors": { "description": "Enables/Disables colorful output", "oneOf": [ { "description": "`webpack --colors` equivalent", "type": "boolean" }, { "type": "object", "additionalProperties": false, "properties": { "bold": { "description": "Custom color for bold text", "type": "string" }, "cyan": { "description": "Custom color for cyan text", "type": "string" }, "green": { "description": "Custom color for green text", "type": "string" }, "magenta": { "description": "Custom color for magenta text", "type": "string" }, "red": { "description": "Custom color for red text", "type": "string" }, "yellow": { "description": "Custom color for yellow text", "type": "string" } } } ] }, "context": { "description": "context directory for request shortening", "type": "string", "absolutePath": true }, "depth": { "description": "add module depth in module graph", "type": "boolean" }, "entrypoints": { "description": "Display the entry points with the corresponding bundles", "type": "boolean" }, "env": { "description": "add --env information", "type": "boolean" }, "errorDetails": { "description": "add details to errors (like resolving log)", "type": "boolean" }, "errors": { "description": "add errors", "type": "boolean" }, "exclude": { "description": "Please use excludeModules instead.", "anyOf": [ { "$ref": "#/definitions/FilterTypes" }, { "type": "boolean" } ] }, "excludeAssets": { "description": "Suppress assets that match the specified filters. Filters can be Strings, RegExps or Functions", "anyOf": [ { "$ref": "#/definitions/FilterTypes" } ] }, "excludeModules": { "description": "Suppress modules that match the specified filters. Filters can be Strings, RegExps, Booleans or Functions", "anyOf": [ { "$ref": "#/definitions/FilterTypes" }, { "type": "boolean" } ] }, "hash": { "description": "add the hash of the compilation", "type": "boolean" }, "maxModules": { "description": "Set the maximum number of modules to be shown", "type": "number" }, "moduleAssets": { "description": "add information about assets inside modules", "type": "boolean" }, "moduleTrace": { "description": "add dependencies and origin of warnings/errors", "type": "boolean" }, "modules": { "description": "add built modules information", "type": "boolean" }, "modulesSort": { "description": "sort the modules by that field", "type": "string" }, "nestedModules": { "description": "add information about modules nested in other modules (like with module concatenation)", "type": "boolean" }, "optimizationBailout": { "description": "show reasons why optimization bailed out for modules", "type": "boolean" }, "outputPath": { "description": "Add output path information", "type": "boolean" }, "performance": { "description": "add performance hint flags", "type": "boolean" }, "providedExports": { "description": "show exports provided by modules", "type": "boolean" }, "publicPath": { "description": "Add public path information", "type": "boolean" }, "reasons": { "description": "add information about the reasons why modules are included", "type": "boolean" }, "source": { "description": "add the source code of modules", "type": "boolean" }, "timings": { "description": "add timing information", "type": "boolean" }, "usedExports": { "description": "show exports used by modules", "type": "boolean" }, "version": { "description": "add webpack version information", "type": "boolean" }, "warnings": { "description": "add warnings", "type": "boolean" }, "warningsFilter": { "description": "Suppress warnings that match the specified filters. Filters can be Strings, RegExps or Functions", "anyOf": [ { "$ref": "#/definitions/FilterTypes" } ] } } }, "WebpackPluginFunction": { "description": "Function acting as plugin", "instanceof": "Function", "tsType": "(this: import('../lib/Compiler'), compiler: import('../lib/Compiler')) => void" }, "WebpackPluginInstance": { "description": "Plugin instance", "type": "object", "additionalProperties": true, "properties": { "apply": { "description": "The run point of the plugin, required method.", "instanceof": "Function", "tsType": "(compiler: import('../lib/Compiler')) => void" } }, "required": ["apply"] } }, "type": "object", "additionalProperties": false, "properties": { "amd": { "description": "Set the value of `require.amd` and `define.amd`. Or disable AMD support.", "anyOf": [ { "description": "You can pass `false` to disable AMD support.", "enum": [false] }, { "description": "You can pass an object to set the value of `require.amd` and `define.amd`.", "type": "object" } ] }, "bail": { "description": "Report the first error as a hard error instead of tolerating it.", "type": "boolean" }, "cache": { "description": "Cache generated modules and chunks to improve performance for multiple incremental builds.", "anyOf": [ { "description": "You can pass `false` to disable it.", "type": "boolean" }, { "description": "You can pass an object to enable it and let webpack use the passed object as cache. This way you can share the cache object between multiple compiler calls.", "type": "object" } ] }, "context": { "description": "The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory.", "type": "string", "absolutePath": true }, "dependencies": { "description": "References to other configurations to depend on.", "type": "array", "items": { "description": "References to another configuration to depend on.", "type": "string" } }, "devServer": { "description": "Options for the webpack-dev-server", "type": "object" }, "devtool": { "description": "A developer tool to enhance debugging.", "anyOf": [ { "type": "string" }, { "enum": [false] } ] }, "entry": { "description": "The entry point(s) of the compilation.", "anyOf": [ { "$ref": "#/definitions/Entry" } ] }, "externals": { "description": "Specify dependencies that shouldn't be resolved by webpack, but should become dependencies of the resulting bundle. The kind of the dependency depends on `output.libraryTarget`.", "anyOf": [ { "$ref": "#/definitions/Externals" } ] }, "loader": { "description": "Custom values available in the loader context.", "type": "object" }, "mode": { "description": "Enable production optimizations or development hints.", "enum": ["development", "production", "none"] }, "module": { "description": "Options affecting the normal modules (`NormalModuleFactory`).", "anyOf": [ { "$ref": "#/definitions/ModuleOptions" } ] }, "name": { "description": "Name of the configuration. Used when loading multiple configurations.", "type": "string" }, "node": { "description": "Include polyfills or mocks for various node stuff.", "anyOf": [ { "enum": [false] }, { "$ref": "#/definitions/NodeOptions" } ] }, "optimization": { "description": "Enables/Disables integrated optimizations", "anyOf": [ { "$ref": "#/definitions/OptimizationOptions" } ] }, "output": { "description": "Options affecting the output of the compilation. `output` options tell webpack how to write the compiled files to disk.", "anyOf": [ { "$ref": "#/definitions/OutputOptions" } ] }, "parallelism": { "description": "The number of parallel processed modules in the compilation.", "type": "number", "minimum": 1 }, "performance": { "description": "Configuration for web performance recommendations.", "anyOf": [ { "enum": [false] }, { "$ref": "#/definitions/PerformanceOptions" } ] }, "plugins": { "description": "Add additional plugins to the compiler.", "type": "array", "items": { "description": "Plugin of type object or instanceof Function", "anyOf": [ { "$ref": "#/definitions/WebpackPluginInstance" }, { "$ref": "#/definitions/WebpackPluginFunction" } ] } }, "profile": { "description": "Capture timing information for each module.", "type": "boolean" }, "recordsInputPath": { "description": "Store compiler state to a json file.", "type": "string", "absolutePath": true }, "recordsOutputPath": { "description": "Load compiler state from a json file.", "type": "string", "absolutePath": true }, "recordsPath": { "description": "Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks. An absolute path is expected. `recordsPath` is used for `recordsInputPath` and `recordsOutputPath` if they left undefined.", "type": "string", "absolutePath": true }, "resolve": { "description": "Options for the resolver", "anyOf": [ { "$ref": "#/definitions/ResolveOptions" } ] }, "resolveLoader": { "description": "Options for the resolver when resolving loaders", "anyOf": [ { "$ref": "#/definitions/ResolveOptions" } ] }, "serve": { "description": "Options for webpack-serve", "type": "object" }, "stats": { "description": "Used by the webpack CLI program to pass stats options.", "anyOf": [ { "$ref": "#/definitions/StatsOptions" }, { "type": "boolean" }, { "enum": [ "none", "errors-only", "minimal", "normal", "detailed", "verbose" ] } ] }, "target": { "description": "Environment to build for", "anyOf": [ { "enum": [ "web", "webworker", "node", "async-node", "node-webkit", "electron-main", "electron-renderer" ] }, { "instanceof": "Function", "tsType": "((compiler: import('../lib/Compiler')) => void)" } ] }, "watch": { "description": "Enter watch mode, which rebuilds on file change.", "type": "boolean" }, "watchOptions": { "description": "Options for the watcher", "type": "object", "additionalProperties": false, "properties": { "aggregateTimeout": { "description": "Delay the rebuilt after the first change. Value is a time in ms.", "type": "number" }, "ignored": { "description": "Ignore some files from watching" }, "poll": { "description": "Enable polling mode for watching", "anyOf": [ { "description": "`true`: use polling.", "type": "boolean" }, { "description": "`number`: use polling with specified interval.", "type": "number" } ] }, "stdin": { "description": "Stop watching when stdin stream has ended", "type": "boolean" } } } } } webpack-4.30.0/schemas/ajv.absolutePath.js000066400000000000000000000025211345416772700204250ustar00rootroot00000000000000"use strict"; const errorMessage = (schema, data, message) => ({ keyword: "absolutePath", params: { absolutePath: data }, message: message, parentSchema: schema }); const getErrorFor = (shouldBeAbsolute, data, schema) => { const message = shouldBeAbsolute ? `The provided value ${JSON.stringify(data)} is not an absolute path!` : `A relative path is expected. However, the provided value ${JSON.stringify( data )} is an absolute path!`; return errorMessage(schema, data, message); }; module.exports = ajv => ajv.addKeyword("absolutePath", { errors: true, type: "string", compile(expected, schema) { function callback(data) { let passes = true; const isExclamationMarkPresent = data.includes("!"); const isCorrectAbsoluteOrRelativePath = expected === /^(?:[A-Za-z]:\\|\/)/.test(data); if (isExclamationMarkPresent) { callback.errors = [ errorMessage( schema, data, `The provided value ${JSON.stringify( data )} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.` ) ]; passes = false; } if (!isCorrectAbsoluteOrRelativePath) { callback.errors = [getErrorFor(expected, data, schema)]; passes = false; } return passes; } callback.errors = []; return callback; } }); webpack-4.30.0/schemas/plugins/000077500000000000000000000000001345416772700163365ustar00rootroot00000000000000webpack-4.30.0/schemas/plugins/BannerPlugin.json000066400000000000000000000046251345416772700216240ustar00rootroot00000000000000{ "definitions": { "BannerFunction": { "description": "The banner as function, it will be wrapped in a comment", "instanceof": "Function", "tsType": "(data: { hash: string, chunk: import('../../lib/Chunk'), filename: string, basename: string, query: string}) => string" }, "Rule": { "oneOf": [ { "instanceof": "RegExp", "tsType": "RegExp" }, { "type": "string", "minLength": 1 } ] }, "Rules": { "oneOf": [ { "type": "array", "items": { "description": "A rule condition", "anyOf": [ { "$ref": "#/definitions/Rule" } ] } }, { "$ref": "#/definitions/Rule" } ] } }, "title": "BannerPluginArgument", "oneOf": [ { "title": "BannerPluginOptions", "type": "object", "additionalProperties": false, "properties": { "banner": { "description": "Specifies the banner", "anyOf": [ { "$ref": "#/definitions/BannerFunction" }, { "type": "string" } ] }, "entryOnly": { "description": "If true, the banner will only be added to the entry chunks", "type": "boolean" }, "exclude": { "description": "Exclude all modules matching any of these conditions", "anyOf": [ { "$ref": "#/definitions/Rules" } ] }, "include": { "description": "Include all modules matching any of these conditions", "anyOf": [ { "$ref": "#/definitions/Rules" } ] }, "raw": { "description": "If true, banner will not be wrapped in a comment", "type": "boolean" }, "test": { "description": "Include all modules that pass test assertion", "anyOf": [ { "$ref": "#/definitions/Rules" } ] } }, "required": ["banner"] }, { "$ref": "#/definitions/BannerFunction" }, { "description": "The banner as string, it will be wrapped in a comment", "type": "string", "minLength": 1 } ] } webpack-4.30.0/schemas/plugins/DllPlugin.json000066400000000000000000000017731345416772700211330ustar00rootroot00000000000000{ "title": "DllPluginOptions", "type": "object", "additionalProperties": false, "properties": { "context": { "description": "Context of requests in the manifest file (defaults to the webpack context)", "type": "string", "minLength": 1 }, "entryOnly": { "description": "If true, only entry points will be exposed", "type": "boolean" }, "format": { "description": "If true, manifest json file (output) will be formatted", "type": "boolean" }, "name": { "description": "Name of the exposed dll function (external name, use value of 'output.library')", "type": "string", "minLength": 1 }, "path": { "description": "Absolute path to the manifest json file (output)", "type": "string", "minLength": 1 }, "type": { "description": "Type of the dll bundle (external type, use value of 'output.libraryTarget')", "type": "string", "minLength": 1 } }, "required": ["path"] } webpack-4.30.0/schemas/plugins/DllReferencePlugin.json000066400000000000000000000136301345416772700227450ustar00rootroot00000000000000{ "definitions": { "DllReferencePluginOptionsContent": { "description": "The mappings from request to module info", "type": "object", "additionalProperties": { "description": "Module info", "type": "object", "additionalProperties": false, "properties": { "buildMeta": { "description": "Meta information about the module", "type": "object" }, "exports": { "description": "Information about the provided exports of the module", "anyOf": [ { "description": "Exports unknown/dynamic", "enum": [true] }, { "description": "List of provided exports of the module", "type": "array", "items": { "description": "Name of the export", "type": "string", "minLength": 1 } } ] }, "id": { "description": "Module ID", "anyOf": [ { "type": "number" }, { "type": "string", "minLength": 1 } ] } }, "required": ["id"] }, "minProperties": 1 }, "DllReferencePluginOptionsManifest": { "description": "An object containing content, name and type", "type": "object", "additionalProperties": false, "properties": { "content": { "description": "The mappings from request to module info", "anyOf": [ { "$ref": "#/definitions/DllReferencePluginOptionsContent" } ] }, "name": { "description": "The name where the dll is exposed (external name)", "type": "string", "minLength": 1 }, "type": { "description": "The type how the dll is exposed (external type)", "anyOf": [ { "$ref": "#/definitions/DllReferencePluginOptionsSourceType" } ] } }, "required": ["content"] }, "DllReferencePluginOptionsSourceType": { "description": "The type how the dll is exposed (external type)", "enum": [ "var", "assign", "this", "window", "global", "commonjs", "commonjs2", "commonjs-module", "amd", "amd-require", "umd", "umd2", "jsonp" ] } }, "title": "DllReferencePluginOptions", "anyOf": [ { "type": "object", "additionalProperties": false, "properties": { "context": { "description": "(absolute path) context of requests in the manifest (or content property)", "type": "string", "absolutePath": true }, "extensions": { "description": "Extensions used to resolve modules in the dll bundle (only used when using 'scope')", "type": "array", "items": { "description": "An extension", "type": "string" } }, "manifest": { "description": "An object containing content and name or a string to the absolute path of the JSON manifest to be loaded upon compilation", "oneOf": [ { "$ref": "#/definitions/DllReferencePluginOptionsManifest" }, { "type": "string", "absolutePath": true } ] }, "name": { "description": "The name where the dll is exposed (external name, defaults to manifest.name)", "type": "string", "minLength": 1 }, "scope": { "description": "Prefix which is used for accessing the content of the dll", "type": "string", "minLength": 1 }, "sourceType": { "description": "How the dll is exposed (libraryTarget, defaults to manifest.type)", "anyOf": [ { "$ref": "#/definitions/DllReferencePluginOptionsSourceType" } ] }, "type": { "description": "The way how the export of the dll bundle is used", "enum": ["require", "object"] } }, "required": ["manifest"] }, { "type": "object", "additionalProperties": false, "properties": { "content": { "description": "The mappings from request to module info", "anyOf": [ { "$ref": "#/definitions/DllReferencePluginOptionsContent" } ] }, "context": { "description": "(absolute path) context of requests in the manifest (or content property)", "type": "string", "absolutePath": true }, "extensions": { "description": "Extensions used to resolve modules in the dll bundle (only used when using 'scope')", "type": "array", "items": { "description": "An extension", "type": "string" } }, "name": { "description": "The name where the dll is exposed (external name)", "type": "string", "minLength": 1 }, "scope": { "description": "Prefix which is used for accessing the content of the dll", "type": "string", "minLength": 1 }, "sourceType": { "description": "How the dll is exposed (libraryTarget)", "anyOf": [ { "$ref": "#/definitions/DllReferencePluginOptionsSourceType" } ] }, "type": { "description": "The way how the export of the dll bundle is used", "enum": ["require", "object"] } }, "required": ["content", "name"] } ] } webpack-4.30.0/schemas/plugins/HashedModuleIdsPlugin.json000066400000000000000000000015161345416772700234150ustar00rootroot00000000000000{ "title": "HashedModuleIdsPluginOptions", "type": "object", "additionalProperties": false, "properties": { "context": { "description": "The context directory for creating names.", "type": "string", "absolutePath": true }, "hashDigest": { "description": "The encoding to use when generating the hash, defaults to 'base64'. All encodings from Node.JS' hash.digest are supported.", "enum": ["hex", "latin1", "base64"] }, "hashDigestLength": { "description": "The prefix length of the hash digest to use, defaults to 4.", "type": "number", "minimum": 1 }, "hashFunction": { "description": "The hashing algorithm to use, defaults to 'md5'. All functions from Node.JS' crypto.createHash are supported.", "type": "string", "minLength": 1 } } } webpack-4.30.0/schemas/plugins/IgnorePlugin.json000066400000000000000000000017551345416772700216430ustar00rootroot00000000000000{ "title": "IgnorePluginOptions", "oneOf": [ { "type": "object", "additionalProperties": false, "properties": { "contextRegExp": { "description": "A RegExp to test the context (directory) against", "instanceof": "RegExp", "tsType": "RegExp" }, "resourceRegExp": { "description": "A RegExp to test the request against", "instanceof": "RegExp", "tsType": "RegExp" } } }, { "type": "object", "additionalProperties": false, "properties": { "checkContext": { "description": "A filter function for context", "instanceof": "Function", "tsType": "((context: string) => boolean)" }, "checkResource": { "description": "A filter function for resource and context", "instanceof": "Function", "tsType": "((resource: string, context: string) => boolean)" } } } ] } webpack-4.30.0/schemas/plugins/LoaderOptionsPlugin.json000066400000000000000000000014051345416772700231720ustar00rootroot00000000000000{ "title": "LoaderOptionsPluginOptions", "type": "object", "additionalProperties": true, "properties": { "debug": { "description": "Whether loaders should be in debug mode or not. debug will be removed as of webpack 3", "type": "boolean" }, "minimize": { "description": "Where loaders can be switched to minimize mode", "type": "boolean" }, "options": { "description": "A configuration object that can be used to configure older loaders", "type": "object", "additionalProperties": true, "properties": { "context": { "description": "The context that can be used to configure older loaders", "type": "string", "absolutePath": true } } } } } webpack-4.30.0/schemas/plugins/ProgressPlugin.json000066400000000000000000000027411345416772700222200ustar00rootroot00000000000000{ "definitions": { "HandlerFunction": { "description": "Function that executes for every progress step", "instanceof": "Function", "tsType": "((percentage: number, msg: string, ...args: string[]) => void)" }, "ProgressPluginOptions": { "type": "object", "additionalProperties": false, "properties": { "activeModules": { "description": "Show active modules count and one active module in progress message", "type": "boolean" }, "entries": { "description": "Show entries count in progress message", "type": "boolean" }, "handler": { "description": "Function that executes for every progress step", "anyOf": [ { "$ref": "#/definitions/HandlerFunction" } ] }, "modules": { "description": "Show modules count in progress message", "type": "boolean" }, "modulesCount": { "description": "Minimum modules count to start with. Only for mode=modules. Default: 500", "type": "number" }, "profile": { "description": "Collect profile data for progress steps. Default: false", "enum": [true, false, null] } } } }, "title": "ProgressPluginArgument", "oneOf": [ { "$ref": "#/definitions/ProgressPluginOptions" }, { "$ref": "#/definitions/HandlerFunction" } ] } webpack-4.30.0/schemas/plugins/SourceMapDevToolPlugin.json000066400000000000000000000123041345416772700236030ustar00rootroot00000000000000{ "definitions": { "rule": { "oneOf": [ { "instanceof": "RegExp", "tsType": "RegExp" }, { "type": "string", "minLength": 1 } ] }, "rules": { "oneOf": [ { "type": "array", "items": { "description": "A rule condition", "anyOf": [ { "$ref": "#/definitions/rule" } ] } }, { "$ref": "#/definitions/rule" } ] } }, "title": "SourceMapDevToolPluginOptions", "type": "object", "additionalProperties": false, "properties": { "append": { "description": "Appends the given value to the original asset. Usually the #sourceMappingURL comment. [url] is replaced with a URL to the source map file. false disables the appending", "oneOf": [ { "description": "Append no SourceMap comment to the bundle, but still generate SourceMaps", "enum": [false, null] }, { "type": "string", "minLength": 1 } ] }, "columns": { "description": "Indicates whether column mappings should be used (defaults to true)", "type": "boolean" }, "exclude": { "description": "Exclude modules that match the given value from source map generation", "anyOf": [ { "$ref": "#/definitions/rules" } ] }, "fallbackModuleFilenameTemplate": { "description": "Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap used only if 'moduleFilenameTemplate' would result in a conflict", "oneOf": [ { "description": "Custom function generating the identifer", "instanceof": "Function", "tsType": "Function" }, { "type": "string", "minLength": 1 } ] }, "fileContext": { "description": "Path prefix to which the [file] placeholder is relative to", "type": "string" }, "filename": { "description": "Defines the output filename of the SourceMap (will be inlined if no value is provided)", "oneOf": [ { "description": "Disable separate SourceMap file and inline SourceMap as DataUrl", "enum": [false, null] }, { "type": "string", "absolutePath": false, "minLength": 1 } ] }, "include": { "description": "Include source maps for module paths that match the given value", "anyOf": [ { "$ref": "#/definitions/rules" } ] }, "lineToLine": { "description": "(deprecated) try to map original files line to line to generated files", "anyOf": [ { "type": "boolean" }, { "description": "Simplify and speed up source mapping by using line to line source mappings for matched modules", "type": "object", "additionalProperties": false, "properties": { "exclude": { "description": "Exclude modules that match the given value from source map generation", "anyOf": [ { "$ref": "#/definitions/rules" } ] }, "include": { "description": "Include source maps for module paths that match the given value", "anyOf": [ { "$ref": "#/definitions/rules" } ] }, "test": { "description": "Include source maps for modules based on their extension (defaults to .js and .css)", "anyOf": [ { "$ref": "#/definitions/rules" } ] } } } ] }, "module": { "description": "Indicates whether SourceMaps from loaders should be used (defaults to true)", "type": "boolean" }, "moduleFilenameTemplate": { "description": "Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap", "oneOf": [ { "description": "Custom function generating the identifer", "instanceof": "Function", "tsType": "Function" }, { "type": "string", "minLength": 1 } ] }, "namespace": { "description": "Namespace prefix to allow multiple webpack roots in the devtools", "type": "string" }, "noSources": { "description": "Omit the 'sourceContents' array from the SourceMap", "type": "boolean" }, "publicPath": { "description": "Provide a custom public path for the SourceMapping comment", "type": "string" }, "sourceRoot": { "description": "Provide a custom value for the 'sourceRoot' property in the SourceMap", "type": "string" }, "test": { "description": "Include source maps for modules based on their extension (defaults to .js and .css)", "anyOf": [ { "$ref": "#/definitions/rules" } ] } } } webpack-4.30.0/schemas/plugins/WatchIgnorePlugin.json000066400000000000000000000006561345416772700226310ustar00rootroot00000000000000{ "title": "WatchIgnorePluginOptions", "description": "A list of RegExps or absolute paths to directories or files that should be ignored", "type": "array", "items": { "description": "RegExp or absolute path to directories or files that should be ignored", "oneOf": [ { "type": "string" }, { "instanceof": "RegExp", "tsType": "RegExp" } ] }, "minItems": 1 } webpack-4.30.0/schemas/plugins/debug/000077500000000000000000000000001345416772700174245ustar00rootroot00000000000000webpack-4.30.0/schemas/plugins/debug/ProfilingPlugin.json000066400000000000000000000005011345416772700234230ustar00rootroot00000000000000{ "title": "ProfilingPluginOptions", "type": "object", "additionalProperties": false, "properties": { "outputPath": { "description": "Path to the output file e.g. `profiling/events.json`. Defaults to `events.json`.", "type": "string", "absolutePath": false, "minLength": 4 } } } webpack-4.30.0/schemas/plugins/optimize/000077500000000000000000000000001345416772700201765ustar00rootroot00000000000000webpack-4.30.0/schemas/plugins/optimize/AggressiveSplittingPlugin.json000066400000000000000000000010211345416772700262370ustar00rootroot00000000000000{ "title": "AggressiveSplittingPluginOptions", "type": "object", "additionalProperties": false, "properties": { "chunkOverhead": { "description": "Default: 0", "type": "number" }, "entryChunkMultiplicator": { "description": "Default: 1", "type": "number" }, "maxSize": { "description": "Byte, maxsize of per file. Default: 51200", "type": "number" }, "minSize": { "description": "Byte, split point. Default: 30720", "type": "number" } } } webpack-4.30.0/schemas/plugins/optimize/LimitChunkCountPlugin.json000066400000000000000000000006171345416772700253340ustar00rootroot00000000000000{ "title": "LimitChunkCountPluginOptions", "type": "object", "additionalProperties": false, "properties": { "maxChunks": { "description": "Limit the maximum number of chunks using a value greater greater than or equal to 1", "type": "number", "minimum": 1 }, "minChunkSize": { "description": "Set a minimum chunk size", "type": "number" } } } webpack-4.30.0/schemas/plugins/optimize/MinChunkSizePlugin.json000066400000000000000000000003771345416772700246260ustar00rootroot00000000000000{ "title": "MinChunkSizePluginOptions", "type": "object", "additionalProperties": false, "properties": { "minChunkSize": { "description": "Minimum number of characters", "type": "number" } }, "required": ["minChunkSize"] } webpack-4.30.0/schemas/plugins/optimize/OccurrenceOrderChunkIdsPlugin.json000066400000000000000000000003731345416772700267700ustar00rootroot00000000000000{ "title": "OccurrenceOrderChunkIdsPluginOptions", "type": "object", "additionalProperties": false, "properties": { "prioritiseInitial": { "description": "Prioritise initial size over total size", "type": "boolean" } } } webpack-4.30.0/schemas/plugins/optimize/OccurrenceOrderModuleIdsPlugin.json000066400000000000000000000003741345416772700271460ustar00rootroot00000000000000{ "title": "OccurrenceOrderModuleIdsPluginOptions", "type": "object", "additionalProperties": false, "properties": { "prioritiseInitial": { "description": "Prioritise initial size over total size", "type": "boolean" } } } webpack-4.30.0/setup/000077500000000000000000000000001345416772700143725ustar00rootroot00000000000000webpack-4.30.0/setup/setup.js000066400000000000000000000054111345416772700160710ustar00rootroot00000000000000"use strict"; const fs = require("fs"); const path = require("path"); const root = process.cwd(); const node_modulesFolder = path.resolve(root, "node_modules"); const webpackDependencyFolder = path.resolve(root, "node_modules/webpack"); function setup() { return checkSymlinkExistsAsync() .then(hasSymlink => { if (!hasSymlink) { return ensureYarnInstalledAsync().then(() => { return runSetupAsync().then(() => { return checkSymlinkExistsAsync(); }); }); } }) .then(message => { process.exitCode = 0; }) .catch(e => { console.error(e); process.exitCode = 1; }); } function runSetupAsync() { return exec("yarn", ["install"], "Install dependencies") .then(() => exec("yarn", ["link"], "Create webpack symlink")) .then(() => exec("yarn", ["link", "webpack"], "Link webpack into itself")); } function checkSymlinkExistsAsync() { return new Promise((resolve, reject) => { if ( fs.existsSync(node_modulesFolder) && fs.existsSync(webpackDependencyFolder) && fs.lstatSync(webpackDependencyFolder).isSymbolicLink() ) { resolve(true); } else { resolve(false); } }); } function ensureYarnInstalledAsync() { const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/; return execGetOutput("yarn", ["-v"], "Check yarn version") .then(stdout => semverPattern.test(stdout), () => false) .then(hasYarn => hasYarn || installYarnAsync()); } function installYarnAsync() { return exec("npm", ["install", "-g", "yarn"], "Install yarn"); } function exec(command, args, description) { console.log(`Setup: ${description}`); return new Promise((resolve, reject) => { let cp = require("child_process").spawn(command, args, { cwd: root, stdio: "inherit", shell: true }); cp.on("error", error => { reject(new Error(`${description} failed with ${error}`)); }); cp.on("exit", exitCode => { if (exitCode) { reject(`${description} failed with exitcode ${exitCode}`); } else { resolve(); } }); }); } function execGetOutput(command, args, description) { console.log(`Setup: ${description}`); return new Promise((resolve, reject) => { let cp = require("child_process").spawn(command, args, { cwd: root, stdio: [process.stdin, "pipe", process.stderr], shell: true }); cp.on("error", error => { reject(new Error(`${description} failed with ${error}`)); }); cp.on("exit", exitCode => { if (exitCode) { reject(`${description} failed with exitcode ${exitCode}`); } else { resolve( Buffer.concat(buffers) .toString("utf-8") .trim() ); } }); const buffers = []; cp.stdout.on("data", data => buffers.push(data)); }); } setup(); webpack-4.30.0/test/000077500000000000000000000000001345416772700142115ustar00rootroot00000000000000webpack-4.30.0/test/BenchmarkTestCases.benchmark.js000066400000000000000000000221411345416772700222110ustar00rootroot00000000000000"use strict"; const path = require("path"); const fs = require("fs"); const asyncLib = require("neo-async"); const Benchmark = require("benchmark"); const { remove } = require("./helpers/remove"); describe("BenchmarkTestCases", function() { const casesPath = path.join(__dirname, "benchmarkCases"); const tests = fs.readdirSync(casesPath).filter(function(folder) { return ( folder.indexOf("_") < 0 && fs.existsSync(path.resolve(casesPath, folder, "webpack.config.js")) ); }); const baselinesPath = path.join(__dirname, "js", "benchmark-baselines"); const baselines = []; try { fs.mkdirSync(path.join(__dirname, "js")); } catch (e) {} // eslint-disable-line no-empty try { fs.mkdirSync(baselinesPath); } catch (e) {} // eslint-disable-line no-empty beforeAll(function(done) { const git = require("simple-git"); const rootPath = path.join(__dirname, ".."); getBaselineRevs(rootPath, (err, baselineRevisions) => { if (err) return done(err); asyncLib.eachSeries( baselineRevisions, (baselineInfo, callback) => { const baselineRevision = baselineInfo.rev; const baselinePath = path.resolve(baselinesPath, baselineRevision); if (fs.existsSync(path.resolve(baselinePath, ".git"))) { doLoadWebpack(); } else { try { fs.mkdirSync(baselinePath); } catch (e) {} // eslint-disable-line no-empty const gitIndex = path.resolve(rootPath, ".git/index"); const index = fs.readFileSync(gitIndex); git(rootPath).raw( ["rev-list", "-n", "1", "HEAD"], (err, prevHead) => { if (err) return callback(err); git(baselinePath).raw( [ "--git-dir", path.join(rootPath, ".git"), "reset", "--hard", baselineRevision ], err => { if (err) return callback(err); git(rootPath).raw( ["reset", "--soft", prevHead.split("\n")[0]], err => { if (err) return callback(err); fs.writeFileSync(gitIndex, index); try { doLoadWebpack(); } catch (err) { callback(err); } } ); } ); } ); } function doLoadWebpack() { const baselineWebpack = require.requireActual( path.resolve(baselinePath, "lib/webpack.js") ); baselines.push({ name: baselineInfo.name, rev: baselineRevision, webpack: baselineWebpack }); callback(); } }, err => { if (err) { done(err); return; } createTests(); done(); } ); }); }, 270000); afterAll(() => { remove(baselinesPath); }); function getBaselineRevs(rootPath, callback) { const git = require("simple-git")(rootPath); const lastVersionTag = "v" + require("../package.json").version; git.raw(["rev-list", "-n", "1", lastVersionTag], (err, resultVersion) => { if (err) return callback(err); const matchVersion = /^([a-f0-9]+)\s*$/.exec(resultVersion); if (!matchVersion) return callback(new Error("Invalid result from git revparse")); const revLastVersion = matchVersion[1]; git.raw( ["rev-list", "--parents", "-n", "1", "HEAD"], (err, resultParents) => { if (err) return callback(err); const match = /^([a-f0-9]+)\s*([a-f0-9]+)\s*([a-f0-9]+)?\s*$/.exec( resultParents ); if (!match) return callback(new Error("Invalid result from git rev-list")); const head = match[1]; const parent1 = match[2]; const parent2 = match[3]; if (parent2 && parent1) { return callback( null, [ { name: "HEAD", rev: head }, head !== revLastVersion && { name: lastVersionTag, rev: revLastVersion }, parent1 !== revLastVersion && head !== revLastVersion && { name: "base", rev: parent1 } ].filter(Boolean) ); } else if (parent1) { return callback( null, [ { name: "HEAD", rev: head }, head !== revLastVersion && { name: lastVersionTag, rev: revLastVersion } ].filter(Boolean) ); } else { return callback(new Error("No baseline found")); } } ); }); } function tDistribution(n) { // two-sided, 90% // https://en.wikipedia.org/wiki/Student%27s_t-distribution if (n <= 30) { // 1 2 ... const data = [ 6.314, 2.92, 2.353, 2.132, 2.015, 1.943, 1.895, 1.86, 1.833, 1.812, 1.796, 1.782, 1.771, 1.761, 1.753, 1.746, 1.74, 1.734, 1.729, 1.725, 1.721, 1.717, 1.714, 1.711, 1.708, 1.706, 1.703, 1.701, 1.699, 1.697 ]; return data[n - 1]; } else if (n <= 120) { // 30 40 50 60 70 80 90 100 110 120 const data = [ 1.697, 1.684, 1.676, 1.671, 1.667, 1.664, 1.662, 1.66, 1.659, 1.658 ]; var a = data[Math.floor(n / 10) - 3]; var b = data[Math.ceil(n / 10) - 3]; var f = n / 10 - Math.floor(n / 10); return a * (1 - f) + b * f; } else { return 1.645; } } function runBenchmark(webpack, config, callback) { // warmup const warmupCompiler = webpack(config, (err, stats) => { warmupCompiler.purgeInputFileSystem(); const bench = new Benchmark( function(deferred) { const compiler = webpack(config, (err, stats) => { compiler.purgeInputFileSystem(); if (err) { callback(err); return; } if (stats.hasErrors()) { callback(new Error(stats.toJson().errors.join("\n\n"))); return; } deferred.resolve(); }); }, { maxTime: 30, defer: true, initCount: 1, onComplete: function() { const stats = bench.stats; const n = stats.sample.length; const nSqrt = Math.sqrt(n); const z = tDistribution(n - 1); stats.minConfidence = stats.mean - (z * stats.deviation) / nSqrt; stats.maxConfidence = stats.mean + (z * stats.deviation) / nSqrt; stats.text = `${Math.round(stats.mean * 1000)}ms ± ${Math.round( stats.deviation * 1000 )}ms [${Math.round(stats.minConfidence * 1000)}ms; ${Math.round( stats.maxConfidence * 1000 )}ms]`; callback(null, bench.stats); }, onError: callback } ); bench.run({ async: true }); }); } function createTests() { tests.forEach(testName => { const testDirectory = path.join(casesPath, testName); let headStats = null; describe(`${testName} create benchmarks`, function() { baselines.forEach(baseline => { let baselineStats = null; it(`should benchmark ${baseline.name} (${ baseline.rev })`, function(done) { const outputDirectory = path.join( __dirname, "js", "benchmark", `baseline-${baseline.name}`, testName ); const config = Object.create( require.requireActual( path.join(testDirectory, "webpack.config.js") ) ) || {}; config.output = Object.create(config.output || {}); if (!config.context) config.context = testDirectory; if (!config.output.path) config.output.path = outputDirectory; runBenchmark(baseline.webpack, config, (err, stats) => { if (err) return done(err); process.stderr.write(` ${baseline.name} ${stats.text}`); if (baseline.name === "HEAD") headStats = stats; else baselineStats = stats; done(); }); }, 180000); it(`should benchmark ${baseline.name} (${baseline.rev})`, done => { const outputDirectory = path.join( __dirname, "js", "benchmark", `baseline-${baseline.name}`, testName ); const config = require.requireActual( path.join(testDirectory, "webpack.config.js") ) || {}; config.output = config.output || {}; if (!config.context) config.context = testDirectory; if (!config.output.path) config.output.path = outputDirectory; runBenchmark(baseline.webpack, config, (err, stats) => { if (err) return done(err); process.stderr.write(` ${baseline.name} ${stats.text}`); if (baseline.name === "HEAD") headStats = stats; else baselineStats = stats; done(); }); }, 180000); if (baseline.name !== "HEAD") { it(`HEAD should not be slower than ${baseline.name} (${ baseline.rev })`, function() { if (baselineStats.maxConfidence < headStats.minConfidence) { throw new Error( `HEAD (${headStats.text}) is slower than ${baseline.name} (${ baselineStats.text }) (90% confidence)` ); } else if ( baselineStats.minConfidence > headStats.maxConfidence ) { console.log( `======> HEAD is ${Math.round( (baselineStats.mean / headStats.mean) * 100 - 100 )}% faster than ${baseline.name} (90% confidence)!` ); } }); } }); }); }); } }); webpack-4.30.0/test/CachePlugin.unittest.js000066400000000000000000000020061345416772700206050ustar00rootroot00000000000000"use strict"; const CachePlugin = require("../lib/CachePlugin"); describe("CachePlugin", () => { let env; beforeEach(() => { env = { compilation: { compiler: {}, warnings: [] } }; }); describe("applyMtime", () => { beforeEach(() => (env.plugin = new CachePlugin())); it("sets file system accuracy to 1 for granular modification timestamp", () => { env.plugin.applyMtime(1483819067001); expect(env.plugin.FS_ACCURACY).toBe(1); }); it("sets file system accuracy to 10 for moderately granular modification timestamp", () => { env.plugin.applyMtime(1483819067004); expect(env.plugin.FS_ACCURACY).toBe(10); }); it("sets file system accuracy to 100 for moderately coarse modification timestamp", () => { env.plugin.applyMtime(1483819067040); expect(env.plugin.FS_ACCURACY).toBe(100); }); it("sets file system accuracy to 1000 for coarse modification timestamp", () => { env.plugin.applyMtime(1483819067400); expect(env.plugin.FS_ACCURACY).toBe(1000); }); }); }); webpack-4.30.0/test/CaseSensitiveModulesWarning.unittest.js000066400000000000000000000027171345416772700240600ustar00rootroot00000000000000"use strict"; const CaseSensitiveModulesWarning = require("../lib/CaseSensitiveModulesWarning"); const createModule = function(identifier, numberOfReasons) { const reasons = new Array(numberOfReasons || 0) .fill(null) .map((value, index) => { return { module: createModule(`${identifier}-reason-${index}`) }; }); return { identifier: () => identifier, reasons }; }; describe("CaseSensitiveModulesWarning", () => { let myCaseSensitiveModulesWarning; let modules; beforeEach(() => { modules = [ createModule("FOOBAR"), createModule("FooBar", 1), createModule("foobar", 2) ]; myCaseSensitiveModulesWarning = new CaseSensitiveModulesWarning(modules); }); it("has the a name", () => { expect(myCaseSensitiveModulesWarning.name).toBe( "CaseSensitiveModulesWarning" ); }); it("has the a message", () => { expect(myCaseSensitiveModulesWarning.message).toBe( ` There are multiple modules with names that only differ in casing. This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. Use equal casing. Compare these module identifiers: * FOOBAR * FooBar Used by 1 module(s), i. e. FooBar-reason-0 * foobar Used by 2 module(s), i. e. foobar-reason-0 `.trim() ); }); it("has the an origin", () => { expect(myCaseSensitiveModulesWarning.origin).toBe(modules[0]); }); it("has the a module", () => { expect(myCaseSensitiveModulesWarning.module).toBe(modules[0]); }); }); webpack-4.30.0/test/Chunk.unittest.js000066400000000000000000000053761345416772700175100ustar00rootroot00000000000000/* globals describe, it, beforeEach */ "use strict"; const Chunk = require("../lib/Chunk"); describe("Chunk", () => { let ChunkInstance; beforeEach(() => { ChunkInstance = new Chunk("chunk-test", "module-test", "loc-test"); }); it("should have debugId more than 999", () => { expect(ChunkInstance.debugId).toBeGreaterThan(999); }); it("returns a string with modules information", () => { expect(ChunkInstance.toString()).toBe("Chunk[]"); }); it("should not be the initial instance", () => { expect(ChunkInstance.canBeInitial()).toBe(false); }); describe("entry", () => { it("returns an error if get entry", () => { expect(() => { ChunkInstance.entry; }).toThrow("Chunk.entry was removed. Use hasRuntime()"); }); it("returns an error if set an entry", () => { expect(() => { ChunkInstance.entry = 10; }).toThrow("Chunk.entry was removed. Use hasRuntime()"); }); }); describe("initial", () => { it("returns an error if get initial", () => { expect(() => { ChunkInstance.initial; }).toThrow("Chunk.initial was removed. Use canBeInitial/isOnlyInitial()"); }); it("returns an error if set an initial", () => { expect(() => { ChunkInstance.initial = 10; }).toThrow("Chunk.initial was removed. Use canBeInitial/isOnlyInitial()"); }); }); describe("hasRuntime", () => { it("returns false", () => { expect(ChunkInstance.hasRuntime()).toBe(false); }); }); describe("isEmpty", () => { it("should NOT have any module by default", () => { expect(ChunkInstance.isEmpty()).toBe(true); }); }); describe("size", () => { it("should NOT have any module by default", () => { expect( ChunkInstance.size({ chunkOverhead: 10, entryChunkMultiplicator: 2 }) ).toBe(10); }); }); describe("removeModule", () => { let module; let removeChunkSpy; beforeEach(() => { removeChunkSpy = jest.fn(); module = { removeChunk: removeChunkSpy }; }); describe("and the chunk does not contain this module", () => { it("returns false", () => { expect(ChunkInstance.removeModule(module)).toBe(false); }); }); describe("and the chunk does contain this module", () => { beforeEach(() => { ChunkInstance._modules = new Set([module]); }); it("calls module.removeChunk with itself and returns true", () => { expect(ChunkInstance.removeModule(module)).toBe(true); expect(removeChunkSpy.mock.calls.length).toBe(1); expect(removeChunkSpy.mock.calls[0][0]).toBe(ChunkInstance); }); }); describe("getNumberOfGroups", () => { beforeEach(() => { ChunkInstance._groups = new Set(); }); it("should return the number of chunk groups contained by the chunk", () => { expect(ChunkInstance.getNumberOfGroups()).toBe(0); }); }); }); }); webpack-4.30.0/test/Compiler-caching.test.js000066400000000000000000000170211345416772700206720ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const path = require("path"); const fs = require("fs"); const rimraf = require("rimraf"); const webpack = require("../"); const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter"); let fixtureCount = 0; describe("Compiler (caching)", () => { jest.setTimeout(15000); function compile(entry, options, callback) { options.mode = "none"; options = new WebpackOptionsDefaulter().process(options); options.cache = true; options.entry = entry; options.optimization.minimize = false; options.context = path.join(__dirname, "fixtures"); options.output.path = "/"; options.output.filename = "bundle.js"; options.output.pathinfo = true; const logs = { mkdirp: [], writeFile: [] }; const c = webpack(options); const files = {}; c.outputFileSystem = { join() { return [].join.call(arguments, "/").replace(/\/+/g, "/"); }, mkdirp(path, callback) { logs.mkdirp.push(path); callback(); }, writeFile(name, content, callback) { logs.writeFile.push(name, content); files[name] = content.toString("utf-8"); callback(); } }; c.hooks.compilation.tap( "CompilerCachingTest", compilation => (compilation.bail = true) ); let compilerIteration = 1; function runCompiler(options, callback) { if (typeof options === "function") { callback = options; options = {}; } c.run((err, stats) => { if (err) throw err; expect(typeof stats).toBe("object"); stats = stats.toJson({ modules: true, reasons: true }); expect(typeof stats).toBe("object"); expect(stats).toHaveProperty("errors"); expect(Array.isArray(stats.errors)).toBe(true); if (options.expectErrors) { expect(stats.errors).toHaveLength(options.expectErrors); } else { if (stats.errors.length > 0) { expect(typeof stats.errors[0]).toBe("string"); throw new Error(stats.errors[0]); } } stats.logs = logs; callback(stats, files, compilerIteration++); }); } runCompiler(callback); return { compilerInstance: c, runAgain: runCompiler }; } const tempFixturePath = path.join( __dirname, "fixtures", "temp-cache-fixture" ); function cleanup() { rimraf.sync(`${tempFixturePath}-*`); } beforeAll(cleanup); afterAll(cleanup); function createTempFixture() { const fixturePath = `${tempFixturePath}-${fixtureCount}`; const aFilepath = path.join(fixturePath, "a.js"); const cFilepath = path.join(fixturePath, "c.js"); // Remove previous copy if present rimraf.sync(fixturePath); // Copy over file since we"ll be modifying some of them fs.mkdirSync(fixturePath); fs.createReadStream(path.join(__dirname, "fixtures", "a.js")).pipe( fs.createWriteStream(aFilepath) ); fs.createReadStream(path.join(__dirname, "fixtures", "c.js")).pipe( fs.createWriteStream(cFilepath) ); fixtureCount++; return { rootPath: fixturePath, aFilepath: aFilepath, cFilepath: cFilepath }; } it("should cache single file (with manual 1s wait) ", done => { const options = {}; const tempFixture = createTempFixture(); const helper = compile(tempFixture.cFilepath, options, (stats, files) => { // Not cached the first time expect(stats.assets[0].name).toBe("bundle.js"); expect(stats.assets[0].emitted).toBe(true); helper.runAgain((stats, files, iteration) => { // Cached the second run expect(stats.assets[0].name).toBe("bundle.js"); expect(stats.assets[0].emitted).toBe(false); const aContent = fs .readFileSync(tempFixture.aFilepath) .toString() .replace("This is a", "This is a MODIFIED"); setTimeout(() => { fs.writeFileSync(tempFixture.aFilepath, aContent); helper.runAgain((stats, files, iteration) => { // Cached the third run expect(stats.assets[0].name).toBe("bundle.js"); expect(stats.assets[0].emitted).toBe(true); done(); }); }, 1100); }); }); }); it("should cache single file (even with no timeout) ", done => { const options = {}; const tempFixture = createTempFixture(); const helper = compile(tempFixture.cFilepath, options, (stats, files) => { // Not cached the first time expect(stats.assets[0].name).toBe("bundle.js"); expect(stats.assets[0].emitted).toBe(true); helper.runAgain((stats, files, iteration) => { // Cached the second run expect(stats.assets[0].name).toBe("bundle.js"); expect(stats.assets[0].emitted).toBe(false); expect(files["/bundle.js"]).toMatch("This is a"); const aContent = fs .readFileSync(tempFixture.aFilepath) .toString() .replace("This is a", "This is a MODIFIED"); fs.writeFileSync(tempFixture.aFilepath, aContent); helper.runAgain((stats, files, iteration) => { // Cached the third run expect(stats.assets[0].name).toBe("bundle.js"); expect(stats.assets[0].emitted).toBe(true); expect(files["/bundle.js"]).toMatch("This is a MODIFIED"); done(); }); }); }); }); it("should only build when modified (with manual 2s wait)", done => { const options = {}; const tempFixture = createTempFixture(); const helper = compile(tempFixture.cFilepath, options, (stats, files) => { // Built the first time expect(stats.modules[0].name).toMatch("c.js"); expect(stats.modules[0].built).toBe(true); expect(stats.modules[1].name).toMatch("a.js"); expect(stats.modules[1].built).toBe(true); setTimeout(() => { helper.runAgain((stats, files, iteration) => { // Not built when cached the second run expect(stats.modules[0].name).toMatch("c.js"); // expect(stats.modules[0].built).toBe(false); expect(stats.modules[1].name).toMatch("a.js"); // expect(stats.modules[1].built).toBe(false); const aContent = fs .readFileSync(tempFixture.aFilepath) .toString() .replace("This is a", "This is a MODIFIED"); setTimeout(() => { fs.writeFileSync(tempFixture.aFilepath, aContent); helper.runAgain((stats, files, iteration) => { // And only a.js built after it was modified expect(stats.modules[0].name).toMatch("c.js"); expect(stats.modules[0].built).toBe(false); expect(stats.modules[1].name).toMatch("a.js"); expect(stats.modules[1].built).toBe(true); done(); }); }, 2100); }); }, 4100); }); }); it("should build when modified (even with no timeout)", done => { const options = {}; const tempFixture = createTempFixture(); const helper = compile(tempFixture.cFilepath, options, (stats, files) => { // Built the first time expect(stats.modules[0].name).toMatch("c.js"); expect(stats.modules[0].built).toBe(true); expect(stats.modules[1].name).toMatch("a.js"); expect(stats.modules[1].built).toBe(true); helper.runAgain((stats, files, iteration) => { // Not built when cached the second run expect(stats.modules[0].name).toMatch("c.js"); // expect(stats.modules[0].built).toBe(false); expect(stats.modules[1].name).toMatch("a.js"); // expect(stats.modules[1].built).toBe(false); const aContent = fs .readFileSync(tempFixture.aFilepath) .toString() .replace("This is a", "This is a MODIFIED"); fs.writeFileSync(tempFixture.aFilepath, aContent); helper.runAgain((stats, files, iteration) => { // And only a.js built after it was modified expect(stats.modules[0].name).toMatch("c.js"); // expect(stats.modules[0].built).toBe(false); expect(stats.modules[1].name).toMatch("a.js"); expect(stats.modules[1].built).toBe(true); done(); }); }); }); }); }); webpack-4.30.0/test/Compiler.test.js000066400000000000000000000331031345416772700172770ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const path = require("path"); const webpack = require("../"); const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter"); const MemoryFs = require("memory-fs"); describe("Compiler", () => { jest.setTimeout(20000); function compile(entry, options, callback) { const noOutputPath = !options.output || !options.output.path; if (!options.mode) options.mode = "production"; options = new WebpackOptionsDefaulter().process(options); options.entry = entry; options.context = path.join(__dirname, "fixtures"); if (noOutputPath) options.output.path = "/"; options.output.pathinfo = true; options.optimization = { minimize: false }; const logs = { mkdirp: [], writeFile: [] }; const c = webpack(options); const files = {}; c.outputFileSystem = { join() { return [].join.call(arguments, "/").replace(/\/+/g, "/"); }, mkdirp(path, callback) { logs.mkdirp.push(path); callback(); }, writeFile(name, content, callback) { logs.writeFile.push(name, content); files[name] = content.toString("utf-8"); callback(); } }; c.hooks.compilation.tap( "CompilerTest", compilation => (compilation.bail = true) ); c.run((err, stats) => { if (err) throw err; expect(typeof stats).toBe("object"); const compilation = stats.compilation; stats = stats.toJson({ modules: true, reasons: true }); expect(typeof stats).toBe("object"); expect(stats).toHaveProperty("errors"); expect(Array.isArray(stats.errors)).toBe(true); if (stats.errors.length > 0) { expect(stats.errors[0]).toBeInstanceOf(Error); throw stats.errors[0]; } stats.logs = logs; callback(stats, files, compilation); }); } it("should compile a single file to deep output", done => { compile( "./c", { output: { path: "/what", filename: "the/hell.js" } }, (stats, files) => { expect(stats.logs.mkdirp).toEqual(["/what", "/what/the"]); done(); } ); }); it("should compile a single file", done => { compile("./c", {}, (stats, files) => { expect(Object.keys(files)).toEqual(["/main.js"]); const bundle = files["/main.js"]; expect(bundle).toMatch("function __webpack_require__("); expect(bundle).toMatch(/__webpack_require__\(\/\*! \.\/a \*\/ \d\);/); expect(bundle).toMatch("./c.js"); expect(bundle).toMatch("./a.js"); expect(bundle).toMatch("This is a"); expect(bundle).toMatch("This is c"); expect(bundle).not.toMatch("2: function("); expect(bundle).not.toMatch("window"); expect(bundle).not.toMatch("jsonp"); expect(bundle).not.toMatch("fixtures"); done(); }); }); it("should compile a complex file", done => { compile("./main1", {}, (stats, files) => { expect(Object.keys(files)).toEqual(["/main.js"]); const bundle = files["/main.js"]; expect(bundle).toMatch("function __webpack_require__("); expect(bundle).toMatch("__webpack_require__(/*! ./a */"); expect(bundle).toMatch("./main1.js"); expect(bundle).toMatch("./a.js"); expect(bundle).toMatch("./b.js"); expect(bundle).toMatch("./node_modules/m1/a.js"); expect(bundle).toMatch("This is a"); expect(bundle).toMatch("This is b"); expect(bundle).toMatch("This is m1/a"); expect(bundle).not.toMatch("4: function("); expect(bundle).not.toMatch("window"); expect(bundle).not.toMatch("jsonp"); expect(bundle).not.toMatch("fixtures"); done(); }); }); it("should compile a file with transitive dependencies", done => { compile("./abc", {}, (stats, files) => { expect(Object.keys(files)).toEqual(["/main.js"]); const bundle = files["/main.js"]; expect(bundle).toMatch("function __webpack_require__("); expect(bundle).toMatch("__webpack_require__(/*! ./a */"); expect(bundle).toMatch("__webpack_require__(/*! ./b */"); expect(bundle).toMatch("__webpack_require__(/*! ./c */"); expect(bundle).toMatch("./abc.js"); expect(bundle).toMatch("./a.js"); expect(bundle).toMatch("./b.js"); expect(bundle).toMatch("./c.js"); expect(bundle).toMatch("This is a"); expect(bundle).toMatch("This is b"); expect(bundle).toMatch("This is c"); expect(bundle).not.toMatch("4: function("); expect(bundle).not.toMatch("window"); expect(bundle).not.toMatch("jsonp"); expect(bundle).not.toMatch("fixtures"); done(); }); }); it("should compile a file with multiple chunks", done => { compile("./chunks", {}, (stats, files) => { expect(stats.chunks).toHaveLength(2); expect(Object.keys(files)).toEqual(["/main.js", "/1.js"]); const bundle = files["/main.js"]; const chunk = files["/1.js"]; expect(bundle).toMatch("function __webpack_require__("); expect(bundle).toMatch("__webpack_require__(/*! ./b */"); expect(chunk).not.toMatch("__webpack_require__(/* ./b */"); expect(bundle).toMatch("./chunks.js"); expect(chunk).toMatch("./a.js"); expect(chunk).toMatch("./b.js"); expect(chunk).toMatch("This is a"); expect(bundle).not.toMatch("This is a"); expect(chunk).toMatch("This is b"); expect(bundle).not.toMatch("This is b"); expect(bundle).not.toMatch("4: function("); expect(bundle).not.toMatch("fixtures"); expect(chunk).not.toMatch("fixtures"); expect(bundle).toMatch("webpackJsonp"); expect(chunk).toMatch('window["webpackJsonp"] || []).push'); done(); }); }); describe("methods", () => { let compiler; beforeEach(() => { compiler = webpack({ entry: "./c", context: path.join(__dirname, "fixtures"), output: { path: "/", pathinfo: true } }); }); describe("purgeInputFileSystem", () => { it("invokes purge() if inputFileSystem.purge", done => { const mockPurge = jest.fn(); compiler.inputFileSystem = { purge: mockPurge }; compiler.purgeInputFileSystem(); expect(mockPurge.mock.calls.length).toBe(1); done(); }); it("does NOT invoke purge() if !inputFileSystem.purge", done => { const mockPurge = jest.fn(); compiler.inputFileSystem = null; compiler.purgeInputFileSystem(); expect(mockPurge.mock.calls.length).toBe(0); done(); }); }); describe("isChild", () => { it("returns booleanized this.parentCompilation", done => { compiler.parentCompilation = "stringyStringString"; const response1 = compiler.isChild(); expect(response1).toBe(true); compiler.parentCompilation = 123456789; const response2 = compiler.isChild(); expect(response2).toBe(true); compiler.parentCompilation = { what: "I belong to an object" }; const response3 = compiler.isChild(); expect(response3).toBe(true); compiler.parentCompilation = ["Array", 123, true, null, [], () => {}]; const response4 = compiler.isChild(); expect(response4).toBe(true); compiler.parentCompilation = false; const response5 = compiler.isChild(); expect(response5).toBe(false); compiler.parentCompilation = 0; const response6 = compiler.isChild(); expect(response6).toBe(false); compiler.parentCompilation = null; const response7 = compiler.isChild(); expect(response7).toBe(false); compiler.parentCompilation = ""; const response8 = compiler.isChild(); expect(response8).toBe(false); compiler.parentCompilation = NaN; const response9 = compiler.isChild(); expect(response9).toBe(false); done(); }); }); }); it("should not emit on errors", done => { const compiler = webpack({ context: __dirname, mode: "production", entry: "./missing", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(err); if (compiler.outputFileSystem.existsSync("/bundle.js")) return done(new Error("Bundle should not be created on error")); done(); }); }); it("should not emit on errors (watch)", done => { const compiler = webpack({ context: __dirname, mode: "production", entry: "./missing", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); const watching = compiler.watch({}, (err, stats) => { watching.close(); if (err) return done(err); if (compiler.outputFileSystem.existsSync("/bundle.js")) return done(new Error("Bundle should not be created on error")); done(); }); }); it("should not be run twice at a time (run)", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(err); }); compiler.run((err, stats) => { if (err) return done(); }); }); it("should not be run twice at a time (watch)", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); compiler.watch({}, (err, stats) => { if (err) return done(err); }); compiler.watch({}, (err, stats) => { if (err) return done(); }); }); it("should not be run twice at a time (run - watch)", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(err); }); compiler.watch({}, (err, stats) => { if (err) return done(); }); }); it("should not be run twice at a time (watch - run)", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); compiler.watch({}, (err, stats) => { if (err) return done(err); }); compiler.run((err, stats) => { if (err) return done(); }); }); it("should not be run twice at a time (instance cb)", function(done) { const compiler = webpack( { context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }, () => {} ); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(); }); }); it("should run again correctly after first compilation", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(err); compiler.run((err, stats) => { if (err) return done(err); done(); }); }); }); it("should watch again correctly after first compilation", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(err); compiler.watch({}, (err, stats) => { if (err) return done(err); done(); }); }); }); it("should run again correctly after first closed watch", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); const watching = compiler.watch({}, (err, stats) => { if (err) return done(err); }); watching.close(() => { compiler.run((err, stats) => { if (err) return done(err); done(); }); }); }); it("should watch again correctly after first closed watch", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); const watching = compiler.watch({}, (err, stats) => { if (err) return done(err); }); watching.close(() => { compiler.watch({}, (err, stats) => { if (err) return done(err); done(); }); }); }); it("should flag watchMode as true in watch", function(done) { const compiler = webpack({ context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }); compiler.outputFileSystem = new MemoryFs(); const watch = compiler.watch({}, err => { if (err) return done(err); expect(compiler.watchMode).toBeTruthy(); watch.close(() => { expect(compiler.watchMode).toBeFalsy(); done(); }); }); }); it("should use cache on second run call", function(done) { const compiler = webpack({ context: __dirname, mode: "development", devtool: false, entry: "./fixtures/count-loader!./fixtures/count-loader", output: { path: "/" } }); compiler.outputFileSystem = new MemoryFs(); compiler.run(() => { compiler.run(() => { const result = compiler.outputFileSystem.readFileSync( "/main.js", "utf-8" ); expect(result).toContain("module.exports = 0;"); done(); }); }); }); it("should call the failed-hook on error", done => { const failedSpy = jest.fn(); const compiler = webpack({ bail: true, context: __dirname, mode: "production", entry: "./missing", output: { path: "/", filename: "bundle.js" } }); compiler.hooks.failed.tap("CompilerTest", failedSpy); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { expect(err).toBeTruthy(); expect(failedSpy).toHaveBeenCalledTimes(1); expect(failedSpy).toHaveBeenCalledWith(err); done(); }); }); }); webpack-4.30.0/test/ConfigTestCases.test.js000066400000000000000000000205731345416772700205600ustar00rootroot00000000000000"use strict"; /* globals describe expect it */ const path = require("path"); const fs = require("fs"); const vm = require("vm"); const mkdirp = require("mkdirp"); const rimraf = require("rimraf"); const checkArrayExpectation = require("./checkArrayExpectation"); const createLazyTestEnv = require("./helpers/createLazyTestEnv"); const FakeDocument = require("./helpers/FakeDocument"); const Stats = require("../lib/Stats"); const webpack = require("../lib/webpack"); const prepareOptions = require("./helpers/prepareOptions"); describe("ConfigTestCases", () => { const casesPath = path.join(__dirname, "configCases"); let categories = fs.readdirSync(casesPath); jest.setTimeout(20000); categories = categories.map(cat => { return { name: cat, tests: fs .readdirSync(path.join(casesPath, cat)) .filter(folder => { return folder.indexOf("_") < 0; }) .sort() .filter(testName => { const testDirectory = path.join(casesPath, cat, testName); const filterPath = path.join(testDirectory, "test.filter.js"); if (fs.existsSync(filterPath) && !require(filterPath)()) { describe.skip(testName, () => it("filtered")); return false; } return true; }) }; }); categories.forEach(category => { describe(category.name, () => { category.tests.forEach(testName => { describe(testName, function() { const testDirectory = path.join(casesPath, category.name, testName); const outputDirectory = path.join( __dirname, "js", "config", category.name, testName ); it( testName + " should compile", () => new Promise((resolve, reject) => { const done = err => { if (err) return reject(err); resolve(); }; rimraf.sync(outputDirectory); mkdirp.sync(outputDirectory); const options = prepareOptions( require(path.join(testDirectory, "webpack.config.js")), { testPath: outputDirectory } ); const optionsArr = [].concat(options); optionsArr.forEach((options, idx) => { if (!options.context) options.context = testDirectory; if (!options.mode) options.mode = "production"; if (!options.optimization) options.optimization = {}; if (options.optimization.minimize === undefined) options.optimization.minimize = false; if (!options.entry) options.entry = "./index.js"; if (!options.target) options.target = "async-node"; if (!options.output) options.output = {}; if (!options.output.path) options.output.path = outputDirectory; if (typeof options.output.pathinfo === "undefined") options.output.pathinfo = true; if (!options.output.filename) options.output.filename = "bundle" + idx + ".js"; }); let testConfig = { findBundle: function(i, options) { const ext = path.extname(options.output.filename); if ( fs.existsSync( path.join(options.output.path, "bundle" + i + ext) ) ) { return "./bundle" + i + ext; } }, timeout: 30000 }; try { // try to load a test file testConfig = Object.assign( testConfig, require(path.join(testDirectory, "test.config.js")) ); } catch (e) { // ignored } if (testConfig.timeout) setDefaultTimeout(testConfig.timeout); webpack(options, (err, stats) => { if (err) { const fakeStats = { errors: [err.stack] }; if ( checkArrayExpectation( testDirectory, fakeStats, "error", "Error", done ) ) return; // Wait for uncaught errors to occur return setTimeout(done, 200); } const statOptions = Stats.presetToOptions("verbose"); statOptions.colors = false; mkdirp.sync(outputDirectory); fs.writeFileSync( path.join(outputDirectory, "stats.txt"), stats.toString(statOptions), "utf-8" ); const jsonStats = stats.toJson({ errorDetails: true }); if ( checkArrayExpectation( testDirectory, jsonStats, "error", "Error", done ) ) return; if ( checkArrayExpectation( testDirectory, jsonStats, "warning", "Warning", done ) ) return; const globalContext = { console: console, expect: expect, setTimeout: setTimeout, clearTimeout: clearTimeout, document: new FakeDocument(), location: { href: "https://test.cases/path/index.html", origin: "https://test.cases", toString() { return "https://test.cases/path/index.html"; } } }; function _require(currentDirectory, module) { if (Array.isArray(module) || /^\.\.?\//.test(module)) { let content; let p; if (Array.isArray(module)) { p = path.join(currentDirectory, module[0]); content = module .map(arg => { p = path.join(currentDirectory, arg); return fs.readFileSync(p, "utf-8"); }) .join("\n"); } else { p = path.join(currentDirectory, module); content = fs.readFileSync(p, "utf-8"); } const m = { exports: {} }; let runInNewContext = false; const moduleScope = { require: _require.bind(null, path.dirname(p)), module: m, exports: m.exports, __dirname: path.dirname(p), __filename: p, it: _it, beforeEach: _beforeEach, afterEach: _afterEach, expect, jest, _globalAssign: { expect }, nsObj: m => { Object.defineProperty(m, Symbol.toStringTag, { value: "Module" }); return m; } }; if ( options.target === "web" || options.target === "webworker" ) { moduleScope.window = globalContext; runInNewContext = true; } if (testConfig.moduleScope) { testConfig.moduleScope(moduleScope); } const args = Object.keys(moduleScope).join(", "); if (!runInNewContext) content = `Object.assign(global, _globalAssign); ${content}`; const code = `(function({${args}}) {${content}\n})`; const fn = runInNewContext ? vm.runInNewContext(code, globalContext, p) : vm.runInThisContext(code, p); fn.call(m.exports, moduleScope); return m.exports; } else if ( testConfig.modules && module in testConfig.modules ) { return testConfig.modules[module]; } else return require(module); } let filesCount = 0; if (testConfig.noTests) return process.nextTick(done); if (testConfig.beforeExecute) testConfig.beforeExecute(); for (let i = 0; i < optionsArr.length; i++) { const bundlePath = testConfig.findBundle(i, optionsArr[i]); if (bundlePath) { filesCount++; _require(outputDirectory, bundlePath); } } // give a free pass to compilation that generated an error if ( !jsonStats.errors.length && filesCount !== optionsArr.length ) return done( new Error( "Should have found at least one bundle file per webpack config" ) ); if (testConfig.afterExecute) testConfig.afterExecute(); if (getNumberOfTests() < filesCount) return done(new Error("No tests exported by test case")); done(); }); }) ); const { it: _it, beforeEach: _beforeEach, afterEach: _afterEach, setDefaultTimeout, getNumberOfTests } = createLazyTestEnv(jasmine.getEnv(), 10000); }); }); }); }); }); webpack-4.30.0/test/ContextModuleFactory.unittest.js000066400000000000000000000027741345416772700225610ustar00rootroot00000000000000/* globals describe, it, beforeEach */ "use strict"; const MemoryFs = require("memory-fs"); const ContextModuleFactory = require("../lib/ContextModuleFactory"); describe("ContextModuleFactory", () => { describe("resolveDependencies", () => { let factory, memfs; beforeEach(() => { factory = new ContextModuleFactory([]); memfs = new MemoryFs(); }); it("should not report an error when ENOENT errors happen", done => { memfs.readdir = (dir, callback) => { setTimeout(() => callback(null, ["/file"])); }; memfs.stat = (file, callback) => { let err = new Error("fake ENOENT error"); err.code = "ENOENT"; setTimeout(() => callback(err, null)); }; factory.resolveDependencies( memfs, { resource: "/", recursive: true, regExp: /.*/ }, (err, res) => { expect(err).toBeFalsy(); expect(Array.isArray(res)).toBe(true); expect(res.length).toBe(0); done(); } ); }); it("should report an error when non-ENOENT errors happen", done => { memfs.readdir = (dir, callback) => { setTimeout(() => callback(null, ["/file"])); }; memfs.stat = (file, callback) => { let err = new Error("fake EACCES error"); err.code = "EACCES"; setTimeout(() => callback(err, null)); }; factory.resolveDependencies( memfs, { resource: "/", recursive: true, regExp: /.*/ }, (err, res) => { expect(err).toBeInstanceOf(Error); expect(res).toBeFalsy(); done(); } ); }); }); }); webpack-4.30.0/test/DelegatedModule.unittest.js000066400000000000000000000015211345416772700214500ustar00rootroot00000000000000/* globals describe, it, beforeEach */ "use strict"; const DelegatedModule = require("../lib/DelegatedModule"); describe("DelegatedModule", () => { describe("#updateHash", () => { const sourceRequest = "dll-reference dll_e54c0fb67f8152792ad2"; const data = { id: "/xg9" }; const type = "require"; const userRequest = "./library.js"; let hashedText; let hash; beforeEach(() => { hashedText = ""; hash = { update: text => { hashedText += text; } }; const delegatedModule = new DelegatedModule( sourceRequest, data, type, userRequest ); delegatedModule.updateHash(hash); }); it("updates hash with delegated module ID", () => { expect(hashedText).toMatch("/xg9"); }); it("updates hash with delegation type", () => { expect(hashedText).toMatch("require"); }); }); }); webpack-4.30.0/test/Dependencies.lint.js000066400000000000000000000013721345416772700201050ustar00rootroot00000000000000const fs = require("fs"); const path = require("path"); const lockfile = require("@yarnpkg/lockfile"); const file = fs.readFileSync(path.resolve(__dirname, "../yarn.lock"), "utf-8"); const result = lockfile.parse(file); describe("Dependencies", () => { it("should parse fine", () => { expect(result.type).toBe("success"); }); if (result.type === "success") { const content = result.object; for (const dep of Object.keys(content)) { describe(dep, () => { const info = content[dep]; it("should resolve to a npm package", () => { expect(info.resolved).toMatch(/^https:\/\/registry\.yarnpkg\.com\//); }); it("should have a integrity hash", () => { expect(info.integrity).toMatch(/^(sha1|sha512)-/); }); }); } } }); webpack-4.30.0/test/Errors.test.js000066400000000000000000000244641345416772700170130ustar00rootroot00000000000000"use strict"; /*globals describe it */ const path = require("path"); const webpack = require("../lib/webpack"); const base = path.join(__dirname, "fixtures", "errors"); describe("Errors", () => { jest.setTimeout(20000); function customOutputFilesystem(c) { const files = {}; c.outputFileSystem = { join: path.join.bind(path), mkdirp(path, callback) { callback(); }, writeFile(name, content, callback) { files[name] = content.toString("utf-8"); callback(); } }; return files; } function getErrors(options, callback) { options.context = base; const c = webpack(options); customOutputFilesystem(c); c.run((err, stats) => { if (err) throw err; expect(typeof stats).toBe("object"); stats = stats.toJson({ errorDetails: false }); expect(typeof stats).toBe("object"); expect(stats).toHaveProperty("errors"); expect(stats).toHaveProperty("warnings"); expect(Array.isArray(stats.errors)).toBe(true); expect(Array.isArray(stats.warnings)).toBe(true); callback(stats.errors, stats.warnings); }); } function getErrorsPromise(options, callback) { return new Promise((resolve, reject) => { getErrors(options, (errors, warnings) => { callback(errors, warnings); resolve(); }); }); } it("should throw an error if file doesn't exist", done => { getErrors( { mode: "development", entry: "./missingFile" }, (errors, warnings) => { expect(errors).toHaveLength(2); expect(warnings).toHaveLength(0); errors.sort(); let lines = errors[0].split("\n"); expect(lines[0]).toMatch(/missingFile.js/); expect(lines[1]).toMatch(/^Module not found/); expect(lines[1]).toMatch(/\.\/dir\/missing2/); expect(lines[2]).toMatch(/missingFile.js 12:9/); lines = errors[1].split("\n"); expect(lines[0]).toMatch(/missingFile.js/); expect(lines[1]).toMatch(/^Module not found/); expect(lines[1]).toMatch(/\.\/missing/); expect(lines[2]).toMatch(/missingFile.js 4:0/); done(); } ); }); it("should report require.extensions as unsupported", done => { getErrors( { mode: "development", entry: "./require.extensions" }, (errors, warnings) => { expect(errors).toHaveLength(0); expect(warnings).toHaveLength(1); const lines = warnings[0].split("\n"); expect(lines[0]).toMatch(/require.extensions\.js/); expect(lines[1]).toMatch( /require.extensions is not supported by webpack/ ); done(); } ); }); it("should report require.main.require as unsupported", done => { getErrors( { mode: "development", entry: "./require.main.require" }, (errors, warnings) => { expect(errors).toHaveLength(0); expect(warnings).toHaveLength(1); const lines = warnings[0].split("\n"); expect(lines[0]).toMatch(/require.main.require\.js/); expect(lines[1]).toMatch( /require.main.require is not supported by webpack/ ); done(); } ); }); it("should report module.parent.require as unsupported", done => { getErrors( { mode: "development", entry: "./module.parent.require" }, (errors, warnings) => { expect(errors).toHaveLength(0); expect(warnings).toHaveLength(1); const lines = warnings[0].split("\n"); expect(lines[0]).toMatch(/module.parent.require\.js/); expect(lines[1]).toMatch( /module.parent.require is not supported by webpack/ ); done(); } ); }); it("should warn about case-sensitive module names", done => { getErrors( { mode: "development", entry: "./case-sensitive" }, (errors, warnings) => { if (errors.length === 0) { expect(warnings).toHaveLength(1); const lines = warnings[0].split("\n"); expect(lines[4]).toMatch(/FILE\.js/); expect(lines[5]).toMatch(/Used by/); expect(lines[6]).toMatch(/case-sensitive/); expect(lines[7]).toMatch(/file\.js/); expect(lines[8]).toMatch(/Used by/); expect(lines[9]).toMatch(/case-sensitive/); } else { expect(errors).toHaveLength(1); expect(warnings).toHaveLength(0); } done(); } ); }); it("should warn when not using mode", done => { getErrors( { entry: "./entry-point" }, (errors, warnings) => { expect(errors).toHaveLength(0); expect(warnings).toHaveLength(1); let lines = warnings[0].split("\n"); expect(lines[0]).toMatch(/configuration/); expect(lines[1]).toMatch(/mode/); expect(lines[1]).toMatch(/development/); expect(lines[1]).toMatch(/production/); done(); } ); }); it("should not warn if the NoEmitOnErrorsPlugin is used over the NoErrorsPlugin", done => { getErrors( { mode: "production", entry: "./no-errors-deprecate" }, (errors, warnings) => { expect(errors).toHaveLength(0); expect(warnings).toHaveLength(0); done(); } ); }); it("should not not emit if NoEmitOnErrorsPlugin is used and there is an error", done => { getErrors( { mode: "production", entry: "./missingFile" }, (errors, warnings) => { expect(errors).toHaveLength(2); expect(warnings).toHaveLength(0); errors.sort(); let lines = errors[0].split("\n"); expect(lines[0]).toMatch(/missingFile.js/); expect(lines[1]).toMatch(/^Module not found/); expect(lines[1]).toMatch(/\.\/dir\/missing2/); expect(lines[2]).toMatch(/missingFile.js 12:9/); lines = errors[1].split("\n"); expect(lines[0]).toMatch(/missingFile.js/); expect(lines[1]).toMatch(/^Module not found/); expect(lines[1]).toMatch(/\.\/missing/); expect(lines[2]).toMatch(/missingFile.js 4:0/); done(); } ); }); it("should throw an error when trying to use [chunkhash] when it's invalid", done => { getErrors( { mode: "development", entry: { a: "./entry-point", b: "./entry-point", c: "./entry-point" }, output: { filename: "[chunkhash].js" }, plugins: [new webpack.HotModuleReplacementPlugin()] }, (errors, warnings) => { expect(errors).toHaveLength(3); expect(warnings).toHaveLength(0); errors.forEach(error => { const lines = error.split("\n"); expect(lines[0]).toMatch(/chunk (a|b|c)/); expect(lines[2]).toMatch(/\[chunkhash\].js/); expect(lines[2]).toMatch(/use \[hash\] instead/); }); done(); } ); }); it("should show loader name when emit/throw errors or warnings from loaders", () => { return Promise.all([ getErrorsPromise( { mode: "development", entry: "./entry-point-error-loader-required.js" }, (errors, warnings) => { expect(warnings).toHaveLength(1); expect(warnings[0].split("\n")[1]).toMatch( /^Module Warning \(from .\/emit-error-loader.js\):$/ ); expect(errors).toHaveLength(1); expect(errors[0].split("\n")[1]).toMatch( /^Module Error \(from .\/emit-error-loader.js\):$/ ); } ), getErrorsPromise( { mode: "development", entry: path.resolve(base, "./emit-error-loader") + "!./entry-point.js" }, (errors, warnings) => { expect(warnings).toHaveLength(1); expect(warnings[0].split("\n")[1]).toMatch( /^Module Warning \(from .\/emit-error-loader.js\):$/ ); expect(errors).toHaveLength(1); expect(errors[0].split("\n")[1]).toMatch( /^Module Error \(from .\/emit-error-loader.js\):$/ ); } ), getErrorsPromise( { mode: "development", entry: "./not-a-json.js", module: { rules: [ { test: /not-a-json\.js$/, use: [ "json-loader", { loader: path.resolve(base, "./emit-error-loader") } ] } ] } }, (errors, warnings) => { expect(warnings).toHaveLength(1); expect(warnings[0].split("\n")[1]).toMatch( /^Module Warning \(from .\/emit-error-loader.js\):$/ ); expect(errors).toHaveLength(2); expect(errors[0].split("\n")[1]).toMatch( /^Module Error \(from .\/emit-error-loader.js\):$/ ); expect(errors[1].split("\n")[1]).toMatch( /^Module build failed \(from \(webpack\)\/node_modules\/json-loader\/index.js\):$/ ); } ), getErrorsPromise( { mode: "development", entry: "./entry-point.js", module: { rules: [ { test: /entry-point\.js$/, use: path.resolve(base, "./async-error-loader") } ] } }, (errors, warnings) => { expect(errors).toHaveLength(1); expect(errors[0].split("\n")[1]).toMatch( /^Module build failed \(from .\/async-error-loader.js\):$/ ); } ), getErrorsPromise( { mode: "development", entry: "./entry-point.js", module: { rules: [ { test: /entry-point\.js$/, use: path.resolve(base, "./throw-error-loader") } ] } }, (errors, warnings) => { expect(errors).toHaveLength(1); expect(errors[0].split("\n")[1]).toMatch( /^Module build failed \(from .\/throw-error-loader.js\):$/ ); } ), getErrorsPromise( { mode: "development", entry: "./entry-point.js", module: { rules: [ { test: /entry-point\.js$/, use: path.resolve(base, "./irregular-error-loader") } ] } }, (errors, warnings) => { expect(warnings).toHaveLength(2); expect(warnings[0].split("\n")[1]).toMatch( /^Module Warning \(from .\/irregular-error-loader.js\):$/ ); expect(warnings[1].split("\n")[1]).toMatch( /^Module Warning \(from .\/irregular-error-loader.js\):$/ ); expect(errors).toHaveLength(3); expect(errors[0].split("\n")[1]).toMatch( /^Module Error \(from .\/irregular-error-loader.js\):$/ ); expect(errors[1].split("\n")[1]).toMatch( /^Module Error \(from .\/irregular-error-loader.js\):$/ ); expect(errors[2].split("\n")[1]).toMatch( /^Module build failed \(from .\/irregular-error-loader.js\):$/ ); } ) ]); }); it("should throw a build error if no source be returned after run loaders", done => { getErrors( { mode: "development", entry: path.resolve(base, "./no-return-loader") + "!./entry-point.js" }, (errors, warnings) => { expect(errors).toHaveLength(1); const messages = errors[0].split("\n"); expect(messages[1]).toMatch( /^Module build failed: Error: Final loader \(.+\) didn't return a Buffer or String/ ); done(); } ); }); }); webpack-4.30.0/test/Examples.test.js000066400000000000000000000034461345416772700173120ustar00rootroot00000000000000"use strict"; /* globals describe it */ const path = require("path"); const fs = require("fs"); const webpack = require("../"); describe("Examples", () => { const basePath = path.join(__dirname, "..", "examples"); const examples = require("../examples/examples.js"); examples.forEach(examplePath => { const filterPath = path.join(examplePath, "test.filter.js"); const relativePath = path.relative(basePath, examplePath); if (fs.existsSync(filterPath) && !require(filterPath)()) { describe.skip(relativePath, () => it("filtered")); return; } it( "should compile " + relativePath, function(done) { let options = {}; let webpackConfigPath = path.join(examplePath, "webpack.config.js"); webpackConfigPath = webpackConfigPath.substr(0, 1).toUpperCase() + webpackConfigPath.substr(1); if (fs.existsSync(webpackConfigPath)) options = require(webpackConfigPath); if (Array.isArray(options)) options.forEach(processOptions); else processOptions(options); function processOptions(options) { options.context = examplePath; options.output = options.output || {}; options.output.pathinfo = true; options.output.path = path.join(examplePath, "dist"); options.output.publicPath = "dist/"; if (!options.entry) options.entry = "./example.js"; if (!options.plugins) options.plugins = []; // To support deprecated loaders // TODO remove in webpack 5 options.plugins.push( new webpack.LoaderOptionsPlugin({ options: {} }) ); } webpack(options, (err, stats) => { if (err) return done(err); stats = stats.toJson({ errorDetails: true }); if (stats.errors.length > 0) { return done(new Error(stats.errors[0])); } done(); }); }, 45000 ); }); }); webpack-4.30.0/test/HarmonyExportImportedSpecifierDependency.unittest.js000066400000000000000000000010201345416772700265720ustar00rootroot00000000000000/* globals describe it */ "use strict"; const HarmonyExportImportedSpecifierDependency = require("../lib/dependencies/HarmonyExportImportedSpecifierDependency"); describe("HarmonyExportImportedSpecifierDependency", () => { describe("getHashValue", () => { it("should return empty string on missing module", () => { // see e.g. PR #4368 var instance = new HarmonyExportImportedSpecifierDependency(); expect(instance.getHashValue(undefined)).toBe(""); expect(instance.getHashValue(null)).toBe(""); }); }); }); webpack-4.30.0/test/HotModuleReplacementPlugin.test.js000066400000000000000000000112331345416772700227640ustar00rootroot00000000000000"use strict"; const path = require("path"); const fs = require("fs"); const mkdirp = require("mkdirp"); const webpack = require("../"); describe("HotModuleReplacementPlugin", () => { jest.setTimeout(20000); it("should not have circular hashes but equal if unmodified", done => { const entryFile = path.join( __dirname, "js", "HotModuleReplacementPlugin", "entry.js" ); const statsFile1 = path.join( __dirname, "js", "HotModuleReplacementPlugin", "HotModuleReplacementPlugin.test.stats1.txt" ); const statsFile2 = path.join( __dirname, "js", "HotModuleReplacementPlugin", "HotModuleReplacementPlugin.test.stats2.txt" ); const recordsFile = path.join( __dirname, "js", "HotModuleReplacementPlugin", "records.json" ); try { mkdirp.sync(path.join(__dirname, "js", "HotModuleReplacementPlugin")); } catch (e) { // empty } try { fs.unlinkSync(recordsFile); } catch (e) { // empty } const compiler = webpack({ cache: false, entry: entryFile, recordsPath: recordsFile, output: { path: path.join(__dirname, "js", "HotModuleReplacementPlugin") }, plugins: [new webpack.HotModuleReplacementPlugin()], optimization: { moduleIds: "size", chunkIds: "size" } }); fs.writeFileSync(entryFile, "1", "utf-8"); compiler.run((err, stats) => { if (err) throw err; const oldHash1 = stats.toJson().hash; fs.writeFileSync(statsFile1, stats.toString()); compiler.run((err, stats) => { if (err) throw err; const lastHash1 = stats.toJson().hash; fs.writeFileSync(statsFile2, stats.toString()); expect(lastHash1).toBe(oldHash1); // hash shouldn't change when bundle stay equal fs.writeFileSync(entryFile, "2", "utf-8"); compiler.run((err, stats) => { if (err) throw err; const lastHash2 = stats.toJson().hash; fs.writeFileSync(statsFile1, stats.toString()); expect(lastHash2).not.toBe(lastHash1); // hash should change when bundle changes fs.writeFileSync(entryFile, "1", "utf-8"); compiler.run((err, stats) => { if (err) throw err; const currentHash1 = stats.toJson().hash; fs.writeFileSync(statsFile2, stats.toString()); expect(currentHash1).not.toBe(lastHash1); // hash shouldn't change to the first hash if bundle changed back to first bundle fs.writeFileSync(entryFile, "2", "utf-8"); compiler.run((err, stats) => { if (err) throw err; const currentHash2 = stats.toJson().hash; fs.writeFileSync(statsFile1, stats.toString()); compiler.run((err, stats) => { if (err) throw err; expect(stats.toJson().hash).toBe(currentHash2); expect(currentHash2).not.toBe(lastHash2); expect(currentHash1).not.toBe(currentHash2); expect(lastHash1).not.toBe(lastHash2); done(); }); }); }); }); }); }); }); it("should correct working when entry is Object and key is a number", done => { const entryFile = path.join( __dirname, "js", "HotModuleReplacementPlugin", "entry.js" ); const statsFile3 = path.join( __dirname, "js", "HotModuleReplacementPlugin", "HotModuleReplacementPlugin.test.stats3.txt" ); const statsFile4 = path.join( __dirname, "js", "HotModuleReplacementPlugin", "HotModuleReplacementPlugin.test.stats4.txt" ); const recordsFile = path.join( __dirname, "js", "HotModuleReplacementPlugin", "records.json" ); try { mkdirp.sync(path.join(__dirname, "js", "HotModuleReplacementPlugin")); } catch (e) { // empty } try { fs.unlinkSync(recordsFile); } catch (e) { // empty } const compiler = webpack({ mode: "development", cache: false, entry: { "0": entryFile }, recordsPath: recordsFile, output: { path: path.join(__dirname, "js", "HotModuleReplacementPlugin") }, plugins: [new webpack.HotModuleReplacementPlugin()], optimization: { namedChunks: true } }); fs.writeFileSync(entryFile, "1", "utf-8"); compiler.run((err, stats) => { if (err) throw err; const jsonStats = stats.toJson(); const hash = jsonStats.hash; const trunkName = Object.keys(jsonStats.assetsByChunkName)[0]; fs.writeFileSync(statsFile3, stats.toString()); compiler.run((err, stats) => { if (err) throw err; fs.writeFileSync(statsFile4, stats.toString()); fs.writeFileSync(entryFile, "2", "utf-8"); compiler.run((err, stats) => { if (err) throw err; fs.writeFileSync(statsFile3, stats.toString()); const result = JSON.parse( stats.compilation.assets[`${hash}.hot-update.json`].source() )["c"][`${trunkName}`]; expect(result).toBe(true); done(); }); }); }); }); }); webpack-4.30.0/test/HotTestCases.test.js000066400000000000000000000124071345416772700201020ustar00rootroot00000000000000"use strict"; /* globals expect */ const path = require("path"); const fs = require("fs"); const vm = require("vm"); const checkArrayExpectation = require("./checkArrayExpectation"); const createLazyTestEnv = require("./helpers/createLazyTestEnv"); const webpack = require("../lib/webpack"); describe("HotTestCases", () => { const casesPath = path.join(__dirname, "hotCases"); let categories = fs .readdirSync(casesPath) .filter(dir => fs.statSync(path.join(casesPath, dir)).isDirectory()); categories = categories.map(cat => { return { name: cat, tests: fs .readdirSync(path.join(casesPath, cat)) .filter(folder => folder.indexOf("_") < 0) }; }); categories.forEach(category => { describe(category.name, () => { category.tests.forEach(testName => { describe(testName, () => { it( testName + " should compile", done => { const testDirectory = path.join( casesPath, category.name, testName ); const outputDirectory = path.join( __dirname, "js", "hot-cases", category.name, testName ); const recordsPath = path.join(outputDirectory, "records.json"); if (fs.existsSync(recordsPath)) fs.unlinkSync(recordsPath); const fakeUpdateLoaderOptions = { updateIndex: 0 }; const configPath = path.join(testDirectory, "webpack.config.js"); let options = {}; if (fs.existsSync(configPath)) options = require(configPath); if (!options.mode) options.mode = "development"; if (!options.devtool) options.devtool = false; if (!options.context) options.context = testDirectory; if (!options.entry) options.entry = "./index.js"; if (!options.output) options.output = {}; if (!options.output.path) options.output.path = outputDirectory; if (!options.output.filename) options.output.filename = "bundle.js"; if (options.output.pathinfo === undefined) options.output.pathinfo = true; if (!options.module) options.module = {}; if (!options.module.rules) options.module.rules = []; options.module.rules.push({ loader: path.join( __dirname, "hotCases", "fake-update-loader.js" ), enforce: "pre" }); if (!options.target) options.target = "async-node"; if (!options.plugins) options.plugins = []; options.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new webpack.LoaderOptionsPlugin(fakeUpdateLoaderOptions) ); if (!options.recordsPath) options.recordsPath = recordsPath; const compiler = webpack(options); compiler.run((err, stats) => { if (err) return done(err); const jsonStats = stats.toJson({ errorDetails: true }); if ( checkArrayExpectation( testDirectory, jsonStats, "error", "Error", done ) ) { return; } if ( checkArrayExpectation( testDirectory, jsonStats, "warning", "Warning", done ) ) { return; } function _next(callback) { fakeUpdateLoaderOptions.updateIndex++; compiler.run((err, stats) => { if (err) return callback(err); const jsonStats = stats.toJson({ errorDetails: true }); if ( checkArrayExpectation( testDirectory, jsonStats, "error", "errors" + fakeUpdateLoaderOptions.updateIndex, "Error", callback ) ) { return; } if ( checkArrayExpectation( testDirectory, jsonStats, "warning", "warnings" + fakeUpdateLoaderOptions.updateIndex, "Warning", callback ) ) { return; } callback(null, jsonStats); }); } function _require(module) { if (module.substr(0, 2) === "./") { const p = path.join(outputDirectory, module); const fn = vm.runInThisContext( "(function(require, module, exports, __dirname, __filename, it, expect, NEXT, STATS) {" + "global.expect = expect;" + 'function nsObj(m) { Object.defineProperty(m, Symbol.toStringTag, { value: "Module" }); return m; }' + fs.readFileSync(p, "utf-8") + "\n})", p ); const m = { exports: {} }; fn.call( m.exports, _require, m, m.exports, outputDirectory, p, _it, expect, _next, jsonStats ); return m.exports; } else return require(module); } _require("./bundle.js"); if (getNumberOfTests() < 1) return done(new Error("No tests exported by test case")); done(); }); }, 10000 ); const { it: _it, getNumberOfTests } = createLazyTestEnv( jasmine.getEnv(), 10000 ); }); }); }); }); }); webpack-4.30.0/test/Integration.test.js000066400000000000000000000043261345416772700200150ustar00rootroot00000000000000"use strict"; const path = require("path"); const webpack = require("../lib/webpack"); describe("Integration", () => { jest.setTimeout(10000); it("should compile library1", done => { webpack( { mode: "production", entry: "library1", bail: true, context: path.join(__dirname, "browsertest"), output: { pathinfo: true, path: path.join(__dirname, "browsertest", "js"), filename: "library1.js", library: "library1" } }, (err, stats) => { if (err) throw err; expect(stats.hasErrors()).toBe(false); expect(stats.hasWarnings()).toBe(false); done(); } ); }); it("should compile library2", done => { webpack( { mode: "production", entry: "library2", context: path.join(__dirname, "browsertest"), output: { pathinfo: true, path: path.join(__dirname, "browsertest", "js"), filename: "library2.js", publicPath: "js/", library: "library2" }, bail: true, module: { rules: [ { test: /extra2\.js/, loader: "raw!extra!val?cacheable", enforce: "post" } ] }, amd: { fromOptions: true }, optimization: { minimize: false }, plugins: [ new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }), new webpack.DefinePlugin({ "typeof CONST_TYPEOF": JSON.stringify("typeof"), CONST_TRUE: true, CONST_FALSE: false, CONST_FUNCTION: function() { return "ok"; }, CONST_NUMBER: 123, CONST_NUMBER_EXPR: "1*100+23", CONST_OBJECT: { A: 1, B: JSON.stringify("B"), C: function() { return "C"; } } }), function() { this.hooks.normalModuleFactory.tap("IntegrationTest", nmf => { nmf.hooks.afterResolve.tapAsync( "IntegrationTest", (data, callback) => { data.resource = data.resource.replace( /extra\.js/, "extra2.js" ); setTimeout(() => callback(null, data), 50); } ); }); } ] }, (err, stats) => { if (err) throw err; expect(stats.hasErrors()).toBe(false); expect(stats.hasWarnings()).toBe(false); done(); } ); }); }); webpack-4.30.0/test/LocalModulesHelpers.unittest.js000066400000000000000000000025251345416772700223370ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const LocalModulesHelpers = require("../lib/dependencies/LocalModulesHelpers"); describe("LocalModulesHelpers", () => { describe("addLocalModule", () => { it("returns a module var without special characters", () => { const state = { module: "module_sample", localModules: ["first", "second"] }; const localModule = LocalModulesHelpers.addLocalModule( state, "local_module_sample" ); expect(localModule).toBeInstanceOf(Object); expect(localModule).toMatchObject({ module: "module_sample", name: "local_module_sample", idx: 2, used: false }); expect(state.localModules.length).toBe(3); }); }); describe("getLocalModule", () => { it("returns `null` if names information doesn't match", () => { const state = { module: "module_sample", localModules: [ { name: "first" }, { name: "second" } ] }; expect( LocalModulesHelpers.getLocalModule(state, "local_module_sample") ).toBe(null); }); it("returns local module information", () => { const state = { module: "module_sample", localModules: [ { name: "first" }, { name: "second" } ] }; expect(LocalModulesHelpers.getLocalModule(state, "first")).toEqual({ name: "first" }); }); }); }); webpack-4.30.0/test/ModuleDependencyError.unittest.js000066400000000000000000000023361345416772700226670ustar00rootroot00000000000000"use strict"; const path = require("path"); const ModuleDependencyError = require("../lib/ModuleDependencyError"); describe("ModuleDependencyError", () => { let env; beforeEach(() => { env = {}; }); describe("when new error created", () => { beforeEach(() => { env.error = new Error("Error Message"); env.moduleDependencyError = new ModuleDependencyError( "myModule", env.error, "Location" ); }); it("is an error", () => { expect(env.moduleDependencyError).toBeInstanceOf(Error); }); it("has a name property", () => { expect(env.moduleDependencyError.name).toBe("ModuleDependencyError"); }); it("has a message property", () => { expect(env.moduleDependencyError.message).toBe("Error Message"); }); it("has a loc property", () => { expect(env.moduleDependencyError.loc).toBe("Location"); }); it("has a details property", () => { expect(env.moduleDependencyError.details).toMatch( path.join("test", "ModuleDependencyError.unittest.js:") ); }); it("has an module property", () => { expect(env.moduleDependencyError.module).toBe("myModule"); }); it("has an error property", () => { expect(env.moduleDependencyError.error).toBe(env.error); }); }); }); webpack-4.30.0/test/ModuleReason.unittest.js000066400000000000000000000034721345416772700210300ustar00rootroot00000000000000"use strict"; const Module = require("../lib/Module"); const Chunk = require("../lib/Chunk"); const Dependency = require("../lib/Dependency"); const ModuleReason = require("../lib/ModuleReason"); describe("ModuleReason", () => { let myModule; let myDependency; let myModuleReason; let myChunk; let myChunk2; beforeEach(() => { myModule = new Module(); myDependency = new Dependency(); myChunk = new Chunk("chunk-test", "module-test", "loc-test"); myChunk2 = new Chunk("chunk-test", "module-test", "loc-test"); myModuleReason = new ModuleReason(myModule, myDependency); }); describe("hasChunk", () => { it("returns false when chunk is not present", () => { expect(myModuleReason.hasChunk(myChunk)).toBe(false); }); it("returns true when chunk is present", () => { myModuleReason.module.addChunk(myChunk); expect(myModuleReason.hasChunk(myChunk)).toBe(true); }); }); describe("rewriteChunks", () => { it("if old chunk is present, it is replaced with new chunks", () => { myModuleReason.module.addChunk(myChunk); myModuleReason.rewriteChunks(myChunk, [myChunk2]); expect(myModuleReason.hasChunk(myChunk)).toBe(false); expect(myModuleReason.hasChunk(myChunk2)).toBe(true); }); it("if old chunk is not present, new chunks are not added", () => { myModuleReason.rewriteChunks(myChunk, [myChunk2]); expect(myModuleReason.hasChunk(myChunk)).toBe(false); expect(myModuleReason.hasChunk(myChunk2)).toBe(false); }); it("if already rewritten chunk is present, it is replaced with new chunks", () => { myModuleReason.module.addChunk(myChunk); myModuleReason.rewriteChunks(myChunk, [myChunk2]); myModuleReason.rewriteChunks(myChunk2, [myChunk]); expect(myModuleReason.hasChunk(myChunk)).toBe(true); expect(myModuleReason.hasChunk(myChunk2)).toBe(false); }); }); }); webpack-4.30.0/test/MultiCompiler.test.js000066400000000000000000000075451345416772700203250ustar00rootroot00000000000000"use strict"; /* globals describe it */ const path = require("path"); const MemoryFs = require("memory-fs"); const webpack = require("../"); const createMultiCompiler = () => { const compiler = webpack([ { context: path.join(__dirname, "fixtures"), entry: "./a.js" }, { context: path.join(__dirname, "fixtures"), entry: "./b.js" } ]); compiler.outputFileSystem = new MemoryFs(); return compiler; }; describe("MultiCompiler", function() { jest.setTimeout(20000); it("should trigger 'run' for each child compiler", done => { const compiler = createMultiCompiler(); let called = 0; compiler.hooks.run.tap("MultiCompiler test", () => called++); compiler.run(err => { if (err) { throw err; } else { expect(called).toBe(2); done(); } }); }); it("should trigger 'watchRun' for each child compiler", done => { const compiler = createMultiCompiler(); let called = 0; compiler.hooks.watchRun.tap("MultiCompiler test", () => called++); const watcher = compiler.watch(1000, err => { if (err) { throw err; } else { watcher.close(); expect(called).toBe(2); done(); } }); }); it("should not be run twice at a time (run)", function(done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); }); compiler.run((err, stats) => { if (err) return done(); }); }); it("should not be run twice at a time (watch)", function(done) { const compiler = createMultiCompiler(); const watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); }); compiler.watch({}, (err, stats) => { if (err) return watcher.close(done); }); }); it("should not be run twice at a time (run - watch)", function(done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); }); compiler.watch({}, (err, stats) => { if (err) return done(); }); }); it("should not be run twice at a time (watch - run)", function(done) { const compiler = createMultiCompiler(); let watcher; watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); }); compiler.run((err, stats) => { if (err) return watcher.close(done); }); }); it("should not be run twice at a time (instance cb)", function(done) { const compiler = webpack( { context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }, () => {} ); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(); }); }); it("should run again correctly after first compilation", function(done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); compiler.run((err, stats) => { if (err) return done(err); done(); }); }); }); it("should watch again correctly after first compilation", function(done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); let watcher; watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); watcher.close(done); }); }); }); it("should run again correctly after first closed watch", function(done) { const compiler = createMultiCompiler(); const watching = compiler.watch({}, (err, stats) => { if (err) return done(err); }); watching.close(() => { compiler.run((err, stats) => { if (err) return done(err); done(); }); }); }); it("should watch again correctly after first closed watch", function(done) { const compiler = createMultiCompiler(); const watching = compiler.watch({}, (err, stats) => { if (err) return done(err); }); watching.close(() => { let watcher; watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); watcher.close(done); }); }); }); }); webpack-4.30.0/test/MultiStats.unittest.js000066400000000000000000000124171345416772700205430ustar00rootroot00000000000000"use strict"; const packageJSON = require("../package.json"); const MultiStats = require("../lib/MultiStats"); const createStat = overrides => { return Object.assign( { hash: "foo", compilation: { name: "bar" }, hasErrors: () => false, hasWarnings: () => false, toJson: () => Object.assign( { hash: "foo", version: "version", warnings: [], errors: [] }, overrides ) }, overrides ); }; describe("MultiStats", () => { let packageVersion, stats, myMultiStats, result; beforeEach(() => { packageVersion = packageJSON.version; packageJSON.version = "1.2.3"; }); afterEach(() => { packageJSON.version = packageVersion; }); describe("created", () => { beforeEach(() => { stats = [ createStat({ hash: "abc123" }), createStat({ hash: "xyz890" }) ]; myMultiStats = new MultiStats(stats); }); it("creates a hash string", () => { expect(myMultiStats.hash).toBe("abc123xyz890"); }); }); describe("hasErrors", () => { describe("when both have errors", () => { beforeEach(() => { stats = [ createStat({ hasErrors: () => true }), createStat({ hasErrors: () => true }) ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => { expect(myMultiStats.hasErrors()).toBe(true); }); }); describe("when one has an error", () => { beforeEach(() => { stats = [ createStat({ hasErrors: () => true }), createStat() ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => { expect(myMultiStats.hasErrors()).toBe(true); }); }); describe("when none have errors", () => { beforeEach(() => { stats = [createStat(), createStat()]; myMultiStats = new MultiStats(stats); }); it("returns false", () => { expect(myMultiStats.hasErrors()).toBe(false); }); }); }); describe("hasWarnings", () => { describe("when both have warnings", () => { beforeEach(() => { stats = [ createStat({ hasWarnings: () => true }), createStat({ hasWarnings: () => true }) ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => { expect(myMultiStats.hasWarnings()).toBe(true); }); }); describe("when one has a warning", () => { beforeEach(() => { stats = [ createStat({ hasWarnings: () => true }), createStat() ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => { expect(myMultiStats.hasWarnings()).toBe(true); }); }); describe("when none have warnings", () => { beforeEach(() => { stats = [createStat(), createStat()]; myMultiStats = new MultiStats(stats); }); it("returns false", () => { expect(myMultiStats.hasWarnings()).toBe(false); }); }); }); describe("toJson", () => { beforeEach(() => { stats = [ createStat({ hash: "abc123", compilation: { name: "abc123-compilation" }, toJson: () => ({ warnings: ["abc123-warning"], errors: ["abc123-error"] }) }), createStat({ hash: "xyz890", compilation: { name: "xyz890-compilation" }, toJson: () => ({ warnings: ["xyz890-warning-1", "xyz890-warning-2"], errors: [] }) }) ]; }); it("returns plain object representation", () => { myMultiStats = new MultiStats(stats); result = myMultiStats.toJson({ version: false, hash: false }); expect(result).toEqual({ errors: ["(abc123-compilation) abc123-error"], warnings: [ "(abc123-compilation) abc123-warning", "(xyz890-compilation) xyz890-warning-1", "(xyz890-compilation) xyz890-warning-2" ], children: [ { errors: ["abc123-error"], name: "abc123-compilation", warnings: ["abc123-warning"] }, { errors: [], name: "xyz890-compilation", warnings: ["xyz890-warning-1", "xyz890-warning-2"] } ] }); }); it("returns plain object representation with json set to true", () => { myMultiStats = new MultiStats(stats); result = myMultiStats.toJson(true); expect(result).toEqual({ errors: ["(abc123-compilation) abc123-error"], warnings: [ "(abc123-compilation) abc123-warning", "(xyz890-compilation) xyz890-warning-1", "(xyz890-compilation) xyz890-warning-2" ], children: [ { warnings: ["abc123-warning"], errors: ["abc123-error"], name: "abc123-compilation" }, { warnings: ["xyz890-warning-1", "xyz890-warning-2"], errors: [], name: "xyz890-compilation" } ] }); }); }); describe("toString", () => { beforeEach(() => { stats = [ createStat({ hash: "abc123", compilation: { name: "abc123-compilation" } }), createStat({ hash: "xyz890", compilation: { name: "xyz890-compilation" } }) ]; myMultiStats = new MultiStats(stats); result = myMultiStats.toString(); }); it("returns string representation", () => { expect(result).toEqual( "Hash: abc123xyz890\n" + "Version: webpack 1.2.3\n" + "Child abc123-compilation:\n" + " Hash: abc123\n" + "Child xyz890-compilation:\n" + " Hash: xyz890" ); }); }); }); webpack-4.30.0/test/MultiWatching.unittest.js000066400000000000000000000030041345416772700212010ustar00rootroot00000000000000"use strict"; const Tapable = require("tapable").Tapable; const SyncHook = require("tapable").SyncHook; const MultiWatching = require("../lib/MultiWatching"); const createWatching = () => { return { invalidate: jest.fn(), close: jest.fn() }; }; const createCompiler = () => { const compiler = { hooks: { watchClose: new SyncHook([]) } }; Tapable.addCompatLayer(compiler); return compiler; }; describe("MultiWatching", () => { let watchings; let compiler; let myMultiWatching; beforeEach(() => { watchings = [createWatching(), createWatching()]; compiler = createCompiler(); myMultiWatching = new MultiWatching(watchings, compiler); }); describe("invalidate", () => { beforeEach(() => { myMultiWatching.invalidate(); }); it("invalidates each watching", () => { expect(watchings[0].invalidate.mock.calls.length).toBe(1); expect(watchings[1].invalidate.mock.calls.length).toBe(1); }); }); describe("close", () => { let callback; const callClosedFinishedCallback = watching => { watching.close.mock.calls[0][0](); }; beforeEach(() => { callback = jest.fn(); myMultiWatching.close(callback); }); it("closes each watching", () => { expect(watchings[0].close.mock.calls.length).toBe(1); expect(watchings[1].close.mock.calls.length).toBe(1); }); it("calls callback after each watching has closed", () => { callClosedFinishedCallback(watchings[0]); callClosedFinishedCallback(watchings[1]); expect(callback.mock.calls.length).toBe(1); }); }); }); webpack-4.30.0/test/NodeTemplatePlugin.test.js000066400000000000000000000043451345416772700212730ustar00rootroot00000000000000/* global describe, it */ "use strict"; const path = require("path"); const webpack = require("../lib/webpack"); describe("NodeTemplatePlugin", () => { jest.setTimeout(20000); it("should compile and run a simple module", done => { webpack( { mode: "production", context: path.join(__dirname, "fixtures", "nodetest"), target: "node", output: { path: path.join(__dirname, "js", "NodeTemplatePlugin"), filename: "result.js", chunkFilename: "[hash].result.[id].js", library: "abc", libraryTarget: "commonjs" }, entry: "./entry" }, (err, stats) => { if (err) return err; expect(stats.hasErrors()).toBe(false); expect(stats.hasWarnings()).toBe(false); // eslint-disable-next-line node/no-missing-require const result = require("./js/NodeTemplatePlugin/result").abc; expect(result.nextTick).toBe(process.nextTick); expect(result.fs).toBe(require("fs")); result.loadChunk(456, chunk => { expect(chunk).toBe(123); result.loadChunk(567, chunk => { expect(chunk).toEqual({ a: 1 }); done(); }); }); } ); }); it("should compile and run a simple module in single mode", done => { webpack( { mode: "production", context: path.join(__dirname, "fixtures", "nodetest"), target: "node", output: { path: path.join(__dirname, "js", "NodeTemplatePluginSingle"), filename: "result2.js", chunkFilename: "[hash].result2.[id].js", library: "def", libraryTarget: "umd", auxiliaryComment: "test" }, entry: "./entry", plugins: [ new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }) ] }, (err, stats) => { if (err) return err; expect(stats.hasErrors()).toBe(false); // eslint-disable-next-line node/no-missing-require const result = require("./js/NodeTemplatePluginSingle/result2"); expect(result.nextTick).toBe(process.nextTick); expect(result.fs).toBe(require("fs")); const sameTick = true; result.loadChunk(456, chunk => { expect(chunk).toBe(123); expect(sameTick).toBe(true); result.loadChunk(567, chunk => { expect(chunk).toEqual({ a: 1 }); done(); }); }); } ); }); }); webpack-4.30.0/test/NormalModule.unittest.js000066400000000000000000000254341345416772700210330ustar00rootroot00000000000000/* globals describe it beforeEach */ "use strict"; const NormalModule = require("../lib/NormalModule"); const NullDependency = require("../lib/dependencies/NullDependency"); const SourceMapSource = require("webpack-sources").SourceMapSource; const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; describe("NormalModule", () => { let normalModule; let request; let userRequest; let rawRequest; let loaders; let resource; let parser; beforeEach(() => { request = "/some/request"; userRequest = "/some/userRequest"; rawRequest = "some/rawRequest"; loaders = []; resource = "/some/resource"; parser = { parse() {} }; normalModule = new NormalModule({ type: "javascript/auto", request, userRequest, rawRequest, loaders, resource, parser, generator: null, resolveOptions: {} }); normalModule.buildInfo = { cacheable: true }; }); describe("#identifier", () => { it("returns an identifier for this module", () => { expect(normalModule.identifier()).toBe(request); }); it("returns an identifier from toString", () => { normalModule.debugId = 1000; expect(normalModule.toString()).toBe("Module[1000]"); normalModule.id = 1; expect(normalModule.toString()).toBe("Module[1]"); }); }); describe("#readableIdentifier", () => { it("calls the given requestShortener with the user request", () => { const spy = jest.fn(); normalModule.readableIdentifier({ shorten: spy }); expect(spy.mock.calls.length).toBe(1); expect(spy.mock.calls[0][0]).toBe(userRequest); }); }); describe("#libIdent", () => { it("contextifies the userRequest of the module", () => { expect( normalModule.libIdent({ context: "/some/context" }) ).toBe("../userRequest"); }); describe("given a userRequest containing loaders", () => { beforeEach(() => { userRequest = "/some/userRequest!/some/other/userRequest!/some/thing/is/off/here"; normalModule = new NormalModule({ type: "javascript/auto", request, userRequest, rawRequest, loaders, resource, parser }); }); it("contextifies every path in the userRequest", () => { expect( normalModule.libIdent({ context: "/some/context" }) ).toBe("../userRequest!../other/userRequest!../thing/is/off/here"); }); }); describe("given a userRequest containing query parameters", () => { it("ignores paths in query parameters", () => { userRequest = "F:\\some\\context\\loader?query=foo\\bar&otherPath=testpath/other"; normalModule = new NormalModule({ type: "javascript/auto", request, userRequest, rawRequest, loaders, resource, parser }); expect( normalModule.libIdent({ context: "F:\\some\\context" }) ).toBe("./loader?query=foo\\bar&otherPath=testpath/other"); }); }); }); describe("#nameForCondition", () => { it("return the resource", () => { expect(normalModule.nameForCondition()).toBe(resource); }); describe("given a resource containing a ?-sign", () => { const baseResource = "some/resource"; beforeEach(() => { resource = baseResource + "?some=query"; normalModule = new NormalModule({ type: "javascript/auto", request, userRequest, rawRequest, loaders, resource, parser }); }); it("return only the part before the ?-sign", () => { expect(normalModule.nameForCondition()).toBe(baseResource); }); }); }); describe("#createSourceForAsset", () => { let name; let content; let sourceMap; beforeEach(() => { name = "some name"; content = "some content"; sourceMap = "some sourcemap"; }); describe("given no sourcemap", () => { it("returns a RawSource", () => { expect(normalModule.createSourceForAsset(name, content)).toBeInstanceOf( RawSource ); }); }); describe("given a string as the sourcemap", () => { it("returns a OriginalSource", () => { expect( normalModule.createSourceForAsset(name, content, sourceMap) ).toBeInstanceOf(OriginalSource); }); }); describe("given a some other kind of sourcemap", () => { beforeEach(() => { sourceMap = () => {}; }); it("returns a SourceMapSource", () => { expect( normalModule.createSourceForAsset(name, content, sourceMap) ).toBeInstanceOf(SourceMapSource); }); }); }); describe("#originalSource", () => { let expectedSource = "some source"; beforeEach(() => { normalModule._source = new RawSource(expectedSource); }); it("returns an original Source", () => { expect(normalModule.originalSource()).toBe(normalModule._source); }); }); describe("#hasDependencies", () => { it("returns true if has dependencies", () => { normalModule.addDependency(new NullDependency()); expect(normalModule.hasDependencies()).toBe(true); }); it("returns false if has dependencies", () => { expect(normalModule.hasDependencies()).toBe(false); }); }); describe("#needRebuild", () => { let fileTimestamps; let contextTimestamps; let fileDependencies; let contextDependencies; let fileA; let fileB; function setDeps(fileDependencies, contextDependencies) { normalModule.buildInfo.fileDependencies = fileDependencies; normalModule.buildInfo.contextDependencies = contextDependencies; } beforeEach(() => { fileA = "fileA"; fileB = "fileB"; fileDependencies = [fileA, fileB]; contextDependencies = [fileA, fileB]; fileTimestamps = new Map([[fileA, 1], [fileB, 1]]); contextTimestamps = new Map([[fileA, 1], [fileB, 1]]); normalModule.buildTimestamp = 2; setDeps(fileDependencies, contextDependencies); }); describe("given all timestamps are older than the buildTimestamp", () => { it("returns false", () => { expect( normalModule.needRebuild(fileTimestamps, contextTimestamps) ).toBe(false); }); }); describe("given a file timestamp is newer than the buildTimestamp", () => { beforeEach(() => { fileTimestamps.set(fileA, 3); }); it("returns true", () => { expect( normalModule.needRebuild(fileTimestamps, contextTimestamps) ).toBe(true); }); }); describe("given a no file timestamp exists", () => { beforeEach(() => { fileTimestamps = new Map(); }); it("returns true", () => { expect( normalModule.needRebuild(fileTimestamps, contextTimestamps) ).toBe(true); }); }); describe("given a context timestamp is newer than the buildTimestamp", () => { beforeEach(() => { contextTimestamps.set(fileA, 3); }); it("returns true", () => { expect( normalModule.needRebuild(fileTimestamps, contextTimestamps) ).toBe(true); }); }); describe("given a no context timestamp exists", () => { beforeEach(() => { contextTimestamps = new Map(); }); it("returns true", () => { expect( normalModule.needRebuild(fileTimestamps, contextTimestamps) ).toBe(true); }); }); }); describe("#applyNoParseRule", () => { let rule; let content; describe("given a string as rule", () => { beforeEach(() => { rule = "some-rule"; }); describe("and the content starting with the string specified in rule", () => { beforeEach(() => { content = rule + "some-content"; }); it("returns true", () => { expect(normalModule.shouldPreventParsing(rule, content)).toBe(true); }); }); describe("and the content does not start with the string specified in rule", () => { beforeEach(() => { content = "some-content"; }); it("returns false", () => { expect(normalModule.shouldPreventParsing(rule, content)).toBe(false); }); }); }); describe("given a regex as rule", () => { beforeEach(() => { rule = /some-rule/; }); describe("and the content matches the rule", () => { beforeEach(() => { content = rule + "some-content"; }); it("returns true", () => { expect(normalModule.shouldPreventParsing(rule, content)).toBe(true); }); }); describe("and the content does not match the rule", () => { beforeEach(() => { content = "some-content"; }); it("returns false", () => { expect(normalModule.shouldPreventParsing(rule, content)).toBe(false); }); }); }); }); describe("#shouldPreventParsing", () => { let applyNoParseRuleSpy; beforeEach(() => { applyNoParseRuleSpy = jest.fn(); normalModule.applyNoParseRule = applyNoParseRuleSpy; }); describe("given no noParseRule", () => { it("returns false", () => { expect(normalModule.shouldPreventParsing()).toBe(false); expect(applyNoParseRuleSpy.mock.calls.length).toBe(0); }); }); describe("given a noParseRule", () => { let returnValOfSpy; beforeEach(() => { returnValOfSpy = true; applyNoParseRuleSpy.mockReturnValue(returnValOfSpy); }); describe("that is a string", () => { it("calls and returns whatever applyNoParseRule returns", () => { expect(normalModule.shouldPreventParsing("some rule")).toBe( returnValOfSpy ); expect(applyNoParseRuleSpy.mock.calls.length).toBe(1); }); }); describe("that is a regex", () => { it("calls and returns whatever applyNoParseRule returns", () => { expect(normalModule.shouldPreventParsing("some rule")).toBe( returnValOfSpy ); expect(applyNoParseRuleSpy.mock.calls.length).toBe(1); }); }); describe("that is an array", () => { describe("of strings and or regexs", () => { let someRules; beforeEach(() => { someRules = ["some rule", /some rule1/, "some rule2"]; }); describe("and none of them match", () => { beforeEach(() => { returnValOfSpy = false; applyNoParseRuleSpy.mockReturnValue(returnValOfSpy); }); it("returns false", () => { expect(normalModule.shouldPreventParsing(someRules)).toBe( returnValOfSpy ); expect(applyNoParseRuleSpy.mock.calls.length).toBe(3); }); }); describe("and the first of them matches", () => { beforeEach(() => { returnValOfSpy = true; applyNoParseRuleSpy.mockReturnValue(returnValOfSpy); }); it("returns true", () => { expect(normalModule.shouldPreventParsing(someRules)).toBe( returnValOfSpy ); expect(applyNoParseRuleSpy.mock.calls.length).toBe(1); }); }); describe("and the last of them matches", () => { beforeEach(() => { returnValOfSpy = true; applyNoParseRuleSpy.mockReturnValueOnce(false); applyNoParseRuleSpy.mockReturnValueOnce(false); applyNoParseRuleSpy.mockReturnValue(true); }); it("returns true", () => { expect(normalModule.shouldPreventParsing(someRules)).toBe( returnValOfSpy ); expect(applyNoParseRuleSpy.mock.calls.length).toBe(3); }); }); }); }); }); }); }); webpack-4.30.0/test/NullDependency.unittest.js000066400000000000000000000021311345416772700213330ustar00rootroot00000000000000"use strict"; const NullDependency = require("../lib/dependencies/NullDependency"); describe("NullDependency", () => { let env; beforeEach(() => (env = {})); it("is a function", () => { expect(NullDependency).toBeTypeOf("function"); }); describe("when created", () => { beforeEach(() => (env.nullDependency = new NullDependency())); it("has a null type", () => { expect(env.nullDependency.type).toBe("null"); }); it("has update hash function", () => { expect(env.nullDependency.updateHash).toBeTypeOf("function"); }); it("does not update hash", () => { const hash = { update: jest.fn() }; env.nullDependency.updateHash(hash); expect(hash.update).not.toHaveBeenCalled(); }); }); describe("Template", () => { it("is a function", () => { expect(NullDependency.Template).toBeTypeOf("function"); }); describe("when created", () => { beforeEach(() => { env.nullDependencyTemplate = new NullDependency.Template(); }); it("has apply function", () => { expect(env.nullDependencyTemplate.apply).toBeTypeOf("function"); }); }); }); }); webpack-4.30.0/test/Parser.unittest.js000066400000000000000000000426271345416772700176740ustar00rootroot00000000000000"use strict"; const Parser = require("../lib/Parser"); const BasicEvaluatedExpression = require("../lib/BasicEvaluatedExpression"); describe("Parser", () => { /* eslint-disable no-undef */ /* eslint-disable no-unused-vars */ /* eslint-disable no-inner-declarations */ const testCases = { "call ident": [ function() { abc("test"); }, { abc: ["test"] } ], "call member": [ function() { cde.abc("membertest"); }, { cdeabc: ["membertest"] } ], "call member using bracket notation": [ function() { cde["abc"]("membertest"); }, { cdeabc: ["membertest"] } ], "call inner member": [ function() { cde.ddd.abc("inner"); }, { cdedddabc: ["inner"] } ], "call inner member using bracket notation": [ function() { cde.ddd["abc"]("inner"); }, { cdedddabc: ["inner"] } ], expression: [ function() { fgh; }, { fgh: [""] } ], "expression sub": [ function() { fgh.sub; }, { fghsub: ["notry"] } ], "member expression": [ function() { test[memberExpr]; test[+memberExpr]; }, { expressions: ["memberExpr", "memberExpr"] } ], "in function definition": [ function() { (function(abc, cde, fgh) { abc("test"); cde.abc("test"); cde.ddd.abc("test"); fgh; fgh.sub; })(); }, {} ], "const definition": [ function() { let abc, cde, fgh; abc("test"); cde.abc("test"); cde.ddd.abc("test"); fgh; fgh.sub; }, {} ], "var definition": [ function() { var abc, cde, fgh; abc("test"); cde.abc("test"); cde.ddd.abc("test"); fgh; fgh.sub; }, {} ], "function definition": [ function() { function abc() {} function cde() {} function fgh() {} abc("test"); cde.abc("test"); cde.ddd.abc("test"); fgh; fgh.sub; }, {} ], "class definition": [ function() { class memberExpr { cde() { abc("cde"); } static fgh() { abc("fgh"); fgh(); } } }, { abc: ["cde", "fgh"], fgh: ["memberExpr"] } ], "in try": [ function() { try { fgh.sub; fgh; function test(ttt) { fgh.sub; fgh; } } catch (e) { fgh.sub; fgh; } }, { fghsub: ["try", "notry", "notry"], fgh: ["test", "test ttt", "test e"] } ], "renaming with const": [ function() { const xyz = abc; xyz("test"); }, { abc: ["test"] } ], "renaming with var": [ function() { var xyz = abc; xyz("test"); }, { abc: ["test"] } ], "renaming with assignment": [ function() { const xyz = abc; xyz("test"); }, { abc: ["test"] } ], "renaming with IIFE": [ function() { !(function(xyz) { xyz("test"); })(abc); }, { abc: ["test"] } ], "renaming arguments with IIFE (called)": [ function() { !function(xyz) { xyz("test"); }.call(fgh, abc); }, { abc: ["test"], fgh: [""] } ], "renaming this's properties with IIFE (called)": [ function() { !function() { this.sub; }.call(ijk); }, { ijksub: ["test"] } ], "renaming this's properties with nested IIFE (called)": [ function() { !function() { !function() { this.sub; }.call(this); }.call(ijk); }, { ijksub: ["test"] } ], "new Foo(...)": [ function() { new xyz("membertest"); }, { xyz: ["membertest"] } ], "spread calls/literals": [ function() { var xyz = [...abc("xyz"), cde]; Math.max(...fgh); }, { abc: ["xyz"], fgh: ["xyz"] } ] }; /* eslint-enable no-undef */ /* eslint-enable no-unused-vars */ /* eslint-enable no-inner-declarations */ Object.keys(testCases).forEach(name => { it("should parse " + name, () => { let source = testCases[name][0].toString(); source = source.substr(13, source.length - 14).trim(); const state = testCases[name][1]; const testParser = new Parser({}); testParser.hooks.canRename.tap("abc", "ParserTest", expr => true); testParser.hooks.canRename.tap("ijk", "ParserTest", expr => true); testParser.hooks.call.tap("abc", "ParserTest", expr => { if (!testParser.state.abc) testParser.state.abc = []; testParser.state.abc.push(testParser.parseString(expr.arguments[0])); return true; }); testParser.hooks.call.tap("cde.abc", "ParserTest", expr => { if (!testParser.state.cdeabc) testParser.state.cdeabc = []; testParser.state.cdeabc.push(testParser.parseString(expr.arguments[0])); return true; }); testParser.hooks.call.tap("cde.ddd.abc", "ParserTest", expr => { if (!testParser.state.cdedddabc) testParser.state.cdedddabc = []; testParser.state.cdedddabc.push( testParser.parseString(expr.arguments[0]) ); return true; }); testParser.hooks.expression.tap("fgh", "ParserTest", expr => { if (!testParser.state.fgh) testParser.state.fgh = []; testParser.state.fgh.push( Array.from(testParser.scope.definitions.asSet()).join(" ") ); return true; }); testParser.hooks.expression.tap("fgh.sub", "ParserTest", expr => { if (!testParser.state.fghsub) testParser.state.fghsub = []; testParser.state.fghsub.push(testParser.scope.inTry ? "try" : "notry"); return true; }); testParser.hooks.expression.tap("ijk.sub", "ParserTest", expr => { if (!testParser.state.ijksub) testParser.state.ijksub = []; testParser.state.ijksub.push("test"); return true; }); testParser.hooks.expression.tap("memberExpr", "ParserTest", expr => { if (!testParser.state.expressions) testParser.state.expressions = []; testParser.state.expressions.push(expr.name); return true; }); testParser.hooks.new.tap("xyz", "ParserTest", expr => { if (!testParser.state.xyz) testParser.state.xyz = []; testParser.state.xyz.push(testParser.parseString(expr.arguments[0])); return true; }); const actual = testParser.parse(source); expect(typeof actual).toBe("object"); expect(actual).toEqual(state); }); }); it("should parse comments", () => { const source = "//comment1\n/*comment2*/"; const state = [ { type: "Line", value: "comment1" }, { type: "Block", value: "comment2" } ]; const testParser = new Parser({}); testParser.hooks.program.tap("ParserTest", (ast, comments) => { if (!testParser.state.comments) testParser.state.comments = comments; return true; }); const actual = testParser.parse(source); expect(typeof actual).toBe("object"); expect(typeof actual.comments).toBe("object"); actual.comments.forEach((element, index) => { expect(typeof element.type).toBe("string"); expect(typeof element.value).toBe("string"); expect(element.type).toBe(state[index].type); expect(element.value).toBe(state[index].value); }); }); describe("expression evaluation", () => { function evaluateInParser(source) { const parser = new Parser(); parser.hooks.call.tap("test", "ParserTest", expr => { parser.state.result = parser.evaluateExpression(expr.arguments[0]); }); parser.hooks.evaluateIdentifier.tap("aString", "ParserTest", expr => new BasicEvaluatedExpression().setString("aString").setRange(expr.range) ); parser.hooks.evaluateIdentifier.tap("b.Number", "ParserTest", expr => new BasicEvaluatedExpression().setNumber(123).setRange(expr.range) ); return parser.parse("test(" + source + ");").result; } const testCases = { '"strrring"': "string=strrring", '"strr" + "ring"': "string=strrring", '"s" + ("trr" + "rin") + "g"': "string=strrring", "'S' + (\"strr\" + \"ring\") + 'y'": "string=Sstrrringy", "/abc/": "regExp=/abc/", "1": "number=1", "1 + 3": "number=4", "3 - 1": "number=2", "2 * 3": "number=6", "8 / 2": "number=4", "2 ** 3": "number=8", "12 & 5": "number=4", "12 | 5": "number=13", "12 ^ 5": "number=9", "9 >>> 2": "number=2", "9 >> 2": "number=2", "9 << 2": "number=36", "~3": "number=-4", "1 == 1": "bool=true", "1 === 1": "bool=true", "3 != 1": "bool=true", "3 !== 1": "bool=true", "3 == 1": "bool=false", "3 === 1": "bool=false", "1 != 1": "bool=false", "1 !== 1": "bool=false", "true === false": "bool=false", "false !== false": "bool=false", "true == true": "bool=true", "false != true": "bool=true", "!'a'": "bool=false", "!''": "bool=true", "'pre' + a": "wrapped=['pre' string=pre]+[null]", "a + 'post'": "wrapped=[null]+['post' string=post]", "'pre' + a + 'post'": "wrapped=['pre' string=pre]+['post' string=post]", "1 + a + 2": "", "1 + a + 'post'": "wrapped=[null]+['post' string=post]", "'' + 1 + a + 2": "wrapped=['' + 1 string=1]+[2 string=2]", "'' + 1 + a + 2 + 3": "wrapped=['' + 1 string=1]+[2 + 3 string=23]", "'' + 1 + a + (2 + 3)": "wrapped=['' + 1 string=1]+[2 + 3 string=5]", "'pre' + (1 + a) + (2 + 3)": "wrapped=['pre' string=pre]+[2 + 3 string=5]", "a ? 'o1' : 'o2'": "options=['o1' string=o1],['o2' string=o2]", "a ? 'o1' : b ? 'o2' : 'o3'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3]", "a ? (b ? 'o1' : 'o2') : 'o3'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3]", "a ? (b ? 'o1' : 'o2') : c ? 'o3' : 'o4'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3],['o4' string=o4]", "a ? 'o1' : b ? 'o2' : c ? 'o3' : 'o4'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3],['o4' string=o4]", "a ? 'o1' : b ? b : c ? 'o3' : c": "options=['o1' string=o1],[b],['o3' string=o3],[c]", "['i1', 'i2', 3, a, b ? 4 : 5]": "items=['i1' string=i1],['i2' string=i2],[3 number=3],[a],[b ? 4 : 5 options=[4 number=4],[5 number=5]]", "typeof 'str'": "string=string", "typeof aString": "string=string", "typeof b.Number": "string=number", "typeof b['Number']": "string=number", "typeof b[Number]": "", "b.Number": "number=123", "b['Number']": "number=123", "b[Number]": "", "'str'.concat()": "string=str", "'str'.concat('one')": "string=strone", "'str'.concat('one').concat('two')": "string=stronetwo", "'str'.concat('one').concat('two', 'three')": "string=stronetwothree", "'str'.concat('one', 'two')": "string=stronetwo", "'str'.concat('one', 'two').concat('three')": "string=stronetwothree", "'str'.concat('one', 'two').concat('three', 'four')": "string=stronetwothreefour", "'str'.concat('one', obj)": "wrapped=['str' string=str]+[null]", "'str'.concat('one', obj).concat()": "wrapped=['str' string=str]+[null]", "'str'.concat('one', obj, 'two')": "wrapped=['str' string=str]+['two' string=two]", "'str'.concat('one', obj, 'two').concat()": "wrapped=['str' string=str]+['two' string=two]", "'str'.concat('one', obj, 'two').concat('three')": "wrapped=['str' string=str]+['three' string=three]", "'str'.concat(obj)": "wrapped=['str' string=str]+[null]", "'str'.concat(obj).concat()": "wrapped=['str' string=str]+[null]", "'str'.concat(obj).concat('one', 'two')": "wrapped=['str' string=str]+['one', 'two' string=onetwo]", "'str'.concat(obj).concat(obj, 'one')": "wrapped=['str' string=str]+['one' string=one]", "'str'.concat(obj).concat(obj, 'one', 'two')": "wrapped=['str' string=str]+['one', 'two' string=onetwo]", "'str'.concat(obj).concat('one', obj, 'one')": "wrapped=['str' string=str]+['one' string=one]", "'str'.concat(obj).concat('one', obj, 'two', 'three')": "wrapped=['str' string=str]+['two', 'three' string=twothree]", "'str'.concat(obj, 'one')": "wrapped=['str' string=str]+['one' string=one]", "'str'.concat(obj, 'one').concat()": "wrapped=['str' string=str]+['one' string=one]", "'str'.concat(obj, 'one').concat('two', 'three')": "wrapped=['str' string=str]+['two', 'three' string=twothree]", "'str'.concat(obj, 'one').concat(obj, 'two', 'three')": "wrapped=['str' string=str]+['two', 'three' string=twothree]", "'str'.concat(obj, 'one').concat('two', obj, 'three')": "wrapped=['str' string=str]+['three' string=three]", "'str'.concat(obj, 'one').concat('two', obj, 'three', 'four')": "wrapped=['str' string=str]+['three', 'four' string=threefour]", "'str'.concat(obj, 'one', 'two')": "wrapped=['str' string=str]+['one', 'two' string=onetwo]", "'str'.concat(obj, 'one', 'two').concat()": "wrapped=['str' string=str]+['one', 'two' string=onetwo]", "'str'.concat(obj, 'one', 'two').concat('three', 'four')": "wrapped=['str' string=str]+['three', 'four' string=threefour]", "'str'.concat(obj, 'one', 'two').concat(obj, 'three', 'four')": "wrapped=['str' string=str]+['three', 'four' string=threefour]", "'str'.concat(obj, 'one', 'two').concat('three', obj, 'four')": "wrapped=['str' string=str]+['four' string=four]", "'str'.concat(obj, 'one', 'two').concat('three', obj, 'four', 'five')": "wrapped=['str' string=str]+['four', 'five' string=fourfive]", // eslint-disable-next-line no-template-curly-in-string "`start${obj}mid${obj2}end`": "template=[start string=start],[mid string=mid],[end string=end]", // eslint-disable-next-line no-template-curly-in-string "`start${'str'}mid${obj2}end`": // eslint-disable-next-line no-template-curly-in-string "template=[start${'str'}mid string=startstrmid],[end string=end]", "'abc'.substr(1)": "string=bc", "'abcdef'.substr(2, 3)": "string=cde", "'abcdef'.substring(2, 3)": "string=c", "'abcdef'.substring(2, 3, 4)": "", "'abc'[\"substr\"](1)": "string=bc", "'abc'[substr](1)": "", "'1,2+3'.split(/[,+]/)": "array=[1],[2],[3]", "'1,2+3'.split(expr)": "", "'a' + (expr + 'c')": "wrapped=['a' string=a]+['c' string=c]", "1 + 'a'": "string=1a", "'a' + 1": "string=a1", "'a' + expr + 1": "wrapped=['a' string=a]+[1 string=1]" }; Object.keys(testCases).forEach(key => { function evalExprToString(evalExpr) { if (!evalExpr) { return "null"; } else { const result = []; if (evalExpr.isString()) result.push("string=" + evalExpr.string); if (evalExpr.isNumber()) result.push("number=" + evalExpr.number); if (evalExpr.isBoolean()) result.push("bool=" + evalExpr.bool); if (evalExpr.isRegExp()) result.push("regExp=" + evalExpr.regExp); if (evalExpr.isConditional()) result.push( "options=[" + evalExpr.options.map(evalExprToString).join("],[") + "]" ); if (evalExpr.isArray()) result.push( "items=[" + evalExpr.items.map(evalExprToString).join("],[") + "]" ); if (evalExpr.isConstArray()) result.push("array=[" + evalExpr.array.join("],[") + "]"); if (evalExpr.isTemplateString()) result.push( "template=[" + evalExpr.quasis.map(evalExprToString).join("],[") + "]" ); if (evalExpr.isWrapped()) result.push( "wrapped=[" + evalExprToString(evalExpr.prefix) + "]+[" + evalExprToString(evalExpr.postfix) + "]" ); if (evalExpr.range) { const start = evalExpr.range[0] - 5; const end = evalExpr.range[1] - 5; return ( key.substr(start, end - start) + (result.length > 0 ? " " + result.join(" ") : "") ); } return result.join(" "); } } it("should eval " + key, () => { const evalExpr = evaluateInParser(key); expect(evalExprToString(evalExpr)).toBe( testCases[key] ? key + " " + testCases[key] : key ); }); }); }); describe("async/await support", () => { describe("should accept", () => { const cases = { "async function": "async function x() {}", "async arrow function": "async () => {}", "await expression": "async function x(y) { await y }", "await iteration": "async function f() { for await (x of xs); }" }; const parser = new Parser(); Object.keys(cases).forEach(name => { const expr = cases[name]; it(name, () => { const actual = parser.parse(expr); expect(typeof actual).toBe("object"); }); }); }); describe("should parse await", () => { const cases = { require: [ "async function x() { await require('y'); }", { param: "y" } ], import: [ "async function x() { const y = await import('z'); }", { param: "z" } ] }; const parser = new Parser(); parser.hooks.call.tap("require", "ParserTest", expr => { const param = parser.evaluateExpression(expr.arguments[0]); parser.state.param = param.string; }); parser.hooks.importCall.tap("ParserTest", expr => { const param = parser.evaluateExpression(expr.arguments[0]); parser.state.param = param.string; }); Object.keys(cases).forEach(name => { it(name, () => { const actual = parser.parse(cases[name][0]); expect(actual).toEqual(cases[name][1]); }); }); }); }); describe("object rest/spread support", () => { describe("should accept", () => { const cases = { "object spread": "({...obj})", "object rest": "({...obj} = foo)" }; Object.keys(cases).forEach(name => { const expr = cases[name]; it(name, () => { const actual = Parser.parse(expr); expect(typeof actual).toBe("object"); }); }); }); }); describe("optional catch binding support", () => { describe("should accept", () => { const cases = { "optional binding": "try {} catch {}" }; Object.keys(cases).forEach(name => { const expr = cases[name]; it(name, () => { const actual = Parser.parse(expr); expect(typeof actual).toBe("object"); }); }); }); }); }); webpack-4.30.0/test/ProfilingPlugin.test.js000066400000000000000000000014231345416772700206350ustar00rootroot00000000000000"use strict"; const path = require("path"); const fs = require("fs"); const webpack = require("../"); const rimraf = require("rimraf"); describe("Profiling Plugin", function() { jest.setTimeout(15000); it("should handle output path with folder creation", done => { const finalPath = "test/js/profilingPath/events.json"; const outputPath = path.join(__dirname, "/js/profilingPath"); rimraf(outputPath, () => { const compiler = webpack({ context: "/", entry: "./fixtures/a.js", plugins: [ new webpack.debug.ProfilingPlugin({ outputPath: finalPath }) ] }); compiler.run(err => { if (err) return done(err); if (!fs.existsSync(outputPath)) return done(new Error("Folder should be created.")); done(); }); }); }); }); webpack-4.30.0/test/ProfilingPlugin.unittest.js000066400000000000000000000022101345416772700215300ustar00rootroot00000000000000"use strict"; const ProfilingPlugin = require("../lib/debug/ProfilingPlugin"); describe("Profiling Plugin", () => { it("should persist the passed outpath", () => { const plugin = new ProfilingPlugin({ outputPath: "invest_in_doge_coin" }); expect(plugin.outputPath).toBe("invest_in_doge_coin"); }); it("should handle no options", () => { const plugin = new ProfilingPlugin(); expect(plugin.outputPath).toBe("events.json"); }); it("should handle when unable to require the inspector", () => { const profiler = new ProfilingPlugin.Profiler(); return profiler.startProfiling(); }); it("should handle when unable to start a profiling session", () => { const profiler = new ProfilingPlugin.Profiler({ Session() { throw new Error("Sean Larkin was here."); } }); return profiler.startProfiling(); }); it("handles sending a profiling message when no session", () => { const profiler = new ProfilingPlugin.Profiler(); return profiler.sendCommand("randy", "is a puppers"); }); it("handles destroying when no session", () => { const profiler = new ProfilingPlugin.Profiler(); return profiler.destroy(); }); }); webpack-4.30.0/test/ProgressPlugin.test.js000066400000000000000000000015021345416772700205060ustar00rootroot00000000000000"use strict"; const path = require("path"); const MemoryFs = require("memory-fs"); const webpack = require("../"); const createMultiCompiler = () => { const compiler = webpack([ { context: path.join(__dirname, "fixtures"), entry: "./a.js" }, { context: path.join(__dirname, "fixtures"), entry: "./b.js" } ]); compiler.outputFileSystem = new MemoryFs(); return compiler; }; describe("ProgressPlugin", function() { it("should not contain NaN as a percentage when it is applied to MultiCompiler", function(done) { const compiler = createMultiCompiler(); let percentage = 0; new webpack.ProgressPlugin((p, msg, ...args) => { percentage += p; }).apply(compiler); compiler.run(err => { if (err) { throw err; } else { expect(percentage).not.toBe(NaN); done(); } }); }); }); webpack-4.30.0/test/README.md000066400000000000000000000111771345416772700154770ustar00rootroot00000000000000# Welcome to the webpack test suite!!!! Every pull request that you submit to webpack (besides README and spelling corrections in comments) requires tests that are created. But don't give up hope!!! Although our tests may appear complex and overwhelming, once you become familiar with the test suite and structure, adding and creating tests will be fun and beneficial as you work inside the codebase! ❤ ## tl;dr Run all tests (this automatically runs the setup): ```sh yarn test ``` Run an individual suite: ```sh yarn jest ConfigTestCases ``` Watch mode: ```sh yarn jest --watch ConfigTestCases ``` See also: [Jest CLI docs](https://jestjs.io/docs/cli) ## Test suite overview We use Jest for our tests. For more information on Jest you can visit their [homepage](https://jestjs.io/)! ### Class Tests All test files can be found in *.test.js. There are many tests that simply test API's of a specific class/file (such as `Compiler`, `Errors`, Integration, `Parser`, `RuleSet`, Validation). If the feature you are contributing involves one of those classes, then best to start there to understand the structure. ### xCases In addition to Class specific tests, there are also directories that end in "Cases". The suites for these cases also have corresponding *.test.js files. #### cases (`TestCases.test.js`) 1 Cases are a set of general purpose tests that will run against a variety of permutations of webpack configurations. When you are making a general purpose change that doesn't require you to have a special configuration, you would likely add your tests here. Inside of the `./test/cases` directory you will find tests are broken into thematic sub directories. Take a moment to explore the different options. To add a new case, create a new directory inside of the top level test groups, and then add an `index.js` file (and any other supporting files). By default this file will be the entry point for the test suite and you can add your `it()`'s there. This will also become bundled so that node env support happens as well. #### configCases (`ConfigTestCases.test.js`) 1 If you are trying to solve a bug which is reproducible when x and y properties are used together in a config, then configCases is the place to be!!!! In addition to an `index.js`, these configCases require a `webpack.config.js` is located inside of your test suite. This will run this specific config through `webpack` just as you were building individually. They will use the same loading/bundling technique of your `it()` tests, however you now have a more specific config use cases that you can write even before you start coding. #### statsCases (`StatsTestCases.test.js`) Stats cases are similar to configCases except specifically focusing on the `expected` output of your stats. Instead of writing to the console, however the output of stats will be written to disk. By default, the "expected" outcome is a pain to write by hand so instead when statsCases are run, runner is checking output using jest's awesome snapshot functionality. Basically you don't need to write any expected behaviors your self. The assumption is that the stats output from your test code is what you expect. Please follow the approach described bellow: * write your test code in `statsCases/` folder by creating a separate folder for it, for example `statsCases/some-file-import-stats/index.js` ```javascript import("./someModule"); ``` * don't forget the `webpack.config.js` * run the test * jest will automatically add the output from your test code to `StatsTestCases.test.js.snap` and you can always check your results there * Next time test will run -> runner will compare results against your output written to snapshot previously You can read more about SnapShot testing [right here](https://jestjs.io/docs/snapshot-testing) ## Questions? Comments? If you are still nervous or don't quite understand, please submit an issue and tag us in it, and provide a relevant PR while working on! ## Footnotes 1 webpack's parser supports the use of ES2015 features like arrow functions, harmony exports, etc. However as a library we follow NodeJS's timeline for dropping older versions of node. Because of this we expect your tests on Travis to pass all the way back to NodeJS v0.12; Therefore if you would like specific tests that use these features to be ignored if they are not supported, then you should add a `test.filter.js` file. This allows you to import the syntax needed for that test, meanwhile ignoring it on node versions (during CI) that don't support it. webpack has a variety of helpful examples you can refer to if you are just starting out. See the `./helpers` folder to find a list of the versions. webpack-4.30.0/test/RawModule.unittest.js000066400000000000000000000047601345416772700203330ustar00rootroot00000000000000"use strict"; const RawModule = require("../lib/RawModule"); const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; const RequestShortener = require("../lib/RequestShortener"); const path = require("path"); const crypto = require("crypto"); describe("RawModule", () => { const source = "sourceStr attribute"; const identifier = "identifierStr attribute"; const readableIdentifier = "readableIdentifierStr attribute"; const myRawModule = new RawModule(source, identifier, readableIdentifier); describe("identifier", () => { it("returns value for identifierStr attribute", () => { expect(myRawModule.identifier()).toBe("identifierStr attribute"); }); }); describe("size", () => { it('returns value for sourceStr attribute"s length property', () => { const sourceStrLength = myRawModule.sourceStr.length; expect(myRawModule.size()).toBe(sourceStrLength); }); }); describe("readableIdentifier", () => { it( 'returns result of calling provided requestShortener"s shorten method ' + "on readableIdentifierStr attribute", () => { const requestShortener = new RequestShortener(path.resolve()); expect(myRawModule.readableIdentifier(requestShortener)).toBeDefined(); } ); }); describe("needRebuild", () => { it("returns false", () => { expect(myRawModule.needRebuild()).toBe(false); }); }); describe("source", () => { it( "returns a new OriginalSource instance with sourceStr attribute and " + "return value of identifier() function provided as constructor arguments", () => { const originalSource = new OriginalSource( myRawModule.sourceStr, myRawModule.identifier() ); myRawModule.useSourceMap = true; expect(myRawModule.source()).toEqual(originalSource); } ); it( "returns a new RawSource instance with sourceStr attribute provided " + "as constructor argument if useSourceMap is falsy", () => { const rawSource = new RawSource(myRawModule.sourceStr); myRawModule.useSourceMap = false; expect(myRawModule.source()).toEqual(rawSource); } ); }); describe("updateHash", () => { it("should include sourceStr in its hash", () => { const hashModule = module => { const hash = crypto.createHash("sha256"); module.updateHash(hash); return hash.digest("hex"); }; const hashFoo = hashModule(new RawModule('"foo"')); const hashBar = hashModule(new RawModule('"bar"')); expect(hashFoo).not.toBe(hashBar); }); }); }); webpack-4.30.0/test/RemoveFiles.test.js000066400000000000000000000060221345416772700177450ustar00rootroot00000000000000"use strict"; /* globals describe it */ const path = require("path"); const MemoryFs = require("memory-fs"); const webpack = require("../"); const fs = require("fs"); const rimraf = require("rimraf"); const createCompiler = config => { const compiler = webpack(config); compiler.outputFileSystem = new MemoryFs(); return compiler; }; const tempFolderPath = path.join(__dirname, "temp"); const tempFilePath = path.join(tempFolderPath, "temp-file.js"); const tempFile2Path = path.join(tempFolderPath, "temp-file2.js"); const createSingleCompiler = () => { return createCompiler({ entry: tempFilePath, watch: true, output: { path: tempFolderPath, filename: "bundle.js" } }); }; describe("RemovedFiles", () => { if (process.env.NO_WATCH_TESTS) { it.skip("watch tests excluded", () => {}); return; } jest.setTimeout(20000); function cleanup() { rimraf.sync(tempFolderPath); } beforeAll(() => { cleanup(); fs.mkdirSync(tempFolderPath); fs.writeFileSync( tempFilePath, "module.exports = function temp() {return 'temp file';};\n require('./temp-file2')", "utf-8" ); fs.writeFileSync( tempFile2Path, "module.exports = function temp2() {return 'temp file 2';};", "utf-8" ); }); afterAll(done => { cleanup(); done(); }); it("should track removed files when they've been deleted in watchRun", done => { const compiler = createSingleCompiler(); let watcher; function handleError(err) { if (err) done(err); } setTimeout(() => { fs.unlinkSync(tempFilePath, handleError); }, 2000); compiler.hooks.watchRun.tap("RemovedFilesTest", (compiler, err) => { if (err) { done(err); } const removals = Array.from(compiler.removedFiles); if (removals.length > 0) { setTimeout(() => { expect(removals).toContain(tempFilePath); watcher.close(); done(); }, 100); } }); watcher = compiler.watch( { aggregateTimeout: 50 }, (err, stats) => {} ); }); it("should not track removed files when they have not been deleted in watchRun", done => { const compiler = createSingleCompiler(); let watcher; compiler.hooks.watchRun.tap("RemovedFilesTest", (compiler, err) => { if (err) { done(err); } expect(Array.from(compiler.removedFiles)).toHaveLength(0); done(); watcher.close(); }); watcher = compiler.watch( { aggregateTimeout: 50 }, (err, stats) => {} ); }); it("should not track removed files when files have been modified", done => { const compiler = createSingleCompiler(); let watcher; function handleError(err) { if (err) done(err); } let updateFile = () => { fs.writeFile(tempFile2Path, "hello world", "utf-8", handleError); }; updateFile(); compiler.hooks.watchRun.tap("RemovedFilesTest", (compiler, err) => { handleError(err); setTimeout(() => { expect(Array.from(compiler.removedFiles)).toHaveLength(0); watcher.close(); done(); }, 500); watcher.close(); }); watcher = compiler.watch( { aggregateTimeout: 50 }, (err, stats) => {} ); }); }); webpack-4.30.0/test/RemovedPlugins.unittest.js000066400000000000000000000010631345416772700213700ustar00rootroot00000000000000const webpack = require("../lib/webpack"); const RemovedPluginError = require("../lib/RemovedPluginError"); describe("removed plugin errors", () => { it("should error when accessing removed plugins", () => { expect(() => webpack.optimize.UglifyJsPlugin).toThrow(RemovedPluginError); expect( () => webpack.optimize.UglifyJsPlugin ).toThrowErrorMatchingSnapshot(); expect(() => webpack.optimize.CommonsChunkPlugin).toThrow( RemovedPluginError ); expect( () => webpack.optimize.CommonsChunkPlugin ).toThrowErrorMatchingSnapshot(); }); }); webpack-4.30.0/test/RuleSet.unittest.js000066400000000000000000000240501345416772700200110ustar00rootroot00000000000000"use strict"; const RuleSet = require("../lib/RuleSet"); function match(ruleSet, resource) { const result = ruleSet.exec({ resource: resource }); return result .filter(r => { return r.type === "use"; }) .map(r => r.value) .map(r => { if (!r.options) return r.loader; if (typeof r.options === "string") return r.loader + "?" + r.options; return r.loader + "?" + JSON.stringify(r.options); }); } describe("RuleSet", () => { it("should create RuleSet with a blank array", () => { const loader = new RuleSet([]); expect(loader.rules).toEqual([]); }); it("should create RuleSet and match with empty array", () => { const loader = new RuleSet([]); expect(match(loader, "something")).toEqual([]); }); it("should not match with loaders array", () => { const loader = new RuleSet([ { test: /\.css$/, loader: "css" } ]); expect(match(loader, "something")).toEqual([]); }); it("should match with regex", () => { const loader = new RuleSet([ { test: /\.css$/, loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should match with string", () => { const loader = new RuleSet([ { test: "style.css", loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should match with function", () => { const loader = new RuleSet([ { test: function(str) { return str === "style.css"; }, loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should throw if invalid test", () => { expect(() => { const loader = new RuleSet([ { test: { invalid: "test" }, loader: "css" } ]); match(loader, "style.css"); }).toThrow(/Unexcepted property invalid in condition/); }); it("should accept multiple test array that all match", () => { const loader = new RuleSet([ { test: [/style.css/, /yle.css/], loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should accept multiple test array that not all match", () => { const loader = new RuleSet([ { test: [/style.css/, /something.css/], loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should not match if include does not match", () => { const loader = new RuleSet([ { test: /\.css$/, include: /output.css/, loader: "css" } ]); expect(match(loader, "style.css")).toEqual([]); }); it("should match if include matches", () => { const loader = new RuleSet([ { test: /\.css$/, include: /style.css/, loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should not match if exclude matches", () => { const loader = new RuleSet([ { test: /\.css$/, exclude: /style.css/, loader: "css" } ]); expect(match(loader, "style.css")).toEqual([]); }); it("should match if exclude does not match", () => { const loader = new RuleSet([ { test: /\.css$/, exclude: /output.css/, loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should work if a loader is applied to all files", () => { const loader = new RuleSet([ { loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); expect(match(loader, "scripts.js")).toEqual(["css"]); }); it("should work with using loader as string", () => { const loader = new RuleSet([ { test: /\.css$/, loader: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should work with using loader as array", () => { const loader = new RuleSet([ { test: /\.css$/, loader: ["css"] } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should work with using loaders as string", () => { const loader = new RuleSet([ { test: /\.css$/, loaders: "css" } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should work with using loaders as array", () => { const loader = new RuleSet([ { test: /\.css$/, loaders: ["css"] } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should throw if using loaders with non-string or array", () => { expect(() => { const loader = new RuleSet([ { test: /\.css$/, loaders: { someObj: true } } ]); match(loader, "style.css"); }).toThrow(/No loader specified/); }); it("should work with using loader with inline query", () => { const loader = new RuleSet([ { test: /\.css$/, loader: "css?modules=1" } ]); expect(match(loader, "style.css")).toEqual(["css?modules=1"]); }); it("should work with using loader with string query", () => { const loader = new RuleSet([ { test: /\.css$/, loader: "css", query: "modules=1" } ]); expect(match(loader, "style.css")).toEqual(["css?modules=1"]); }); it("should work with using loader with object query", () => { const loader = new RuleSet([ { test: /\.css$/, loader: "css", query: { modules: 1 } } ]); expect(match(loader, "style.css")).toEqual(['css?{"modules":1}']); }); it("should work with using array loaders with basic object notation", () => { const loader = new RuleSet([ { test: /\.css$/, loaders: [ { loader: "css" } ] } ]); expect(match(loader, "style.css")).toEqual(["css"]); }); it("should throw if using array loaders with object notation without specifying a loader", () => { expect(() => { const loader = new RuleSet([ { test: /\.css$/, loaders: [ { stuff: 1 } ] } ]); match(loader, "style.css"); }).toThrow(/No loader specified/); }); it("should work with using array loaders with object notation", () => { const loader = new RuleSet([ { test: /\.css$/, loaders: [ { loader: "css", query: "modules=1" } ] } ]); expect(match(loader, "style.css")).toEqual(["css?modules=1"]); }); it("should work with using multiple array loaders with object notation", () => { const loader = new RuleSet([ { test: /\.css$/, loaders: [ { loader: "style", query: "filesize=1000" }, { loader: "css", query: "modules=1" } ] } ]); expect(match(loader, "style.css")).toEqual([ "style?filesize=1000", "css?modules=1" ]); }); it("should work with using string multiple loaders", () => { const loader = new RuleSet([ { test: /\.css$/, loaders: "style?filesize=1000!css?modules=1" } ]); expect(match(loader, "style.css")).toEqual([ "style?filesize=1000", "css?modules=1" ]); }); it("should throw if using array loaders with a single legacy", () => { expect(() => { const loader = new RuleSet([ { test: /\.css$/, loaders: ["style-loader", "css-loader"], query: "modules=1" } ]); match(loader, "style.css"); }).toThrow(/options\/query cannot be used with loaders/); }); it("should work when using array loaders", () => { const loader = new RuleSet([ { test: /\.css$/, loaders: ["style-loader", "css-loader"] } ]); expect(match(loader, "style.css")).toEqual(["style-loader", "css-loader"]); }); it("should work when using an array of functions returning a loader", () => { const loader = new RuleSet([ { test: /\.css$/, use: [ function(data) { return { loader: "style-loader" }; }, function(data) { return { loader: "css-loader" }; } ] } ]); expect(match(loader, "style.css")).toEqual(["style-loader", "css-loader"]); }); it("should work when using an array of either functions or strings returning a loader", () => { const loader = new RuleSet([ { test: /\.css$/, use: [ "style-loader", function(data) { return { loader: "css-loader" }; } ] } ]); expect(match(loader, "style.css")).toEqual(["style-loader", "css-loader"]); }); it("should work when using an array of functions returning either a loader object or loader name string", () => { const loader = new RuleSet([ { test: /\.css$/, use: [ function(data) { return "style-loader"; }, function(data) { return { loader: "css-loader" }; } ] } ]); expect(match(loader, "style.css")).toEqual(["style-loader", "css-loader"]); }); it("should throw if using array loaders with invalid type", () => { expect(() => { const loader = new RuleSet([ { test: /\.css$/, loaders: ["style-loader", "css-loader", 5] } ]); match(loader, "style.css"); }).toThrow(/No loader specified/); }); describe("when exclude array holds an undefined item", () => { function errorHasContext(err) { return ( /Expected condition but got falsy value/.test(err) && /test/.test(err) && /include/.test(err) && /exclude/.test(err) && /node_modules/.test(err) && /undefined/.test(err) ); } it("should throw with context", () => { try { const loader = new RuleSet([ { test: /\.css$/, loader: "css", include: ["src"], exclude: ["node_modules", undefined] } ]); match(loader, "style.css"); throw new Error("unreachable"); } catch (e) { expect(errorHasContext(e.message)).toBe(true); } }); it("in resource should throw with context", () => { try { const loader = new RuleSet([ { resource: { test: /\.css$/, include: ["src"], exclude: ["node_modules", undefined] } } ]); match(loader, "style.css"); throw new Error("unreachable"); } catch (e) { expect(errorHasContext(e.message)).toBe(true); } }); it("in issuer should throw with context", () => { try { const loader = new RuleSet([ { issuer: { test: /\.css$/, include: ["src"], exclude: ["node_modules", undefined] } } ]); match(loader, "style.css"); throw new Error("unreachable"); } catch (e) { expect(errorHasContext(e.message)).toBe(true); } }); }); }); webpack-4.30.0/test/Schemas.lint.js000066400000000000000000000103761345416772700171060ustar00rootroot00000000000000"use strict"; const fs = require("fs"); const path = require("path"); const glob = require("glob"); const rootDir = path.resolve(__dirname, ".."); describe("Schemas", () => { const schemas = glob.sync("schemas/**/*.json", { cwd: rootDir }); schemas.forEach(filename => { describe(filename, () => { let content; let fileContent; let errorWhileParsing; try { fileContent = fs.readFileSync(path.resolve(rootDir, filename), "utf-8"); content = JSON.parse(fileContent); } catch (e) { errorWhileParsing = e; } it("should be parse-able", () => { if (errorWhileParsing) throw errorWhileParsing; }); if (content) { const arrayProperties = ["oneOf", "anyOf", "allOf"]; const allowedProperties = [ "definitions", "$ref", "$id", "title", "items", "properties", "additionalProperties", "type", "oneOf", "anyOf", "absolutePath", "description", "enum", "minLength", "minimum", "required", "uniqueItems", "minItems", "minProperties", "instanceof", "tsType" ]; const validateProperty = property => { it("should have description set", () => { expect(typeof property.description).toBe("string"); expect(property.description.length).toBeGreaterThan(1); }); }; const walker = item => { it("should only use allowed schema properties", () => { const otherProperties = Object.keys(item).filter( p => allowedProperties.indexOf(p) < 0 ); if (otherProperties.length > 0) { throw new Error( `The properties ${otherProperties.join( ", " )} are not allowed to use` ); // When allowing more properties make sure to add nice error messages for them in WebpackOptionsValidationError } }); if ("$ref" in item) { it("should not have other properties next to $ref", () => { const otherProperties = Object.keys(item).filter( p => p !== "$ref" ); if (otherProperties.length > 0) { throw new Error( `When using $ref not other properties are possible (${otherProperties.join( ", " )})` ); } }); } if ("instanceof" in item) { it("should have tsType specified when using instanceof", () => { if (!("tsType" in item)) { throw new Error("When using instanceof, tsType is required"); } }); } if ("absolutePath" in item) { it("should have type: 'string' specified when using absolutePath", () => { if (item.type !== "string") { throw new Error( "When using absolutePath, type must be 'string'" ); } }); } if ("properties" in item || "additionalProperties" in item) { it("should have type: 'object' specified when using properties or additionalProperties", () => { if (item.type !== "object") { throw new Error( "When using properties or additionalProperties, type must be 'object'" ); } }); } arrayProperties.forEach(prop => { if (prop in item) { describe(prop, () => { item[prop].forEach(walker); }); } }); if ("items" in item) { describe("items", () => { if (Object.keys(item).join() !== "$ref") { validateProperty(item.items); } walker(item.items); }); } if ("definitions" in item) { Object.keys(item.definitions).forEach(name => { describe(`#${name}`, () => { walker(item.definitions[name]); }); }); } if ("properties" in item) { it("should have additionalProperties set to some value when describing properties", () => { expect(item.additionalProperties).toBeDefined(); }); Object.keys(item.properties).forEach(name => { describe(`> '${name}'`, () => { const property = item.properties[name]; validateProperty(property); walker(property); }); }); } if (typeof item.additionalProperties === "object") { describe("properties", () => { validateProperty(item.additionalProperties); walker(item.additionalProperties); }); } }; walker(content); } }); }); }); webpack-4.30.0/test/SideEffectsFlagPlugin.unittest.js000066400000000000000000000053011345416772700225610ustar00rootroot00000000000000"use strict"; const SideEffectsFlagPlugin = require("../lib/optimize/SideEffectsFlagPlugin"); describe("SideEffectsFlagPlugin", () => { it("should assume true", () => { expect( SideEffectsFlagPlugin.moduleHasSideEffects("./foo/bar.js", undefined) ).toBe(true); }); it("should understand boolean values", () => { expect( SideEffectsFlagPlugin.moduleHasSideEffects("./foo/bar.js", true) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./foo/bar.js", false) ).toBe(false); }); it("should understand a glob", () => { expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "./src/**/*.js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./x.js", "./src/**/*.js") ).toBe(false); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "./**/src/x/y/z.js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./src/x/y/z.js", "**.js") ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "./src/**/z.js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "./**/x/**/z.js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "./**/src/**" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./src/x/y/z.js", "./**/src/*") ).toBe(false); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./src/x/y/z.js", "*.js") ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./src/x/y/z.js", "x/**/z.js") ).toBe(false); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "src/**/z.js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "src/**/{x,y,z}.js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "src/**/[x-z].js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects( "./src/x/y/z.js", "src/**/[[:lower:]].js" ) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./src/x/y/z.js", "!*.js") ).toBe(false); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./src/x/y/z.js", "!**/*.js") ).toBe(false); }); it("should understand arrays", () => { const array = ["./src/**/*.js", "./dirty.js"]; expect( SideEffectsFlagPlugin.moduleHasSideEffects("./src/x/y/z.js", array) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./dirty.js", array) ).toBe(true); expect( SideEffectsFlagPlugin.moduleHasSideEffects("./clean.js", array) ).toBe(false); }); }); webpack-4.30.0/test/SizeFormatHelpers.unittest.js000066400000000000000000000025321345416772700220350ustar00rootroot00000000000000/* globals describe it */ "use strict"; const SizeFormatHelpers = require("../lib/SizeFormatHelpers"); describe("SizeFormatHelpers", () => { describe("formatSize", () => { it("should handle zero size", () => { expect(SizeFormatHelpers.formatSize(0)).toBe("0 bytes"); }); it("should handle bytes", () => { expect(SizeFormatHelpers.formatSize(1000)).toBe("1000 bytes"); }); it("should handle integer kibibytes", () => { expect(SizeFormatHelpers.formatSize(2048)).toBe("2 KiB"); }); it("should handle float kibibytes", () => { expect(SizeFormatHelpers.formatSize(2560)).toBe("2.5 KiB"); }); it("should handle integer mebibytes", () => { expect(SizeFormatHelpers.formatSize(10 * 1024 * 1024)).toBe("10 MiB"); }); it("should handle float mebibytes", () => { expect(SizeFormatHelpers.formatSize(12.5 * 1024 * 1024)).toBe("12.5 MiB"); }); it("should handle integer gibibytes", () => { expect(SizeFormatHelpers.formatSize(3 * 1024 * 1024 * 1024)).toBe( "3 GiB" ); }); it("should handle float gibibytes", () => { expect(SizeFormatHelpers.formatSize(1.2 * 1024 * 1024 * 1024)).toBe( "1.2 GiB" ); }); it("should handle undefined/NaN", () => { expect(SizeFormatHelpers.formatSize(undefined)).toBe("unknown size"); expect(SizeFormatHelpers.formatSize(NaN)).toBe("unknown size"); }); }); }); webpack-4.30.0/test/SortableSet.unittest.js000066400000000000000000000015621345416772700206600ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const SortableSet = require("../lib/util/SortableSet"); describe("util/SortableSet", () => { it("Can be constructed like a normal Set", () => { const sortableSet = new SortableSet([1, 1, 1, 1, 1, 4, 5, 2], () => {}); expect(Array.from(sortableSet)).toEqual([1, 4, 5, 2]); }); it("Can sort its content", () => { const sortableSet = new SortableSet( [1, 1, 1, 6, 6, 1, 1, 4, 5, 2, 3, 8, 5, 7, 9, 0, 3, 1], (a, b) => a - b ); sortableSet.sort(); expect(Array.from(sortableSet)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); }); it("Can sort by a specified function", () => { const sortableSet = new SortableSet( [1, 1, 1, 6, 6, 1, 1, 4, 5, 2, 3, 8, 5, 7, 9, 0, 3, 1], (a, b) => a - b ); sortableSet.sortWith((a, b) => b - a); expect(Array.from(sortableSet)).toEqual([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]); }); }); webpack-4.30.0/test/SourceMapDevToolModuleOptionsPlugin.unittest.js000066400000000000000000000063751345416772700255340ustar00rootroot00000000000000"use strict"; const SourceMapDevToolModuleOptionsPlugin = require("../lib/SourceMapDevToolModuleOptionsPlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("SourceMapDevToolModuleOptionsPlugin", () => { describe("when applied", () => { let eventBindings; beforeEach(() => { eventBindings = undefined; }); describe("with module false and line-to-line false", () => { beforeEach(() => { eventBindings = applyPluginWithOptions( SourceMapDevToolModuleOptionsPlugin, { module: false, lineToLine: false } ); }); it("does not bind any event handlers", () => { expect(eventBindings.length).toBe(0); }); }); describe("with module true", () => { beforeEach(() => { eventBindings = applyPluginWithOptions( SourceMapDevToolModuleOptionsPlugin, { module: true, lineToLine: false } ); }); it("binds one event handler", () => { expect(eventBindings.length).toBe(1); }); describe("event handler", () => { it("binds to build-module event", () => { expect(eventBindings[0].name).toBe("build-module"); }); it("sets source map flag", () => { const module = {}; eventBindings[0].handler(module); expect(module).toEqual({ useSourceMap: true }); }); }); }); describe("with line-to-line true", () => { beforeEach( () => (eventBindings = applyPluginWithOptions( SourceMapDevToolModuleOptionsPlugin, { module: false, lineToLine: true } )) ); it("binds one event handler", () => { expect(eventBindings.length).toBe(1); }); describe("event handler", () => { it("binds to build-module event", () => { expect(eventBindings[0].name).toBe("build-module"); }); it("sets line-to-line flag", () => { const module = {}; eventBindings[0].handler(module); expect(module).toEqual({ lineToLine: true }); }); }); }); describe("with line-to-line object", () => { beforeEach(() => { eventBindings = applyPluginWithOptions( SourceMapDevToolModuleOptionsPlugin, { module: false, lineToLine: {} } ); }); it("binds one event handler", () => { expect(eventBindings.length).toBe(1); }); describe("event handler", () => { it("binds to build-module event", () => { expect(eventBindings[0].name).toBe("build-module"); }); describe("when module has no resource", () => { it("makes no changes", () => { const module = {}; eventBindings[0].handler(module); expect(module).toEqual({}); }); }); describe("when module has a resource", () => { it("sets line-to-line flag", () => { const module = { resource: "foo" }; eventBindings[0].handler(module); expect(module).toEqual({ lineToLine: true, resource: "foo" }); }); }); describe("when module has a resource with query", () => { it("sets line-to-line flag", () => { const module = { resource: "foo?bar" }; eventBindings[0].handler(module); expect(module).toEqual({ lineToLine: true, resource: "foo?bar" }); }); }); }); }); }); }); webpack-4.30.0/test/Stats.test.js000066400000000000000000000016451345416772700166310ustar00rootroot00000000000000/*globals describe it */ "use strict"; const webpack = require("../lib/webpack"); const MemoryFs = require("memory-fs"); describe("Stats", () => { it("should print env string in stats", done => { const compiler = webpack({ context: __dirname, entry: "./fixtures/a" }); compiler.outputFileSystem = new MemoryFs(); compiler.run((err, stats) => { if (err) return done(err); try { expect( stats.toString({ all: false, env: true, _env: "production" }) ).toBe('Environment (--env): "production"'); expect( stats.toString({ all: false, env: true, _env: { prod: ["foo", "bar"], baz: true } }) ).toBe( "Environment (--env): {\n" + ' "prod": [\n' + ' "foo",\n' + ' "bar"\n' + " ],\n" + ' "baz": true\n' + "}" ); done(); } catch (e) { done(e); } }); }); }); webpack-4.30.0/test/Stats.unittest.js000066400000000000000000000114061345416772700175250ustar00rootroot00000000000000/*globals describe it */ "use strict"; const Stats = require("../lib/Stats"); const packageJson = require("../package.json"); describe("Stats", () => { describe("formatFilePath", () => { it("emit the file path and request", () => { const mockStats = new Stats({ children: [], errors: ["firstError"], hash: "1234", compiler: { context: "" } }); const inputPath = "./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/app.vue"; const expectPath = `./src/app.vue (${inputPath})`; expect(mockStats.formatFilePath(inputPath)).toBe(expectPath); }); }); describe("Error Handling", () => { describe("does have", () => { it("hasErrors", () => { const mockStats = new Stats({ children: [], errors: ["firstError"], hash: "1234", compiler: { context: "" } }); expect(mockStats.hasErrors()).toBe(true); }); it("hasWarnings", () => { const mockStats = new Stats({ children: [], warnings: ["firstError"], hash: "1234", compiler: { context: "" } }); expect(mockStats.hasWarnings()).toBe(true); }); }); describe("does not have", () => { it("hasErrors", () => { const mockStats = new Stats({ children: [], errors: [], hash: "1234", compiler: { context: "" } }); expect(mockStats.hasErrors()).toBe(false); }); it("hasWarnings", () => { const mockStats = new Stats({ children: [], warnings: [], hash: "1234", compiler: { context: "" } }); expect(mockStats.hasWarnings()).toBe(false); }); }); describe("children have", () => { it("hasErrors", () => { const mockStats = new Stats({ children: [ { getStats: () => new Stats({ errors: ["firstError"], hash: "5678" }) } ], errors: [], hash: "1234" }); expect(mockStats.hasErrors()).toBe(true); }); it("hasWarnings", () => { const mockStats = new Stats({ children: [ { getStats: () => new Stats({ warnings: ["firstError"], hash: "5678" }) } ], warnings: [], hash: "1234" }); expect(mockStats.hasWarnings()).toBe(true); }); }); it("formatError handles string errors", () => { const mockStats = new Stats({ errors: ["firstError"], warnings: [], assets: [], entrypoints: new Map(), namedChunkGroups: new Map(), chunks: [], modules: [], children: [], hash: "1234", mainTemplate: { outputOptions: { path: "" }, getPublicPath: () => "path" }, compiler: { context: "" } }); const obj = mockStats.toJson(); expect(obj.errors[0]).toEqual("firstError"); }); }); describe("toJson", () => { it("returns plain object representation", () => { const mockStats = new Stats({ errors: [], warnings: [], assets: [], entrypoints: new Map(), chunks: [], namedChunkGroups: new Map(), modules: [], children: [], hash: "1234", mainTemplate: { outputOptions: { path: "/" }, getPublicPath: () => "path" }, compiler: { context: "" } }); const result = mockStats.toJson(); expect(result).toEqual({ assets: [], assetsByChunkName: {}, children: [], chunks: [], entrypoints: {}, namedChunkGroups: {}, filteredAssets: 0, filteredModules: 0, errors: [], hash: "1234", modules: [], outputPath: "/", publicPath: "path", version: packageJson.version, warnings: [] }); }); }); describe("Presets", () => { describe("presetToOptions", () => { it("returns correct object with 'Normal'", () => { expect(Stats.presetToOptions("Normal")).toEqual({}); }); it("truthy values behave as 'normal'", () => { const normalOpts = Stats.presetToOptions("normal"); expect(Stats.presetToOptions("pizza")).toEqual(normalOpts); expect(Stats.presetToOptions(true)).toEqual(normalOpts); expect(Stats.presetToOptions(1)).toEqual(normalOpts); expect(Stats.presetToOptions("verbose")).not.toEqual(normalOpts); expect(Stats.presetToOptions(false)).not.toEqual(normalOpts); }); it("returns correct object with 'none'", () => { expect(Stats.presetToOptions("none")).toEqual({ all: false }); }); it("falsy values behave as 'none'", () => { const noneOpts = Stats.presetToOptions("none"); expect(Stats.presetToOptions("")).toEqual(noneOpts); expect(Stats.presetToOptions(null)).toEqual(noneOpts); expect(Stats.presetToOptions()).toEqual(noneOpts); expect(Stats.presetToOptions(0)).toEqual(noneOpts); expect(Stats.presetToOptions(false)).toEqual(noneOpts); }); }); }); }, 10000); webpack-4.30.0/test/StatsTestCases.test.js000066400000000000000000000103301345416772700204370ustar00rootroot00000000000000/*globals describe it */ "use strict"; const path = require("path"); const fs = require("fs"); const webpack = require("../lib/webpack"); const Stats = require("../lib/Stats"); const base = path.join(__dirname, "statsCases"); const outputBase = path.join(__dirname, "js", "stats"); const tests = fs .readdirSync(base) .filter( testName => fs.existsSync(path.join(base, testName, "index.js")) || fs.existsSync(path.join(base, testName, "webpack.config.js")) ) .filter(testName => { const testDirectory = path.join(base, testName); const filterPath = path.join(testDirectory, "test.filter.js"); if (fs.existsSync(filterPath) && !require(filterPath)()) { describe.skip(testName, () => it("filtered")); return false; } return true; }); describe("StatsTestCases", () => { tests.forEach(testName => { it("should print correct stats for " + testName, done => { jest.setTimeout(10000); let options = { mode: "development", entry: "./index", output: { filename: "bundle.js" } }; if (fs.existsSync(path.join(base, testName, "webpack.config.js"))) { options = require(path.join(base, testName, "webpack.config.js")); } (Array.isArray(options) ? options : [options]).forEach(options => { if (!options.context) options.context = path.join(base, testName); if (!options.output) options.output = options.output || {}; if (!options.output.path) options.output.path = path.join(outputBase, testName); if (!options.plugins) options.plugins = []; if (!options.optimization) options.optimization = {}; if (options.optimization.minimize === undefined) options.optimization.minimize = false; // To support deprecated loaders // TODO remove in webpack 5 options.plugins.push( new webpack.LoaderOptionsPlugin({ options: {} }) ); }); const c = webpack(options); const compilers = c.compilers ? c.compilers : [c]; compilers.forEach(c => { const ifs = c.inputFileSystem; c.inputFileSystem = Object.create(ifs); c.inputFileSystem.readFile = function() { const args = Array.prototype.slice.call(arguments); const callback = args.pop(); ifs.readFile.apply( ifs, args.concat([ (err, result) => { if (err) return callback(err); callback(null, result.toString("utf-8").replace(/\r/g, "")); } ]) ); }; }); c.run((err, stats) => { if (err) return done(err); if (/error$/.test(testName)) { expect(stats.hasErrors()).toBe(true); } else if (stats.hasErrors()) { return done(new Error(stats.toJson().errors.join("\n\n"))); } let toStringOptions = { context: path.join(base, testName), colors: false }; let hasColorSetting = false; if (typeof options.stats !== "undefined") { toStringOptions = options.stats; if (toStringOptions === null || typeof toStringOptions !== "object") toStringOptions = Stats.presetToOptions(toStringOptions); hasColorSetting = typeof options.stats.colors !== "undefined"; if (!toStringOptions.context) toStringOptions.context = path.join(base, testName); } if (Array.isArray(options) && !toStringOptions.children) { toStringOptions.children = options.map(o => o.stats); } let actual = stats.toString(toStringOptions); expect(typeof actual).toBe("string"); if (!hasColorSetting) { actual = actual .replace(/\u001b\[[0-9;]*m/g, "") .replace(/[0-9]+(\s?ms)/g, "X$1") .replace( /^(\s*Built at:) (.*)$/gm, "$1 Thu Jan 01 1970 00:00:00 GMT" ); } else { actual = actual .replace(/\u001b\[1m\u001b\[([0-9;]*)m/g, "") .replace(/\u001b\[1m/g, "") .replace(/\u001b\[39m\u001b\[22m/g, "") .replace(/\u001b\[([0-9;]*)m/g, "") .replace(/[0-9]+(<\/CLR>)?(\s?ms)/g, "X$1$2") .replace( /^(\s*Built at:) (.*)$/gm, "$1 Thu Jan 01 1970 00:00:00 GMT" ); } actual = actual .replace(/\r\n?/g, "\n") .replace(/[\t ]*Version:.+\n/g, "") .replace(path.join(base, testName), "Xdir/" + testName) .replace(/ dependencies:Xms/g, ""); expect(actual).toMatchSnapshot(); done(); }); }); }); }); webpack-4.30.0/test/Template.unittest.js000066400000000000000000000011761345416772700202050ustar00rootroot00000000000000"use strict"; const Template = require("../lib/Template"); describe("Template", () => { it("should generate valid identifiers", () => { expect(Template.toIdentifier("0abc-def9")).toBe("_0abc_def9"); }); it("should generate valid number identifiers", () => { const items = []; let item; for (let i = 0; i < 80; i += 1) { item = Template.numberToIdentifer(i); expect(item).not.toBe(""); expect(items).not.toContain(item); items.push(item); } }); it("should generate sanitized path identifiers", () => { expect(Template.toPath("path/to-sdfas/sadfome$$.js")).toBe( "path-to-sdfas-sadfome$$-js" ); }); }); webpack-4.30.0/test/TestCases.template.js000066400000000000000000000150411345416772700202600ustar00rootroot00000000000000/* global describe it expect */ "use strict"; const path = require("path"); const fs = require("fs"); const vm = require("vm"); const mkdirp = require("mkdirp"); const TerserPlugin = require("terser-webpack-plugin"); const checkArrayExpectation = require("./checkArrayExpectation"); const createLazyTestEnv = require("./helpers/createLazyTestEnv"); const Stats = require("../lib/Stats"); const webpack = require("../lib/webpack"); const terserForTesting = new TerserPlugin({ cache: false, parallel: false, sourceMap: true }); const DEFAULT_OPTIMIZATIONS = { removeAvailableModules: true, removeEmptyChunks: true, mergeDuplicateChunks: true, flagIncludedChunks: true, occurrenceOrder: true, sideEffects: true, providedExports: true, usedExports: true, noEmitOnErrors: false, concatenateModules: false, namedModules: false, hashedModuleIds: false, minimizer: [terserForTesting] }; const NO_EMIT_ON_ERRORS_OPTIMIZATIONS = { noEmitOnErrors: false, minimizer: [terserForTesting] }; const casesPath = path.join(__dirname, "cases"); let categories = fs.readdirSync(casesPath); categories = categories.map(cat => { return { name: cat, tests: fs .readdirSync(path.join(casesPath, cat)) .filter(folder => folder.indexOf("_") < 0) }; }); const describeCases = config => { describe(config.name, () => { categories.forEach(category => { describe(category.name, function() { jest.setTimeout(20000); category.tests .filter(test => { const testDirectory = path.join(casesPath, category.name, test); const filterPath = path.join(testDirectory, "test.filter.js"); if (fs.existsSync(filterPath) && !require(filterPath)(config)) { describe.skip(test, () => { it("filtered", () => {}); }); return false; } return true; }) .forEach(testName => { describe(testName, () => { const testDirectory = path.join( casesPath, category.name, testName ); const outputDirectory = path.join( __dirname, "js", config.name, category.name, testName ); const options = { context: casesPath, entry: "./" + category.name + "/" + testName + "/index", target: "async-node", devtool: config.devtool, mode: config.mode || "none", optimization: config.mode ? NO_EMIT_ON_ERRORS_OPTIMIZATIONS : Object.assign( {}, config.optimization, DEFAULT_OPTIMIZATIONS ), performance: { hints: false }, output: { pathinfo: true, path: outputDirectory, filename: "bundle.js" }, resolve: { modules: ["web_modules", "node_modules"], mainFields: [ "webpack", "browser", "web", "browserify", ["jam", "main"], "main" ], aliasFields: ["browser"], extensions: [ ".mjs", ".webpack.js", ".web.js", ".js", ".json" ], concord: true }, resolveLoader: { modules: [ "web_loaders", "web_modules", "node_loaders", "node_modules" ], mainFields: ["webpackLoader", "webLoader", "loader", "main"], extensions: [ ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js" ] }, module: { rules: [ { test: /\.coffee$/, loader: "coffee-loader" }, { test: /\.pug/, loader: "pug-loader" }, { test: /\.wat$/i, loader: "wast-loader", type: "webassembly/experimental" } ] }, plugins: (config.plugins || []).concat(function() { this.hooks.compilation.tap("TestCasesTest", compilation => { [ "optimize", "optimizeModulesBasic", "optimizeChunksBasic", "afterOptimizeTree", "afterOptimizeAssets" ].forEach(hook => { compilation.hooks[hook].tap("TestCasesTest", () => compilation.checkConstraints() ); }); }); }) }; it( testName + " should compile", done => { webpack(options, (err, stats) => { if (err) done(err); const statOptions = Stats.presetToOptions("verbose"); statOptions.colors = false; mkdirp.sync(outputDirectory); fs.writeFileSync( path.join(outputDirectory, "stats.txt"), stats.toString(statOptions), "utf-8" ); const jsonStats = stats.toJson({ errorDetails: true }); if ( checkArrayExpectation( testDirectory, jsonStats, "error", "Error", done ) ) return; if ( checkArrayExpectation( testDirectory, jsonStats, "warning", "Warning", done ) ) return; function _require(module) { if (module.substr(0, 2) === "./") { const p = path.join(outputDirectory, module); const fn = vm.runInThisContext( "(function(require, module, exports, __dirname, it, expect) {" + "global.expect = expect;" + 'function nsObj(m) { Object.defineProperty(m, Symbol.toStringTag, { value: "Module" }); return m; }' + fs.readFileSync(p, "utf-8") + "\n})", p ); const m = { exports: {}, webpackTestSuiteModule: true }; fn.call( m.exports, _require, m, m.exports, outputDirectory, _it, expect ); return m.exports; } else return require(module); } _require.webpackTestSuiteRequire = true; _require("./bundle.js"); if (getNumberOfTests() === 0) return done(new Error("No tests exported by test case")); done(); }); }, 60000 ); const { it: _it, getNumberOfTests } = createLazyTestEnv( jasmine.getEnv(), 10000 ); }); }); }); }); }); }; module.exports.describeCases = describeCases; webpack-4.30.0/test/TestCasesAllCombined.test.js000066400000000000000000000006001345416772700215110ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); const webpack = require("../lib/webpack"); describe("TestCases", () => { describeCases({ name: "all-combined", mode: "production", devtool: "#@source-map", minimize: true, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new webpack.NamedChunksPlugin() ] }); }); webpack-4.30.0/test/TestCasesDevelopment.test.js000066400000000000000000000002641345416772700216300ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "development", mode: "development", devtool: "none" }); }); webpack-4.30.0/test/TestCasesDevtoolCheapEvalModuleSourceMap.test.js000066400000000000000000000003161345416772700255160ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-cheap-eval-module-source-map", devtool: "cheap-eval-module-source-map" }); }); webpack-4.30.0/test/TestCasesDevtoolCheapEvalSourceMap.test.js000066400000000000000000000003001345416772700243410ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-cheap-eval-source-map", devtool: "cheap-eval-source-map" }); }); webpack-4.30.0/test/TestCasesDevtoolCheapInlineSourceMap.test.js000066400000000000000000000003041345416772700246740ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-cheap-inline-source-map", devtool: "cheap-inline-source-map" }); }); webpack-4.30.0/test/TestCasesDevtoolCheapSourceMap.test.js000066400000000000000000000002661345416772700235440ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-cheap-source-map", devtool: "cheap-source-map" }); }); webpack-4.30.0/test/TestCasesDevtoolEval.test.js000066400000000000000000000002361345416772700215710ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-eval", devtool: "eval" }); }); webpack-4.30.0/test/TestCasesDevtoolEvalNamedModules.test.js000066400000000000000000000004061345416772700240660ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); const webpack = require("../lib/webpack"); describe("TestCases", () => { describeCases({ name: "devtool-eval-named-modules", devtool: "eval", plugins: [new webpack.NamedModulesPlugin()] }); }); webpack-4.30.0/test/TestCasesDevtoolEvalSourceMap.test.js000066400000000000000000000002651345416772700234120ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-eval-source-map", devtool: "#eval-source-map" }); }); webpack-4.30.0/test/TestCasesDevtoolInlineSourceMap.test.js000066400000000000000000000002701345416772700237350ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-inline-source-map", devtool: "inline-source-map" }); }); webpack-4.30.0/test/TestCasesDevtoolSourceMap.test.js000066400000000000000000000002541345416772700226000ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "devtool-source-map", devtool: "#@source-map" }); }); webpack-4.30.0/test/TestCasesHot.test.js000066400000000000000000000003441345416772700200770ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); const webpack = require("../lib/webpack"); describe("TestCases", () => { describeCases({ name: "hot", plugins: [new webpack.HotModuleReplacementPlugin()] }); }); webpack-4.30.0/test/TestCasesHotMultiStep.test.js000066400000000000000000000004201345416772700217410ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); const webpack = require("../lib/webpack"); describe("TestCases", () => { describeCases({ name: "hot-multi-step", plugins: [ new webpack.HotModuleReplacementPlugin({ multiStep: true }) ] }); }); webpack-4.30.0/test/TestCasesMinimizedHashedModules.test.js000066400000000000000000000004341345416772700237400ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); const webpack = require("../lib/webpack"); describe("TestCases", () => { describeCases({ name: "minimized-hashed-modules", mode: "production", minimize: true, plugins: [new webpack.HashedModuleIdsPlugin()] }); }); webpack-4.30.0/test/TestCasesMinimizedSourceMap.test.js000066400000000000000000000003461345416772700231130ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "minimized-source-map", mode: "production", devtool: "eval-cheap-module-source-map", minimize: true }); }); webpack-4.30.0/test/TestCasesNormal.test.js000066400000000000000000000002051345416772700205710ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "normal" }); }); webpack-4.30.0/test/TestCasesProduction.test.js000066400000000000000000000002371345416772700214740ustar00rootroot00000000000000const { describeCases } = require("./TestCases.template"); describe("TestCases", () => { describeCases({ name: "production", mode: "production" }); }); webpack-4.30.0/test/Validation.test.js000066400000000000000000000333261345416772700176260ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const webpack = require("../lib/webpack"); describe("Validation", () => { const testCases = [ { name: "undefined configuration", config: undefined, message: [" - configuration should be an object."] }, { name: "null configuration", config: null, message: [" - configuration should be an object."] }, { name: "empty entry string", config: { entry: "" }, message: [ " - configuration.entry should be one of these:", " function | object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " -> The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an instance of function", " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.", " * configuration.entry should be an object.", " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.", " * configuration.entry should not be empty.", " -> An entry point without name. The string is resolved to a module which is loaded upon startup.", " * configuration.entry should be an array:", " [non-empty string]" ] }, { name: "empty entry bundle array", config: { entry: { bundle: [] } }, message: [ " - configuration.entry should be one of these:", " function | object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " -> The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an instance of function", " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.", " * configuration.entry['bundle'] should be a string.", " -> The string is resolved to a module which is loaded upon startup.", " * configuration.entry['bundle'] should not be empty.", " * configuration.entry should be a string.", " -> An entry point without name. The string is resolved to a module which is loaded upon startup.", " * configuration.entry should be an array:", " [non-empty string]" ] }, { name: "invalid instanceof", config: { entry: "a", module: { wrappedContextRegExp: 1337 } }, message: [ " - configuration.module.wrappedContextRegExp should be an instance of RegExp", " -> Set the inner regular expression for partial dynamic dependencies" ] }, { name: "invalid minimum", config: { entry: "a", parallelism: 0 }, message: [ " - configuration.parallelism should be >= 1.", " -> The number of parallel processed modules in the compilation." ] }, { name: "repeated value", config: { entry: ["abc", "def", "abc"] }, message: [ " - configuration.entry should be one of these:", " function | object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " -> The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an instance of function", " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.", " * configuration.entry should be an object.", " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.", " * configuration.entry should be a string.", " -> An entry point without name. The string is resolved to a module which is loaded upon startup.", " * configuration.entry should not contain the item 'abc' twice." ] }, { name: "multiple errors", config: { entry: [/a/], output: { filename: /a/ } }, message: [ " - configuration.entry should be one of these:", " function | object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " -> The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an instance of function", " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.", " * configuration.entry should be an object.", " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.", " * configuration.entry should be a string.", " -> An entry point without name. The string is resolved to a module which is loaded upon startup.", " * configuration.entry[0] should be a string.", " -> A non-empty string", " - configuration.output.filename should be one of these:", " string | function", " -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.", " Details:", " * configuration.output.filename should be a string.", " * configuration.output.filename should be an instance of function" ] }, { name: "multiple configurations", config: [ { entry: [/a/] }, { entry: "a", output: { filename: /a/ } } ], message: [ " - configuration[0].entry should be one of these:", " function | object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string]", " -> The entry point(s) of the compilation.", " Details:", " * configuration[0].entry should be an instance of function", " -> A Function returning an entry object, an entry string, an entry array or a promise to these things.", " * configuration[0].entry should be an object.", " -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.", " * configuration[0].entry should be a string.", " -> An entry point without name. The string is resolved to a module which is loaded upon startup.", " * configuration[0].entry[0] should be a string.", " -> A non-empty string", " - configuration[1].output.filename should be one of these:", " string | function", " -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.", " Details:", " * configuration[1].output.filename should be a string.", " * configuration[1].output.filename should be an instance of function" ] }, { name: "deep error", config: { entry: "a", module: { rules: [ { oneOf: [ { test: "/a", passer: { amd: false } } ] } ] } }, message: [ " - configuration.module.rules[0].oneOf[0] has an unknown property 'passer'. These properties are valid:", " object { compiler?, enforce?, exclude?, include?, issuer?, loader?, loaders?, oneOf?, options?, parser?, query?, resolve?, resource?, resourceQuery?, rules?, sideEffects?, test?, type?, use? }", " -> A rule" ] }, { name: "additional key on root", config: { entry: "a", postcss: () => {} }, message: [ " - configuration has an unknown property 'postcss'. These properties are valid:", " object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, externals?, loader?, mode?, module?, " + "name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, " + "recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }", " For typos: please correct them.", " For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.", " Loaders should be updated to allow passing options via loader options in module.rules.", " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:", " plugins: [", " new webpack.LoaderOptionsPlugin({", " // test: /\\.xxx$/, // may apply this only for some modules", " options: {", " postcss: …", " }", " })", " ]" ] }, { name: "enum", config: { entry: "a", devtool: true }, message: [ " - configuration.devtool should be one of these:", " string | false", " -> A developer tool to enhance debugging.", " Details:", " * configuration.devtool should be a string.", " * configuration.devtool should be false" ] }, { name: "! in path", config: { entry: "foo.js", output: { path: "/somepath/!test", filename: "bar" } }, message: [ ' - configuration.output.path: The provided value "/somepath/!test" contains exclamation mark (!) which is not allowed because it\'s reserved for loader syntax.', " -> The output directory as **absolute path** (required)." ] }, { name: "relative path", config: { entry: "foo.js", output: { filename: "/bar" } }, message: [ " - configuration.output.filename should be one of these:", " string | function", " -> Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.", " Details:", ' * configuration.output.filename: A relative path is expected. However, the provided value "/bar" is an absolute path!', " Please use output.path to specify absolute path and output.filename for the file name.", " * configuration.output.filename should be an instance of function" ] }, { name: "absolute path", config: { entry: "foo.js", output: { filename: "bar" }, context: "baz" }, message: [ ' - configuration.context: The provided value "baz" is not an absolute path!', " -> The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory." ] }, { name: "missing stats option", config: { entry: "foo.js", stats: { foobar: true } }, test(err) { expect(err.message).toMatch(/^Invalid configuration object./); expect(err.message.split("\n").slice(1)[0]).toBe( " - configuration.stats should be one of these:" ); } }, { name: "Invalid plugin provided: bool", config: { entry: "foo.js", plugins: [false] }, message: [ " - configuration.plugins[0] should be one of these:", " object { apply, … } | function", " -> Plugin of type object or instanceof Function", " Details:", " * configuration.plugins[0] should be an object.", " -> Plugin instance", " * configuration.plugins[0] should be an instance of function", " -> Function acting as plugin" ] }, { name: "Invalid plugin provided: array", config: { entry: "foo.js", plugins: [[]] }, message: [ " - configuration.plugins[0] should be one of these:", " object { apply, … } | function", " -> Plugin of type object or instanceof Function", " Details:", " * configuration.plugins[0] should be an object.", " -> Plugin instance", " * configuration.plugins[0] should be an instance of function", " -> Function acting as plugin" ] }, { name: "Invalid plugin provided: string", config: { entry: "foo.js", plugins: ["abc123"] }, message: [ " - configuration.plugins[0] should be one of these:", " object { apply, … } | function", " -> Plugin of type object or instanceof Function", " Details:", " * configuration.plugins[0] should be an object.", " -> Plugin instance", " * configuration.plugins[0] should be an instance of function", " -> Function acting as plugin" ] }, { name: "Invalid plugin provided: int", config: { entry: "foo.js", plugins: [12] }, message: [ " - configuration.plugins[0] should be one of these:", " object { apply, … } | function", " -> Plugin of type object or instanceof Function", " Details:", " * configuration.plugins[0] should be an object.", " -> Plugin instance", " * configuration.plugins[0] should be an instance of function", " -> Function acting as plugin" ] }, { name: "Invalid plugin provided: object without apply function", config: { entry: "foo.js", plugins: [{}] }, message: [ " - configuration.plugins[0] should be one of these:", " object { apply, … } | function", " -> Plugin of type object or instanceof Function", " Details:", " * configuration.plugins[0] misses the property 'apply'.", " function", " -> The run point of the plugin, required method.", " * configuration.plugins[0] should be an instance of function", " -> Function acting as plugin" ] } ]; testCases.forEach(testCase => { it("should fail validation for " + testCase.name, () => { try { webpack(testCase.config); } catch (err) { if (err.name !== "WebpackOptionsValidationError") throw err; if (testCase.test) { testCase.test(err); return; } expect(err.message).toMatch(/^Invalid configuration object./); expect(err.message.split("\n").slice(1)).toEqual(testCase.message); return; } throw new Error("Validation didn't fail"); }); }); }); webpack-4.30.0/test/WatchDetection.test.js000066400000000000000000000060661345416772700204420ustar00rootroot00000000000000"use strict"; /*globals describe it */ const path = require("path"); const fs = require("fs"); const MemoryFs = require("memory-fs"); const webpack = require("../"); describe("WatchDetection", () => { if (process.env.NO_WATCH_TESTS) { it.skip("long running tests excluded", () => {}); return; } jest.setTimeout(10000); for (let changeTimeout = 10; changeTimeout < 100; changeTimeout += 10) { createTestCase(changeTimeout); } for (let changeTimeout = 200; changeTimeout <= 2000; changeTimeout += 200) { createTestCase(changeTimeout); } function createTestCase(changeTimeout) { describe(`time between changes ${changeTimeout}ms`, () => { const fixturePath = path.join( __dirname, "fixtures", "temp-" + changeTimeout ); const filePath = path.join(fixturePath, "file.js"); const file2Path = path.join(fixturePath, "file2.js"); const loaderPath = path.join(__dirname, "fixtures", "delay-loader.js"); beforeAll(() => { try { fs.mkdirSync(fixturePath); } catch (e) { // empty } fs.writeFileSync(filePath, "require('./file2')", "utf-8"); fs.writeFileSync(file2Path, "original", "utf-8"); }); afterAll(done => { setTimeout(() => { try { fs.unlinkSync(filePath); } catch (e) { // empty } try { fs.unlinkSync(file2Path); } catch (e) { // empty } try { fs.rmdirSync(fixturePath); } catch (e) { // empty } done(); }, 100); // cool down a bit }); it("should build the bundle correctly", done => { const compiler = webpack({ mode: "development", entry: loaderPath + "!" + filePath, output: { path: "/", filename: "bundle.js" } }); const memfs = (compiler.outputFileSystem = new MemoryFs()); let onChange; compiler.hooks.done.tap("WatchDetectionTest", () => { if (onChange) onChange(); }); let watcher; step1(); function step1() { onChange = () => { if ( memfs.readFileSync("/bundle.js") && memfs .readFileSync("/bundle.js") .toString() .indexOf("original") >= 0 ) step2(); }; watcher = compiler.watch( { aggregateTimeout: 50 }, () => {} ); } function step2() { onChange = null; fs.writeFile( filePath, "require('./file2'); again", "utf-8", handleError ); setTimeout(step3, changeTimeout); } function step3() { onChange = null; fs.writeFile(file2Path, "wrong", "utf-8", handleError); setTimeout(step4, changeTimeout); } function step4() { onChange = () => { if ( memfs .readFileSync("/bundle.js") .toString() .indexOf("correct") >= 0 ) step5(); }; fs.writeFile(file2Path, "correct", "utf-8", handleError); } function step5() { onChange = null; watcher.close(() => { setTimeout(done, 500); }); } function handleError(err) { if (err) done(err); } }); }); } }); webpack-4.30.0/test/WatchTestCases.test.js000066400000000000000000000243261345416772700204210ustar00rootroot00000000000000/* global beforeAll expect */ "use strict"; const path = require("path"); const fs = require("fs"); const vm = require("vm"); const mkdirp = require("mkdirp"); const rimraf = require("rimraf"); const checkArrayExpectation = require("./checkArrayExpectation"); const createLazyTestEnv = require("./helpers/createLazyTestEnv"); const { remove } = require("./helpers/remove"); const Stats = require("../lib/Stats"); const webpack = require("../lib/webpack"); function copyDiff(src, dest, initial) { if (!fs.existsSync(dest)) fs.mkdirSync(dest); const files = fs.readdirSync(src); files.forEach(filename => { const srcFile = path.join(src, filename); const destFile = path.join(dest, filename); const directory = fs.statSync(srcFile).isDirectory(); if (directory) { copyDiff(srcFile, destFile, initial); } else { var content = fs.readFileSync(srcFile); if (/^DELETE\s*$/.test(content.toString("utf-8"))) { fs.unlinkSync(destFile); } else { fs.writeFileSync(destFile, content); if (initial) { const longTimeAgo = Date.now() - 1000 * 60 * 60 * 24; fs.utimesSync( destFile, Date.now() - longTimeAgo, Date.now() - longTimeAgo ); } } } }); } describe("WatchTestCases", () => { if (process.env.NO_WATCH_TESTS) { it.skip("long running tests excluded", () => {}); return; } const casesPath = path.join(__dirname, "watchCases"); let categories = fs.readdirSync(casesPath); categories = categories.map(cat => { return { name: cat, tests: fs .readdirSync(path.join(casesPath, cat)) .filter(folder => folder.indexOf("_") < 0) .filter(testName => { const testDirectory = path.join(casesPath, cat, testName); const filterPath = path.join(testDirectory, "test.filter.js"); if (fs.existsSync(filterPath) && !require(filterPath)()) { describe.skip(testName, () => it("filtered")); return false; } return true; }) .sort() }; }); beforeAll(() => { let dest = path.join(__dirname, "js"); if (!fs.existsSync(dest)) fs.mkdirSync(dest); dest = path.join(__dirname, "js", "watch-src"); if (!fs.existsSync(dest)) fs.mkdirSync(dest); }); categories.forEach(category => { beforeAll(() => { const dest = path.join(__dirname, "js", "watch-src", category.name); if (!fs.existsSync(dest)) fs.mkdirSync(dest); }); describe(category.name, () => { category.tests.forEach(testName => { describe(testName, () => { const tempDirectory = path.join( __dirname, "js", "watch-src", category.name, testName ); const testDirectory = path.join(casesPath, category.name, testName); const runs = fs .readdirSync(testDirectory) .sort() .filter(name => { return fs.statSync(path.join(testDirectory, name)).isDirectory(); }) .map(name => ({ name })); beforeAll(done => { rimraf(tempDirectory, done); }); it( testName + " should compile", done => { const outputDirectory = path.join( __dirname, "js", "watch", category.name, testName ); let options = {}; const configPath = path.join(testDirectory, "webpack.config.js"); if (fs.existsSync(configPath)) options = require(configPath); const applyConfig = options => { if (!options.mode) options.mode = "development"; if (!options.context) options.context = tempDirectory; if (!options.entry) options.entry = "./index.js"; if (!options.target) options.target = "async-node"; if (!options.output) options.output = {}; if (!options.output.path) options.output.path = outputDirectory; if (typeof options.output.pathinfo === "undefined") options.output.pathinfo = true; if (!options.output.filename) options.output.filename = "bundle.js"; }; if (Array.isArray(options)) { options.forEach(applyConfig); } else { applyConfig(options); } const state = {}; let runIdx = 0; let waitMode = false; let run = runs[runIdx]; let triggeringFilename; let lastHash = ""; const currentWatchStepModule = require("./helpers/currentWatchStep"); let compilationFinished = done; currentWatchStepModule.step = run.name; copyDiff(path.join(testDirectory, run.name), tempDirectory, true); setTimeout(() => { const compiler = webpack(options); compiler.hooks.invalid.tap( "WatchTestCasesTest", (filename, mtime) => { triggeringFilename = filename; } ); const watching = compiler.watch( { aggregateTimeout: 1000 }, (err, stats) => { if (err) return compilationFinished(err); if (!stats) return compilationFinished( new Error("No stats reported from Compiler") ); if (stats.hash === lastHash) return; lastHash = stats.hash; if (run.done && lastHash !== stats.hash) { return compilationFinished( new Error( "Compilation changed but no change was issued " + lastHash + " != " + stats.hash + " (run " + runIdx + ")\n" + "Triggering change: " + triggeringFilename ) ); } if (waitMode) return; run.done = true; if (err) return compilationFinished(err); const statOptions = Stats.presetToOptions("verbose"); statOptions.colors = false; mkdirp.sync(outputDirectory); fs.writeFileSync( path.join(outputDirectory, "stats.txt"), stats.toString(statOptions), "utf-8" ); const jsonStats = stats.toJson({ errorDetails: true }); if ( checkArrayExpectation( path.join(testDirectory, run.name), jsonStats, "error", "Error", compilationFinished ) ) return; if ( checkArrayExpectation( path.join(testDirectory, run.name), jsonStats, "warning", "Warning", compilationFinished ) ) return; const globalContext = { console: console, expect: expect }; function _require(currentDirectory, module) { if (Array.isArray(module) || /^\.\.?\//.test(module)) { let fn; let content; let p; if (Array.isArray(module)) { p = path.join(currentDirectory, module[0]); content = module .map(arg => { p = path.join(currentDirectory, arg); return fs.readFileSync(p, "utf-8"); }) .join("\n"); } else { p = path.join(currentDirectory, module); content = fs.readFileSync(p, "utf-8"); } if ( options.target === "web" || options.target === "webworker" ) { fn = vm.runInNewContext( "(function(require, module, exports, __dirname, __filename, it, WATCH_STEP, STATS_JSON, STATE, expect, window) {" + 'function nsObj(m) { Object.defineProperty(m, Symbol.toStringTag, { value: "Module" }); return m; }' + content + "\n})", globalContext, p ); } else { fn = vm.runInThisContext( "(function(require, module, exports, __dirname, __filename, it, WATCH_STEP, STATS_JSON, STATE, expect) {" + "global.expect = expect;" + 'function nsObj(m) { Object.defineProperty(m, Symbol.toStringTag, { value: "Module" }); return m; }' + content + "\n})", p ); } const m = { exports: {} }; fn.call( m.exports, _require.bind(null, path.dirname(p)), m, m.exports, path.dirname(p), p, run.it, run.name, jsonStats, state, expect, globalContext ); return module.exports; } else if ( testConfig.modules && module in testConfig.modules ) { return testConfig.modules[module]; } else return require.requireActual(module); } let testConfig = {}; try { // try to load a test file testConfig = require(path.join( testDirectory, "test.config.js" )); } catch (e) { // empty } if (testConfig.noTests) return process.nextTick(compilationFinished); _require( outputDirectory, testConfig.bundlePath || "./bundle.js" ); if (run.getNumberOfTests() < 1) return compilationFinished( new Error("No tests exported by test case") ); run.it("should compile the next step", done => { runIdx++; if (runIdx < runs.length) { run = runs[runIdx]; waitMode = true; setTimeout(() => { waitMode = false; compilationFinished = done; currentWatchStepModule.step = run.name; copyDiff( path.join(testDirectory, run.name), tempDirectory, false ); }, 1500); } else { watching.close(); done(); } }); compilationFinished(); } ); }, 300); }, 45000 ); for (const run of runs) { const { it: _it, getNumberOfTests } = createLazyTestEnv( jasmine.getEnv(), 10000, run.name ); run.it = _it; run.getNumberOfTests = getNumberOfTests; } afterAll(() => { remove(tempDirectory); }); }); }); }); }); }); webpack-4.30.0/test/WatcherEvents.test.js000066400000000000000000000031271345416772700203120ustar00rootroot00000000000000"use strict"; /* globals describe it */ const path = require("path"); const MemoryFs = require("memory-fs"); const webpack = require("../"); const createCompiler = config => { const compiler = webpack(config); compiler.outputFileSystem = new MemoryFs(); return compiler; }; const createSingleCompiler = () => { return createCompiler({ context: path.join(__dirname, "fixtures"), entry: "./a.js" }); }; const createMultiCompiler = () => { return createCompiler([ { context: path.join(__dirname, "fixtures"), entry: "./a.js" } ]); }; describe("WatcherEvents", () => { if (process.env.NO_WATCH_TESTS) { it.skip("long running tests excluded", () => {}); return; } jest.setTimeout(10000); it("should emit 'watch-close' when using single-compiler mode and the compiler is not running", done => { let called = false; const compiler = createSingleCompiler(); const watcher = compiler.watch({}, (err, stats) => { expect(called).toBe(true); done(err); }); compiler.hooks.watchClose.tap("WatcherEventsTest", () => { called = true; }); compiler.hooks.done.tap("WatcherEventsTest", () => { watcher.close(); }); }); it("should emit 'watch-close' when using multi-compiler mode and the compiler is not running", done => { let called = false; const compiler = createMultiCompiler(); const watcher = compiler.watch({}, (err, stats) => { expect(called).toBe(true); done(err); }); compiler.hooks.watchClose.tap("WatcherEventsTest", () => { called = true; }); compiler.hooks.done.tap("WatcherEventsTest", () => { watcher.close(); }); }); }); webpack-4.30.0/test/WebEnvironmentPlugin.unittest.js000066400000000000000000000011561345416772700225510ustar00rootroot00000000000000"use strict"; const WebEnvironmentPlugin = require("../lib/web/WebEnvironmentPlugin"); describe("WebEnvironmentPlugin", () => { describe("apply", () => { const WebEnvironmentPluginInstance = new WebEnvironmentPlugin( "inputFileSystem", "outputFileSystem" ); const compileSpy = { outputFileSystem: "otherOutputFileSystem" }; WebEnvironmentPluginInstance.apply(compileSpy); it("should set compiler.outputFileSystem information with the same as set in WebEnvironmentPlugin", () => { expect(compileSpy.outputFileSystem).toBe( WebEnvironmentPluginInstance.outputFileSystem ); }); }); }); webpack-4.30.0/test/WebpackError.unittest.js000066400000000000000000000014001345416772700210060ustar00rootroot00000000000000"use strict"; const path = require("path"); const util = require("util"); const WebpackError = require("../lib/WebpackError"); describe("WebpackError", () => { class CustomError extends WebpackError { constructor(message) { super(); this.name = "CustomError"; this.message = "CustomMessage"; this.details = "CustomDetails"; Error.captureStackTrace(this, this.constructor); } } it("Should provide inspect method for use by for util.inspect", () => { const errorStr = util.inspect(new CustomError("Message")); const errorArr = errorStr.split("\n"); expect(errorArr[0]).toBe("CustomError: CustomMessage"); expect(errorArr[1]).toMatch(path.basename(__filename)); expect(errorArr[errorArr.length - 1]).toBe("CustomDetails"); }); }); webpack-4.30.0/test/WebpackMissingModule.unittest.js000066400000000000000000000023151345416772700225020ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const WebpackMissingModule = require("../lib/dependencies/WebpackMissingModule"); describe("WebpackMissingModule", () => { describe("#moduleCode", () => { it("returns an error message based on given error message", () => { const errorMessage = WebpackMissingModule.moduleCode("mock message"); expect(errorMessage).toBe( "var e = new Error(\"Cannot find module 'mock message'\"); e.code = 'MODULE_NOT_FOUND'; throw e;" ); }); }); describe("#promise", () => { it("returns an error message based on given error message", () => { const errorMessage = WebpackMissingModule.promise("mock message"); expect(errorMessage).toBe( "Promise.reject(function webpackMissingModule() { var e = new Error(\"Cannot find module 'mock message'\"); e.code = 'MODULE_NOT_FOUND'; return e; }())" ); }); }); describe("#module", () => { it("returns an error message based on given error message", () => { const errorMessage = WebpackMissingModule.module("mock message"); expect(errorMessage).toBe( "!(function webpackMissingModule() { var e = new Error(\"Cannot find module 'mock message'\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())" ); }); }); }); webpack-4.30.0/test/__snapshots__/000077500000000000000000000000001345416772700170275ustar00rootroot00000000000000webpack-4.30.0/test/__snapshots__/ConfigTestCases.test.js.snap000066400000000000000000000024101345416772700243240ustar00rootroot00000000000000// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ConfigTestCases records issue-2991 exported tests should write relative paths to records 1`] = ` "{ \\"modules\\": { \\"byIdentifier\\": { \\"test.js\\": 0, \\"ignored pkgs/somepackage/foo\\": 1, \\"external \\\\\\"fs\\\\\\"\\": 2, \\"external \\\\\\"path\\\\\\"\\": 3 }, \\"usedIds\\": { \\"0\\": 0, \\"1\\": 1, \\"2\\": 2, \\"3\\": 3 } }, \\"chunks\\": { \\"byName\\": { \\"main\\": 0 }, \\"bySource\\": {}, \\"usedIds\\": [ 0 ] } }" `; exports[`ConfigTestCases records issue-7339 exported tests should write relative dynamic-require paths to records 1`] = ` "{ \\"modules\\": { \\"byIdentifier\\": { \\"dependencies/bar.js\\": 0, \\"dependencies/foo.js\\": 1, \\"test.js\\": 2, \\"dependencies sync /^\\\\\\\\.\\\\\\\\/.*$/\\": 3, \\"external \\\\\\"fs\\\\\\"\\": 4, \\"external \\\\\\"path\\\\\\"\\": 5 }, \\"usedIds\\": { \\"0\\": 0, \\"1\\": 1, \\"2\\": 2, \\"3\\": 3, \\"4\\": 4, \\"5\\": 5 } }, \\"chunks\\": { \\"byName\\": { \\"main\\": 0 }, \\"bySource\\": {}, \\"usedIds\\": [ 0 ] } }" `; webpack-4.30.0/test/__snapshots__/RemovedPlugins.unittest.js.snap000066400000000000000000000006461345416772700251540ustar00rootroot00000000000000// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`removed plugin errors should error when accessing removed plugins 1`] = `"webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead."`; exports[`removed plugin errors should error when accessing removed plugins 2`] = `"webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead."`; webpack-4.30.0/test/__snapshots__/StatsTestCases.test.js.snap000066400000000000000000005270251345416772700242330ustar00rootroot00000000000000// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`StatsTestCases should print correct stats for aggressive-splitting-entry 1`] = ` "Hash: 6b5ddd5d48acc0426e7a6b5ddd5d48acc0426e7a Child fitting: Hash: 6b5ddd5d48acc0426e7a Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 33966214360bbbb31383.js 1.94 KiB 2 [emitted] 445d4c6a1d7381d6cb2c.js 1.94 KiB 3 [emitted] d4b551c6319035df2898.js 1.05 KiB 0 [emitted] ed31350d9c86da6a8353.js 11 KiB 1 [emitted] Entrypoint main = 33966214360bbbb31383.js 445d4c6a1d7381d6cb2c.js ed31350d9c86da6a8353.js chunk {0} d4b551c6319035df2898.js 916 bytes <{1}> <{2}> <{3}> > ./g [4] ./index.js 7:0-13 [7] ./g.js 916 bytes {0} [built] chunk {1} ed31350d9c86da6a8353.js 1.87 KiB ={2}= ={3}= >{0}< [entry] [rendered] > ./index main [3] ./e.js 899 bytes {1} [built] [4] ./index.js 111 bytes {1} [built] [6] ./f.js 900 bytes {1} [built] chunk {2} 33966214360bbbb31383.js 1.76 KiB ={1}= ={3}= >{0}< [initial] [rendered] [recorded] aggressive splitted > ./index main [0] ./b.js 899 bytes {2} [built] [5] ./a.js 899 bytes {2} [built] chunk {3} 445d4c6a1d7381d6cb2c.js 1.76 KiB ={1}= ={2}= >{0}< [initial] [rendered] [recorded] aggressive splitted > ./index main [1] ./c.js 899 bytes {3} [built] [2] ./d.js 899 bytes {3} [built] Child content-change: Hash: 6b5ddd5d48acc0426e7a Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 33966214360bbbb31383.js 1.94 KiB 2 [emitted] 445d4c6a1d7381d6cb2c.js 1.94 KiB 3 [emitted] d4b551c6319035df2898.js 1.05 KiB 0 [emitted] ed31350d9c86da6a8353.js 11 KiB 1 [emitted] Entrypoint main = 33966214360bbbb31383.js 445d4c6a1d7381d6cb2c.js ed31350d9c86da6a8353.js chunk {0} d4b551c6319035df2898.js 916 bytes <{1}> <{2}> <{3}> > ./g [4] ./index.js 7:0-13 [7] ./g.js 916 bytes {0} [built] chunk {1} ed31350d9c86da6a8353.js 1.87 KiB ={2}= ={3}= >{0}< [entry] [rendered] > ./index main [3] ./e.js 899 bytes {1} [built] [4] ./index.js 111 bytes {1} [built] [6] ./f.js 900 bytes {1} [built] chunk {2} 33966214360bbbb31383.js 1.76 KiB ={1}= ={3}= >{0}< [initial] [rendered] [recorded] aggressive splitted > ./index main [0] ./b.js 899 bytes {2} [built] [5] ./a.js 899 bytes {2} [built] chunk {3} 445d4c6a1d7381d6cb2c.js 1.76 KiB ={1}= ={2}= >{0}< [initial] [rendered] [recorded] aggressive splitted > ./index main [1] ./c.js 899 bytes {3} [built] [2] ./d.js 899 bytes {3} [built]" `; exports[`StatsTestCases should print correct stats for aggressive-splitting-on-demand 1`] = ` "Hash: f682b6dfa3cec23b4fff Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 01a8254701931adbf278.js 1.01 KiB 9 [emitted] 07830cd8072d83cdc6ad.js 1.01 KiB 10 [emitted] 1cd3a64e15add49c06d8.js 9.64 KiB 4 [emitted] main 2736cf9d79233cd0a9b6.js 1.93 KiB 0 [emitted] 29de52df747b400f6177.js 1 KiB 1 [emitted] 41be79832883258c21e6.js 1.94 KiB 6 [emitted] 43c1ac24102c075ecb2d.js 1.94 KiB 3, 1 [emitted] 5bc7f208cd99a83b4e33.js 1.94 KiB 8 [emitted] 7f83e5c2f4e52435dd2c.js 1.96 KiB 2 [emitted] ba9fedb7aa0c69201639.js 1.94 KiB 11 [emitted] d40ae25f5e7ef09d2e24.js 1.94 KiB 7, 10 [emitted] e5fb899955fa03a8053b.js 1.94 KiB 5 [emitted] Entrypoint main = 1cd3a64e15add49c06d8.js chunk {0} 2736cf9d79233cd0a9b6.js 1.76 KiB <{4}> ={1}= ={2}= ={3}= ={6}= ={10}= [recorded] aggressive splitted > ./b ./d ./e ./f ./g [11] ./index.js 5:0-44 > ./b ./d ./e ./f ./g ./h ./i ./j ./k [11] ./index.js 6:0-72 [0] ./b.js 899 bytes {0} {5} [built] [1] ./d.js 899 bytes {0} {8} [built] chunk {1} 29de52df747b400f6177.js 899 bytes <{4}> ={0}= ={2}= ={8}= > ./c ./d ./e [11] ./index.js 3:0-30 > ./b ./d ./e ./f ./g [11] ./index.js 5:0-44 [2] ./e.js 899 bytes {1} {3} [built] chunk {2} 7f83e5c2f4e52435dd2c.js 1.76 KiB <{4}> ={0}= ={1}= ={3}= ={6}= ={7}= ={10}= ={11}= [recorded] aggressive splitted > ./f ./g ./h ./i ./j ./k [11] ./index.js 4:0-51 > ./b ./d ./e ./f ./g [11] ./index.js 5:0-44 > ./b ./d ./e ./f ./g ./h ./i ./j ./k [11] ./index.js 6:0-72 [3] ./f.js 899 bytes {2} [built] [4] ./g.js 901 bytes {2} [built] chunk {3} 43c1ac24102c075ecb2d.js 1.76 KiB <{4}> ={0}= ={2}= ={6}= ={10}= [rendered] [recorded] aggressive splitted > ./b ./d ./e ./f ./g ./h ./i ./j ./k [11] ./index.js 6:0-72 [2] ./e.js 899 bytes {1} {3} [built] [6] ./h.js 899 bytes {3} {11} [built] chunk {4} 1cd3a64e15add49c06d8.js (main) 248 bytes >{0}< >{1}< >{2}< >{3}< >{5}< >{6}< >{7}< >{8}< >{9}< >{10}< >{11}< [entry] [rendered] > ./index main [11] ./index.js 248 bytes {4} [built] chunk {5} e5fb899955fa03a8053b.js 1.76 KiB <{4}> > ./b ./c [11] ./index.js 2:0-23 [0] ./b.js 899 bytes {0} {5} [built] [5] ./c.js 899 bytes {5} {8} [built] chunk {6} 41be79832883258c21e6.js 1.76 KiB <{4}> ={0}= ={2}= ={3}= ={10}= [rendered] [recorded] aggressive splitted > ./b ./d ./e ./f ./g ./h ./i ./j ./k [11] ./index.js 6:0-72 [7] ./i.js 899 bytes {6} {11} [built] [8] ./j.js 901 bytes {6} {7} [built] chunk {7} d40ae25f5e7ef09d2e24.js 1.76 KiB <{4}> ={2}= ={11}= > ./f ./g ./h ./i ./j ./k [11] ./index.js 4:0-51 [8] ./j.js 901 bytes {6} {7} [built] [9] ./k.js 899 bytes {7} {10} [built] chunk {8} 5bc7f208cd99a83b4e33.js 1.76 KiB <{4}> ={1}= [recorded] aggressive splitted > ./c ./d ./e [11] ./index.js 3:0-30 [1] ./d.js 899 bytes {0} {8} [built] [5] ./c.js 899 bytes {5} {8} [built] chunk {9} 01a8254701931adbf278.js 899 bytes <{4}> > ./a [11] ./index.js 1:0-16 [10] ./a.js 899 bytes {9} [built] chunk {10} 07830cd8072d83cdc6ad.js 899 bytes <{4}> ={0}= ={2}= ={3}= ={6}= > ./b ./d ./e ./f ./g ./h ./i ./j ./k [11] ./index.js 6:0-72 [9] ./k.js 899 bytes {7} {10} [built] chunk {11} ba9fedb7aa0c69201639.js 1.76 KiB <{4}> ={2}= ={7}= [rendered] [recorded] aggressive splitted > ./f ./g ./h ./i ./j ./k [11] ./index.js 4:0-51 [6] ./h.js 899 bytes {3} {11} [built] [7] ./i.js 899 bytes {6} {11} [built]" `; exports[`StatsTestCases should print correct stats for async-commons-chunk 1`] = ` "Entrypoint main = main.js chunk {0} 0.js 21 bytes <{1}> ={2}= ={3}= [rendered] reused as split chunk (cache group: default) > [1] ./index.js 17:1-21:3 > [1] ./index.js 2:1-5:3 > ./a ./b [1] ./index.js 9:1-13:3 [0] ./a.js 21 bytes {0} [built] chunk {1} main.js (main) 515 bytes >{0}< >{2}< >{3}< [entry] [rendered] > ./ main [1] ./index.js 515 bytes {1} [built] chunk {2} 2.js 21 bytes <{1}> ={0}= [rendered] > ./a ./b [1] ./index.js 9:1-13:3 [2] ./b.js 21 bytes {2} [built] chunk {3} 3.js 21 bytes <{1}> ={0}= [rendered] > [1] ./index.js 17:1-21:3 [3] ./c.js 21 bytes {3} [built]" `; exports[`StatsTestCases should print correct stats for async-commons-chunk-auto 1`] = ` "Child disabled: Entrypoint main = disabled/main.js Entrypoint a = disabled/a.js Entrypoint b = disabled/b.js Entrypoint c = disabled/c.js chunk {0} disabled/a.js (a) 216 bytes >{4}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [1] ./node_modules/x.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [3] ./node_modules/y.js 20 bytes {0} {1} {2} {5} [built] [5] ./a.js + 1 modules 156 bytes {0} {1} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {1} disabled/async-a.js (async-a) 216 bytes <{7}> >{4}< [rendered] > ./a [7] ./index.js 1:0-47 [0] ./d.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [1] ./node_modules/x.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [3] ./node_modules/y.js 20 bytes {0} {1} {2} {5} [built] [5] ./a.js + 1 modules 156 bytes {0} {1} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {2} disabled/async-b.js (async-b) 152 bytes <{7}> [rendered] > ./b [7] ./index.js 2:0-47 [0] ./d.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [1] ./node_modules/x.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [2] ./f.js 20 bytes {2} {3} {4} {5} {6} [built] [3] ./node_modules/y.js 20 bytes {0} {1} {2} {5} [built] [4] ./b.js 72 bytes {2} {5} [built] chunk {3} disabled/async-c.js (async-c) 167 bytes <{7}> [rendered] > ./c [7] ./index.js 3:0-47 [0] ./d.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [1] ./node_modules/x.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [2] ./f.js 20 bytes {2} {3} {4} {5} {6} [built] [6] ./c.js + 1 modules 107 bytes {3} {6} [built] | ./c.js 72 bytes [built] | ./node_modules/z.js 20 bytes [built] chunk {4} disabled/async-g.js (async-g) 54 bytes <{0}> <{1}> [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [2] ./f.js 20 bytes {2} {3} {4} {5} {6} [built] [8] ./g.js 34 bytes {4} [built] chunk {5} disabled/b.js (b) 152 bytes [entry] [rendered] > ./b b [0] ./d.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [1] ./node_modules/x.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [2] ./f.js 20 bytes {2} {3} {4} {5} {6} [built] [3] ./node_modules/y.js 20 bytes {0} {1} {2} {5} [built] [4] ./b.js 72 bytes {2} {5} [built] chunk {6} disabled/c.js (c) 167 bytes [entry] [rendered] > ./c c [0] ./d.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [1] ./node_modules/x.js 20 bytes {0} {1} {2} {3} {5} {6} [built] [2] ./f.js 20 bytes {2} {3} {4} {5} {6} [built] [6] ./c.js + 1 modules 107 bytes {3} {6} [built] | ./c.js 72 bytes [built] | ./node_modules/z.js 20 bytes [built] chunk {7} disabled/main.js (main) 147 bytes >{1}< >{2}< >{3}< [entry] [rendered] > ./ main [7] ./index.js 147 bytes {7} [built] Child default: Entrypoint main = default/main.js Entrypoint a = default/a.js Entrypoint b = default/b.js Entrypoint c = default/c.js chunk {0} default/async-a~async-b~async-c.js (async-a~async-b~async-c) 20 bytes <{11}> ={1}= ={2}= ={3}= ={5}= ={6}= ={7}= ={12}= >{1}< >{8}< [rendered] split chunk (cache group: default) (name: async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {0} {4} {9} {10} [built] chunk {1} default/async-b~async-c~async-g.js (async-b~async-c~async-g) 20 bytes <{0}> <{2}> <{3}> <{4}> <{5}> <{11}> ={0}= ={2}= ={3}= ={6}= ={7}= ={8}= ={12}= [rendered] split chunk (cache group: default) (name: async-b~async-c~async-g) > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./g [] 6:0-47 > ./g [] 6:0-47 [2] ./f.js 20 bytes {1} {9} {10} [built] chunk {2} default/vendors~async-a~async-b~async-c.js (vendors~async-a~async-b~async-c) 20 bytes <{11}> ={0}= ={1}= ={3}= ={5}= ={6}= ={7}= ={12}= >{1}< >{8}< [rendered] split chunk (cache group: vendors) (name: vendors~async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] chunk {3} default/vendors~async-a~async-b.js (vendors~async-a~async-b) 20 bytes <{11}> ={0}= ={1}= ={2}= ={5}= ={6}= >{1}< >{8}< [rendered] split chunk (cache group: vendors) (name: vendors~async-a~async-b) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 [3] ./node_modules/y.js 20 bytes {3} {4} {9} [built] chunk {4} default/a.js (a) 216 bytes >{1}< >{8}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {0} {4} {9} {10} [built] [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] [3] ./node_modules/y.js 20 bytes {3} {4} {9} [built] [6] ./a.js + 1 modules 156 bytes {4} {5} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {5} default/async-a.js (async-a) 156 bytes <{11}> ={0}= ={2}= ={3}= >{1}< >{8}< [rendered] > ./a [8] ./index.js 1:0-47 [6] ./a.js + 1 modules 156 bytes {4} {5} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {6} default/async-b.js (async-b) 72 bytes <{11}> ={0}= ={1}= ={2}= ={3}= [rendered] > ./b [8] ./index.js 2:0-47 [4] ./b.js 72 bytes {6} {9} [built] chunk {7} default/async-c.js (async-c) 72 bytes <{11}> ={0}= ={1}= ={2}= ={12}= [rendered] > ./c [8] ./index.js 3:0-47 [5] ./c.js 72 bytes {7} {10} [built] chunk {8} default/async-g.js (async-g) 34 bytes <{0}> <{2}> <{3}> <{4}> <{5}> ={1}= [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [9] ./g.js 34 bytes {8} [built] chunk {9} default/b.js (b) 152 bytes [entry] [rendered] > ./b b [0] ./d.js 20 bytes {0} {4} {9} {10} [built] [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] [2] ./f.js 20 bytes {1} {9} {10} [built] [3] ./node_modules/y.js 20 bytes {3} {4} {9} [built] [4] ./b.js 72 bytes {6} {9} [built] chunk {10} default/c.js (c) 152 bytes [entry] [rendered] > ./c c [0] ./d.js 20 bytes {0} {4} {9} {10} [built] [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] [2] ./f.js 20 bytes {1} {9} {10} [built] [5] ./c.js 72 bytes {7} {10} [built] [7] ./node_modules/z.js 20 bytes {10} {12} [built] chunk {11} default/main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{5}< >{6}< >{7}< >{12}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {11} [built] chunk {12} default/vendors~async-c.js (vendors~async-c) 20 bytes <{11}> ={0}= ={1}= ={2}= ={7}= [rendered] split chunk (cache group: vendors) (name: vendors~async-c) > ./c [8] ./index.js 3:0-47 [7] ./node_modules/z.js 20 bytes {10} {12} [built] Child vendors: Entrypoint main = vendors/main.js Entrypoint a = vendors/vendors.js vendors/a.js Entrypoint b = vendors/vendors.js vendors/b.js Entrypoint c = vendors/vendors.js vendors/c.js chunk {0} vendors/vendors.js (vendors) 60 bytes ={1}= ={6}= ={7}= >{5}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors) > ./a a > ./b b > ./c c [1] ./node_modules/x.js 20 bytes {0} {2} {3} {4} [built] [3] ./node_modules/y.js 20 bytes {0} {2} {3} [built] [7] ./node_modules/z.js 20 bytes {0} {4} [built] chunk {1} vendors/a.js (a) 176 bytes ={0}= >{5}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [6] ./a.js + 1 modules 156 bytes {1} {2} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {2} vendors/async-a.js (async-a) 216 bytes <{8}> >{5}< [rendered] > ./a [8] ./index.js 1:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [1] ./node_modules/x.js 20 bytes {0} {2} {3} {4} [built] [3] ./node_modules/y.js 20 bytes {0} {2} {3} [built] [6] ./a.js + 1 modules 156 bytes {1} {2} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {3} vendors/async-b.js (async-b) 152 bytes <{8}> [rendered] > ./b [8] ./index.js 2:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [1] ./node_modules/x.js 20 bytes {0} {2} {3} {4} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [3] ./node_modules/y.js 20 bytes {0} {2} {3} [built] [4] ./b.js 72 bytes {3} {6} [built] chunk {4} vendors/async-c.js (async-c) 152 bytes <{8}> [rendered] > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [1] ./node_modules/x.js 20 bytes {0} {2} {3} {4} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [5] ./c.js 72 bytes {4} {7} [built] [7] ./node_modules/z.js 20 bytes {0} {4} [built] chunk {5} vendors/async-g.js (async-g) 54 bytes <{0}> <{1}> <{2}> [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [9] ./g.js 34 bytes {5} [built] chunk {6} vendors/b.js (b) 112 bytes ={0}= [entry] [rendered] > ./b b [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [4] ./b.js 72 bytes {3} {6} [built] chunk {7} vendors/c.js (c) 112 bytes ={0}= [entry] [rendered] > ./c c [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [5] ./c.js 72 bytes {4} {7} [built] chunk {8} vendors/main.js (main) 147 bytes >{2}< >{3}< >{4}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {8} [built] Child multiple-vendors: Entrypoint main = multiple-vendors/main.js Entrypoint a = multiple-vendors/libs-x.js multiple-vendors/vendors~a~async-a~async-b~b.js multiple-vendors/a.js Entrypoint b = multiple-vendors/libs-x.js multiple-vendors/vendors~a~async-a~async-b~b.js multiple-vendors/b.js Entrypoint c = multiple-vendors/libs-x.js multiple-vendors/vendors~async-c~c.js multiple-vendors/c.js chunk {0} multiple-vendors/libs-x.js (libs-x) 20 bytes <{12}> ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= >{3}< >{9}< [initial] [rendered] split chunk (cache group: libs) (name: libs-x) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./a a > ./b b > ./c c [2] ./node_modules/x.js 20 bytes {0} [built] chunk {1} multiple-vendors/vendors~a~async-a~async-b~b.js (vendors~a~async-a~async-b~b) 20 bytes <{12}> ={0}= ={2}= ={3}= ={5}= ={6}= ={7}= ={10}= >{3}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~a~async-a~async-b~b) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./a a > ./b b [3] ./node_modules/y.js 20 bytes {1} [built] chunk {2} multiple-vendors/async-a~async-b~async-c.js (async-a~async-b~async-c) 20 bytes <{12}> ={0}= ={1}= ={3}= ={4}= ={6}= ={7}= ={8}= >{3}< >{9}< [rendered] split chunk (cache group: default) (name: async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {2} {5} {10} {11} [built] chunk {3} multiple-vendors/async-b~async-c~async-g.js (async-b~async-c~async-g) 20 bytes <{0}> <{1}> <{2}> <{5}> <{6}> <{12}> ={0}= ={1}= ={2}= ={4}= ={7}= ={8}= ={9}= [rendered] split chunk (cache group: default) (name: async-b~async-c~async-g) > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./g [] 6:0-47 > ./g [] 6:0-47 [1] ./f.js 20 bytes {3} {10} {11} [built] chunk {4} multiple-vendors/vendors~async-c~c.js (vendors~async-c~c) 20 bytes <{12}> ={0}= ={2}= ={3}= ={8}= ={11}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~async-c~c) > ./c [8] ./index.js 3:0-47 > ./c c [7] ./node_modules/z.js 20 bytes {4} [built] chunk {5} multiple-vendors/a.js (a) 176 bytes ={0}= ={1}= >{3}< >{9}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {6} multiple-vendors/async-a.js (async-a) 156 bytes <{12}> ={0}= ={1}= ={2}= >{3}< >{9}< [rendered] > ./a [8] ./index.js 1:0-47 [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {7} multiple-vendors/async-b.js (async-b) 72 bytes <{12}> ={0}= ={1}= ={2}= ={3}= [rendered] > ./b [8] ./index.js 2:0-47 [4] ./b.js 72 bytes {7} {10} [built] chunk {8} multiple-vendors/async-c.js (async-c) 72 bytes <{12}> ={0}= ={2}= ={3}= ={4}= [rendered] > ./c [8] ./index.js 3:0-47 [5] ./c.js 72 bytes {8} {11} [built] chunk {9} multiple-vendors/async-g.js (async-g) 34 bytes <{0}> <{1}> <{2}> <{5}> <{6}> ={3}= [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [9] ./g.js 34 bytes {9} [built] chunk {10} multiple-vendors/b.js (b) 112 bytes ={0}= ={1}= [entry] [rendered] > ./b b [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [1] ./f.js 20 bytes {3} {10} {11} [built] [4] ./b.js 72 bytes {7} {10} [built] chunk {11} multiple-vendors/c.js (c) 112 bytes ={0}= ={4}= [entry] [rendered] > ./c c [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [1] ./f.js 20 bytes {3} {10} {11} [built] [5] ./c.js 72 bytes {8} {11} [built] chunk {12} multiple-vendors/main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{4}< >{6}< >{7}< >{8}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {12} [built] Child all: Entrypoint main = all/main.js Entrypoint a = all/vendors~a~async-a~async-b~async-c~b~c.js all/vendors~a~async-a~async-b~b.js all/a.js Entrypoint b = all/vendors~a~async-a~async-b~async-c~b~c.js all/vendors~a~async-a~async-b~b.js all/b.js Entrypoint c = all/vendors~a~async-a~async-b~async-c~b~c.js all/vendors~async-c~c.js all/c.js chunk {0} all/vendors~a~async-a~async-b~async-c~b~c.js (vendors~a~async-a~async-b~async-c~b~c) 20 bytes <{12}> ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= >{3}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~a~async-a~async-b~async-c~b~c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./a a > ./b b > ./c c [2] ./node_modules/x.js 20 bytes {0} [built] chunk {1} all/vendors~a~async-a~async-b~b.js (vendors~a~async-a~async-b~b) 20 bytes <{12}> ={0}= ={2}= ={3}= ={5}= ={6}= ={7}= ={10}= >{3}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~a~async-a~async-b~b) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./a a > ./b b [3] ./node_modules/y.js 20 bytes {1} [built] chunk {2} all/async-a~async-b~async-c.js (async-a~async-b~async-c) 20 bytes <{12}> ={0}= ={1}= ={3}= ={4}= ={6}= ={7}= ={8}= >{3}< >{9}< [rendered] split chunk (cache group: default) (name: async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {2} {5} {10} {11} [built] chunk {3} all/async-b~async-c~async-g.js (async-b~async-c~async-g) 20 bytes <{0}> <{1}> <{2}> <{5}> <{6}> <{12}> ={0}= ={1}= ={2}= ={4}= ={7}= ={8}= ={9}= [rendered] split chunk (cache group: default) (name: async-b~async-c~async-g) > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./g [] 6:0-47 > ./g [] 6:0-47 [1] ./f.js 20 bytes {3} {10} {11} [built] chunk {4} all/vendors~async-c~c.js (vendors~async-c~c) 20 bytes <{12}> ={0}= ={2}= ={3}= ={8}= ={11}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~async-c~c) > ./c [8] ./index.js 3:0-47 > ./c c [7] ./node_modules/z.js 20 bytes {4} [built] chunk {5} all/a.js (a) 176 bytes ={0}= ={1}= >{3}< >{9}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {6} all/async-a.js (async-a) 156 bytes <{12}> ={0}= ={1}= ={2}= >{3}< >{9}< [rendered] > ./a [8] ./index.js 1:0-47 [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {7} all/async-b.js (async-b) 72 bytes <{12}> ={0}= ={1}= ={2}= ={3}= [rendered] > ./b [8] ./index.js 2:0-47 [4] ./b.js 72 bytes {7} {10} [built] chunk {8} all/async-c.js (async-c) 72 bytes <{12}> ={0}= ={2}= ={3}= ={4}= [rendered] > ./c [8] ./index.js 3:0-47 [5] ./c.js 72 bytes {8} {11} [built] chunk {9} all/async-g.js (async-g) 34 bytes <{0}> <{1}> <{2}> <{5}> <{6}> ={3}= [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [9] ./g.js 34 bytes {9} [built] chunk {10} all/b.js (b) 112 bytes ={0}= ={1}= [entry] [rendered] > ./b b [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [1] ./f.js 20 bytes {3} {10} {11} [built] [4] ./b.js 72 bytes {7} {10} [built] chunk {11} all/c.js (c) 112 bytes ={0}= ={4}= [entry] [rendered] > ./c c [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [1] ./f.js 20 bytes {3} {10} {11} [built] [5] ./c.js 72 bytes {8} {11} [built] chunk {12} all/main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{4}< >{6}< >{7}< >{8}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {12} [built]" `; exports[`StatsTestCases should print correct stats for chunk-module-id-range 1`] = ` "Hash: 88889d87c9bc8eba9a2b Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main1.js 4.86 KiB 1 [emitted] main1 main2.js 4.85 KiB 0 [emitted] main2 Entrypoint main1 = main1.js Entrypoint main2 = main2.js chunk {0} main2.js (main2) 136 bytes [entry] [rendered] > ./main2 main2 [0] ./d.js 20 bytes {0} {1} [built] [1] ./e.js 20 bytes {0} [built] [2] ./f.js 20 bytes {0} [built] [3] ./main2.js 56 bytes {0} [built] [101] ./a.js 20 bytes {0} {1} [built] chunk {1} main1.js (main1) 136 bytes [entry] [rendered] > ./main1 main1 [0] ./d.js 20 bytes {0} {1} [built] [4] ./c.js 20 bytes {1} [built] [100] ./main1.js 56 bytes {1} [built] [101] ./a.js 20 bytes {0} {1} [built] [102] ./b.js 20 bytes {1} [built]" `; exports[`StatsTestCases should print correct stats for chunks 1`] = ` "Hash: 34cad0d1897c8ba31143 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.bundle.js 232 bytes 1 [emitted] 2.bundle.js 152 bytes 2 [emitted] 3.bundle.js 289 bytes 3 [emitted] bundle.js 8.23 KiB 0 [emitted] main Entrypoint main = bundle.js chunk {0} bundle.js (main) 73 bytes >{2}< >{3}< [entry] [rendered] > ./index main [0] ./index.js 51 bytes {0} [built] single entry ./index main factory:Xms building:Xms = Xms [1] ./a.js 22 bytes {0} [built] cjs require ./a [0] ./index.js 1:0-14 [0] Xms -> factory:Xms building:Xms = Xms chunk {1} 1.bundle.js 44 bytes <{3}> [rendered] > [3] ./c.js 1:0-52 [4] ./d.js 22 bytes {1} [built] require.ensure item ./d [3] ./c.js 1:0-52 [0] Xms -> [3] Xms -> factory:Xms building:Xms = Xms [5] ./e.js 22 bytes {1} [built] require.ensure item ./e [3] ./c.js 1:0-52 [0] Xms -> [3] Xms -> factory:Xms building:Xms = Xms chunk {2} 2.bundle.js 22 bytes <{0}> [rendered] > ./b [0] ./index.js 2:0-16 [2] ./b.js 22 bytes {2} [built] amd require ./b [0] ./index.js 2:0-16 [0] Xms -> factory:Xms building:Xms = Xms chunk {3} 3.bundle.js 54 bytes <{0}> >{1}< [rendered] > ./c [0] ./index.js 3:0-16 [3] ./c.js 54 bytes {3} [built] amd require ./c [0] ./index.js 3:0-16 [0] Xms -> factory:Xms building:Xms = Xms" `; exports[`StatsTestCases should print correct stats for chunks-development 1`] = ` "Hash: 7192da34b98e59fe39b2 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 0.bundle.js 588 bytes 0 [emitted] 1.bundle.js 297 bytes 1 [emitted] 2.bundle.js 433 bytes 2 [emitted] bundle.js 8.61 KiB main [emitted] main Entrypoint main = bundle.js chunk {0} 0.bundle.js 60 bytes <{2}> [rendered] > [./c.js] ./c.js 1:0-52 [./d.js] 22 bytes {0} [built] require.ensure item ./d [./c.js] 1:0-52 [./index.js] Xms -> [./c.js] Xms -> factory:Xms building:Xms = Xms [./e.js] 38 bytes {0} [built] require.ensure item ./e [./c.js] 1:0-52 [./index.js] Xms -> [./c.js] Xms -> factory:Xms building:Xms = Xms chunk {1} 1.bundle.js 22 bytes <{main}> [rendered] > ./b [./index.js] ./index.js 2:0-16 [./b.js] 22 bytes {1} [built] amd require ./b [./index.js] 2:0-16 [./index.js] Xms -> factory:Xms building:Xms = Xms chunk {2} 2.bundle.js 54 bytes <{main}> >{0}< [rendered] > ./c [./index.js] ./index.js 3:0-16 [./c.js] 54 bytes {2} [built] amd require ./c [./index.js] 3:0-16 [./index.js] Xms -> factory:Xms building:Xms = Xms chunk {main} bundle.js (main) 73 bytes >{1}< >{2}< [entry] [rendered] > ./index main [./a.js] 22 bytes {main} [built] cjs require ./a [./e.js] 1:0-14 cjs require ./a [./index.js] 1:0-14 [./index.js] Xms -> factory:Xms building:Xms = Xms [./index.js] 51 bytes {main} [built] single entry ./index main factory:Xms building:Xms = Xms" `; exports[`StatsTestCases should print correct stats for circular-correctness 1`] = ` "Entrypoint main = bundle.js chunk {0} 0.bundle.js (a) 49 bytes <{2}> <{3}> >{2}< [rendered] [1] ./module-a.js 49 bytes {0} [built] chunk {1} 1.bundle.js (b) 49 bytes <{2}> <{3}> >{2}< [rendered] [2] ./module-b.js 49 bytes {1} [built] chunk {2} 2.bundle.js (c) 98 bytes <{0}> <{1}> >{0}< >{1}< [rendered] [3] ./module-c.js 98 bytes {2} [built] chunk {3} bundle.js (main) 98 bytes >{0}< >{1}< [entry] [rendered] [0] ./index.js 98 bytes {3} [built]" `; exports[`StatsTestCases should print correct stats for color-disabled 1`] = ` "Hash: aa5b75cccf66cd9b1ffa Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.57 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 0 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for color-enabled 1`] = ` "Hash: aa5b75cccf66cd9b1ffa Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.57 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 0 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for color-enabled-custom 1`] = ` "Hash: aa5b75cccf66cd9b1ffa Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.57 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 0 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for commons-chunk-min-size-0 1`] = ` "Hash: 578e4c7a1795861b0a9c Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names entry-1.js 6.6 KiB 0 [emitted] entry-1 vendor-1~entry-1.js 314 bytes 1 [emitted] vendor-1~entry-1 Entrypoint entry-1 = vendor-1~entry-1.js entry-1.js [0] ./entry-1.js 145 bytes {0} [built] [1] ./modules/a.js 22 bytes {1} [built] [2] ./modules/b.js 22 bytes {1} [built] [3] ./modules/c.js 22 bytes {1} [built] [4] ./modules/d.js 22 bytes {0} [built] [5] ./modules/e.js 22 bytes {0} [built] [6] ./modules/f.js 22 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for commons-chunk-min-size-Infinity 1`] = ` "Hash: 8d92f1bebd2cb6793d22 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names entry-1.js 6.6 KiB 0 [emitted] entry-1 vendor-1.js 314 bytes 1 [emitted] vendor-1 Entrypoint entry-1 = vendor-1.js entry-1.js [0] ./entry-1.js 145 bytes {0} [built] [1] ./modules/a.js 22 bytes {1} [built] [2] ./modules/b.js 22 bytes {1} [built] [3] ./modules/c.js 22 bytes {1} [built] [4] ./modules/d.js 22 bytes {0} [built] [5] ./modules/e.js 22 bytes {0} [built] [6] ./modules/f.js 22 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for commons-plugin-issue-4980 1`] = ` "Hash: 159313d738428f44ef68a283ef191845660a080d Child Hash: 159313d738428f44ef68 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names app.js 6.69 KiB 0 [emitted] app vendor.aa94f0c872c214f6cb2e.js 619 bytes 1 [emitted] vendor Entrypoint app = vendor.aa94f0c872c214f6cb2e.js app.js [./constants.js] 87 bytes {1} [built] [./entry-1.js] ./entry-1.js + 2 modules 190 bytes {0} [built] | ./entry-1.js 67 bytes [built] | ./submodule-a.js 59 bytes [built] | ./submodule-b.js 59 bytes [built] Child Hash: a283ef191845660a080d Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names app.js 6.7 KiB 0 [emitted] app vendor.aa94f0c872c214f6cb2e.js 619 bytes 1 [emitted] vendor Entrypoint app = vendor.aa94f0c872c214f6cb2e.js app.js [./constants.js] 87 bytes {1} [built] [./entry-2.js] ./entry-2.js + 2 modules 197 bytes {0} [built] | ./entry-2.js 67 bytes [built] | ./submodule-a.js 59 bytes [built] | ./submodule-c.js 66 bytes [built]" `; exports[`StatsTestCases should print correct stats for concat-and-sideeffects 1`] = ` "[0] ./index.js + 2 modules 119 bytes {0} [built] | ./index.js 46 bytes [built] | ModuleConcatenation bailout: Module is an entry point | ./node_modules/pmodule/a.js 49 bytes [built] | ./node_modules/pmodule/aa.js 24 bytes [built] [1] ./node_modules/pmodule/index.js 63 bytes [built] ModuleConcatenation bailout: Module is not in any chunk [2] ./node_modules/pmodule/b.js 49 bytes [built] ModuleConcatenation bailout: Module is not in any chunk [3] ./node_modules/pmodule/bb.js 24 bytes [built] ModuleConcatenation bailout: Module is not in any chunk [4] ./node_modules/pmodule/c.js 49 bytes [built] ModuleConcatenation bailout: Module is not in any chunk [5] ./node_modules/pmodule/cc.js 24 bytes [built] ModuleConcatenation bailout: Module is not in any chunk" `; exports[`StatsTestCases should print correct stats for define-plugin 1`] = ` "Hash: 97d5f15cb3086ba8eb8878ce8186fd9442bfeb83c3284590614d84a86804 Child Hash: 97d5f15cb3086ba8eb88 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.6 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 24 bytes {0} [built] Child Hash: 78ce8186fd9442bfeb83 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.6 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 24 bytes {0} [built] Child Hash: c3284590614d84a86804 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.6 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 24 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for dll-reference-plugin-issue-7624 1`] = ` "Hash: 5a94740543bfdf73ae19 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 3.6 KiB 0 [emitted] main Entrypoint main = bundle.js [0] ./entry.js 29 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for dll-reference-plugin-issue-7624-error 1`] = ` "Hash: 85ed2c36acb938b99695 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 3.6 KiB 0 main Entrypoint main = bundle.js [0] ./entry.js 29 bytes {0} [built] ERROR in Dll manifest blank-manifest.json Unexpected end of JSON input while parsing near ''" `; exports[`StatsTestCases should print correct stats for exclude-with-loader 1`] = ` "Hash: b79137b5927646440aa7 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 4.01 KiB 0 [emitted] main + 1 hidden asset Entrypoint main = bundle.js [0] ./index.js 77 bytes {0} [built] [1] ./a.txt 43 bytes {0} [built] + 2 hidden modules" `; exports[`StatsTestCases should print correct stats for external 1`] = ` "Hash: ce617e255d7a82e9e1e3 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.71 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 17 bytes {0} [built] [1] external \\"test\\" 42 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for filter-warnings 1`] = ` "Hash: 36eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c836eb8b91d0120efd48c8 Child undefined: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js WARNING in Terser Plugin: Dropping side-effect-free statement [./index.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction1 [./index.js:8,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction2 [./index.js:9,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction3 [./index.js:10,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction4 [./index.js:11,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction5 [./index.js:12,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction5 [./a.js:7,0] Child Terser: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js Child /Terser/: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js Child warnings => true: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js Child [Terser]: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js Child [/Terser/]: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js Child [warnings => true]: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js Child should not filter: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js WARNING in Terser Plugin: Dropping side-effect-free statement [./index.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction1 [./index.js:8,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction2 [./index.js:9,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction3 [./index.js:10,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction4 [./index.js:11,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction5 [./index.js:12,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction5 [./a.js:7,0] Child /should not filter/: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js WARNING in Terser Plugin: Dropping side-effect-free statement [./index.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction1 [./index.js:8,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction2 [./index.js:9,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction3 [./index.js:10,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction4 [./index.js:11,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction5 [./index.js:12,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction5 [./a.js:7,0] Child warnings => false: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js WARNING in Terser Plugin: Dropping side-effect-free statement [./index.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction1 [./index.js:8,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction2 [./index.js:9,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction3 [./index.js:10,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction4 [./index.js:11,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction5 [./index.js:12,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction5 [./a.js:7,0] Child [should not filter]: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js WARNING in Terser Plugin: Dropping side-effect-free statement [./index.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction1 [./index.js:8,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction2 [./index.js:9,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction3 [./index.js:10,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction4 [./index.js:11,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction5 [./index.js:12,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction5 [./a.js:7,0] Child [/should not filter/]: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js WARNING in Terser Plugin: Dropping side-effect-free statement [./index.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction1 [./index.js:8,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction2 [./index.js:9,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction3 [./index.js:10,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction4 [./index.js:11,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction5 [./index.js:12,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction5 [./a.js:7,0] Child [warnings => false]: Hash: 36eb8b91d0120efd48c8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js WARNING in Terser Plugin: Dropping side-effect-free statement [./index.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction1 [./index.js:8,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction2 [./index.js:9,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction3 [./index.js:10,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction4 [./index.js:11,0] WARNING in Terser Plugin: Dropping unused function someUnUsedFunction5 [./index.js:12,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someRemoteUnUsedFunction5 [./a.js:7,0]" `; exports[`StatsTestCases should print correct stats for graph-correctness-entries 1`] = ` "Entrypoint e1 = e1.js Entrypoint e2 = e2.js chunk {0} a.js (a) 49 bytes <{2}> <{3}> >{1}< [rendered] [2] ./module-a.js 49 bytes {0} [built] import() ./module-a [0] ./e1.js 1:0-47 import() ./module-a [3] ./module-c.js 1:0-47 chunk {1} b.js (b) 49 bytes <{0}> >{2}< [rendered] [4] ./module-b.js 49 bytes {1} [built] import() ./module-b [2] ./module-a.js 1:0-47 chunk {2} c.js (c) 49 bytes <{1}> <{4}> >{0}< [rendered] [3] ./module-c.js 49 bytes {2} [built] import() ./module-c [1] ./e2.js 1:0-47 import() ./module-c [4] ./module-b.js 1:0-47 chunk {3} e1.js (e1) 49 bytes >{0}< [entry] [rendered] [0] ./e1.js 49 bytes {3} [built] single entry ./e1 e1 chunk {4} e2.js (e2) 49 bytes >{2}< [entry] [rendered] [1] ./e2.js 49 bytes {4} [built] single entry ./e2 e2" `; exports[`StatsTestCases should print correct stats for graph-correctness-modules 1`] = ` "Entrypoint e1 = e1.js Entrypoint e2 = e2.js chunk {0} a.js (a) 49 bytes <{2}> <{3}> >{1}< [rendered] [4] ./module-a.js 49 bytes {0} [built] import() ./module-a [2] ./e1.js 2:0-47 import() ./module-a [5] ./module-c.js 1:0-47 chunk {1} b.js (b) 179 bytes <{0}> >{2}< [rendered] [6] ./module-b.js 179 bytes {1} [built] import() ./module-b [4] ./module-a.js 1:0-47 chunk {2} c.js (c) 49 bytes <{1}> <{4}> >{0}< [rendered] [5] ./module-c.js 49 bytes {2} [built] import() ./module-c [3] ./e2.js 2:0-47 import() ./module-c [6] ./module-b.js 1:0-47 chunk {3} e1.js (e1) 119 bytes >{0}< >{5}< [entry] [rendered] [0] ./module-x.js 49 bytes {3} {4} [built] harmony side effect evaluation ./module-x [2] ./e1.js 1:0-20 harmony side effect evaluation ./module-x [3] ./e2.js 1:0-20 import() ./module-x [6] ./module-b.js 2:0-20 [2] ./e1.js 70 bytes {3} [built] single entry ./e1 e1 chunk {4} e2.js (e2) 119 bytes >{2}< >{5}< [entry] [rendered] [0] ./module-x.js 49 bytes {3} {4} [built] harmony side effect evaluation ./module-x [2] ./e1.js 1:0-20 harmony side effect evaluation ./module-x [3] ./e2.js 1:0-20 import() ./module-x [6] ./module-b.js 2:0-20 [3] ./e2.js 70 bytes {4} [built] single entry ./e2 e2 chunk {5} y.js (y) 0 bytes <{3}> <{4}> [rendered] [1] ./module-y.js 0 bytes {5} [built] import() ./module-y [0] ./module-x.js 1:0-47" `; exports[`StatsTestCases should print correct stats for import-context-filter 1`] = ` "Hash: cbf8fc5e9562c9249823 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 0.js 305 bytes 0 [emitted] 1.js 314 bytes 1 [emitted] 2.js 308 bytes 2 [emitted] entry.js 9.05 KiB 3 [emitted] entry Entrypoint entry = entry.js [0] ./templates/bar.js 38 bytes {0} [optional] [built] [1] ./templates/baz.js 38 bytes {1} [optional] [built] [2] ./templates/foo.js 38 bytes {2} [optional] [built] [3] ./entry.js 450 bytes {3} [built] [4] ./templates lazy ^\\\\.\\\\/.*$ include: \\\\.js$ exclude: \\\\.noimport\\\\.js$ namespace object 160 bytes {3} [optional] [built]" `; exports[`StatsTestCases should print correct stats for import-weak 1`] = ` "Hash: 818b39ea7c5c1ff94df3 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 149 bytes 1 [emitted] entry.js 8.47 KiB 0 [emitted] entry Entrypoint entry = entry.js [0] ./modules/b.js 22 bytes {1} [built] [1] ./entry.js 120 bytes {0} [built] [2] ./modules/a.js 37 bytes [built]" `; exports[`StatsTestCases should print correct stats for import-with-invalid-options-comments 1`] = ` "Built at: Thu Jan 01 1970 00:00:00 GMT [0] ./index.js 50 bytes {2} [built] [1] ./chunk.js 401 bytes {0} [built] [3 warnings] [2] ./chunk-a.js 27 bytes {4} [built] [3] ./chunk-b.js 27 bytes {1} [built] [4] ./chunk-c.js 27 bytes {5} [built] [5] ./chunk-d.js 27 bytes {3} [built] WARNING in ./chunk.js 4:11-77 Compilation error while processing magic comment(-s): /* webpack Prefetch: 0, webpackChunkName: \\"notGoingToCompile-c\\" */: Unexpected identifier @ ./index.js 1:0-49 WARNING in ./chunk.js 5:11-38 Compilation error while processing magic comment(-s): /* webpackPrefetch: nope */: nope is not defined @ ./index.js 1:0-49 WARNING in ./chunk.js 2:11-84 Compilation error while processing magic comment(-s): /* webpackPrefetch: true, webpackChunkName: notGoingToCompileChunkName */: notGoingToCompileChunkName is not defined @ ./index.js 1:0-49" `; exports[`StatsTestCases should print correct stats for issue-7577 1`] = ` "Hash: 3a382f7c6759b0401b6ff9bcd7c310309db5b68ce2bf53b0bf1432b722d8 Child Hash: 3a382f7c6759b0401b6f Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names a-all~main-0034bb84916bcade4cc7.js 154 bytes all~main [emitted] all~main a-main-14ee9c594789bd77b887.js 108 bytes main [emitted] main a-runtime~main-7b4918090cfe19b7778a.js 6.05 KiB runtime~main [emitted] runtime~main Entrypoint main = a-runtime~main-7b4918090cfe19b7778a.js a-all~main-0034bb84916bcade4cc7.js a-main-14ee9c594789bd77b887.js [0] ./a.js 18 bytes {all~main} [built] Child Hash: f9bcd7c310309db5b68c Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names b-all~main-3f0b62a9e243706ccaf8.js 468 bytes all~main [emitted] all~main b-main-09f4ddfc4098d7f3f188.js 123 bytes main [emitted] main b-runtime~main-7b4918090cfe19b7778a.js 6.05 KiB runtime~main [emitted] runtime~main b-vendors~main-f7664221ad5d986cf06a.js 163 bytes vendors~main [emitted] vendors~main Entrypoint main = b-runtime~main-7b4918090cfe19b7778a.js b-vendors~main-f7664221ad5d986cf06a.js b-all~main-3f0b62a9e243706ccaf8.js b-main-09f4ddfc4098d7f3f188.js [0] ./node_modules/vendor.js 23 bytes {vendors~main} [built] [1] ./b.js 17 bytes {all~main} [built] Child Hash: e2bf53b0bf1432b722d8 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names c-0-5b8bdddff2dcbbac44bf.js 450 bytes 0 [emitted] c-1-5eacbd7fee2224716029.js 153 bytes 1 [emitted] c-all~main-3de9f206741c28715d19.js 305 bytes all~main [emitted] all~main c-main-75156155081cda3092db.js 114 bytes main [emitted] main c-runtime~main-a95c7b9d72f76dc9feef.js 8.78 KiB runtime~main [emitted] runtime~main Entrypoint main = c-runtime~main-a95c7b9d72f76dc9feef.js c-all~main-3de9f206741c28715d19.js c-main-75156155081cda3092db.js (prefetch: c-1-5eacbd7fee2224716029.js c-0-5b8bdddff2dcbbac44bf.js) [0] ./b.js 17 bytes {0} [built] [1] ./c.js 61 bytes {all~main} [built] [2] ./node_modules/vendor.js 23 bytes {1} [built]" `; exports[`StatsTestCases should print correct stats for limit-chunk-count-plugin 1`] = ` "Hash: 4c228d725cbf3eab49b0c4c4e0337021c38dadbfe19eb8024444df3ec45e8ce9ff5edae99037259a Child 1 chunks: Hash: 4c228d725cbf3eab49b0 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 6.67 KiB 0 [emitted] main Entrypoint main = bundle.js chunk {0} bundle.js (main) 219 bytes <{0}> >{0}< [entry] [rendered] [0] ./index.js 101 bytes {0} [built] [1] ./a.js 22 bytes {0} [built] [2] ./b.js 22 bytes {0} [built] [3] ./c.js 30 bytes {0} [built] [4] ./d.js 22 bytes {0} [built] [5] ./e.js 22 bytes {0} [built] Child 2 chunks: Hash: c4c4e0337021c38dadbf Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 0.bundle.js 401 bytes 0 [emitted] bundle.js 8.46 KiB 1 [emitted] main Entrypoint main = bundle.js chunk {0} 0.bundle.js 88 bytes <{1}> [rendered] [2] ./a.js 22 bytes {0} [built] [3] ./b.js 22 bytes {0} [built] [4] ./d.js 22 bytes {0} [built] [5] ./e.js 22 bytes {0} [built] chunk {1} bundle.js (main) 131 bytes <{1}> >{0}< >{1}< [entry] [rendered] [0] ./index.js 101 bytes {1} [built] [1] ./c.js 30 bytes {1} [built] Child 3 chunks: Hash: e19eb8024444df3ec45e Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.bundle.js 245 bytes 1 [emitted] 2.bundle.js 232 bytes 2 [emitted] bundle.js 8.46 KiB 0 [emitted] main Entrypoint main = bundle.js chunk {0} bundle.js (main) 131 bytes <{0}> >{0}< >{1}< >{2}< [entry] [rendered] [0] ./index.js 101 bytes {0} [built] [1] ./c.js 30 bytes {0} [built] chunk {1} 1.bundle.js 44 bytes <{0}> [rendered] [2] ./a.js 22 bytes {1} [built] [3] ./b.js 22 bytes {1} [built] chunk {2} 2.bundle.js 44 bytes <{0}> [rendered] [4] ./d.js 22 bytes {2} [built] [5] ./e.js 22 bytes {2} [built] Child 4 chunks: Hash: 8ce9ff5edae99037259a Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.bundle.js 245 bytes 1 [emitted] 2.bundle.js 152 bytes 2 [emitted] 3.bundle.js 152 bytes 3 [emitted] bundle.js 8.46 KiB 0 [emitted] main Entrypoint main = bundle.js chunk {0} bundle.js (main) 131 bytes <{0}> >{0}< >{1}< >{2}< >{3}< [entry] [rendered] [0] ./index.js 101 bytes {0} [built] [1] ./c.js 30 bytes {0} [built] chunk {1} 1.bundle.js 44 bytes <{0}> [rendered] [2] ./a.js 22 bytes {1} [built] [3] ./b.js 22 bytes {1} [built] chunk {2} 2.bundle.js 22 bytes <{0}> [rendered] [4] ./d.js 22 bytes {2} [built] chunk {3} 3.bundle.js 22 bytes <{0}> [rendered] [5] ./e.js 22 bytes {3} [built]" `; exports[`StatsTestCases should print correct stats for max-modules 1`] = ` "Hash: d0b29852af8ccc4949b7 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 6.81 KiB 0 [emitted] main Entrypoint main = main.js [0] ./a.js?1 33 bytes {0} [built] [1] ./a.js?2 33 bytes {0} [built] [2] ./a.js?3 33 bytes {0} [built] [3] ./a.js?4 33 bytes {0} [built] [4] ./a.js?5 33 bytes {0} [built] [5] ./a.js?6 33 bytes {0} [built] [6] ./a.js?7 33 bytes {0} [built] [7] ./a.js?8 33 bytes {0} [built] [8] ./a.js?9 33 bytes {0} [built] [9] ./a.js?10 33 bytes {0} [built] [10] ./index.js 181 bytes {0} [built] [11] ./c.js?1 33 bytes {0} [built] [13] ./c.js?2 33 bytes {0} [built] [15] ./c.js?3 33 bytes {0} [built] [17] ./c.js?4 33 bytes {0} [built] [19] ./c.js?5 33 bytes {0} [built] [21] ./c.js?6 33 bytes {0} [built] [23] ./c.js?7 33 bytes {0} [built] [25] ./c.js?8 33 bytes {0} [built] [27] ./c.js?9 33 bytes {0} [built] + 11 hidden modules" `; exports[`StatsTestCases should print correct stats for max-modules-default 1`] = ` "Hash: d0b29852af8ccc4949b7 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 6.81 KiB 0 [emitted] main Entrypoint main = main.js [0] ./a.js?1 33 bytes {0} [built] [1] ./a.js?2 33 bytes {0} [built] [2] ./a.js?3 33 bytes {0} [built] [3] ./a.js?4 33 bytes {0} [built] [4] ./a.js?5 33 bytes {0} [built] [5] ./a.js?6 33 bytes {0} [built] [6] ./a.js?7 33 bytes {0} [built] [7] ./a.js?8 33 bytes {0} [built] [8] ./a.js?9 33 bytes {0} [built] [9] ./a.js?10 33 bytes {0} [built] [10] ./index.js 181 bytes {0} [built] [11] ./c.js?1 33 bytes {0} [built] [13] ./c.js?2 33 bytes {0} [built] [15] ./c.js?3 33 bytes {0} [built] [17] ./c.js?4 33 bytes {0} [built] + 16 hidden modules" `; exports[`StatsTestCases should print correct stats for module-assets 1`] = ` "Hash: 3800082315c6d35bb423 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Entrypoint main = main.js chunk {0} main.js (main) 12 bytes >{1}< [entry] [rendered] [0] ./index.js 12 bytes {0} [built] chunk {1} 1.js 68 bytes <{0}> [rendered] [1] ./node_modules/a/index.js 17 bytes {1} [built] [2] ./node_modules/a/1.png 51 bytes {1} [built] [1 asset] [0] ./index.js 12 bytes {0} [built] [1] ./node_modules/a/index.js 17 bytes {1} [built] [2] ./node_modules/a/1.png 51 bytes {1} [built] [1 asset]" `; exports[`StatsTestCases should print correct stats for module-deduplication 1`] = ` "Asset Size Chunks Chunk Names 0.js 730 bytes 0, 6 [emitted] 1.js 730 bytes 1, 7 [emitted] 2.js 730 bytes 2, 8 [emitted] 6.js 661 bytes 6 [emitted] 7.js 661 bytes 7 [emitted] 8.js 661 bytes 8 [emitted] e1.js 9.37 KiB 3 [emitted] e1 e2.js 9.39 KiB 4 [emitted] e2 e3.js 9.41 KiB 5 [emitted] e3 Entrypoint e1 = e1.js Entrypoint e2 = e2.js Entrypoint e3 = e3.js chunk {0} 0.js 37 bytes <{4}> <{5}> [rendered] [2] ./async1.js 28 bytes {0} {6} [built] [5] ./d.js 9 bytes {0} {3} [built] chunk {1} 1.js 37 bytes <{3}> <{5}> [rendered] [3] ./async2.js 28 bytes {1} {7} [built] [6] ./f.js 9 bytes {1} {4} [built] chunk {2} 2.js 37 bytes <{3}> <{4}> [rendered] [4] ./async3.js 28 bytes {2} {8} [built] [7] ./h.js 9 bytes {2} {5} [built] chunk {3} e1.js (e1) 152 bytes >{1}< >{2}< >{6}< [entry] [rendered] [0] ./b.js 9 bytes {3} {4} {5} [built] [1] ./a.js 9 bytes {3} {4} {5} [built] [5] ./d.js 9 bytes {0} {3} [built] [8] ./e1.js 116 bytes {3} [built] [9] ./c.js 9 bytes {3} [built] chunk {4} e2.js (e2) 152 bytes >{0}< >{2}< >{7}< [entry] [rendered] [0] ./b.js 9 bytes {3} {4} {5} [built] [1] ./a.js 9 bytes {3} {4} {5} [built] [6] ./f.js 9 bytes {1} {4} [built] [10] ./e2.js 116 bytes {4} [built] [11] ./e.js 9 bytes {4} [built] chunk {5} e3.js (e3) 152 bytes >{0}< >{1}< >{8}< [entry] [rendered] [0] ./b.js 9 bytes {3} {4} {5} [built] [1] ./a.js 9 bytes {3} {4} {5} [built] [7] ./h.js 9 bytes {2} {5} [built] [12] ./e3.js 116 bytes {5} [built] [13] ./g.js 9 bytes {5} [built] chunk {6} 6.js 28 bytes <{3}> [rendered] [2] ./async1.js 28 bytes {0} {6} [built] chunk {7} 7.js 28 bytes <{4}> [rendered] [3] ./async2.js 28 bytes {1} {7} [built] chunk {8} 8.js 28 bytes <{5}> [rendered] [4] ./async3.js 28 bytes {2} {8} [built]" `; exports[`StatsTestCases should print correct stats for module-deduplication-named 1`] = ` " Asset Size Chunks Chunk Names async1.js 820 bytes 0 [emitted] async1 async2.js 820 bytes 1 [emitted] async2 async3.js 820 bytes 2 [emitted] async3 e1.js 9.23 KiB 3 [emitted] e1 e2.js 9.25 KiB 4 [emitted] e2 e3.js 9.27 KiB 5 [emitted] e3 Entrypoint e1 = e1.js Entrypoint e2 = e2.js Entrypoint e3 = e3.js chunk {0} async1.js (async1) 89 bytes <{2}> <{3}> >{1}< [rendered] [2] ./d.js 9 bytes {0} {3} [built] [11] ./async1.js 80 bytes {0} [built] chunk {1} async2.js (async2) 89 bytes <{0}> <{4}> >{2}< [rendered] [3] ./f.js 9 bytes {1} {4} [built] [12] ./async2.js 80 bytes {1} [built] chunk {2} async3.js (async3) 89 bytes <{1}> <{5}> >{0}< [rendered] [4] ./h.js 9 bytes {2} {5} [built] [13] ./async3.js 80 bytes {2} [built] chunk {3} e1.js (e1) 144 bytes >{0}< [entry] [rendered] [0] ./b.js 9 bytes {3} {4} {5} [built] [1] ./a.js 9 bytes {3} {4} {5} [built] [2] ./d.js 9 bytes {0} {3} [built] [5] ./e1.js 108 bytes {3} [built] [6] ./c.js 9 bytes {3} [built] chunk {4} e2.js (e2) 144 bytes >{1}< [entry] [rendered] [0] ./b.js 9 bytes {3} {4} {5} [built] [1] ./a.js 9 bytes {3} {4} {5} [built] [3] ./f.js 9 bytes {1} {4} [built] [7] ./e2.js 108 bytes {4} [built] [8] ./e.js 9 bytes {4} [built] chunk {5} e3.js (e3) 144 bytes >{2}< [entry] [rendered] [0] ./b.js 9 bytes {3} {4} {5} [built] [1] ./a.js 9 bytes {3} {4} {5} [built] [4] ./h.js 9 bytes {2} {5} [built] [9] ./e3.js 108 bytes {5} [built] [10] ./g.js 9 bytes {5} [built]" `; exports[`StatsTestCases should print correct stats for module-trace-disabled-in-error 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.75 KiB 0 main Entrypoint main = main.js [0] ./index.js 25 bytes {0} [built] ERROR in ./index.js Module not found: Error: Can't resolve 'does-not-exist' in 'Xdir/module-trace-disabled-in-error'" `; exports[`StatsTestCases should print correct stats for module-trace-enabled-in-error 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.75 KiB 0 main Entrypoint main = main.js [0] ./index.js 25 bytes {0} [built] ERROR in ./index.js Module not found: Error: Can't resolve 'does-not-exist' in 'Xdir/module-trace-enabled-in-error' @ ./index.js 1:0-25" `; exports[`StatsTestCases should print correct stats for named-chunk-groups 1`] = ` "Child Chunk Group main = main.js Chunk Group async-a = async-a~async-b.js async-a.js Chunk Group async-b = async-a~async-b.js async-b.js Chunk Group async-c = vendors.js async-c.js chunk {0} async-a~async-b.js (async-a~async-b) 133 bytes <{4}> ={1}= ={2}= [rendered] split chunk (cache group: default) (name: async-a~async-b) > ./a [0] ./index.js 1:0-47 > ./b [0] ./index.js 2:0-47 [4] ./shared.js 133 bytes {0} [built] chunk {1} async-a.js (async-a) 40 bytes <{4}> ={0}= [rendered] > ./a [0] ./index.js 1:0-47 [1] ./a.js 40 bytes {1} [built] chunk {2} async-b.js (async-b) 40 bytes <{4}> ={0}= [rendered] > ./b [0] ./index.js 2:0-47 [2] ./b.js 40 bytes {2} [built] chunk {3} async-c.js (async-c) 45 bytes <{4}> ={5}= [rendered] > ./c [0] ./index.js 3:0-47 [3] ./c.js 45 bytes {3} [built] chunk {4} main.js (main) 146 bytes >{0}< >{1}< >{2}< >{3}< >{5}< [entry] [rendered] > ./ main [0] ./index.js 146 bytes {4} [built] chunk {5} vendors.js (vendors) 40 bytes <{4}> ={3}= [rendered] split chunk (cache group: vendors) (name: vendors) > ./c [0] ./index.js 3:0-47 [5] ./node_modules/x.js 20 bytes {5} [built] [6] ./node_modules/y.js 20 bytes {5} [built] Child Entrypoint main = main.js Chunk Group async-a = async-a~async-b.js async-a.js Chunk Group async-b = async-a~async-b.js async-b.js Chunk Group async-c = vendors.js async-c.js chunk {0} async-a~async-b.js (async-a~async-b) 133 bytes <{4}> ={1}= ={2}= [rendered] split chunk (cache group: default) (name: async-a~async-b) > ./a [0] ./index.js 1:0-47 > ./b [0] ./index.js 2:0-47 [4] ./shared.js 133 bytes {0} [built] chunk {1} async-a.js (async-a) 40 bytes <{4}> ={0}= [rendered] > ./a [0] ./index.js 1:0-47 [1] ./a.js 40 bytes {1} [built] chunk {2} async-b.js (async-b) 40 bytes <{4}> ={0}= [rendered] > ./b [0] ./index.js 2:0-47 [2] ./b.js 40 bytes {2} [built] chunk {3} async-c.js (async-c) 45 bytes <{4}> ={5}= [rendered] > ./c [0] ./index.js 3:0-47 [3] ./c.js 45 bytes {3} [built] chunk {4} main.js (main) 146 bytes >{0}< >{1}< >{2}< >{3}< >{5}< [entry] [rendered] > ./ main [0] ./index.js 146 bytes {4} [built] chunk {5} vendors.js (vendors) 40 bytes <{4}> ={3}= [rendered] split chunk (cache group: vendors) (name: vendors) > ./c [0] ./index.js 3:0-47 [5] ./node_modules/x.js 20 bytes {5} [built] [6] ./node_modules/y.js 20 bytes {5} [built]" `; exports[`StatsTestCases should print correct stats for named-chunks-plugin 1`] = ` "Hash: deb7cd22c634f1c52662 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names entry.js 6.45 KiB entry [emitted] entry vendor.js 269 bytes vendor [emitted] vendor Entrypoint entry = vendor.js entry.js [./entry.js] 72 bytes {entry} [built] [./modules/a.js] 22 bytes {vendor} [built] [./modules/b.js] 22 bytes {vendor} [built] [./modules/c.js] 22 bytes {entry} [built]" `; exports[`StatsTestCases should print correct stats for named-chunks-plugin-async 1`] = ` "Hash: c90d9bc140f3e8bbd29c Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names chunk-containing-__a_js.js 307 bytes chunk-containing-__a_js [emitted] chunk-containing-__b_js.js 182 bytes chunk-containing-__b_js [emitted] entry.js 8.13 KiB entry [emitted] entry Entrypoint entry = entry.js [0] ./entry.js 47 bytes {entry} [built] [1] ./modules/b.js 22 bytes {chunk-containing-__b_js} [built] [2] ./modules/a.js 37 bytes {chunk-containing-__a_js} [built]" `; exports[`StatsTestCases should print correct stats for no-emit-on-errors-plugin-with-child-error 1`] = ` "Hash: c07d925d7e60129ffc69 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 3.57 KiB 0 main child.js 3.57 KiB Entrypoint main = bundle.js [0] ./index.js 0 bytes {0} [built] WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment. You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/ Child child: Asset Size Chunks Chunk Names child.js 3.57 KiB 0 child Entrypoint child = child.js [0] ./index.js 0 bytes {0} [built] ERROR in forced error" `; exports[`StatsTestCases should print correct stats for optimize-chunks 1`] = ` "Hash: aa85d85eda19bac37a2e Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names ab.js 183 bytes 1 [emitted] ab abd.js 250 bytes 2, 1 [emitted] abd ac in ab.js 130 bytes 3 [emitted] ac in ab chunk.js 212 bytes 4, 3 [emitted] chunk cir1.js 299 bytes 0 [emitted] cir1 cir2 from cir1.js 359 bytes 6, 5 [emitted] cir2 from cir1 cir2.js 299 bytes 5 [emitted] cir2 main.js 9.03 KiB 7 [emitted] main Entrypoint main = main.js chunk {0} cir1.js (cir1) 81 bytes <{5}> <{7}> >{6}< [rendered] > [5] ./index.js 13:0-54 > [7] ./circular2.js 1:0-79 > [7] ./circular2.js 1:0-79 [6] ./circular1.js 81 bytes {0} [built] chunk {1} ab.js (ab) 0 bytes <{7}> >{3}< [rendered] > [5] ./index.js 1:0-6:8 [0] ./modules/a.js 0 bytes {1} {2} [built] [1] ./modules/b.js 0 bytes {1} {2} [built] chunk {2} abd.js (abd) 0 bytes <{7}> >{4}< [rendered] > [5] ./index.js 8:0-11:9 [0] ./modules/a.js 0 bytes {1} {2} [built] [1] ./modules/b.js 0 bytes {1} {2} [built] [3] ./modules/d.js 0 bytes {2} {4} [built] chunk {3} ac in ab.js (ac in ab) 0 bytes <{1}> >{4}< [rendered] > [5] ./index.js 2:1-5:15 [4] ./modules/c.js 0 bytes {3} {4} [built] chunk {4} chunk.js (chunk) 0 bytes <{2}> <{3}> [rendered] > [5] ./index.js 3:2-4:13 > [5] ./index.js 9:1-10:12 [3] ./modules/d.js 0 bytes {2} {4} [built] [4] ./modules/c.js 0 bytes {3} {4} [built] chunk {5} cir2.js (cir2) 81 bytes <{7}> >{0}< [rendered] > [5] ./index.js 14:0-54 [7] ./circular2.js 81 bytes {5} {6} [built] chunk {6} cir2 from cir1.js (cir2 from cir1) 81 bytes <{0}> [rendered] > [6] ./circular1.js 1:0-79 > [6] ./circular1.js 1:0-79 [7] ./circular2.js 81 bytes {5} {6} [built] [8] ./modules/e.js 0 bytes {6} [built] chunk {7} main.js (main) 523 bytes >{0}< >{1}< >{2}< >{5}< [entry] [rendered] > ./index main [2] ./modules/f.js 0 bytes {7} [built] [5] ./index.js 523 bytes {7} [built]" `; exports[`StatsTestCases should print correct stats for parse-error 1`] = ` " Asset Size Chunks Chunk Names main.js 4.01 KiB 0 main Entrypoint main = main.js [0] ./b.js 169 bytes {0} [built] [failed] [1 error] [1] ./index.js + 1 modules 35 bytes {0} [built] | ./index.js 15 bytes [built] | ./a.js 15 bytes [built] ERROR in ./b.js 6:7 Module parse failed: Unexpected token (6:7) You may need an appropriate loader to handle this file type. | includes | a > parser ) | error | in @ ./a.js 2:0-13 @ ./index.js" `; exports[`StatsTestCases should print correct stats for performance-different-mode-and-target 1`] = ` "Hash: fdd848419e60e2d013b0259ddac6a2fc2be16d5d2ff383e3c2c0c58d07840c13a912a795f6e4940364a02963586e6b6811420c13a912a795f6e494032ff383e3c2c0c58d0784 Child Hash: fdd848419e60e2d013b0 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names warning.pro-web.js 297 KiB 0 [emitted] [big] main Entrypoint main [big] = warning.pro-web.js [0] ./index.js 293 KiB {0} [built] WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: warning.pro-web.js (297 KiB) WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (297 KiB) warning.pro-web.js WARNING in webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/ Child Hash: 259ddac6a2fc2be16d5d Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names warning.pro-webworker.js 297 KiB 0 [emitted] [big] main Entrypoint main [big] = warning.pro-webworker.js [0] ./index.js 293 KiB {0} [built] WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: warning.pro-webworker.js (297 KiB) WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (297 KiB) warning.pro-webworker.js WARNING in webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/ Child Hash: 2ff383e3c2c0c58d0784 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names no-warning.pro-node.js 297 KiB 0 [emitted] main Entrypoint main = no-warning.pro-node.js [0] ./index.js 293 KiB {0} [built] Child Hash: 0c13a912a795f6e49403 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names no-warning.dev-web.js 1.72 MiB main [emitted] main Entrypoint main = no-warning.dev-web.js [./index.js] 293 KiB {main} [built] Child Hash: 64a02963586e6b681142 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names no-warning.dev-node.js 1.72 MiB main [emitted] main Entrypoint main = no-warning.dev-node.js [./index.js] 293 KiB {main} [built] Child Hash: 0c13a912a795f6e49403 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names no-warning.dev-web-with-limit-set.js 1.72 MiB main [emitted] [big] main Entrypoint main [big] = no-warning.dev-web-with-limit-set.js [./index.js] 293 KiB {main} [built] Child Hash: 2ff383e3c2c0c58d0784 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names warning.pro-node-with-hints-set.js 297 KiB 0 [emitted] [big] main Entrypoint main [big] = warning.pro-node-with-hints-set.js [0] ./index.js 293 KiB {0} [built] WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: warning.pro-node-with-hints-set.js (297 KiB) WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (297 KiB) warning.pro-node-with-hints-set.js WARNING in webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/" `; exports[`StatsTestCases should print correct stats for performance-disabled 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 232 bytes 1 [emitted] 2.js 152 bytes 2 [emitted] 3.js 289 bytes 3 [emitted] main.js 301 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 52 bytes {0} [built] [1] ./a.js 293 KiB {0} [built] [2] ./b.js 22 bytes {2} [built] [3] ./c.js 54 bytes {3} [built] [4] ./d.js 22 bytes {1} [built] [5] ./e.js 22 bytes {1} [built]" `; exports[`StatsTestCases should print correct stats for performance-error 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 232 bytes 1 [emitted] 2.js 152 bytes 2 [emitted] 3.js 289 bytes 3 [emitted] main.js 301 KiB 0 [emitted] [big] main Entrypoint main [big] = main.js [0] ./index.js 52 bytes {0} [built] [1] ./a.js 293 KiB {0} [built] [2] ./b.js 22 bytes {2} [built] [3] ./c.js 54 bytes {3} [built] [4] ./d.js 22 bytes {1} [built] [5] ./e.js 22 bytes {1} [built] ERROR in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: main.js (301 KiB) ERROR in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (301 KiB) main.js " `; exports[`StatsTestCases should print correct stats for performance-no-async-chunks-shown 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 297 KiB 0 [emitted] [big] main sec.js 3.91 KiB 1 [emitted] sec Entrypoint main [big] = main.js Entrypoint sec = sec.js [0] ./b.js 22 bytes {0} {1} [built] [1] ./index.js 32 bytes {0} [built] [2] ./a.js 293 KiB {0} [built] [3] ./index2.js 48 bytes {1} [built] [4] ./c.js 22 bytes {1} [built] [5] ./d.js 22 bytes {1} [built] WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: main.js (297 KiB) WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (297 KiB) main.js WARNING in webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/" `; exports[`StatsTestCases should print correct stats for performance-no-hints 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 232 bytes 1 [emitted] 2.js 152 bytes 2 [emitted] 3.js 289 bytes 3 [emitted] main.js 301 KiB 0 [emitted] [big] main Entrypoint main [big] = main.js [0] ./index.js 52 bytes {0} [built] [1] ./a.js 293 KiB {0} [built] [2] ./b.js 22 bytes {2} [built] [3] ./c.js 54 bytes {3} [built] [4] ./d.js 22 bytes {1} [built] [5] ./e.js 22 bytes {1} [built]" `; exports[`StatsTestCases should print correct stats for performance-oversize-limit-error 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 297 KiB 0 [emitted] [big] main sec.js 297 KiB 1 [emitted] [big] sec Entrypoint main [big] = main.js Entrypoint sec [big] = sec.js [0] ./a.js 293 KiB {0} {1} [built] [1] ./index.js 16 bytes {0} [built] [2] ./index2.js 16 bytes {1} [built] ERROR in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: main.js (297 KiB) sec.js (297 KiB) ERROR in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (297 KiB) main.js sec (297 KiB) sec.js ERROR in webpack performance recommendations: You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application. For more info visit https://webpack.js.org/guides/code-splitting/" `; exports[`StatsTestCases should print correct stats for prefetch 1`] = ` " Asset Size Chunks Chunk Names inner.js 130 bytes 0 [emitted] inner inner2.js 188 bytes 1 [emitted] inner2 main.js 9.55 KiB 2 [emitted] main normal.js 130 bytes 3 [emitted] normal prefetched.js 475 bytes 4 [emitted] prefetched prefetched2.js 127 bytes 5 [emitted] prefetched2 prefetched3.js 130 bytes 6 [emitted] prefetched3 Entrypoint main = main.js (prefetch: prefetched2.js prefetched.js prefetched3.js) chunk {0} inner.js (inner) 0 bytes <{4}> [rendered] chunk {1} inner2.js (inner2) 0 bytes <{4}> [rendered] chunk {2} main.js (main) 436 bytes >{3}< >{4}< >{5}< >{6}< (prefetch: {5} {4} {6}) [entry] [rendered] chunk {3} normal.js (normal) 0 bytes <{2}> [rendered] chunk {4} prefetched.js (prefetched) 228 bytes <{2}> >{0}< >{1}< (prefetch: {1} {0}) [rendered] chunk {5} prefetched2.js (prefetched2) 0 bytes <{2}> [rendered] chunk {6} prefetched3.js (prefetched3) 0 bytes <{2}> [rendered]" `; exports[`StatsTestCases should print correct stats for prefetch-preload-mixed 1`] = ` "chunk {0} a.js (a) 136 bytes <{10}> >{1}< >{2}< (prefetch: {1} {2}) [rendered] chunk {1} a1.js (a1) 0 bytes <{0}> [rendered] chunk {2} a2.js (a2) 0 bytes <{0}> [rendered] chunk {3} b.js (b) 203 bytes <{10}> >{4}< >{5}< >{6}< (prefetch: {4} {6}) (preload: {5}) [rendered] chunk {4} b1.js (b1) 0 bytes <{3}> [rendered] chunk {5} b2.js (b2) 0 bytes <{3}> [rendered] chunk {6} b3.js (b3) 0 bytes <{3}> [rendered] chunk {7} c.js (c) 134 bytes <{10}> >{8}< >{9}< (preload: {8} {9}) [rendered] chunk {8} c1.js (c1) 0 bytes <{7}> [rendered] chunk {9} c2.js (c2) 0 bytes <{7}> [rendered] chunk {10} main.js (main) 195 bytes >{0}< >{3}< >{7}< (prefetch: {0} {3} {7}) [entry] [rendered]" `; exports[`StatsTestCases should print correct stats for preload 1`] = ` " Asset Size Chunks Chunk Names inner.js 130 bytes 0 [emitted] inner inner2.js 188 bytes 1 [emitted] inner2 main.js 9.75 KiB 2 [emitted] main normal.js 130 bytes 3 [emitted] normal preloaded.js 467 bytes 4 [emitted] preloaded preloaded2.js 127 bytes 5 [emitted] preloaded2 preloaded3.js 130 bytes 6 [emitted] preloaded3 Entrypoint main = main.js (preload: preloaded2.js preloaded.js preloaded3.js) chunk {0} inner.js (inner) 0 bytes <{4}> [rendered] chunk {1} inner2.js (inner2) 0 bytes <{4}> [rendered] chunk {2} main.js (main) 424 bytes >{3}< >{4}< >{5}< >{6}< (preload: {5} {4} {6}) [entry] [rendered] chunk {3} normal.js (normal) 0 bytes <{2}> [rendered] chunk {4} preloaded.js (preloaded) 226 bytes <{2}> >{0}< >{1}< (preload: {1} {0}) [rendered] chunk {5} preloaded2.js (preloaded2) 0 bytes <{2}> [rendered] chunk {6} preloaded3.js (preloaded3) 0 bytes <{2}> [rendered]" `; exports[`StatsTestCases should print correct stats for preset-detailed 1`] = ` "Hash: 934b93428d78d30a6bf2 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 232 bytes 1 [emitted] 2.js 152 bytes 2 [emitted] 3.js 289 bytes 3 [emitted] main.js 8.23 KiB 0 [emitted] main Entrypoint main = main.js chunk {0} main.js (main) 73 bytes >{2}< >{3}< [entry] [rendered] > ./index main chunk {1} 1.js 44 bytes <{3}> [rendered] > [3] ./c.js 1:0-52 chunk {2} 2.js 22 bytes <{0}> [rendered] > ./b [0] ./index.js 2:0-16 chunk {3} 3.js 54 bytes <{0}> >{1}< [rendered] > ./c [0] ./index.js 3:0-16 [0] ./index.js 51 bytes {0} [depth 0] [built] ModuleConcatenation bailout: Module is not an ECMAScript module [1] ./a.js 22 bytes {0} [depth 1] [built] ModuleConcatenation bailout: Module is not an ECMAScript module [2] ./b.js 22 bytes {2} [depth 1] [built] ModuleConcatenation bailout: Module is not an ECMAScript module [3] ./c.js 54 bytes {3} [depth 1] [built] ModuleConcatenation bailout: Module is not an ECMAScript module [4] ./d.js 22 bytes {1} [depth 2] [built] ModuleConcatenation bailout: Module is not an ECMAScript module [5] ./e.js 22 bytes {1} [depth 2] [built] ModuleConcatenation bailout: Module is not an ECMAScript module" `; exports[`StatsTestCases should print correct stats for preset-errors-only 1`] = `""`; exports[`StatsTestCases should print correct stats for preset-errors-only-error 1`] = ` " ERROR in ./index.js Module not found: Error: Can't resolve 'does-not-exist' in 'Xdir/preset-errors-only-error' @ ./index.js 1:0-25" `; exports[`StatsTestCases should print correct stats for preset-minimal 1`] = `" 6 modules"`; exports[`StatsTestCases should print correct stats for preset-minimal-simple 1`] = `" 1 module"`; exports[`StatsTestCases should print correct stats for preset-mixed-array 1`] = ` "Child minimal: 1 module Child verbose: Entrypoint main = main.js [0] ./index.js 8 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for preset-none 1`] = `""`; exports[`StatsTestCases should print correct stats for preset-none-array 1`] = `""`; exports[`StatsTestCases should print correct stats for preset-none-error 1`] = `""`; exports[`StatsTestCases should print correct stats for preset-normal 1`] = ` "Hash: 934b93428d78d30a6bf2 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 232 bytes 1 [emitted] 2.js 152 bytes 2 [emitted] 3.js 289 bytes 3 [emitted] main.js 8.23 KiB 0 [emitted] main Entrypoint main = main.js [0] ./index.js 51 bytes {0} [built] [1] ./a.js 22 bytes {0} [built] [2] ./b.js 22 bytes {2} [built] [3] ./c.js 54 bytes {3} [built] [4] ./d.js 22 bytes {1} [built] [5] ./e.js 22 bytes {1} [built]" `; exports[`StatsTestCases should print correct stats for preset-normal-performance 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 232 bytes 1 [emitted] 2.js 152 bytes 2 [emitted] 3.js 289 bytes 3 [emitted] main.js 301 KiB 0 [emitted] [big] main Entrypoint main [big] = main.js [0] ./index.js 52 bytes {0} [built] [1] ./a.js 293 KiB {0} [built] [2] ./b.js 22 bytes {2} [built] [3] ./c.js 54 bytes {3} [built] [4] ./d.js 22 bytes {1} [built] [5] ./e.js 22 bytes {1} [built] WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: main.js (301 KiB) WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (301 KiB) main.js " `; exports[`StatsTestCases should print correct stats for preset-normal-performance-ensure-filter-sourcemaps 1`] = ` "Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 262 bytes 1 [emitted] 1.js.map 216 bytes 1 [emitted] 2.js 182 bytes 2 [emitted] 2.js.map 156 bytes 2 [emitted] 3.js 319 bytes 3 [emitted] 3.js.map 210 bytes 3 [emitted] main.js 301 KiB 0 [emitted] [big] main main.js.map 1.72 MiB 0 [emitted] main Entrypoint main [big] = main.js main.js.map [0] ./index.js 52 bytes {0} [built] [1] ./a.js 293 KiB {0} [built] [2] ./b.js 22 bytes {2} [built] [3] ./c.js 54 bytes {3} [built] [4] ./d.js 22 bytes {1} [built] [5] ./e.js 22 bytes {1} [built] WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: main.js (301 KiB) WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance. Entrypoints: main (301 KiB) main.js " `; exports[`StatsTestCases should print correct stats for preset-verbose 1`] = ` "Hash: 934b93428d78d30a6bf2 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 232 bytes 1 [emitted] 2.js 152 bytes 2 [emitted] 3.js 289 bytes 3 [emitted] main.js 8.23 KiB 0 [emitted] main Entrypoint main = main.js chunk {0} main.js (main) 73 bytes >{2}< >{3}< [entry] [rendered] > ./index main [0] ./index.js 51 bytes {0} [depth 0] [built] ModuleConcatenation bailout: Module is not an ECMAScript module single entry ./index main factory:Xms building:Xms = Xms [1] ./a.js 22 bytes {0} [depth 1] [built] ModuleConcatenation bailout: Module is not an ECMAScript module cjs require ./a [0] ./index.js 1:0-14 [0] Xms -> factory:Xms building:Xms = Xms chunk {1} 1.js 44 bytes <{3}> [rendered] > [3] ./c.js 1:0-52 [4] ./d.js 22 bytes {1} [depth 2] [built] ModuleConcatenation bailout: Module is not an ECMAScript module require.ensure item ./d [3] ./c.js 1:0-52 [0] Xms -> [3] Xms -> factory:Xms building:Xms = Xms [5] ./e.js 22 bytes {1} [depth 2] [built] ModuleConcatenation bailout: Module is not an ECMAScript module require.ensure item ./e [3] ./c.js 1:0-52 [0] Xms -> [3] Xms -> factory:Xms building:Xms = Xms chunk {2} 2.js 22 bytes <{0}> [rendered] > ./b [0] ./index.js 2:0-16 [2] ./b.js 22 bytes {2} [depth 1] [built] ModuleConcatenation bailout: Module is not an ECMAScript module amd require ./b [0] ./index.js 2:0-16 [0] Xms -> factory:Xms building:Xms = Xms chunk {3} 3.js 54 bytes <{0}> >{1}< [rendered] > ./c [0] ./index.js 3:0-16 [3] ./c.js 54 bytes {3} [depth 1] [built] ModuleConcatenation bailout: Module is not an ECMAScript module amd require ./c [0] ./index.js 3:0-16 [0] Xms -> factory:Xms building:Xms = Xms" `; exports[`StatsTestCases should print correct stats for resolve-plugin-context 1`] = ` "Hash: d16253da1f9a8f6c689f Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 3.97 KiB 0 [emitted] main Entrypoint main = bundle.js [0] ./node_modules/xyz/index.js 0 bytes {0} [built] [1] ./index.js 48 bytes {0} [built] [2] ./node_modules/abc/index.js 16 bytes {0} [built] [3] ./node_modules/def/index.js 16 bytes {0} [built] [4] ./node_modules/def/node_modules/xyz/index.js 0 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for reverse-sort-modules 1`] = ` "Hash: d0b29852af8ccc4949b7 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 6.81 KiB 0 [emitted] main Entrypoint main = main.js [27] ./c.js?9 33 bytes {0} [built] [25] ./c.js?8 33 bytes {0} [built] [23] ./c.js?7 33 bytes {0} [built] [21] ./c.js?6 33 bytes {0} [built] [19] ./c.js?5 33 bytes {0} [built] [17] ./c.js?4 33 bytes {0} [built] [15] ./c.js?3 33 bytes {0} [built] [13] ./c.js?2 33 bytes {0} [built] [11] ./c.js?1 33 bytes {0} [built] [10] ./index.js 181 bytes {0} [built] [9] ./a.js?10 33 bytes {0} [built] [8] ./a.js?9 33 bytes {0} [built] [7] ./a.js?8 33 bytes {0} [built] [6] ./a.js?7 33 bytes {0} [built] [5] ./a.js?6 33 bytes {0} [built] [4] ./a.js?5 33 bytes {0} [built] [3] ./a.js?4 33 bytes {0} [built] [2] ./a.js?3 33 bytes {0} [built] [1] ./a.js?2 33 bytes {0} [built] [0] ./a.js?1 33 bytes {0} [built] + 11 hidden modules" `; exports[`StatsTestCases should print correct stats for runtime-chunk 1`] = ` "Entrypoint e1 = runtime~e1.js e1.js Entrypoint e2 = runtime~e2.js e2.js" `; exports[`StatsTestCases should print correct stats for runtime-chunk-integration 1`] = ` "Child base: Asset Size Chunks Chunk Names 0.js 728 bytes 0 [emitted] main1.js 539 bytes 1 [emitted] main1 runtime.js 8.7 KiB 2 [emitted] runtime Entrypoint main1 = runtime.js main1.js [0] ./main1.js 66 bytes {1} [built] [1] ./b.js 20 bytes {0} [built] [2] ./c.js 20 bytes {0} [built] [3] ./d.js 20 bytes {0} [built] Child manifest is named entry: Asset Size Chunks Chunk Names 0.js 737 bytes 0 [emitted] main1.js 539 bytes 2 [emitted] main1 manifest.js 9.01 KiB 1 [emitted] manifest Entrypoint main1 = manifest.js main1.js Entrypoint manifest = manifest.js [0] ./main1.js 66 bytes {2} [built] [1] ./f.js 20 bytes {1} [built] [2] ./b.js 20 bytes {0} [built] [3] ./c.js 20 bytes {0} [built] [4] ./d.js 20 bytes {0} [built]" `; exports[`StatsTestCases should print correct stats for runtime-chunk-issue-7382 1`] = ` "Entrypoint e1 = runtime.js all.js e1.js Entrypoint e2 = runtime.js all.js e2.js" `; exports[`StatsTestCases should print correct stats for runtime-chunk-single 1`] = ` "Entrypoint e1 = runtime.js e1.js Entrypoint e2 = runtime.js e2.js" `; exports[`StatsTestCases should print correct stats for scope-hoisting-bailouts 1`] = ` "Hash: 21b74df86e904b9e34c1 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Entrypoint index = index.js Entrypoint entry = entry.js [0] ./entry.js 32 bytes {0} {1} [built] ModuleConcatenation bailout: Module is an entry point [1] ./ref-from-cjs.js 45 bytes {1} [built] ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./cjs.js (referenced with cjs require) [2] ./index.js 176 bytes {1} [built] ModuleConcatenation bailout: Module is an entry point [3] ./cjs.js 59 bytes {1} [built] ModuleConcatenation bailout: Module is not an ECMAScript module [4] ./eval.js 35 bytes {1} [built] ModuleConcatenation bailout: Module uses eval() [5] ./injected-vars.js 40 bytes {1} [built] ModuleConcatenation bailout: Module uses injected variables (__dirname, __filename) [6] ./module-id.js 26 bytes {1} [built] ModuleConcatenation bailout: Module uses module.id [7] ./module-loaded.js 30 bytes {1} [built] ModuleConcatenation bailout: Module uses module.loaded [8] external \\"external\\" 42 bytes {1} [built] ModuleConcatenation bailout: Module is not an ECMAScript module [9] ./concatenated.js + 2 modules 116 bytes {2} [built] ModuleConcatenation bailout: Cannot concat with external \\"external\\" (<- Module is not an ECMAScript module) | ./concatenated.js 26 bytes [built] | ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./index.js (referenced with import()) | ./concatenated1.js 37 bytes [built] | ./concatenated2.js 48 bytes [built]" `; exports[`StatsTestCases should print correct stats for scope-hoisting-multi 1`] = ` "Hash: e9ee59c952da1a23368e3ae60c31c1c21dd62d86 Child Hash: e9ee59c952da1a23368e Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Entrypoint first = vendor.js first.js Entrypoint second = vendor.js second.js [0] ./common2.js 25 bytes {1} {5} [built] [1] ./common.js 37 bytes {1} {5} [built] [2] ./vendor.js 25 bytes {0} [built] [3] ./lazy_shared.js 31 bytes {4} [built] [4] ./first.js 207 bytes {1} [built] [5] ./module_first.js 31 bytes {1} [built] [6] ./second.js 177 bytes {5} [built] [7] ./lazy_first.js 55 bytes {2} [built] [8] ./lazy_second.js 55 bytes {3} [built] [9] ./common_lazy_shared.js 25 bytes {2} {3} {4} [built] [10] ./common_lazy.js 25 bytes {2} {3} [built] Child Hash: 3ae60c31c1c21dd62d86 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Entrypoint first = vendor.js first.js Entrypoint second = vendor.js second.js [0] ./common.js + 1 modules 62 bytes {1} {5} [built] | ./common.js 37 bytes [built] | ./common2.js 25 bytes [built] [1] ./vendor.js 25 bytes {0} [built] [2] ./second.js 177 bytes {5} [built] ModuleConcatenation bailout: Module is an entry point [3] ./first.js + 1 modules 248 bytes {1} [built] ModuleConcatenation bailout: Cannot concat with ./common.js ModuleConcatenation bailout: Cannot concat with ./vendor.js | ./first.js 207 bytes [built] | ModuleConcatenation bailout: Module is an entry point | ./module_first.js 31 bytes [built] [4] ./lazy_shared.js 31 bytes {4} [built] ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./first.js (referenced with import()), ./second.js (referenced with import()) [5] ./lazy_second.js 55 bytes {3} [built] ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./second.js (referenced with import()) [6] ./common_lazy_shared.js 25 bytes {2} {3} {4} [built] [7] ./common_lazy.js 25 bytes {2} {3} [built] [8] ./lazy_first.js 55 bytes {2} [built] ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./first.js (referenced with import())" `; exports[`StatsTestCases should print correct stats for side-effects-issue-7428 1`] = ` "Hash: 1db323720a3bbea98b3b Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names 1.js 481 bytes 1 [emitted] main.js 9.29 KiB 0 [emitted] main Entrypoint main = main.js [0] ./components/src/CompAB/index.js 87 bytes [built] [no exports used] harmony side effect evaluation ./CompAB [3] ./components/src/index.js 1:0-40 harmony export imported specifier ./CompAB [3] ./components/src/index.js 1:0-40 harmony export imported specifier ./CompAB [3] ./components/src/index.js 1:0-40 [1] ./components/src/CompC/CompC.js 33 bytes [built] [no exports used] harmony side effect evaluation ./CompC [2] ./components/src/CompC/index.js 1:0-34 harmony export imported specifier ./CompC [2] ./components/src/CompC/index.js 1:0-34 [2] ./components/src/CompC/index.js 34 bytes [built] [no exports used] harmony side effect evaluation ./CompC [3] ./components/src/index.js 2:0-43 harmony export imported specifier ./CompC [3] ./components/src/index.js 2:0-43 [3] ./components/src/index.js 84 bytes [built] [no exports used] harmony side effect evaluation ./components [6] ./foo.js 1:0-37 harmony side effect evaluation ./components [7] ./main.js + 1 modules 1:0-44 [4] ./components/src/CompAB/CompA.js 89 bytes {0} [built] [only some exports used: default] harmony side effect evaluation ./CompA [0] ./components/src/CompAB/index.js 1:0-43 harmony export imported specifier ./CompA [0] ./components/src/CompAB/index.js 1:0-43 harmony import specifier ./components [6] ./foo.js 3:20-25 (skipped side-effect-free modules) harmony import specifier ./components ./main.js 3:15-20 (skipped side-effect-free modules) [5] ./components/src/CompAB/utils.js 97 bytes {0} [built] harmony side effect evaluation ./utils [4] ./components/src/CompAB/CompA.js 1:0-35 harmony import specifier ./utils [4] ./components/src/CompAB/CompA.js 5:5-12 harmony side effect evaluation ./utils [7] ./main.js + 1 modules 1:0-30 harmony import specifier ./utils [7] ./main.js + 1 modules 5:2-5 [6] ./foo.js 101 bytes {1} [built] import() ./foo ./main.js 6:0-15 [7] ./main.js + 1 modules 231 bytes {0} [built] single entry ./main.js main | ./main.js 144 bytes [built] | single entry ./main.js main | ./components/src/CompAB/CompB.js 77 bytes [built] | [only some exports used: default] | harmony side effect evaluation ./CompB [0] ./components/src/CompAB/index.js 2:0-43 | harmony export imported specifier ./CompB [0] ./components/src/CompAB/index.js 2:0-43 | harmony import specifier ./components ./main.js 4:15-20 (skipped side-effect-free modules)" `; exports[`StatsTestCases should print correct stats for side-effects-simple-unused 1`] = ` "Hash: 518ad50555bd6e64c28b Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names main.js 3.9 KiB 0 [emitted] main Entrypoint main = main.js [0] ./node_modules/pmodule/b.js 69 bytes [built] [no exports used] [1] ./node_modules/pmodule/a.js 60 bytes [built] [no exports used] [2] ./index.js + 2 modules 158 bytes {0} [built] | ./index.js 55 bytes [built] | ./node_modules/pmodule/index.js 75 bytes [built] | [only some exports used: default] | ./node_modules/pmodule/c.js 28 bytes [built] | [only some exports used: z]" `; exports[`StatsTestCases should print correct stats for simple 1`] = ` "Hash: dae46aaa6722cda9498d Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 3.75 KiB main [emitted] main Entrypoint main = bundle.js [./index.js] 0 bytes {main} [built]" `; exports[`StatsTestCases should print correct stats for simple-more-info 1`] = ` "Hash: 008517b920c1aeb23c7e Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 3.57 KiB 0 [emitted] main Entrypoint main = bundle.js [0] ./index.js 0 bytes {0} [built] single entry ./index main factory:Xms building:Xms = Xms" `; exports[`StatsTestCases should print correct stats for split-chunks 1`] = ` "Child default: Entrypoint main = default/main.js Entrypoint a = default/a.js Entrypoint b = default/b.js Entrypoint c = default/c.js chunk {0} default/async-a~async-b~async-c.js (async-a~async-b~async-c) 20 bytes <{11}> ={1}= ={2}= ={3}= ={5}= ={6}= ={7}= ={12}= >{1}< >{8}< [rendered] split chunk (cache group: default) (name: async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {0} {4} {9} {10} [built] chunk {1} default/async-b~async-c~async-g.js (async-b~async-c~async-g) 20 bytes <{0}> <{2}> <{3}> <{4}> <{5}> <{11}> ={0}= ={2}= ={3}= ={6}= ={7}= ={8}= ={12}= [rendered] split chunk (cache group: default) (name: async-b~async-c~async-g) > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./g [] 6:0-47 > ./g [] 6:0-47 [2] ./f.js 20 bytes {1} {9} {10} [built] chunk {2} default/vendors~async-a~async-b~async-c.js (vendors~async-a~async-b~async-c) 20 bytes <{11}> ={0}= ={1}= ={3}= ={5}= ={6}= ={7}= ={12}= >{1}< >{8}< [rendered] split chunk (cache group: vendors) (name: vendors~async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] chunk {3} default/vendors~async-a~async-b.js (vendors~async-a~async-b) 20 bytes <{11}> ={0}= ={1}= ={2}= ={5}= ={6}= >{1}< >{8}< [rendered] split chunk (cache group: vendors) (name: vendors~async-a~async-b) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 [3] ./node_modules/y.js 20 bytes {3} {4} {9} [built] chunk {4} default/a.js (a) 216 bytes >{1}< >{8}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {0} {4} {9} {10} [built] [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] [3] ./node_modules/y.js 20 bytes {3} {4} {9} [built] [6] ./a.js + 1 modules 156 bytes {4} {5} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {5} default/async-a.js (async-a) 156 bytes <{11}> ={0}= ={2}= ={3}= >{1}< >{8}< [rendered] > ./a [8] ./index.js 1:0-47 [6] ./a.js + 1 modules 156 bytes {4} {5} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {6} default/async-b.js (async-b) 72 bytes <{11}> ={0}= ={1}= ={2}= ={3}= [rendered] > ./b [8] ./index.js 2:0-47 [4] ./b.js 72 bytes {6} {9} [built] chunk {7} default/async-c.js (async-c) 72 bytes <{11}> ={0}= ={1}= ={2}= ={12}= [rendered] > ./c [8] ./index.js 3:0-47 [5] ./c.js 72 bytes {7} {10} [built] chunk {8} default/async-g.js (async-g) 34 bytes <{0}> <{2}> <{3}> <{4}> <{5}> ={1}= [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [9] ./g.js 34 bytes {8} [built] chunk {9} default/b.js (b) 152 bytes [entry] [rendered] > ./b b [0] ./d.js 20 bytes {0} {4} {9} {10} [built] [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] [2] ./f.js 20 bytes {1} {9} {10} [built] [3] ./node_modules/y.js 20 bytes {3} {4} {9} [built] [4] ./b.js 72 bytes {6} {9} [built] chunk {10} default/c.js (c) 152 bytes [entry] [rendered] > ./c c [0] ./d.js 20 bytes {0} {4} {9} {10} [built] [1] ./node_modules/x.js 20 bytes {2} {4} {9} {10} [built] [2] ./f.js 20 bytes {1} {9} {10} [built] [5] ./c.js 72 bytes {7} {10} [built] [7] ./node_modules/z.js 20 bytes {10} {12} [built] chunk {11} default/main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{5}< >{6}< >{7}< >{12}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {11} [built] chunk {12} default/vendors~async-c.js (vendors~async-c) 20 bytes <{11}> ={0}= ={1}= ={2}= ={7}= [rendered] split chunk (cache group: vendors) (name: vendors~async-c) > ./c [8] ./index.js 3:0-47 [7] ./node_modules/z.js 20 bytes {10} {12} [built] Child all-chunks: Entrypoint main = default/main.js Entrypoint a = default/vendors~a~async-a~async-b~async-c~b~c.js default/vendors~a~async-a~async-b~b.js default/a.js Entrypoint b = default/vendors~a~async-a~async-b~async-c~b~c.js default/vendors~a~async-a~async-b~b.js default/b.js Entrypoint c = default/vendors~a~async-a~async-b~async-c~b~c.js default/vendors~async-c~c.js default/c.js chunk {0} default/vendors~a~async-a~async-b~async-c~b~c.js (vendors~a~async-a~async-b~async-c~b~c) 20 bytes <{12}> ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= >{3}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~a~async-a~async-b~async-c~b~c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./a a > ./b b > ./c c [2] ./node_modules/x.js 20 bytes {0} [built] chunk {1} default/vendors~a~async-a~async-b~b.js (vendors~a~async-a~async-b~b) 20 bytes <{12}> ={0}= ={2}= ={3}= ={5}= ={6}= ={7}= ={10}= >{3}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~a~async-a~async-b~b) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./a a > ./b b [3] ./node_modules/y.js 20 bytes {1} [built] chunk {2} default/async-a~async-b~async-c.js (async-a~async-b~async-c) 20 bytes <{12}> ={0}= ={1}= ={3}= ={4}= ={6}= ={7}= ={8}= >{3}< >{9}< [rendered] split chunk (cache group: default) (name: async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {2} {5} {10} {11} [built] chunk {3} default/async-b~async-c~async-g.js (async-b~async-c~async-g) 20 bytes <{0}> <{1}> <{2}> <{5}> <{6}> <{12}> ={0}= ={1}= ={2}= ={4}= ={7}= ={8}= ={9}= [rendered] split chunk (cache group: default) (name: async-b~async-c~async-g) > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./g [] 6:0-47 > ./g [] 6:0-47 [1] ./f.js 20 bytes {3} {10} {11} [built] chunk {4} default/vendors~async-c~c.js (vendors~async-c~c) 20 bytes <{12}> ={0}= ={2}= ={3}= ={8}= ={11}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~async-c~c) > ./c [8] ./index.js 3:0-47 > ./c c [7] ./node_modules/z.js 20 bytes {4} [built] chunk {5} default/a.js (a) 176 bytes ={0}= ={1}= >{3}< >{9}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {6} default/async-a.js (async-a) 156 bytes <{12}> ={0}= ={1}= ={2}= >{3}< >{9}< [rendered] > ./a [8] ./index.js 1:0-47 [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {7} default/async-b.js (async-b) 72 bytes <{12}> ={0}= ={1}= ={2}= ={3}= [rendered] > ./b [8] ./index.js 2:0-47 [4] ./b.js 72 bytes {7} {10} [built] chunk {8} default/async-c.js (async-c) 72 bytes <{12}> ={0}= ={2}= ={3}= ={4}= [rendered] > ./c [8] ./index.js 3:0-47 [5] ./c.js 72 bytes {8} {11} [built] chunk {9} default/async-g.js (async-g) 34 bytes <{0}> <{1}> <{2}> <{5}> <{6}> ={3}= [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [9] ./g.js 34 bytes {9} [built] chunk {10} default/b.js (b) 112 bytes ={0}= ={1}= [entry] [rendered] > ./b b [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [1] ./f.js 20 bytes {3} {10} {11} [built] [4] ./b.js 72 bytes {7} {10} [built] chunk {11} default/c.js (c) 112 bytes ={0}= ={4}= [entry] [rendered] > ./c c [0] ./d.js 20 bytes {2} {5} {10} {11} [built] [1] ./f.js 20 bytes {3} {10} {11} [built] [5] ./c.js 72 bytes {8} {11} [built] chunk {12} default/main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{4}< >{6}< >{7}< >{8}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {12} [built] Child manual: Entrypoint main = default/main.js Entrypoint a = default/vendors.js default/a.js Entrypoint b = default/vendors.js default/b.js Entrypoint c = default/vendors.js default/c.js chunk {0} default/vendors.js (vendors) 112 bytes <{8}> ={1}= ={2}= ={3}= ={4}= ={6}= ={7}= >{5}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./a a > ./b b > ./c c [1] ./node_modules/x.js 20 bytes {0} [built] [3] ./node_modules/y.js 20 bytes {0} [built] [6] ./node_modules/z.js 20 bytes {0} [built] [9] multi x y z 52 bytes {0} [built] chunk {1} default/a.js (a) 176 bytes ={0}= >{5}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [7] ./a.js + 1 modules 156 bytes {1} {2} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {2} default/async-a.js (async-a) 176 bytes <{8}> ={0}= >{5}< [rendered] > ./a [8] ./index.js 1:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [7] ./a.js + 1 modules 156 bytes {1} {2} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {3} default/async-b.js (async-b) 112 bytes <{8}> ={0}= [rendered] > ./b [8] ./index.js 2:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [4] ./b.js 72 bytes {3} {6} [built] chunk {4} default/async-c.js (async-c) 112 bytes <{8}> ={0}= [rendered] > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [5] ./c.js 72 bytes {4} {7} [built] chunk {5} default/async-g.js (async-g) 54 bytes <{0}> <{1}> <{2}> [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [10] ./g.js 34 bytes {5} [built] chunk {6} default/b.js (b) 112 bytes ={0}= [entry] [rendered] > ./b b [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [4] ./b.js 72 bytes {3} {6} [built] chunk {7} default/c.js (c) 112 bytes ={0}= [entry] [rendered] > ./c c [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [2] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [5] ./c.js 72 bytes {4} {7} [built] chunk {8} default/main.js (main) 147 bytes >{0}< >{2}< >{3}< >{4}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {8} [built] Child name-too-long: Entrypoint main = main.js Entrypoint aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccc~50ebc41f.js vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.js aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccc~18066793.js async-a.js aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.js Entrypoint bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccc~50ebc41f.js vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.js aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccc~18066793.js async-b~async-c~async-g~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccccccccccccccccccc.js async-b.js bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.js Entrypoint cccccccccccccccccccccccccccccc = vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccc~50ebc41f.js vendors~async-c~cccccccccccccccccccccccccccccc.js aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccc~18066793.js async-b~async-c~async-g~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccccccccccccccccccc.js async-c.js cccccccccccccccccccccccccccccc.js chunk {0} aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccc~18066793.js (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccc~18066793) 20 bytes <{12}> ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= >{2}< >{9}< [initial] [rendered] split chunk (cache group: default) (name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccc~18066793) > ./a [4] ./index.js 1:0-47 > ./b [4] ./index.js 2:0-47 > ./c [4] ./index.js 3:0-47 > ./a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > ./b bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb > ./c cccccccccccccccccccccccccccccc [0] ./d.js 20 bytes {0} [built] chunk {1} vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccc~50ebc41f.js (vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccc~50ebc41f) 20 bytes <{12}> ={0}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= >{2}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~async-c~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccc~50ebc41f) > ./a [4] ./index.js 1:0-47 > ./b [4] ./index.js 2:0-47 > ./c [4] ./index.js 3:0-47 > ./a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > ./b bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb > ./c cccccccccccccccccccccccccccccc [1] ./node_modules/x.js 20 bytes {1} [built] chunk {2} async-b~async-c~async-g~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccccccccccccccccccc.js (async-b~async-c~async-g~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccccccccccccccccccc) 20 bytes <{0}> <{1}> <{3}> <{4}> <{8}> <{12}> ={0}= ={1}= ={3}= ={5}= ={6}= ={7}= ={9}= ={10}= ={11}= [initial] [rendered] split chunk (cache group: default) (name: async-b~async-c~async-g~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb~cccccccccccccccccccccccccccccc) > ./b [4] ./index.js 2:0-47 > ./c [4] ./index.js 3:0-47 > ./g [] 6:0-47 > ./g [] 6:0-47 > ./b bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb > ./c cccccccccccccccccccccccccccccc [2] ./f.js 20 bytes {2} [built] chunk {3} vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.js (vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) 20 bytes <{12}> ={0}= ={1}= ={2}= ={4}= ={5}= ={8}= ={10}= >{2}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~async-a~async-b~bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) > ./a [4] ./index.js 1:0-47 > ./b [4] ./index.js 2:0-47 > ./a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > ./b bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb [3] ./node_modules/y.js 20 bytes {3} [built] chunk {4} async-a.js (async-a) 156 bytes <{12}> ={0}= ={1}= ={3}= ={8}= >{2}< >{9}< [initial] [rendered] reused as split chunk (cache group: default) > ./a [4] ./index.js 1:0-47 > ./a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa [8] ./a.js + 1 modules 156 bytes {4} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {5} async-b.js (async-b) 72 bytes <{12}> ={0}= ={1}= ={2}= ={3}= ={10}= [initial] [rendered] reused as split chunk (cache group: default) > ./b [4] ./index.js 2:0-47 > ./b bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb [5] ./b.js 72 bytes {5} [built] chunk {6} async-c.js (async-c) 72 bytes <{12}> ={0}= ={1}= ={2}= ={7}= ={11}= [initial] [rendered] reused as split chunk (cache group: default) > ./c [4] ./index.js 3:0-47 > ./c cccccccccccccccccccccccccccccc [6] ./c.js 72 bytes {6} [built] chunk {7} vendors~async-c~cccccccccccccccccccccccccccccc.js (vendors~async-c~cccccccccccccccccccccccccccccc) 20 bytes <{12}> ={0}= ={1}= ={2}= ={6}= ={11}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~async-c~cccccccccccccccccccccccccccccc) > ./c [4] ./index.js 3:0-47 > ./c cccccccccccccccccccccccccccccc [7] ./node_modules/z.js 20 bytes {7} [built] chunk {8} aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.js (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) 0 bytes ={0}= ={1}= ={3}= ={4}= >{2}< >{9}< [entry] [rendered] > ./a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa chunk {9} async-g.js (async-g) 34 bytes <{0}> <{1}> <{3}> <{4}> <{8}> ={2}= [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [9] ./g.js 34 bytes {9} [built] chunk {10} bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.js (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) 0 bytes ={0}= ={1}= ={2}= ={3}= ={5}= [entry] [rendered] > ./b bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb chunk {11} cccccccccccccccccccccccccccccc.js (cccccccccccccccccccccccccccccc) 0 bytes ={0}= ={1}= ={2}= ={6}= ={7}= [entry] [rendered] > ./c cccccccccccccccccccccccccccccc chunk {12} main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{4}< >{5}< >{6}< >{7}< [entry] [rendered] > ./ main [4] ./index.js 147 bytes {12} [built] Child custom-chunks-filter: Entrypoint main = default/main.js Entrypoint a = default/a.js Entrypoint b = default/vendors~async-a~async-b~async-c~b~c.js default/vendors~async-a~async-b~b.js default/b.js Entrypoint c = default/vendors~async-a~async-b~async-c~b~c.js default/vendors~async-c~c.js default/c.js chunk {0} default/vendors~async-a~async-b~async-c~b~c.js (vendors~async-a~async-b~async-c~b~c) 20 bytes <{12}> ={1}= ={2}= ={3}= ={4}= ={6}= ={7}= ={8}= ={10}= ={11}= >{2}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~async-a~async-b~async-c~b~c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./b b > ./c c [1] ./node_modules/x.js 20 bytes {0} {5} [built] chunk {1} default/async-a~async-b~async-c.js (async-a~async-b~async-c) 20 bytes <{12}> ={0}= ={2}= ={3}= ={4}= ={6}= ={7}= ={8}= >{2}< >{9}< [rendered] split chunk (cache group: default) (name: async-a~async-b~async-c) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {1} {5} {10} {11} [built] chunk {2} default/async-b~async-c~async-g.js (async-b~async-c~async-g) 20 bytes <{0}> <{1}> <{3}> <{5}> <{6}> <{12}> ={0}= ={1}= ={3}= ={4}= ={7}= ={8}= ={9}= [rendered] split chunk (cache group: default) (name: async-b~async-c~async-g) > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./g [] 6:0-47 > ./g [] 6:0-47 [2] ./f.js 20 bytes {2} {10} {11} [built] chunk {3} default/vendors~async-a~async-b~b.js (vendors~async-a~async-b~b) 20 bytes <{12}> ={0}= ={1}= ={2}= ={6}= ={7}= ={10}= >{2}< >{9}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors~async-a~async-b~b) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./b b [3] ./node_modules/y.js 20 bytes {3} {5} [built] chunk {4} default/vendors~async-c~c.js (vendors~async-c~c) 20 bytes <{12}> ={0}= ={1}= ={2}= ={8}= ={11}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~async-c~c) > ./c [8] ./index.js 3:0-47 > ./c c [7] ./node_modules/z.js 20 bytes {4} [built] chunk {5} default/a.js (a) 216 bytes >{2}< >{9}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {1} {5} {10} {11} [built] [1] ./node_modules/x.js 20 bytes {0} {5} [built] [3] ./node_modules/y.js 20 bytes {3} {5} [built] [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {6} default/async-a.js (async-a) 156 bytes <{12}> ={0}= ={1}= ={3}= >{2}< >{9}< [rendered] > ./a [8] ./index.js 1:0-47 [6] ./a.js + 1 modules 156 bytes {5} {6} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {7} default/async-b.js (async-b) 72 bytes <{12}> ={0}= ={1}= ={2}= ={3}= [rendered] > ./b [8] ./index.js 2:0-47 [4] ./b.js 72 bytes {7} {10} [built] chunk {8} default/async-c.js (async-c) 72 bytes <{12}> ={0}= ={1}= ={2}= ={4}= [rendered] > ./c [8] ./index.js 3:0-47 [5] ./c.js 72 bytes {8} {11} [built] chunk {9} default/async-g.js (async-g) 34 bytes <{0}> <{1}> <{3}> <{5}> <{6}> ={2}= [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [9] ./g.js 34 bytes {9} [built] chunk {10} default/b.js (b) 112 bytes ={0}= ={3}= [entry] [rendered] > ./b b [0] ./d.js 20 bytes {1} {5} {10} {11} [built] [2] ./f.js 20 bytes {2} {10} {11} [built] [4] ./b.js 72 bytes {7} {10} [built] chunk {11} default/c.js (c) 112 bytes ={0}= ={4}= [entry] [rendered] > ./c c [0] ./d.js 20 bytes {1} {5} {10} {11} [built] [2] ./f.js 20 bytes {2} {10} {11} [built] [5] ./c.js 72 bytes {8} {11} [built] chunk {12} default/main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{4}< >{6}< >{7}< >{8}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {12} [built] Child custom-chunks-filter-in-cache-groups: Entrypoint main = default/main.js Entrypoint a = default/a.js Entrypoint b = default/vendors.js default/b.js Entrypoint c = default/vendors.js default/c.js chunk {0} default/vendors.js (vendors) 112 bytes <{8}> ={2}= ={3}= ={4}= ={6}= ={7}= >{5}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors) > ./a [8] ./index.js 1:0-47 > ./b [8] ./index.js 2:0-47 > ./c [8] ./index.js 3:0-47 > ./b b > ./c c [1] ./node_modules/x.js 20 bytes {0} {1} [built] [2] ./node_modules/y.js 20 bytes {0} {1} [built] [6] ./node_modules/z.js 20 bytes {0} [built] [9] multi x y z 52 bytes {0} [built] chunk {1} default/a.js (a) 216 bytes >{5}< [entry] [rendered] > ./a a [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [1] ./node_modules/x.js 20 bytes {0} {1} [built] [2] ./node_modules/y.js 20 bytes {0} {1} [built] [7] ./a.js + 1 modules 156 bytes {1} {2} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {2} default/async-a.js (async-a) 176 bytes <{8}> ={0}= >{5}< [rendered] > ./a [8] ./index.js 1:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [7] ./a.js + 1 modules 156 bytes {1} {2} [built] | ./a.js 121 bytes [built] | ./e.js 20 bytes [built] chunk {3} default/async-b.js (async-b) 112 bytes <{8}> ={0}= [rendered] > ./b [8] ./index.js 2:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [3] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [4] ./b.js 72 bytes {3} {6} [built] chunk {4} default/async-c.js (async-c) 112 bytes <{8}> ={0}= [rendered] > ./c [8] ./index.js 3:0-47 [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [3] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [5] ./c.js 72 bytes {4} {7} [built] chunk {5} default/async-g.js (async-g) 54 bytes <{0}> <{1}> <{2}> [rendered] > ./g [] 6:0-47 > ./g [] 6:0-47 [3] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [10] ./g.js 34 bytes {5} [built] chunk {6} default/b.js (b) 112 bytes ={0}= [entry] [rendered] > ./b b [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [3] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [4] ./b.js 72 bytes {3} {6} [built] chunk {7} default/c.js (c) 112 bytes ={0}= [entry] [rendered] > ./c c [0] ./d.js 20 bytes {1} {2} {3} {4} {6} {7} [built] [3] ./f.js 20 bytes {3} {4} {5} {6} {7} [built] [5] ./c.js 72 bytes {4} {7} [built] chunk {8} default/main.js (main) 147 bytes >{0}< >{2}< >{3}< >{4}< [entry] [rendered] > ./ main [8] ./index.js 147 bytes {8} [built]" `; exports[`StatsTestCases should print correct stats for split-chunks-automatic-name 1`] = ` "Entrypoint main = main.js chunk {0} common~async-a~async-b~async-c.js (common~async-a~async-b~async-c) 40 bytes <{7}> ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= [rendered] split chunk (cache group: default) (name: common~async-a~async-b~async-c) > ./a [0] ./index.js 1:0-47 > ./b [0] ./index.js 2:0-47 > ./c [0] ./index.js 3:0-47 [4] ./d.js 20 bytes {0} [built] [5] ./node_modules/x.js 20 bytes {0} [built] chunk {1} common~async-a~async-b.js (common~async-a~async-b) 20 bytes <{7}> ={0}= ={2}= ={3}= ={4}= [rendered] split chunk (cache group: vendors) (name: common~async-a~async-b) > ./a [0] ./index.js 1:0-47 > ./b [0] ./index.js 2:0-47 [6] ./node_modules/y.js 20 bytes {1} [built] chunk {2} common~async-b~async-c.js (common~async-b~async-c) 20 bytes <{7}> ={0}= ={1}= ={4}= ={5}= ={6}= [rendered] split chunk (cache group: default) (name: common~async-b~async-c) > ./b [0] ./index.js 2:0-47 > ./c [0] ./index.js 3:0-47 [7] ./f.js 20 bytes {2} [built] chunk {3} async-a.js (async-a) 107 bytes <{7}> ={0}= ={1}= [rendered] > ./a [0] ./index.js 1:0-47 [3] ./a.js + 1 modules 107 bytes {3} [built] | ./a.js 72 bytes [built] | ./e.js 20 bytes [built] chunk {4} async-b.js (async-b) 72 bytes <{7}> ={0}= ={1}= ={2}= [rendered] > ./b [0] ./index.js 2:0-47 [1] ./b.js 72 bytes {4} [built] chunk {5} async-c.js (async-c) 72 bytes <{7}> ={0}= ={2}= ={6}= [rendered] > ./c [0] ./index.js 3:0-47 [2] ./c.js 72 bytes {5} [built] chunk {6} common~async-c.js (common~async-c) 20 bytes <{7}> ={0}= ={2}= ={5}= [rendered] split chunk (cache group: vendors) (name: common~async-c) > ./c [0] ./index.js 3:0-47 [8] ./node_modules/z.js 20 bytes {6} [built] chunk {7} main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{4}< >{5}< >{6}< [entry] [rendered] > ./ main [0] ./index.js 147 bytes {7} [built]" `; exports[`StatsTestCases should print correct stats for split-chunks-combinations 1`] = ` "Entrypoint main = main.js chunk {0} async-a~async-b.js (async-a~async-b) 134 bytes <{8}> ={1}= ={2}= [rendered] split chunk (cache group: default) (name: async-a~async-b) > ./a [0] ./index.js 1:0-47 > ./b [0] ./index.js 2:0-47 [8] ./x.js 67 bytes {0} {3} {4} {5} {6} {7} [built] [9] ./y.js 67 bytes {0} [built] chunk {1} async-a.js (async-a) 48 bytes <{8}> ={0}= [rendered] > ./a [0] ./index.js 1:0-47 [1] ./a.js 48 bytes {1} [built] chunk {2} async-b.js (async-b) 48 bytes <{8}> ={0}= [rendered] > ./b [0] ./index.js 2:0-47 [2] ./b.js 48 bytes {2} [built] chunk {3} async-c.js (async-c) 101 bytes <{8}> [rendered] > ./c [0] ./index.js 3:0-47 [3] ./c.js 34 bytes {3} [built] [8] ./x.js 67 bytes {0} {3} {4} {5} {6} {7} [built] chunk {4} async-d.js (async-d) 101 bytes <{8}> [rendered] > ./d [0] ./index.js 4:0-47 [4] ./d.js 34 bytes {4} [built] [8] ./x.js 67 bytes {0} {3} {4} {5} {6} {7} [built] chunk {5} async-e.js (async-e) 101 bytes <{8}> [rendered] > ./e [0] ./index.js 5:0-47 [5] ./e.js 34 bytes {5} [built] [8] ./x.js 67 bytes {0} {3} {4} {5} {6} {7} [built] chunk {6} async-f.js (async-f) 101 bytes <{8}> [rendered] > ./f [0] ./index.js 6:0-47 [6] ./f.js 34 bytes {6} [built] [8] ./x.js 67 bytes {0} {3} {4} {5} {6} {7} [built] chunk {7} async-g.js (async-g) 101 bytes <{8}> [rendered] > ./g [0] ./index.js 7:0-47 [7] ./g.js 34 bytes {7} [built] [8] ./x.js 67 bytes {0} {3} {4} {5} {6} {7} [built] chunk {8} main.js (main) 343 bytes >{0}< >{1}< >{2}< >{3}< >{4}< >{5}< >{6}< >{7}< [entry] [rendered] > ./ main [0] ./index.js 343 bytes {8} [built]" `; exports[`StatsTestCases should print correct stats for split-chunks-issue-6413 1`] = ` "Entrypoint main = main.js chunk {0} async-a~async-b~async-c.js (async-a~async-b~async-c) 11 bytes <{5}> ={1}= ={2}= ={3}= ={4}= [rendered] split chunk (cache group: default) (name: async-a~async-b~async-c) > ./a [0] ./index.js 1:0-47 > ./b [0] ./index.js 2:0-47 > ./c [0] ./index.js 3:0-47 [4] ./common.js 11 bytes {0} [built] chunk {1} vendors~async-a~async-b~async-c.js (vendors~async-a~async-b~async-c) 20 bytes <{5}> ={0}= ={2}= ={3}= ={4}= [rendered] split chunk (cache group: vendors) (name: vendors~async-a~async-b~async-c) > ./a [0] ./index.js 1:0-47 > ./b [0] ./index.js 2:0-47 > ./c [0] ./index.js 3:0-47 [5] ./node_modules/x.js 20 bytes {1} [built] chunk {2} async-a.js (async-a) 19 bytes <{5}> ={0}= ={1}= [rendered] > ./a [0] ./index.js 1:0-47 [1] ./a.js 19 bytes {2} [built] chunk {3} async-b.js (async-b) 19 bytes <{5}> ={0}= ={1}= [rendered] > ./b [0] ./index.js 2:0-47 [2] ./b.js 19 bytes {3} [built] chunk {4} async-c.js (async-c) 19 bytes <{5}> ={0}= ={1}= [rendered] > ./c [0] ./index.js 3:0-47 [3] ./c.js 19 bytes {4} [built] chunk {5} main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< >{4}< [entry] [rendered] > ./ main [0] ./index.js 147 bytes {5} [built]" `; exports[`StatsTestCases should print correct stats for split-chunks-issue-6696 1`] = ` "Entrypoint main = vendors.js main.js chunk {0} async-a.js (async-a) 32 bytes <{2}> <{3}> [rendered] > ./a [0] ./index.js 2:0-47 [2] ./a.js 12 bytes {0} [built] [4] ./node_modules/x.js 20 bytes {0} {1} [built] chunk {1} async-b.js (async-b) 32 bytes <{2}> <{3}> [rendered] > ./b [0] ./index.js 3:0-47 [3] ./b.js 12 bytes {1} [built] [4] ./node_modules/x.js 20 bytes {0} {1} [built] chunk {2} main.js (main) 110 bytes ={3}= >{0}< >{1}< [entry] [rendered] > ./ main [0] ./index.js 110 bytes {2} [built] chunk {3} vendors.js (vendors) 20 bytes ={2}= >{0}< >{1}< [initial] [rendered] split chunk (cache group: vendors) (name: vendors) > ./ main [1] ./node_modules/y.js 20 bytes {3} [built]" `; exports[`StatsTestCases should print correct stats for split-chunks-issue-7401 1`] = ` "Entrypoint a = vendors~a~c.js a.js Entrypoint b = b.js Chunk Group c = vendors~a~c.js c.js chunk {0} vendors~a~c.js (vendors~a~c) 20 bytes <{2}> ={1}= ={3}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~a~c) > ./c [2] ./b.js 1:0-41 > ./a a [0] ./node_modules/x.js 20 bytes {0} [built] chunk {1} a.js (a) 12 bytes ={0}= [entry] [rendered] > ./a a [1] ./a.js 12 bytes {1} [built] chunk {2} b.js (b) 43 bytes >{0}< >{3}< [entry] [rendered] > ./b b [2] ./b.js 43 bytes {2} [built] chunk {3} c.js (c) 12 bytes <{2}> ={0}= [rendered] > ./c [2] ./b.js 1:0-41 [3] ./c.js 12 bytes {3} [built]" `; exports[`StatsTestCases should print correct stats for split-chunks-max-size 1`] = ` "Child production: Entrypoint main = prod-vendors~main~7274e1de.js prod-vendors~main~0feae4ad.js prod-main~6e7ead72.js prod-main~6a2ae26b.js prod-main~17acad98.js prod-main~b2c7414a.js prod-main~75f09de8.js prod-main~052b3814.js prod-main~3ff27526.js prod-main~11485824.js prod-main~c6931360.js prod-main~cd7c5bfc.js prod-main~02369f19.js chunk {0} prod-main~02369f19.js (main~02369f19) 1.57 KiB ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [entry] [rendered] > ./ main [11] ./very-big.js?1 1.57 KiB {0} [built] chunk {1} prod-main~052b3814.js (main~052b3814) 603 bytes ={0}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [2] ./small.js?1 67 bytes {1} [built] [3] ./small.js?2 67 bytes {1} [built] [4] ./small.js?3 67 bytes {1} [built] [5] ./small.js?4 67 bytes {1} [built] [6] ./small.js?5 67 bytes {1} [built] [7] ./small.js?6 67 bytes {1} [built] [8] ./small.js?7 67 bytes {1} [built] [9] ./small.js?8 67 bytes {1} [built] [10] ./small.js?9 67 bytes {1} [built] chunk {2} prod-main~11485824.js (main~11485824) 603 bytes ={0}= ={1}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [16] ./subfolder/small.js?1 67 bytes {2} [built] [17] ./subfolder/small.js?2 67 bytes {2} [built] [18] ./subfolder/small.js?3 67 bytes {2} [built] [19] ./subfolder/small.js?4 67 bytes {2} [built] [20] ./subfolder/small.js?5 67 bytes {2} [built] [21] ./subfolder/small.js?6 67 bytes {2} [built] [22] ./subfolder/small.js?7 67 bytes {2} [built] [23] ./subfolder/small.js?8 67 bytes {2} [built] [24] ./subfolder/small.js?9 67 bytes {2} [built] chunk {3} prod-main~17acad98.js (main~17acad98) 1.57 KiB ={0}= ={1}= ={2}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [39] ./in-some-directory/very-big.js?1 1.57 KiB {3} [built] chunk {4} prod-main~3ff27526.js (main~3ff27526) 536 bytes ={0}= ={1}= ={2}= ={3}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [14] ./subfolder/big.js?1 268 bytes {4} [built] [15] ./subfolder/big.js?2 268 bytes {4} [built] chunk {5} prod-main~6a2ae26b.js (main~6a2ae26b) 536 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [34] ./in-some-directory/big.js?1 268 bytes {5} [built] [35] ./in-some-directory/small.js?1 67 bytes {5} [built] [36] ./in-some-directory/small.js?2 67 bytes {5} [built] [37] ./in-some-directory/small.js?3 67 bytes {5} [built] [38] ./in-some-directory/small.js?4 67 bytes {5} [built] chunk {6} prod-main~6e7ead72.js (main~6e7ead72) 536 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [0] ./big.js?1 268 bytes {6} [built] [1] ./big.js?2 268 bytes {6} [built] chunk {7} prod-main~75f09de8.js (main~75f09de8) 603 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [25] ./inner-module/small.js?1 67 bytes {7} [built] [26] ./inner-module/small.js?2 67 bytes {7} [built] [27] ./inner-module/small.js?3 67 bytes {7} [built] [28] ./inner-module/small.js?4 67 bytes {7} [built] [29] ./inner-module/small.js?5 67 bytes {7} [built] [30] ./inner-module/small.js?6 67 bytes {7} [built] [31] ./inner-module/small.js?7 67 bytes {7} [built] [32] ./inner-module/small.js?8 67 bytes {7} [built] [33] ./inner-module/small.js?9 67 bytes {7} [built] chunk {8} prod-main~b2c7414a.js (main~b2c7414a) 1.19 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [44] ./index.js 1.19 KiB {8} [built] chunk {9} prod-main~c6931360.js (main~c6931360) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [12] ./very-big.js?2 1.57 KiB {9} [built] chunk {10} prod-main~cd7c5bfc.js (main~cd7c5bfc) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={11}= ={12}= [initial] [rendered] > ./ main [13] ./very-big.js?3 1.57 KiB {10} [built] chunk {11} prod-vendors~main~0feae4ad.js (vendors~main~0feae4ad) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={12}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~main) > ./ main [43] ./node_modules/very-big.js?1 1.57 KiB {11} [built] chunk {12} prod-vendors~main~7274e1de.js (vendors~main~7274e1de) 402 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~main) > ./ main [40] ./node_modules/big.js?1 268 bytes {12} [built] [41] ./node_modules/small.js?1 67 bytes {12} [built] [42] ./node_modules/small.js?2 67 bytes {12} [built] Child development: Entrypoint main = dev-vendors~main~._node_modules_b.js dev-vendors~main~._node_modules_very-big.js~6bdbed7b.js dev-main~._big.js~1.js dev-main~._in-some-directory_b.js dev-main~._in-some-directory_very-big.js~8d76cf03.js dev-main~._index.js~41f5a26e.js dev-main~._inner-module_small.js~3.js dev-main~._small.js~1.js dev-main~._subfolder_big.js~b.js dev-main~._subfolder_small.js~1.js dev-main~._very-big.js~08cf55cf.js dev-main~._very-big.js~4647fb9d.js dev-main~._very-big.js~62f7f644.js chunk {main~._big.js~1} dev-main~._big.js~1.js (main~._big.js~1) 536 bytes ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./big.js?1] 268 bytes {main~._big.js~1} [built] [./big.js?2] 268 bytes {main~._big.js~1} [built] chunk {main~._in-some-directory_b} dev-main~._in-some-directory_b.js (main~._in-some-directory_b) 536 bytes ={main~._big.js~1}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./in-some-directory/big.js?1] 268 bytes {main~._in-some-directory_b} [built] [./in-some-directory/small.js?1] 67 bytes {main~._in-some-directory_b} [built] [./in-some-directory/small.js?2] 67 bytes {main~._in-some-directory_b} [built] [./in-some-directory/small.js?3] 67 bytes {main~._in-some-directory_b} [built] [./in-some-directory/small.js?4] 67 bytes {main~._in-some-directory_b} [built] chunk {main~._in-some-directory_very-big.js~8d76cf03} dev-main~._in-some-directory_very-big.js~8d76cf03.js (main~._in-some-directory_very-big.js~8d76cf03) 1.57 KiB ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./in-some-directory/very-big.js?1] 1.57 KiB {main~._in-some-directory_very-big.js~8d76cf03} [built] chunk {main~._index.js~41f5a26e} dev-main~._index.js~41f5a26e.js (main~._index.js~41f5a26e) 1.19 KiB ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./index.js] 1.19 KiB {main~._index.js~41f5a26e} [built] chunk {main~._inner-module_small.js~3} dev-main~._inner-module_small.js~3.js (main~._inner-module_small.js~3) 603 bytes ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./inner-module/small.js?1] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?2] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?3] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?4] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?5] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?6] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?7] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?8] 67 bytes {main~._inner-module_small.js~3} [built] [./inner-module/small.js?9] 67 bytes {main~._inner-module_small.js~3} [built] chunk {main~._small.js~1} dev-main~._small.js~1.js (main~._small.js~1) 603 bytes ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./small.js?1] 67 bytes {main~._small.js~1} [built] [./small.js?2] 67 bytes {main~._small.js~1} [built] [./small.js?3] 67 bytes {main~._small.js~1} [built] [./small.js?4] 67 bytes {main~._small.js~1} [built] [./small.js?5] 67 bytes {main~._small.js~1} [built] [./small.js?6] 67 bytes {main~._small.js~1} [built] [./small.js?7] 67 bytes {main~._small.js~1} [built] [./small.js?8] 67 bytes {main~._small.js~1} [built] [./small.js?9] 67 bytes {main~._small.js~1} [built] chunk {main~._subfolder_big.js~b} dev-main~._subfolder_big.js~b.js (main~._subfolder_big.js~b) 536 bytes ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./subfolder/big.js?1] 268 bytes {main~._subfolder_big.js~b} [built] [./subfolder/big.js?2] 268 bytes {main~._subfolder_big.js~b} [built] chunk {main~._subfolder_small.js~1} dev-main~._subfolder_small.js~1.js (main~._subfolder_small.js~1) 603 bytes ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./subfolder/small.js?1] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?2] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?3] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?4] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?5] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?6] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?7] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?8] 67 bytes {main~._subfolder_small.js~1} [built] [./subfolder/small.js?9] 67 bytes {main~._subfolder_small.js~1} [built] chunk {main~._very-big.js~08cf55cf} dev-main~._very-big.js~08cf55cf.js (main~._very-big.js~08cf55cf) 1.57 KiB ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./very-big.js?2] 1.57 KiB {main~._very-big.js~08cf55cf} [built] chunk {main~._very-big.js~4647fb9d} dev-main~._very-big.js~4647fb9d.js (main~._very-big.js~4647fb9d) 1.57 KiB ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] > ./ main [./very-big.js?3] 1.57 KiB {main~._very-big.js~4647fb9d} [built] chunk {main~._very-big.js~62f7f644} dev-main~._very-big.js~62f7f644.js (main~._very-big.js~62f7f644) 1.57 KiB ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={vendors~main~._node_modules_b}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [entry] [rendered] > ./ main [./very-big.js?1] 1.57 KiB {main~._very-big.js~62f7f644} [built] chunk {vendors~main~._node_modules_b} dev-vendors~main~._node_modules_b.js (vendors~main~._node_modules_b) 402 bytes ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_very-big.js~6bdbed7b}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~main) > ./ main [./node_modules/big.js?1] 268 bytes {vendors~main~._node_modules_b} [built] [./node_modules/small.js?1] 67 bytes {vendors~main~._node_modules_b} [built] [./node_modules/small.js?2] 67 bytes {vendors~main~._node_modules_b} [built] chunk {vendors~main~._node_modules_very-big.js~6bdbed7b} dev-vendors~main~._node_modules_very-big.js~6bdbed7b.js (vendors~main~._node_modules_very-big.js~6bdbed7b) 1.57 KiB ={main~._big.js~1}= ={main~._in-some-directory_b}= ={main~._in-some-directory_very-big.js~8d76cf03}= ={main~._index.js~41f5a26e}= ={main~._inner-module_small.js~3}= ={main~._small.js~1}= ={main~._subfolder_big.js~b}= ={main~._subfolder_small.js~1}= ={main~._very-big.js~08cf55cf}= ={main~._very-big.js~4647fb9d}= ={main~._very-big.js~62f7f644}= ={vendors~main~._node_modules_b}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~main) > ./ main [./node_modules/very-big.js?1] 1.57 KiB {vendors~main~._node_modules_very-big.js~6bdbed7b} [built] Child switched: Entrypoint main = switched-vendors~main~7274e1de.js switched-main~2bc5b870.js switched-main~748942c6.js switched-main~17acad98.js switched-main~b2c7414a.js switched-main~d9f1562b.js switched-main~c6931360.js switched-main~cd7c5bfc.js switched-main~02369f19.js chunk {0} switched-main~02369f19.js (main~02369f19) 1.57 KiB ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= [entry] [rendered] > ./ main [11] ./very-big.js?1 1.57 KiB {0} [built] chunk {1} switched-main~17acad98.js (main~17acad98) 1.57 KiB ={0}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= [initial] [rendered] > ./ main [39] ./in-some-directory/very-big.js?1 1.57 KiB {1} [built] chunk {2} switched-main~2bc5b870.js (main~2bc5b870) 1.05 KiB ={0}= ={1}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= [initial] [rendered] > ./ main [0] ./big.js?1 268 bytes {2} [built] [1] ./big.js?2 268 bytes {2} [built] [34] ./in-some-directory/big.js?1 268 bytes {2} [built] [35] ./in-some-directory/small.js?1 67 bytes {2} [built] [36] ./in-some-directory/small.js?2 67 bytes {2} [built] [37] ./in-some-directory/small.js?3 67 bytes {2} [built] [38] ./in-some-directory/small.js?4 67 bytes {2} [built] chunk {3} switched-main~748942c6.js (main~748942c6) 1.18 KiB ={0}= ={1}= ={2}= ={4}= ={5}= ={6}= ={7}= ={8}= [initial] [rendered] > ./ main [2] ./small.js?1 67 bytes {3} [built] [3] ./small.js?2 67 bytes {3} [built] [4] ./small.js?3 67 bytes {3} [built] [5] ./small.js?4 67 bytes {3} [built] [6] ./small.js?5 67 bytes {3} [built] [7] ./small.js?6 67 bytes {3} [built] [8] ./small.js?7 67 bytes {3} [built] [9] ./small.js?8 67 bytes {3} [built] [10] ./small.js?9 67 bytes {3} [built] [25] ./inner-module/small.js?1 67 bytes {3} [built] [26] ./inner-module/small.js?2 67 bytes {3} [built] [27] ./inner-module/small.js?3 67 bytes {3} [built] [28] ./inner-module/small.js?4 67 bytes {3} [built] [29] ./inner-module/small.js?5 67 bytes {3} [built] [30] ./inner-module/small.js?6 67 bytes {3} [built] + 3 hidden modules chunk {4} switched-main~b2c7414a.js (main~b2c7414a) 1.19 KiB ={0}= ={1}= ={2}= ={3}= ={5}= ={6}= ={7}= ={8}= [initial] [rendered] > ./ main [44] ./index.js 1.19 KiB {4} [built] chunk {5} switched-main~c6931360.js (main~c6931360) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={6}= ={7}= ={8}= [initial] [rendered] > ./ main [12] ./very-big.js?2 1.57 KiB {5} [built] chunk {6} switched-main~cd7c5bfc.js (main~cd7c5bfc) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={7}= ={8}= [initial] [rendered] > ./ main [13] ./very-big.js?3 1.57 KiB {6} [built] chunk {7} switched-main~d9f1562b.js (main~d9f1562b) 1.11 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={8}= [initial] [rendered] > ./ main [14] ./subfolder/big.js?1 268 bytes {7} [built] [15] ./subfolder/big.js?2 268 bytes {7} [built] [16] ./subfolder/small.js?1 67 bytes {7} [built] [17] ./subfolder/small.js?2 67 bytes {7} [built] [18] ./subfolder/small.js?3 67 bytes {7} [built] [19] ./subfolder/small.js?4 67 bytes {7} [built] [20] ./subfolder/small.js?5 67 bytes {7} [built] [21] ./subfolder/small.js?6 67 bytes {7} [built] [22] ./subfolder/small.js?7 67 bytes {7} [built] [23] ./subfolder/small.js?8 67 bytes {7} [built] [24] ./subfolder/small.js?9 67 bytes {7} [built] chunk {8} switched-vendors~main~7274e1de.js (vendors~main~7274e1de) 1.96 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~main) > ./ main [40] ./node_modules/big.js?1 268 bytes {8} [built] [41] ./node_modules/small.js?1 67 bytes {8} [built] [42] ./node_modules/small.js?2 67 bytes {8} [built] [43] ./node_modules/very-big.js?1 1.57 KiB {8} [built] WARNING in SplitChunksPlugin Cache group vendors Configured minSize (1000 bytes) is bigger than maxSize (100 bytes). This seem to be a invalid optimiziation.splitChunks configuration. WARNING in SplitChunksPlugin Fallback cache group Configured minSize (1000 bytes) is bigger than maxSize (100 bytes). This seem to be a invalid optimiziation.splitChunks configuration. Child zero-min: Entrypoint main = zero-min-vendors~main~7274e1de.js zero-min-vendors~main~0feae4ad.js zero-min-main~6e7ead72.js zero-min-main~6a2ae26b.js zero-min-main~17acad98.js zero-min-main~b2c7414a.js zero-min-main~75f09de8.js zero-min-main~052b3814.js zero-min-main~3ff27526.js zero-min-main~11485824.js zero-min-main~c6931360.js zero-min-main~cd7c5bfc.js zero-min-main~02369f19.js chunk {0} zero-min-main~02369f19.js (main~02369f19) 1.57 KiB ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [entry] [rendered] > ./ main [11] ./very-big.js?1 1.57 KiB {0} [built] chunk {1} zero-min-main~052b3814.js (main~052b3814) 603 bytes ={0}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [2] ./small.js?1 67 bytes {1} [built] [3] ./small.js?2 67 bytes {1} [built] [4] ./small.js?3 67 bytes {1} [built] [5] ./small.js?4 67 bytes {1} [built] [6] ./small.js?5 67 bytes {1} [built] [7] ./small.js?6 67 bytes {1} [built] [8] ./small.js?7 67 bytes {1} [built] [9] ./small.js?8 67 bytes {1} [built] [10] ./small.js?9 67 bytes {1} [built] chunk {2} zero-min-main~11485824.js (main~11485824) 603 bytes ={0}= ={1}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [16] ./subfolder/small.js?1 67 bytes {2} [built] [17] ./subfolder/small.js?2 67 bytes {2} [built] [18] ./subfolder/small.js?3 67 bytes {2} [built] [19] ./subfolder/small.js?4 67 bytes {2} [built] [20] ./subfolder/small.js?5 67 bytes {2} [built] [21] ./subfolder/small.js?6 67 bytes {2} [built] [22] ./subfolder/small.js?7 67 bytes {2} [built] [23] ./subfolder/small.js?8 67 bytes {2} [built] [24] ./subfolder/small.js?9 67 bytes {2} [built] chunk {3} zero-min-main~17acad98.js (main~17acad98) 1.57 KiB ={0}= ={1}= ={2}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [39] ./in-some-directory/very-big.js?1 1.57 KiB {3} [built] chunk {4} zero-min-main~3ff27526.js (main~3ff27526) 536 bytes ={0}= ={1}= ={2}= ={3}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [14] ./subfolder/big.js?1 268 bytes {4} [built] [15] ./subfolder/big.js?2 268 bytes {4} [built] chunk {5} zero-min-main~6a2ae26b.js (main~6a2ae26b) 536 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [34] ./in-some-directory/big.js?1 268 bytes {5} [built] [35] ./in-some-directory/small.js?1 67 bytes {5} [built] [36] ./in-some-directory/small.js?2 67 bytes {5} [built] [37] ./in-some-directory/small.js?3 67 bytes {5} [built] [38] ./in-some-directory/small.js?4 67 bytes {5} [built] chunk {6} zero-min-main~6e7ead72.js (main~6e7ead72) 536 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [0] ./big.js?1 268 bytes {6} [built] [1] ./big.js?2 268 bytes {6} [built] chunk {7} zero-min-main~75f09de8.js (main~75f09de8) 603 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={8}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [25] ./inner-module/small.js?1 67 bytes {7} [built] [26] ./inner-module/small.js?2 67 bytes {7} [built] [27] ./inner-module/small.js?3 67 bytes {7} [built] [28] ./inner-module/small.js?4 67 bytes {7} [built] [29] ./inner-module/small.js?5 67 bytes {7} [built] [30] ./inner-module/small.js?6 67 bytes {7} [built] [31] ./inner-module/small.js?7 67 bytes {7} [built] [32] ./inner-module/small.js?8 67 bytes {7} [built] [33] ./inner-module/small.js?9 67 bytes {7} [built] chunk {8} zero-min-main~b2c7414a.js (main~b2c7414a) 1.19 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={9}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [44] ./index.js 1.19 KiB {8} [built] chunk {9} zero-min-main~c6931360.js (main~c6931360) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= ={12}= [initial] [rendered] > ./ main [12] ./very-big.js?2 1.57 KiB {9} [built] chunk {10} zero-min-main~cd7c5bfc.js (main~cd7c5bfc) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={11}= ={12}= [initial] [rendered] > ./ main [13] ./very-big.js?3 1.57 KiB {10} [built] chunk {11} zero-min-vendors~main~0feae4ad.js (vendors~main~0feae4ad) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={12}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~main) > ./ main [43] ./node_modules/very-big.js?1 1.57 KiB {11} [built] chunk {12} zero-min-vendors~main~7274e1de.js (vendors~main~7274e1de) 402 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= [initial] [rendered] split chunk (cache group: vendors) (name: vendors~main) > ./ main [40] ./node_modules/big.js?1 268 bytes {12} [built] [41] ./node_modules/small.js?1 67 bytes {12} [built] [42] ./node_modules/small.js?2 67 bytes {12} [built] Child enforce-min-size: Entrypoint main = enforce-min-size-all~main~6e7ead72.js enforce-min-size-all~main~6a2ae26b.js enforce-min-size-all~main~17acad98.js enforce-min-size-all~main~b2c7414a.js enforce-min-size-all~main~75f09de8.js enforce-min-size-all~main~7274e1de.js enforce-min-size-all~main~0feae4ad.js enforce-min-size-all~main~052b3814.js enforce-min-size-all~main~3ff27526.js enforce-min-size-all~main~11485824.js enforce-min-size-all~main~c6931360.js enforce-min-size-all~main~cd7c5bfc.js enforce-min-size-all~main~02369f19.js enforce-min-size-main.js chunk {0} enforce-min-size-all~main~02369f19.js (all~main~02369f19) 1.57 KiB ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [11] ./very-big.js?1 1.57 KiB {0} [built] chunk {1} enforce-min-size-all~main~052b3814.js (all~main~052b3814) 603 bytes ={0}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [2] ./small.js?1 67 bytes {1} [built] [3] ./small.js?2 67 bytes {1} [built] [4] ./small.js?3 67 bytes {1} [built] [5] ./small.js?4 67 bytes {1} [built] [6] ./small.js?5 67 bytes {1} [built] [7] ./small.js?6 67 bytes {1} [built] [8] ./small.js?7 67 bytes {1} [built] [9] ./small.js?8 67 bytes {1} [built] [10] ./small.js?9 67 bytes {1} [built] chunk {2} enforce-min-size-all~main~0feae4ad.js (all~main~0feae4ad) 1.57 KiB ={0}= ={1}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [43] ./node_modules/very-big.js?1 1.57 KiB {2} [built] chunk {3} enforce-min-size-all~main~11485824.js (all~main~11485824) 603 bytes ={0}= ={1}= ={2}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [16] ./subfolder/small.js?1 67 bytes {3} [built] [17] ./subfolder/small.js?2 67 bytes {3} [built] [18] ./subfolder/small.js?3 67 bytes {3} [built] [19] ./subfolder/small.js?4 67 bytes {3} [built] [20] ./subfolder/small.js?5 67 bytes {3} [built] [21] ./subfolder/small.js?6 67 bytes {3} [built] [22] ./subfolder/small.js?7 67 bytes {3} [built] [23] ./subfolder/small.js?8 67 bytes {3} [built] [24] ./subfolder/small.js?9 67 bytes {3} [built] chunk {4} enforce-min-size-all~main~17acad98.js (all~main~17acad98) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [39] ./in-some-directory/very-big.js?1 1.57 KiB {4} [built] chunk {5} enforce-min-size-all~main~3ff27526.js (all~main~3ff27526) 536 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [14] ./subfolder/big.js?1 268 bytes {5} [built] [15] ./subfolder/big.js?2 268 bytes {5} [built] chunk {6} enforce-min-size-all~main~6a2ae26b.js (all~main~6a2ae26b) 536 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [34] ./in-some-directory/big.js?1 268 bytes {6} [built] [35] ./in-some-directory/small.js?1 67 bytes {6} [built] [36] ./in-some-directory/small.js?2 67 bytes {6} [built] [37] ./in-some-directory/small.js?3 67 bytes {6} [built] [38] ./in-some-directory/small.js?4 67 bytes {6} [built] chunk {7} enforce-min-size-all~main~6e7ead72.js (all~main~6e7ead72) 536 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={8}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [0] ./big.js?1 268 bytes {7} [built] [1] ./big.js?2 268 bytes {7} [built] chunk {8} enforce-min-size-all~main~7274e1de.js (all~main~7274e1de) 402 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={9}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [40] ./node_modules/big.js?1 268 bytes {8} [built] [41] ./node_modules/small.js?1 67 bytes {8} [built] [42] ./node_modules/small.js?2 67 bytes {8} [built] chunk {9} enforce-min-size-all~main~75f09de8.js (all~main~75f09de8) 603 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={10}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [25] ./inner-module/small.js?1 67 bytes {9} [built] [26] ./inner-module/small.js?2 67 bytes {9} [built] [27] ./inner-module/small.js?3 67 bytes {9} [built] [28] ./inner-module/small.js?4 67 bytes {9} [built] [29] ./inner-module/small.js?5 67 bytes {9} [built] [30] ./inner-module/small.js?6 67 bytes {9} [built] [31] ./inner-module/small.js?7 67 bytes {9} [built] [32] ./inner-module/small.js?8 67 bytes {9} [built] [33] ./inner-module/small.js?9 67 bytes {9} [built] chunk {10} enforce-min-size-all~main~b2c7414a.js (all~main~b2c7414a) 1.19 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={11}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [44] ./index.js 1.19 KiB {10} [built] chunk {11} enforce-min-size-all~main~c6931360.js (all~main~c6931360) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={12}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [12] ./very-big.js?2 1.57 KiB {11} [built] chunk {12} enforce-min-size-all~main~cd7c5bfc.js (all~main~cd7c5bfc) 1.57 KiB ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={13}= [initial] [rendered] split chunk (cache group: all) (name: all~main) > ./ main [13] ./very-big.js?3 1.57 KiB {12} [built] chunk {13} enforce-min-size-main.js (main) 0 bytes ={0}= ={1}= ={2}= ={3}= ={4}= ={5}= ={6}= ={7}= ={8}= ={9}= ={10}= ={11}= ={12}= [entry] [rendered] > ./ main" `; exports[`StatsTestCases should print correct stats for split-chunks-prefer-bigger-splits 1`] = ` "Entrypoint main = default/main.js chunk {0} default/async-b~async-c.js (async-b~async-c) 110 bytes <{4}> ={2}= ={3}= [rendered] split chunk (cache group: default) (name: async-b~async-c) > ./b [0] ./index.js 2:0-47 > ./c [0] ./index.js 3:0-47 [4] ./d.js 43 bytes {0} {1} [built] [6] ./f.js 67 bytes {0} [built] chunk {1} default/async-a.js (async-a) 134 bytes <{4}> [rendered] > ./a [0] ./index.js 1:0-47 [1] ./a.js 48 bytes {1} [built] [4] ./d.js 43 bytes {0} {1} [built] [5] ./e.js 43 bytes {1} {2} [built] chunk {2} default/async-b.js (async-b) 105 bytes <{4}> ={0}= [rendered] > ./b [0] ./index.js 2:0-47 [2] ./b.js 62 bytes {2} [built] [5] ./e.js 43 bytes {1} {2} [built] chunk {3} default/async-c.js (async-c) 48 bytes <{4}> ={0}= [rendered] > ./c [0] ./index.js 3:0-47 [3] ./c.js 48 bytes {3} [built] chunk {4} default/main.js (main) 147 bytes >{0}< >{1}< >{2}< >{3}< [entry] [rendered] > ./ main [0] ./index.js 147 bytes {4} [built]" `; exports[`StatsTestCases should print correct stats for tree-shaking 1`] = ` "Hash: ecca8f58566e08b05b03 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 8.23 KiB 0 [emitted] main Entrypoint main = bundle.js [0] ./a.js 13 bytes {0} [built] [exports: a] [all exports used] [1] ./b.js 13 bytes {0} [built] [exports: b] [no exports used] [2] ./unknown.js 0 bytes {0} [built] [only some exports used: c] [3] ./reexport-unknown.js 83 bytes {0} [built] [exports: a, b, c, d] [only some exports used: a, c] [4] ./reexport-star-unknown.js 68 bytes {0} [built] [only some exports used: a, c] [5] ./unknown2.js 0 bytes {0} [built] [only some exports used: y] [6] ./reexport-known.js 49 bytes {0} [built] [exports: a, b] [only some exports used: a] [7] ./reexport-star-known.js 41 bytes {0} [built] [exports: a, b] [only some exports used: a] [8] ./edge.js 45 bytes {0} [built] [only some exports used: y] [9] ./index.js 315 bytes {0} [built] [no exports] [10] ./require.include.js 36 bytes {0} [built] [exports: a, default] [no exports used]" `; exports[`StatsTestCases should print correct stats for warnings-terser 1`] = ` "Hash: eac5781f73c002a640b6 Time: Xms Built at: Thu Jan 01 1970 00:00:00 GMT Asset Size Chunks Chunk Names bundle.js 2.89 KiB 0 [emitted] main Entrypoint main = bundle.js [0] ./index.js 299 bytes {0} [built] [1] ./a.js 249 bytes {0} [built] [2] (webpack)/buildin/module.js 497 bytes {0} [built] WARNING in Terser Plugin: Dropping unused function someUnRemoteUsedFunction1 [./a.js:3,0] WARNING in Terser Plugin: Dropping unused function someUnRemoteUsedFunction2 [./a.js:4,0] WARNING in Terser Plugin: Dropping unused function someUnRemoteUsedFunction3 [./a.js:5,0] WARNING in Terser Plugin: Dropping unused function someUnRemoteUsedFunction4 [./a.js:6,0] WARNING in Terser Plugin: Dropping unused function someUnRemoteUsedFunction5 [./a.js:7,0]" `; webpack-4.30.0/test/benchmarkCases/000077500000000000000000000000001345416772700171225ustar00rootroot00000000000000webpack-4.30.0/test/benchmarkCases/large-ast/000077500000000000000000000000001345416772700210015ustar00rootroot00000000000000webpack-4.30.0/test/benchmarkCases/large-ast/index.js000066400000000000000000000010221345416772700224410ustar00rootroot00000000000000import "react/dist/react-with-addons.js?0"; import "react/dist/react-with-addons.js?1"; import "react/dist/react-with-addons.js?2"; import "react/dist/react-with-addons.js?3"; import "react/dist/react-with-addons.js?4"; import "react/dist/react-with-addons.js?5"; import "react/dist/react-with-addons.js?6"; import "react/dist/react-with-addons.js?7"; import "react/dist/react-with-addons.js?8"; import "react/dist/react-with-addons.js?9"; import "react/dist/react-with-addons.js?10"; import "react/dist/react-with-addons.js?11"; webpack-4.30.0/test/benchmarkCases/large-ast/index2.js000066400000000000000000000003701345416772700225300ustar00rootroot00000000000000import "lodash/lodash.js?0"; import "lodash/lodash.js?1"; import "lodash/lodash.js?2"; import "lodash/lodash.js?3"; import "lodash/lodash.min.js?0"; import "lodash/lodash.min.js?1"; import "lodash/lodash.min.js?2"; import "lodash/lodash.min.js?3"; webpack-4.30.0/test/benchmarkCases/large-ast/webpack.config.js000066400000000000000000000000661345416772700242210ustar00rootroot00000000000000module.exports = { entry: ["./index", "./index2"] }; webpack-4.30.0/test/benchmarkCases/libraries/000077500000000000000000000000001345416772700210765ustar00rootroot00000000000000webpack-4.30.0/test/benchmarkCases/libraries/webpack.config.js000066400000000000000000000000771345416772700243200ustar00rootroot00000000000000module.exports = { entry: ["react", "react-dom", "lodash"] }; webpack-4.30.0/test/benchmarkCases/many-chunks/000077500000000000000000000000001345416772700213575ustar00rootroot00000000000000webpack-4.30.0/test/benchmarkCases/many-chunks/a.js000066400000000000000000000005361345416772700221410ustar00rootroot00000000000000import("./b?0" + __resourceQuery); import("./b?1" + __resourceQuery); import("./b?2" + __resourceQuery); import("./b?3" + __resourceQuery); import("./b?4" + __resourceQuery); import("./b?5" + __resourceQuery); import("./b?6" + __resourceQuery); import("./b?7" + __resourceQuery); import("./b?8" + __resourceQuery); import("./b?9" + __resourceQuery); webpack-4.30.0/test/benchmarkCases/many-chunks/b.js000066400000000000000000000003351345416772700221370ustar00rootroot00000000000000import("./c?0" + __resourceQuery); import("./c?1" + __resourceQuery); import("./c?2" + __resourceQuery); import("./c?3" + __resourceQuery); import("./c?4" + __resourceQuery); import("./a" + __resourceQuery.substr(0, 2)); webpack-4.30.0/test/benchmarkCases/many-chunks/c.js000066400000000000000000000000131345416772700221310ustar00rootroot00000000000000// content webpack-4.30.0/test/benchmarkCases/many-chunks/index.js000066400000000000000000000002521345416772700230230ustar00rootroot00000000000000import("./a?0"); import("./a?1"); import("./a?2"); import("./a?3"); import("./a?4"); import("./a?5"); import("./a?6"); import("./a?7"); import("./a?8"); import("./a?9"); webpack-4.30.0/test/benchmarkCases/many-chunks/webpack.config.js000066400000000000000000000000501345416772700245700ustar00rootroot00000000000000module.exports = { entry: "./index" }; webpack-4.30.0/test/benchmarkCases/many-modules-source-map/000077500000000000000000000000001345416772700236055ustar00rootroot00000000000000webpack-4.30.0/test/benchmarkCases/many-modules-source-map/a.js000066400000000000000000000005501345416772700243630ustar00rootroot00000000000000require("./b?0" + __resourceQuery); require("./b?1" + __resourceQuery); require("./b?2" + __resourceQuery); require("./b?3" + __resourceQuery); require("./b?4" + __resourceQuery); require("./b?5" + __resourceQuery); require("./b?6" + __resourceQuery); require("./b?7" + __resourceQuery); require("./b?8" + __resourceQuery); require("./b?9" + __resourceQuery); webpack-4.30.0/test/benchmarkCases/many-modules-source-map/b.js000066400000000000000000000006271345416772700243710ustar00rootroot00000000000000require("./c?0" + __resourceQuery); require("./c?1" + __resourceQuery); require("./c?2" + __resourceQuery); require("./c?3" + __resourceQuery); require("./c?4" + __resourceQuery); require("./c?5" + __resourceQuery); require("./c?6" + __resourceQuery); require("./c?7" + __resourceQuery); require("./c?8" + __resourceQuery); require("./c?9" + __resourceQuery); require("./a" + __resourceQuery.substr(0, 2)); webpack-4.30.0/test/benchmarkCases/many-modules-source-map/c.js000066400000000000000000000000131345416772700243570ustar00rootroot00000000000000// content webpack-4.30.0/test/benchmarkCases/many-modules-source-map/index.js000066400000000000000000000002401345416772700252460ustar00rootroot00000000000000import "./a?0"; import "./a?1"; import "./a?2"; import "./a?3"; import "./a?4"; import "./a?5"; import "./a?6"; import "./a?7"; import "./a?8"; import "./a?9"; webpack-4.30.0/test/benchmarkCases/many-modules-source-map/webpack.config.js000066400000000000000000000001221345416772700270160ustar00rootroot00000000000000module.exports = { entry: "./index", devtool: "eval-cheap-module-source-map" }; webpack-4.30.0/test/benchmarkCases/many-modules/000077500000000000000000000000001345416772700215345ustar00rootroot00000000000000webpack-4.30.0/test/benchmarkCases/many-modules/a.js000066400000000000000000000005501345416772700223120ustar00rootroot00000000000000require("./b?0" + __resourceQuery); require("./b?1" + __resourceQuery); require("./b?2" + __resourceQuery); require("./b?3" + __resourceQuery); require("./b?4" + __resourceQuery); require("./b?5" + __resourceQuery); require("./b?6" + __resourceQuery); require("./b?7" + __resourceQuery); require("./b?8" + __resourceQuery); require("./b?9" + __resourceQuery); webpack-4.30.0/test/benchmarkCases/many-modules/b.js000066400000000000000000000006271345416772700223200ustar00rootroot00000000000000require("./c?0" + __resourceQuery); require("./c?1" + __resourceQuery); require("./c?2" + __resourceQuery); require("./c?3" + __resourceQuery); require("./c?4" + __resourceQuery); require("./c?5" + __resourceQuery); require("./c?6" + __resourceQuery); require("./c?7" + __resourceQuery); require("./c?8" + __resourceQuery); require("./c?9" + __resourceQuery); require("./a" + __resourceQuery.substr(0, 2)); webpack-4.30.0/test/benchmarkCases/many-modules/c.js000066400000000000000000000000131345416772700223060ustar00rootroot00000000000000// content webpack-4.30.0/test/benchmarkCases/many-modules/index.js000066400000000000000000000002401345416772700231750ustar00rootroot00000000000000import "./a?0"; import "./a?1"; import "./a?2"; import "./a?3"; import "./a?4"; import "./a?5"; import "./a?6"; import "./a?7"; import "./a?8"; import "./a?9"; webpack-4.30.0/test/benchmarkCases/many-modules/webpack.config.js000066400000000000000000000000501345416772700247450ustar00rootroot00000000000000module.exports = { entry: "./index" }; webpack-4.30.0/test/benchmarkCases/many-stuff-harmony/000077500000000000000000000000001345416772700226665ustar00rootroot00000000000000webpack-4.30.0/test/benchmarkCases/many-stuff-harmony/a.js000066400000000000000000000004261345416772700234460ustar00rootroot00000000000000module.exports = function() { let str = ""; let sum = ["1"]; const query = +this.query.substr(1); for(let i = 0; i < query; i++) { str += `import b${i} from "./b?${Math.floor(i/2)}!";\n`; sum.push(`b${i}`); } str += "export default " + sum.join(" + "); return str; } webpack-4.30.0/test/browsertest/000077500000000000000000000000001345416772700165745ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/build.js000066400000000000000000000051151345416772700202330ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var cp = require('child_process'); var argv = process.argv; argv.shift(); argv.shift(); var extraArgs = argv; function bindOutput(p) { p.stdout.on("data", function(data) { process.stdout.write(data); }); p.stderr.on("data", function(data) { process.stderr.write(data); }); } function join(a, b) { a = a.slice(0); Array.prototype.push.apply(a, b); return a; } console.log("compile scripts…"); var extraArgsNoWatch = extraArgs.slice(0); var watchIndex = extraArgsNoWatch.indexOf("--watch"); if(watchIndex != -1) extraArgsNoWatch.splice(watchIndex, 1); // node ../../bin/webpack --output-pathinfo --color --optimize-max-chunks 1 --output-library library1 node_modules/library1 js/library1 var library1 = cp.spawn("node", join(["../../bin/webpack.js", "--output-pathinfo", "--color", "--optimize-max-chunks", "1", "--output-library", "library1", "node_modules/library1", "js/library1.js"], extraArgsNoWatch)); bindOutput(library1); library1.on("exit", function(code) { if(code === 0) { // node ../../bin/webpack --output-pathinfo --color --resolve-alias vm=vm-browserify --output-public-path js/ --output-chunk-filename [name].web.js --module-bind css=style!css --module-bind less=style-loader!css-loader!less-loader --module-bind coffee --module-bind jade --prefetch ./lib/stylesheet.less ./lib/index "js/web.js?h=[hash]" var main = cp.spawn("node", join(["../../bin/webpack.js", "--output-pathinfo", "--color", "--resolve-alias", "vm=vm-browserify", "--output-public-path", "js/", "--output-chunk-filename", "[name].web.js", "--module-bind", "css=style-loader!css-loader", "--module-bind", "less=style-loader/url!file-loader?postfix=.css&string!less-loader", "--module-bind", "coffee", "--module-bind", "jade", "--prefetch", "./lib/stylesheet.less", "./lib/index", "js/web.js?h=[hash]", "--progress"], extraArgs)); bindOutput(main); } }); // node ../../bin/webpack --output-pathinfo --color --output-library-target umd --output-jsonp-function webpackJsonpLib2 --output-public-path js/ --output-chunk-filename [chunkhash].lib2.js --config library2config.coffee library2b library2 js/library2.js var library2 = cp.spawn("node", join(["../../bin/webpack.js", "--output-pathinfo", "--color", "--output-library-target", "umd", "--output-jsonp-function", "webpackJsonpLib2", "--output-public-path", "js/", "--output-chunk-filename", "[chunkhash].lib2.js", "--config", "library2config.coffee", "library2b", "library2", "js/library2.js"], extraArgsNoWatch)); bindOutput(library2); webpack-4.30.0/test/browsertest/img/000077500000000000000000000000001345416772700173505ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/img/fail.png000066400000000000000000000002761345416772700207760ustar00rootroot00000000000000PNG  IHDRZgAMA auIDAT8O E b8my]9]'()ceWaw[{42 resolveIt = -> resolve entry: common: "library2/lib/common" output: hashDigestLength: 5 module: rules: [ { test: /extra2?\.js/, loader: "raw-loader!./node_modules/extra.loader.js!val-loader?cacheable", enforce: "post" } ] amd: fromOptions: true plugins: [ new webpack.optimize.LimitChunkCountPlugin maxChunks: 3 new webpack.DefinePlugin "typeof CONST_TYPEOF": JSON.stringify("typeof"), CONST_UNDEFINED: undefined, CONST_NULL: "null", CONST_TRUE: true, CONST_FALSE: false, CONST_FUNCTION: -> return "ok"; CONST_NUMBER: 123, CONST_NUMBER_EXPR: "(1*100+23)", CONST_OBJECT: { A: 1, B: JSON.stringify("B"), C: -> return "C"; } new webpack.ProvidePlugin s3: "submodule3" -> this.plugin "normal-module-factory", (nmf) -> nmf.plugin "after-resolve", (data, callback) -> data.resource = data.resource.replace /extra\.js/, "extra2.js"; callback null, data; ] setTimeout resolveIt, 300 webpack-4.30.0/test/browsertest/middlewareTest.js000066400000000000000000000022351345416772700221110ustar00rootroot00000000000000var webpackMiddleware = require("webpack-dev-middleware"); var webpack = require("webpack"); var express = require("express"); var path = require("path"); var app = express(); app.configure(function() { app.use(webpackMiddleware(webpack({ context: __dirname, entry: ["../../hot/poll?10000", "./lib/index"], debug: true, devtool: "sourcemap", module: { loaders: [ { test: /\.json$/, loader: "json" }, { test: /\.coffee$/, loader: "coffee" }, { test: /\.jade$/, loader: "jade" }, { test: /\.css$/, loader: "style!css" }, { test: /\.less$/, loader: "style!css!less" }, ] }, resolve: { alias: { vm: "vm-browserify" } }, resolve: { unsafeCache: true }, cache: true, recordsPath: path.join(__dirname, "webpack.records.json"), output: { publicPath: "http://localhost:8080/js/", path: "/", filename: "web.js", chunkFilename: "[chunkhash].chunk.js" }, plugins: [ new webpack.HotModuleReplacementPlugin() ] }), { lazy: false, watchDelay: 5000, publicPath: "/js/", filename: "web.js", stats: { colors: true } })); app.use(express.static(path.join(__dirname))); }); app.listen(8080); webpack-4.30.0/test/browsertest/mocha.css000066400000000000000000000056621345416772700204060ustar00rootroot00000000000000@charset "UTF-8"; body { font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; padding: 60px 50px; } #mocha ul, #mocha li { margin: 0; padding: 0; } #mocha ul { list-style: none; } #mocha h1, #mocha h2 { margin: 0; } #mocha h1 { margin-top: 15px; font-size: 1em; font-weight: 200; } #mocha h1 a { text-decoration: none; color: inherit; } #mocha h1 a:hover { text-decoration: underline; } #mocha .suite .suite h1 { margin-top: 0; font-size: .8em; } .hidden { display: none; } #mocha h2 { font-size: 12px; font-weight: normal; cursor: pointer; } #mocha .suite { margin-left: 15px; } #mocha .test { margin-left: 15px; } #mocha .test:hover h2::after { position: relative; top: 0; right: -10px; content: '(view source)'; font-size: 12px; font-family: arial; color: #888; } #mocha .test.pending:hover h2::after { content: '(pending)'; font-family: arial; } #mocha .test.pass.medium .duration { background: #C09853; } #mocha .test.pass.slow .duration { background: #B94A48; } #mocha .test.pass::before { content: '✓'; font-size: 12px; display: block; float: left; margin-right: 5px; color: #00d6b2; } #mocha .test.pass .duration { font-size: 9px; margin-left: 5px; padding: 2px 5px; color: white; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); box-shadow: inset 0 1px 1px rgba(0,0,0,.2); -webkit-border-radius: 5px; -moz-border-radius: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; border-radius: 5px; } #mocha .test.pass.fast .duration { display: none; } #mocha .test.pending { color: #0b97c4; } #mocha .test.pending::before { content: '◦'; color: #0b97c4; } #mocha .test.fail { color: #c00; } #mocha .test.fail pre { color: black; } #mocha .test.fail::before { content: '✖'; font-size: 12px; display: block; float: left; margin-right: 5px; color: #c00; } #mocha .test pre.error { color: #c00; } #mocha .test pre { display: inline-block; font: 12px/1.5 monaco, monospace; margin: 5px; padding: 15px; border: 1px solid #eee; border-bottom-color: #ddd; -webkit-border-radius: 3px; -webkit-box-shadow: 0 1px 3px #eee; } #report.pass .test.fail { display: none; } #report.fail .test.pass { display: none; } #error { color: #c00; font-size: 1.5 em; font-weight: 100; letter-spacing: 1px; } #stats { position: fixed; top: 15px; right: 10px; font-size: 12px; margin: 0; color: #888; } #stats .progress { float: right; padding-top: 0; } #stats em { color: black; } #stats a { text-decoration: none; color: inherit; } #stats a:hover { border-bottom: 1px solid #eee; } #stats li { display: inline-block; margin: 0 5px; list-style: none; padding-top: 11px; } code .comment { color: #ddd } code .init { color: #2F6FAD } code .string { color: #5890AD } code .keyword { color: #8A6343 } code .number { color: #2F6FAD } webpack-4.30.0/test/browsertest/mocha.js000066400000000000000000002763501345416772700202360ustar00rootroot00000000000000;(function(){ // CommonJS require() function require(p){ var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path){ var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn){ require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p.charAt(0)) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.register("browser/debug.js", function(module, exports, require){ module.exports = function(type){ return function(){ } }; }); // module: browser/debug.js require.register("browser/diff.js", function(module, exports, require){ }); // module: browser/diff.js require.register("browser/events.js", function(module, exports, require){ /** * Module exports. */ exports.EventEmitter = EventEmitter; /** * Check if `obj` is an array. */ function isArray(obj) { return '[object Array]' == {}.toString.call(obj); } /** * Event emitter constructor. * * @api public */ function EventEmitter(){}; /** * Adds a listener. * * @api public */ EventEmitter.prototype.on = function (name, fn) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = fn; } else if (isArray(this.$events[name])) { this.$events[name].push(fn); } else { this.$events[name] = [this.$events[name], fn]; } return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; /** * Adds a volatile listener. * * @api public */ EventEmitter.prototype.once = function (name, fn) { var self = this; function on () { self.removeListener(name, on); fn.apply(this, arguments); }; on.listener = fn; this.on(name, on); return this; }; /** * Removes a listener. * * @api public */ EventEmitter.prototype.removeListener = function (name, fn) { if (this.$events && this.$events[name]) { var list = this.$events[name]; if (isArray(list)) { var pos = -1; for (var i = 0, l = list.length; i < l; i++) { if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { pos = i; break; } } if (pos < 0) { return this; } list.splice(pos, 1); if (!list.length) { delete this.$events[name]; } } else if (list === fn || (list.listener && list.listener === fn)) { delete this.$events[name]; } } return this; }; /** * Removes all listeners for an event. * * @api public */ EventEmitter.prototype.removeAllListeners = function (name) { if (name === undefined) { this.$events = {}; return this; } if (this.$events && this.$events[name]) { this.$events[name] = null; } return this; }; /** * Gets all listeners for a certain event. * * @api public */ EventEmitter.prototype.listeners = function (name) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = []; } if (!isArray(this.$events[name])) { this.$events[name] = [this.$events[name]]; } return this.$events[name]; }; /** * Emits an event. * * @api public */ EventEmitter.prototype.emit = function (name) { if (!this.$events) { return false; } var handler = this.$events[name]; if (!handler) { return false; } var args = [].slice.call(arguments, 1); if ('function' == typeof handler) { handler.apply(this, args); } else if (isArray(handler)) { var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(this, args); } } else { return false; } return true; }; }); // module: browser/events.js require.register("browser/fs.js", function(module, exports, require){ }); // module: browser/fs.js require.register("browser/path.js", function(module, exports, require){ }); // module: browser/path.js require.register("browser/progress.js", function(module, exports, require){ /** * Expose `Progress`. */ module.exports = Progress; /** * Initialize a new `Progress` indicator. */ function Progress() { this.percent = 0; this.size(0); this.fontSize(11); this.font('helvetica, arial, sans-serif'); } /** * Set progress size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.size = function(n){ this._size = n; return this; }; /** * Set text to `str`. * * @param {String} str * @return {Progress} for chaining * @api public */ Progress.prototype.text = function(str){ this._text = str; return this; }; /** * Set font size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.fontSize = function(n){ this._fontSize = n; return this; }; /** * Set font `family`. * * @param {String} family * @return {Progress} for chaining */ Progress.prototype.font = function(family){ this._font = family; return this; }; /** * Update percentage to `n`. * * @param {Number} n * @return {Progress} for chaining */ Progress.prototype.update = function(n){ this.percent = n; return this; }; /** * Draw on `ctx`. * * @param {CanvasRenderingContext2d} ctx * @return {Progress} for chaining */ Progress.prototype.draw = function(ctx){ var percent = Math.min(this.percent, 100) , size = this._size , half = size / 2 , x = half , y = half , rad = half - 1 , fontSize = this._fontSize; ctx.font = fontSize + 'px ' + this._font; var angle = Math.PI * 2 * (percent / 100); ctx.clearRect(0, 0, size, size); // outer circle ctx.strokeStyle = '#9f9f9f'; ctx.beginPath(); ctx.arc(x, y, rad, 0, angle, false); ctx.stroke(); // inner circle ctx.strokeStyle = '#eee'; ctx.beginPath(); ctx.arc(x, y, rad - 1, 0, angle, true); ctx.stroke(); // text var text = this._text || (percent | 0) + '%' , w = ctx.measureText(text).width; ctx.fillText( text , x - w / 2 + 1 , y + fontSize / 2 - 1); return this; }; }); // module: browser/progress.js require.register("browser/tty.js", function(module, exports, require){ exports.isatty = function(){ return true; }; exports.getWindowSize = function(){ return [window.innerHeight, window.innerWidth]; }; }); // module: browser/tty.js require.register("context.js", function(module, exports, require){ /** * Expose `Context`. */ module.exports = Context; /** * Initialize a new `Context`. * * @api private */ function Context(){} /** * Set or get the context `Runnable` to `runnable`. * * @param {Runnable} runnable * @return {Context} * @api private */ Context.prototype.runnable = function(runnable){ if (0 == arguments.length) return this._runnable; this.test = this._runnable = runnable; return this; }; /** * Set test timeout `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.timeout = function(ms){ this.runnable().timeout(ms); return this; }; /** * Set test slowness threshold `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.slow = function(ms){ this.runnable().slow(ms); return this; }; /** * Inspect the context void of `._runnable`. * * @return {String} * @api private */ Context.prototype.inspect = function(){ return JSON.stringify(this, function(key, val){ if ('_runnable' == key) return; if ('test' == key) return; return val; }, 2); }; }); // module: context.js require.register("hook.js", function(module, exports, require){ /** * Module dependencies. */ var Runnable = require('./runnable'); /** * Expose `Hook`. */ module.exports = Hook; /** * Initialize a new `Hook` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Hook(title, fn) { Runnable.call(this, title, fn); this.type = 'hook'; } /** * Inherit from `Runnable.prototype`. */ Hook.prototype = new Runnable; Hook.prototype.constructor = Hook; /** * Get or set the test `err`. * * @param {Error} err * @return {Error} * @api public */ Hook.prototype.error = function(err){ if (0 == arguments.length) { var err = this._error; this._error = null; return err; } this._error = err; }; }); // module: hook.js require.register("interfaces/bdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * BDD-style interface: * * describe('Array', function(){ * describe('#indexOf()', function(){ * it('should return -1 when not present', function(){ * * }); * * it('should return the index when present', function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ context.before = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after running tests. */ context.after = function(fn){ suites[0].afterAll(fn); }; /** * Execute before each test case. */ context.beforeEach = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.afterEach = function(fn){ suites[0].afterEach(fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.describe = context.context = function(title, fn){ var suite = Suite.create(suites[0], title); suites.unshift(suite); fn(); suites.shift(); return suite; }; /** * Pending describe. */ context.xdescribe = context.xcontext = context.describe.skip = function(title, fn){ var suite = Suite.create(suites[0], title); suite.pending = true; suites.unshift(suite); fn(); suites.shift(); }; /** * Exclusive suite. */ context.describe.only = function(title, fn){ var suite = context.describe(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.it = context.specify = function(title, fn){ var suite = suites[0]; if (suite.pending) var fn = null; var test = new Test(title, fn); suite.addTest(test); return test; }; /** * Exclusive test-case. */ context.it.only = function(title, fn){ var test = context.it(title, fn); mocha.grep(test.fullTitle()); }; /** * Pending test case. */ context.xit = context.xspecify = context.it.skip = function(title){ context.it(title); }; }); }; }); // module: interfaces/bdd.js require.register("interfaces/exports.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * TDD-style interface: * * exports.Array = { * '#indexOf()': { * 'should return -1 when the value is not present': function(){ * * }, * * 'should return the correct index when the value is present': function(){ * * } * } * }; * */ module.exports = function(suite){ var suites = [suite]; suite.on('require', visit); function visit(obj) { var suite; for (var key in obj) { if ('function' == typeof obj[key]) { var fn = obj[key]; switch (key) { case 'before': suites[0].beforeAll(fn); break; case 'after': suites[0].afterAll(fn); break; case 'beforeEach': suites[0].beforeEach(fn); break; case 'afterEach': suites[0].afterEach(fn); break; default: suites[0].addTest(new Test(key, fn)); } } else { var suite = Suite.create(suites[0], key); suites.unshift(suite); visit(obj[key]); suites.shift(); } } } }; }); // module: interfaces/exports.js require.register("interfaces/index.js", function(module, exports, require){ exports.bdd = require('./bdd'); exports.tdd = require('./tdd'); exports.qunit = require('./qunit'); exports.exports = require('./exports'); }); // module: interfaces/index.js require.register("interfaces/qunit.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * QUnit-style interface: * * suite('Array'); * * test('#length', function(){ * var arr = [1,2,3]; * ok(arr.length == 3); * }); * * test('#indexOf()', function(){ * var arr = [1,2,3]; * ok(arr.indexOf(1) == 0); * ok(arr.indexOf(2) == 1); * ok(arr.indexOf(3) == 2); * }); * * suite('String'); * * test('#length', function(){ * ok('foo'.length == 3); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context){ /** * Execute before running tests. */ context.before = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after running tests. */ context.after = function(fn){ suites[0].afterAll(fn); }; /** * Execute before each test case. */ context.beforeEach = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.afterEach = function(fn){ suites[0].afterEach(fn); }; /** * Describe a "suite" with the given `title`. */ context.suite = function(title){ if (suites.length > 1) suites.shift(); var suite = Suite.create(suites[0], title); suites.unshift(suite); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ suites[0].addTest(new Test(title, fn)); }; }); }; }); // module: interfaces/qunit.js require.register("interfaces/tdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * TDD-style interface: * * suite('Array', function(){ * suite('#indexOf()', function(){ * suiteSetup(function(){ * * }); * * test('should return -1 when not present', function(){ * * }); * * test('should return the index when present', function(){ * * }); * * suiteTeardown(function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before each test case. */ context.setup = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.teardown = function(fn){ suites[0].afterEach(fn); }; /** * Execute before the suite. */ context.suiteSetup = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after the suite. */ context.suiteTeardown = function(fn){ suites[0].afterAll(fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.suite = function(title, fn){ var suite = Suite.create(suites[0], title); suites.unshift(suite); fn(); suites.shift(); return suite; }; /** * Exclusive test-case. */ context.suite.only = function(title, fn){ var suite = context.suite(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ var test = new Test(title, fn); suites[0].addTest(test); return test; }; /** * Exclusive test-case. */ context.test.only = function(title, fn){ var test = context.test(title, fn); mocha.grep(test.fullTitle()); }; }); }; }); // module: interfaces/tdd.js require.register("mocha.js", function(module, exports, require){ /*! * mocha * Copyright(c) 2011 TJ Holowaychuk * MIT Licensed */ /** * Module dependencies. */ var path = require('browser/path') , utils = require('./utils'); /** * Expose `Mocha`. */ exports = module.exports = Mocha; /** * Expose internals. */ exports.utils = utils; exports.interfaces = require('./interfaces'); exports.reporters = require('./reporters'); exports.Runnable = require('./runnable'); exports.Context = require('./context'); exports.Runner = require('./runner'); exports.Suite = require('./suite'); exports.Hook = require('./hook'); exports.Test = require('./test'); /** * Return image `name` path. * * @param {String} name * @return {String} * @api private */ function image(name) { return __dirname + '/../images/' + name + '.png'; } /** * Setup mocha with `options`. * * Options: * * - `ui` name "bdd", "tdd", "exports" etc * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` * - `globals` array of accepted globals * - `timeout` timeout in milliseconds * - `slow` milliseconds to wait before considering a test slow * - `ignoreLeaks` ignore global leaks * - `grep` string or regexp to filter tests with * * @param {Object} options * @api public */ function Mocha(options) { options = options || {}; this.files = []; this.options = options; this.grep(options.grep); this.suite = new exports.Suite('', new exports.Context); this.ui(options.ui); this.reporter(options.reporter); if (options.timeout) this.timeout(options.timeout); if (options.slow) this.slow(options.slow); } /** * Add test `file`. * * @param {String} file * @api public */ Mocha.prototype.addFile = function(file){ this.files.push(file); return this; }; /** * Set reporter to `reporter`, defaults to "dot". * * @param {String|Function} reporter name of a reporter or a reporter constructor * @api public */ Mocha.prototype.reporter = function(reporter){ if ('function' == typeof reporter) { this._reporter = reporter; } else { reporter = reporter || 'dot'; try { this._reporter = require('./reporters/' + reporter); } catch (err) { this._reporter = require(reporter); } if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); } return this; }; /** * Set test UI `name`, defaults to "bdd". * * @param {String} bdd * @api public */ Mocha.prototype.ui = function(name){ name = name || 'bdd'; this._ui = exports.interfaces[name]; if (!this._ui) throw new Error('invalid interface "' + name + '"'); this._ui = this._ui(this.suite); return this; }; /** * Load registered files. * * @api private */ Mocha.prototype.loadFiles = function(fn){ var self = this; var suite = this.suite; var pending = this.files.length; this.files.forEach(function(file){ file = path.resolve(file); suite.emit('pre-require', global, file, self); suite.emit('require', require(file), file, self); suite.emit('post-require', global, file, self); --pending || (fn && fn()); }); }; /** * Enable growl support. * * @api private */ Mocha.prototype._growl = function(runner, reporter) { var notify = require('growl'); runner.on('end', function(){ var stats = reporter.stats; if (stats.failures) { var msg = stats.failures + ' of ' + runner.total + ' tests failed'; notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); } else { notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { name: 'mocha' , title: 'Passed' , image: image('ok') }); } }); }; /** * Add regexp to grep, if `re` is a string it is escaped. * * @param {RegExp|String} re * @return {Mocha} * @api public */ Mocha.prototype.grep = function(re){ this.options.grep = 'string' == typeof re ? new RegExp(utils.escapeRegexp(re)) : re; return this; }; /** * Invert `.grep()` matches. * * @return {Mocha} * @api public */ Mocha.prototype.invert = function(){ this.options.invert = true; return this; }; /** * Ignore global leaks. * * @return {Mocha} * @api public */ Mocha.prototype.ignoreLeaks = function(){ this.options.ignoreLeaks = true; return this; }; /** * Enable global leak checking. * * @return {Mocha} * @api public */ Mocha.prototype.checkLeaks = function(){ this.options.ignoreLeaks = false; return this; }; /** * Enable growl support. * * @return {Mocha} * @api public */ Mocha.prototype.growl = function(){ this.options.growl = true; return this; }; /** * Ignore `globals` array or string. * * @param {Array|String} globals * @return {Mocha} * @api public */ Mocha.prototype.globals = function(globals){ this.options.globals = (this.options.globals || []).concat(globals); return this; }; /** * Set the timeout in milliseconds. * * @param {Number} timeout * @return {Mocha} * @api public */ Mocha.prototype.timeout = function(timeout){ this.suite.timeout(timeout); return this; }; /** * Set slowness threshold in milliseconds. * * @param {Number} slow * @return {Mocha} * @api public */ Mocha.prototype.slow = function(slow){ this.suite.slow(slow); return this; }; /** * Run tests and invoke `fn()` when complete. * * @param {Function} fn * @return {Runner} * @api public */ Mocha.prototype.run = function(fn){ if (this.files.length) this.loadFiles(); var suite = this.suite; var options = this.options; var runner = new exports.Runner(suite); var reporter = new this._reporter(runner); runner.ignoreLeaks = options.ignoreLeaks; if (options.grep) runner.grep(options.grep, options.invert); if (options.globals) runner.globals(options.globals); if (options.growl) this._growl(runner, reporter); return runner.run(fn); }; }); // module: mocha.js require.register("ms.js", function(module, exports, require){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; /** * Parse or format the given `val`. * * @param {String|Number} val * @return {String|Number} * @api public */ module.exports = function(val){ if ('string' == typeof val) return parse(val); return format(val); } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); if (!m) return; var n = parseFloat(m[1]); var type = (m[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'y': return n * 31557600000; case 'days': case 'day': case 'd': return n * 86400000; case 'hours': case 'hour': case 'h': return n * 3600000; case 'minutes': case 'minute': case 'm': return n * 60000; case 'seconds': case 'second': case 's': return n * 1000; case 'ms': return n; } } /** * Format the given `ms`. * * @param {Number} ms * @return {String} * @api public */ function format(ms) { if (ms == d) return (ms / d) + ' day'; if (ms > d) return (ms / d) + ' days'; if (ms == h) return (ms / h) + ' hour'; if (ms > h) return (ms / h) + ' hours'; if (ms == m) return (ms / m) + ' minute'; if (ms > m) return (ms / m) + ' minutes'; if (ms == s) return (ms / s) + ' second'; if (ms > s) return (ms / s) + ' seconds'; return ms + ' ms'; } }); // module: ms.js require.register("reporters/base.js", function(module, exports, require){ /** * Module dependencies. */ var tty = require('browser/tty') , diff = require('browser/diff') , ms = require('../ms'); /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Check if both stdio streams are associated with a tty. */ var isatty = tty.isatty(1) && tty.isatty(2); /** * Expose `Base`. */ exports = module.exports = Base; /** * Enable coloring by default. */ exports.useColors = isatty; /** * Default color map. */ exports.colors = { 'pass': 90 , 'fail': 31 , 'bright pass': 92 , 'bright fail': 91 , 'bright yellow': 93 , 'pending': 36 , 'suite': 0 , 'error title': 0 , 'error message': 31 , 'error stack': 90 , 'checkmark': 32 , 'fast': 90 , 'medium': 33 , 'slow': 31 , 'green': 32 , 'light': 90 , 'diff gutter': 90 , 'diff added': 42 , 'diff removed': 41 }; /** * Color `str` with the given `type`, * allowing colors to be disabled, * as well as user-defined color * schemes. * * @param {String} type * @param {String} str * @return {String} * @api private */ var color = exports.color = function(type, str) { if (!exports.useColors) return str; return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; }; /** * Expose term window size, with some * defaults for when stderr is not a tty. */ exports.window = { width: isatty ? process.stdout.getWindowSize ? process.stdout.getWindowSize(1)[0] : tty.getWindowSize()[1] : 75 }; /** * Expose some basic cursor interactions * that are common among reporters. */ exports.cursor = { hide: function(){ process.stdout.write('\u001b[?25l'); }, show: function(){ process.stdout.write('\u001b[?25h'); }, deleteLine: function(){ process.stdout.write('\u001b[2K'); }, beginningOfLine: function(){ process.stdout.write('\u001b[0G'); }, CR: function(){ exports.cursor.deleteLine(); exports.cursor.beginningOfLine(); } }; /** * Output the given `failures` as a list. * * @param {Array} failures * @api public */ exports.list = function(failures){ console.error(); failures.forEach(function(test, i){ // format var fmt = color('error title', ' %s) %s:\n') + color('error message', ' %s') + color('error stack', '\n%s\n'); // msg var err = test.err , message = err.message || '' , stack = err.stack || message , index = stack.indexOf(message) + message.length , msg = stack.slice(0, index) , actual = err.actual , expected = err.expected , escape = true; // explicitly show diff if (err.showDiff) { escape = false; err.actual = actual = JSON.stringify(actual, null, 2); err.expected = expected = JSON.stringify(expected, null, 2); } // actual / expected diff if ('string' == typeof actual && 'string' == typeof expected) { var len = Math.max(actual.length, expected.length); if (len < 20) msg = errorDiff(err, 'Chars', escape); else msg = errorDiff(err, 'Words', escape); // linenos var lines = msg.split('\n'); if (lines.length > 4) { var width = String(lines.length).length; msg = lines.map(function(str, i){ return pad(++i, width) + ' |' + ' ' + str; }).join('\n'); } // legend msg = '\n' + color('diff removed', 'actual') + ' ' + color('diff added', 'expected') + '\n\n' + msg + '\n'; // indent msg = msg.replace(/^/gm, ' '); fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); } // indent stack trace without msg stack = stack.slice(index ? index + 1 : index) .replace(/^/gm, ' '); console.error(fmt, (i + 1), test.fullTitle(), msg, stack); }); }; /** * Initialize a new `Base` reporter. * * All other reporters generally * inherit from this reporter, providing * stats such as test duration, number * of tests passed / failed etc. * * @param {Runner} runner * @api public */ function Base(runner) { var self = this , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } , failures = this.failures = []; if (!runner) return; this.runner = runner; runner.on('start', function(){ stats.start = new Date; }); runner.on('suite', function(suite){ stats.suites = stats.suites || 0; suite.root || stats.suites++; }); runner.on('test end', function(test){ stats.tests = stats.tests || 0; stats.tests++; }); runner.on('pass', function(test){ stats.passes = stats.passes || 0; var medium = test.slow() / 2; test.speed = test.duration > test.slow() ? 'slow' : test.duration > medium ? 'medium' : 'fast'; stats.passes++; }); runner.on('fail', function(test, err){ stats.failures = stats.failures || 0; stats.failures++; test.err = err; failures.push(test); }); runner.on('end', function(){ stats.end = new Date; stats.duration = new Date - stats.start; }); runner.on('pending', function(){ stats.pending++; }); } /** * Output common epilogue used by many of * the bundled reporters. * * @api public */ Base.prototype.epilogue = function(){ var stats = this.stats , fmt , tests; console.log(); function pluralize(n) { return 1 == n ? 'test' : 'tests'; } // failure if (stats.failures) { fmt = color('bright fail', ' ✖') + color('fail', ' %d of %d %s failed') + color('light', ':') console.error(fmt, stats.failures, this.runner.total, pluralize(this.runner.total)); Base.list(this.failures); console.error(); return; } // pass fmt = color('bright pass', ' ✔') + color('green', ' %d %s complete') + color('light', ' (%s)'); console.log(fmt, stats.tests || 0, pluralize(stats.tests), ms(stats.duration)); // pending if (stats.pending) { fmt = color('pending', ' •') + color('pending', ' %d %s pending'); console.log(fmt, stats.pending, pluralize(stats.pending)); } console.log(); }; /** * Pad the given `str` to `len`. * * @param {String} str * @param {String} len * @return {String} * @api private */ function pad(str, len) { str = String(str); return Array(len - str.length + 1).join(' ') + str; } /** * Return a character diff for `err`. * * @param {Error} err * @return {String} * @api private */ function errorDiff(err, type, escape) { return diff['diff' + type](err.actual, err.expected).map(function(str){ if (escape) { str.value = str.value .replace(/\t/g, '') .replace(/\r/g, '') .replace(/\n/g, '\n'); } if (str.added) return colorLines('diff added', str.value); if (str.removed) return colorLines('diff removed', str.value); return str.value; }).join(''); } /** * Color lines for `str`, using the color `name`. * * @param {String} name * @param {String} str * @return {String} * @api private */ function colorLines(name, str) { return str.split('\n').map(function(str){ return color(name, str); }).join('\n'); } }); // module: reporters/base.js require.register("reporters/doc.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = Doc; /** * Initialize a new `Doc` reporter. * * @param {Runner} runner * @api public */ function Doc(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , indents = 2; function indent() { return Array(indents).join(' '); } runner.on('suite', function(suite){ if (suite.root) return; ++indents; console.log('%s
', indent()); ++indents; console.log('%s

%s

', indent(), suite.title); console.log('%s
', indent()); }); runner.on('suite end', function(suite){ if (suite.root) return; console.log('%s
', indent()); --indents; console.log('%s
', indent()); --indents; }); runner.on('pass', function(test){ console.log('%s
%s
', indent(), test.title); var code = utils.escape(utils.clean(test.fn.toString())); console.log('%s
%s
', indent(), code); }); } }); // module: reporters/doc.js require.register("reporters/dot.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `Dot`. */ exports = module.exports = Dot; /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ function Dot(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , c = '․' , n = 0; runner.on('start', function(){ process.stdout.write('\n '); }); runner.on('pending', function(test){ process.stdout.write(color('pending', c)); }); runner.on('pass', function(test){ if (++n % width == 0) process.stdout.write('\n '); if ('slow' == test.speed) { process.stdout.write(color('bright yellow', c)); } else { process.stdout.write(color(test.speed, c)); } }); runner.on('fail', function(test, err){ if (++n % width == 0) process.stdout.write('\n '); process.stdout.write(color('fail', c)); }); runner.on('end', function(){ console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ Dot.prototype = new Base; Dot.prototype.constructor = Dot; }); // module: reporters/dot.js require.register("reporters/html-cov.js", function(module, exports, require){ /** * Module dependencies. */ var JSONCov = require('./json-cov') , fs = require('browser/fs'); /** * Expose `HTMLCov`. */ exports = module.exports = HTMLCov; /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner * @api public */ function HTMLCov(runner) { var jade = require('jade') , file = __dirname + '/templates/coverage.jade' , str = fs.readFileSync(file, 'utf8') , fn = jade.compile(str, { filename: file }) , self = this; JSONCov.call(this, runner, false); runner.on('end', function(){ process.stdout.write(fn({ cov: self.cov , coverageClass: coverageClass })); }); } /** * Return coverage class for `n`. * * @return {String} * @api private */ function coverageClass(n) { if (n >= 75) return 'high'; if (n >= 50) return 'medium'; if (n >= 25) return 'low'; return 'terrible'; } }); // module: reporters/html-cov.js require.register("reporters/html.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils') , Progress = require('../browser/progress') , escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `Doc`. */ exports = module.exports = HTML; /** * Stats template. */ var statsTemplate = '
'; /** * Initialize a new `Doc` reporter. * * @param {Runner} runner * @api public */ function HTML(runner, root) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , stat = fragment(statsTemplate) , items = stat.getElementsByTagName('li') , passes = items[1].getElementsByTagName('em')[0] , passesLink = items[1].getElementsByTagName('a')[0] , failures = items[2].getElementsByTagName('em')[0] , failuresLink = items[2].getElementsByTagName('a')[0] , duration = items[3].getElementsByTagName('em')[0] , canvas = stat.getElementsByTagName('canvas')[0] , report = fragment('') , stack = [report] , progress , ctx root = root || document.getElementById('mocha'); if (canvas.getContext) { var ratio = window.devicePixelRatio || 1; canvas.style.width = canvas.width; canvas.style.height = canvas.height; canvas.width *= ratio; canvas.height *= ratio; ctx = canvas.getContext('2d'); ctx.scale(ratio, ratio); progress = new Progress; } if (!root) return error('#mocha div missing, add it to your document'); // pass toggle on(passesLink, 'click', function(){ unhide(); var name = /pass/.test(report.className) ? '' : ' pass'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) hideSuitesWithout('test pass'); }); // failure toggle on(failuresLink, 'click', function(){ unhide(); var name = /fail/.test(report.className) ? '' : ' fail'; report.className = report.className.replace(/fail|pass/g, '') + name; if (report.className.trim()) hideSuitesWithout('test fail'); }); root.appendChild(stat); root.appendChild(report); if (progress) progress.size(40); runner.on('suite', function(suite){ if (suite.root) return; // suite var url = '?grep=' + encodeURIComponent(suite.fullTitle()); var el = fragment('
  • %s

  • ', url, escape(suite.title)); // container stack[0].appendChild(el); stack.unshift(document.createElement('ul')); el.appendChild(stack[0]); }); runner.on('suite end', function(suite){ if (suite.root) return; stack.shift(); }); runner.on('fail', function(test, err){ if ('hook' == test.type || err.uncaught) runner.emit('test end', test); }); runner.on('test end', function(test){ window.scrollTo(0, document.body.scrollHeight); // TODO: add to stats var percent = stats.tests / total * 100 | 0; if (progress) progress.update(percent).draw(ctx); // update stats var ms = new Date - stats.start; text(passes, stats.passes); text(failures, stats.failures); text(duration, (ms / 1000).toFixed(2)); // test if ('passed' == test.state) { var el = fragment('
  • %e%ems

  • ', test.speed, test.title, test.duration); } else if (test.pending) { var el = fragment('
  • %e

  • ', test.title); } else { var el = fragment('
  • %e

  • ', test.title); var str = test.err.stack || test.err.toString(); // FF / Opera do not add the message if (!~str.indexOf(test.err.message)) { str = test.err.message + '\n' + str; } // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we // check for the result of the stringifying. if ('[object Error]' == str) str = test.err.message; // Safari doesn't give you a stack. Let's at least provide a source line. if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; } el.appendChild(fragment('
    %e
    ', str)); } // toggle code // TODO: defer if (!test.pending) { var h2 = el.getElementsByTagName('h2')[0]; on(h2, 'click', function(){ pre.style.display = 'none' == pre.style.display ? 'inline-block' : 'none'; }); var pre = fragment('
    %e
    ', utils.clean(test.fn.toString())); el.appendChild(pre); pre.style.display = 'none'; } stack[0].appendChild(el); }); } /** * Display error `msg`. */ function error(msg) { document.body.appendChild(fragment('
    %s
    ', msg)); } /** * Return a DOM fragment from `html`. */ function fragment(html) { var args = arguments , div = document.createElement('div') , i = 1; div.innerHTML = html.replace(/%([se])/g, function(_, type){ switch (type) { case 's': return String(args[i++]); case 'e': return escape(args[i++]); } }); return div.firstChild; } /** * Check for suites that do not have elements * with `classname`, and hide them. */ function hideSuitesWithout(classname) { var suites = document.getElementsByClassName('suite'); for (var i = 0; i < suites.length; i++) { var els = suites[i].getElementsByClassName(classname); if (0 == els.length) suites[i].className += ' hidden'; } } /** * Unhide .hidden suites. */ function unhide() { var els = document.getElementsByClassName('suite hidden'); for (var i = 0; i < els.length; ++i) { els[i].className = els[i].className.replace('suite hidden', 'suite'); } } /** * Set `el` text to `str`. */ function text(el, str) { if (el.textContent) { el.textContent = str; } else { el.innerText = str; } } /** * Listen on `event` with callback `fn`. */ function on(el, event, fn) { if (el.addEventListener) { el.addEventListener(event, fn, false); } else { el.attachEvent('on' + event, fn); } } }); // module: reporters/html.js require.register("reporters/index.js", function(module, exports, require){ exports.Base = require('./base'); exports.Dot = require('./dot'); exports.Doc = require('./doc'); exports.TAP = require('./tap'); exports.JSON = require('./json'); exports.HTML = require('./html'); exports.List = require('./list'); exports.Min = require('./min'); exports.Spec = require('./spec'); exports.Nyan = require('./nyan'); exports.XUnit = require('./xunit'); exports.Markdown = require('./markdown'); exports.Progress = require('./progress'); exports.Landing = require('./landing'); exports.JSONCov = require('./json-cov'); exports.HTMLCov = require('./html-cov'); exports.JSONStream = require('./json-stream'); exports.Teamcity = require('./teamcity'); }); // module: reporters/index.js require.register("reporters/json-cov.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `JSONCov`. */ exports = module.exports = JSONCov; /** * Initialize a new `JsCoverage` reporter. * * @param {Runner} runner * @param {Boolean} output * @api public */ function JSONCov(runner, output) { var self = this , output = 1 == arguments.length ? true : output; Base.call(this, runner); var tests = [] , failures = [] , passes = []; runner.on('test end', function(test){ tests.push(test); }); runner.on('pass', function(test){ passes.push(test); }); runner.on('fail', function(test){ failures.push(test); }); runner.on('end', function(){ var cov = global._$jscoverage || {}; var result = self.cov = map(cov); result.stats = self.stats; result.tests = tests.map(clean); result.failures = failures.map(clean); result.passes = passes.map(clean); if (!output) return; process.stdout.write(JSON.stringify(result, null, 2 )); }); } /** * Map jscoverage data to a JSON structure * suitable for reporting. * * @param {Object} cov * @return {Object} * @api private */ function map(cov) { var ret = { instrumentation: 'node-jscoverage' , sloc: 0 , hits: 0 , misses: 0 , coverage: 0 , files: [] }; for (var filename in cov) { var data = coverage(filename, cov[filename]); ret.files.push(data); ret.hits += data.hits; ret.misses += data.misses; ret.sloc += data.sloc; } if (ret.sloc > 0) { ret.coverage = (ret.hits / ret.sloc) * 100; } return ret; }; /** * Map jscoverage data for a single source file * to a JSON structure suitable for reporting. * * @param {String} filename name of the source file * @param {Object} data jscoverage coverage data * @return {Object} * @api private */ function coverage(filename, data) { var ret = { filename: filename, coverage: 0, hits: 0, misses: 0, sloc: 0, source: {} }; data.source.forEach(function(line, num){ num++; if (data[num] === 0) { ret.misses++; ret.sloc++; } else if (data[num] !== undefined) { ret.hits++; ret.sloc++; } ret.source[num] = { source: line , coverage: data[num] === undefined ? '' : data[num] }; }); ret.coverage = ret.hits / ret.sloc * 100; return ret; } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json-cov.js require.register("reporters/json-stream.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `List`. */ exports = module.exports = List; /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ function List(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total; runner.on('start', function(){ console.log(JSON.stringify(['start', { total: total }])); }); runner.on('pass', function(test){ console.log(JSON.stringify(['pass', clean(test)])); }); runner.on('fail', function(test, err){ console.log(JSON.stringify(['fail', clean(test)])); }); runner.on('end', function(){ process.stdout.write(JSON.stringify(['end', self.stats])); }); } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json-stream.js require.register("reporters/json.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `JSON`. */ exports = module.exports = JSONReporter; /** * Initialize a new `JSON` reporter. * * @param {Runner} runner * @api public */ function JSONReporter(runner) { var self = this; Base.call(this, runner); var tests = [] , failures = [] , passes = []; runner.on('test end', function(test){ tests.push(test); }); runner.on('pass', function(test){ passes.push(test); }); runner.on('fail', function(test){ failures.push(test); }); runner.on('end', function(){ var obj = { stats: self.stats , tests: tests.map(clean) , failures: failures.map(clean) , passes: passes.map(clean) }; process.stdout.write(JSON.stringify(obj, null, 2)); }); } /** * Return a plain-object representation of `test` * free of cyclic properties etc. * * @param {Object} test * @return {Object} * @api private */ function clean(test) { return { title: test.title , fullTitle: test.fullTitle() , duration: test.duration } } }); // module: reporters/json.js require.register("reporters/landing.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Landing`. */ exports = module.exports = Landing; /** * Airplane color. */ Base.colors.plane = 0; /** * Airplane crash color. */ Base.colors['plane crash'] = 31; /** * Runway color. */ Base.colors.runway = 90; /** * Initialize a new `Landing` reporter. * * @param {Runner} runner * @api public */ function Landing(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , total = runner.total , stream = process.stdout , plane = color('plane', '✈') , crashed = -1 , n = 0; function runway() { var buf = Array(width).join('-'); return ' ' + color('runway', buf); } runner.on('start', function(){ stream.write('\n '); cursor.hide(); }); runner.on('test end', function(test){ // check if the plane crashed var col = -1 == crashed ? width * ++n / total | 0 : crashed; // show the crash if ('failed' == test.state) { plane = color('plane crash', '✈'); crashed = col; } // render landing strip stream.write('\u001b[4F\n\n'); stream.write(runway()); stream.write('\n '); stream.write(color('runway', Array(col).join('⋅'))); stream.write(plane) stream.write(color('runway', Array(width - col).join('⋅') + '\n')); stream.write(runway()); stream.write('\u001b[0m'); }); runner.on('end', function(){ cursor.show(); console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ Landing.prototype = new Base; Landing.prototype.constructor = Landing; }); // module: reporters/landing.js require.register("reporters/list.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `List`. */ exports = module.exports = List; /** * Initialize a new `List` test reporter. * * @param {Runner} runner * @api public */ function List(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 0; runner.on('start', function(){ console.log(); }); runner.on('test', function(test){ process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); runner.on('pending', function(test){ var fmt = color('checkmark', ' -') + color('pending', ' %s'); console.log(fmt, test.fullTitle()); }); runner.on('pass', function(test){ var fmt = color('checkmark', ' ✓') + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); runner.on('fail', function(test, err){ cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); runner.on('end', self.epilogue.bind(self)); } /** * Inherit from `Base.prototype`. */ List.prototype = new Base; List.prototype.constructor = List; }); // module: reporters/list.js require.register("reporters/markdown.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Markdown`. */ exports = module.exports = Markdown; /** * Initialize a new `Markdown` reporter. * * @param {Runner} runner * @api public */ function Markdown(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , level = 0 , buf = ''; function title(str) { return Array(level).join('#') + ' ' + str; } function indent() { return Array(level).join(' '); } function mapTOC(suite, obj) { var ret = obj; obj = obj[suite.title] = obj[suite.title] || { suite: suite }; suite.suites.forEach(function(suite){ mapTOC(suite, obj); }); return ret; } function stringifyTOC(obj, level) { ++level; var buf = ''; var link; for (var key in obj) { if ('suite' == key) continue; if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; if (key) buf += Array(level).join(' ') + link; buf += stringifyTOC(obj[key], level); } --level; return buf; } function generateTOC(suite) { var obj = mapTOC(suite, {}); return stringifyTOC(obj, 0); } generateTOC(runner.suite); runner.on('suite', function(suite){ ++level; var slug = utils.slug(suite.fullTitle()); buf += '' + '\n'; buf += title(suite.title) + '\n'; }); runner.on('suite end', function(suite){ --level; }); runner.on('pass', function(test){ var code = utils.clean(test.fn.toString()); buf += test.title + '.\n'; buf += '\n```js\n'; buf += code + '\n'; buf += '```\n\n'; }); runner.on('end', function(){ process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); }); } }); // module: reporters/markdown.js require.register("reporters/min.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `Min`. */ exports = module.exports = Min; /** * Initialize a new `Min` minimal test reporter (best used with --watch). * * @param {Runner} runner * @api public */ function Min(runner) { Base.call(this, runner); runner.on('start', function(){ // clear screen process.stdout.write('\u001b[2J'); // set cursor position process.stdout.write('\u001b[1;3H'); }); runner.on('end', this.epilogue.bind(this)); } /** * Inherit from `Base.prototype`. */ Min.prototype = new Base; Min.prototype.constructor = Min; }); // module: reporters/min.js require.register("reporters/nyan.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , color = Base.color; /** * Expose `Dot`. */ exports = module.exports = NyanCat; /** * Initialize a new `Dot` matrix test reporter. * * @param {Runner} runner * @api public */ function NyanCat(runner) { Base.call(this, runner); var self = this , stats = this.stats , width = Base.window.width * .75 | 0 , rainbowColors = this.rainbowColors = self.generateColors() , colorIndex = this.colorIndex = 0 , numberOfLines = this.numberOfLines = 4 , trajectories = this.trajectories = [[], [], [], []] , nyanCatWidth = this.nyanCatWidth = 11 , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) , scoreboardWidth = this.scoreboardWidth = 5 , tick = this.tick = 0 , n = 0; runner.on('start', function(){ Base.cursor.hide(); self.draw('start'); }); runner.on('pending', function(test){ self.draw('pending'); }); runner.on('pass', function(test){ self.draw('pass'); }); runner.on('fail', function(test, err){ self.draw('fail'); }); runner.on('end', function(){ Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) write('\n'); self.epilogue(); }); } /** * Draw the nyan cat with runner `status`. * * @param {String} status * @api private */ NyanCat.prototype.draw = function(status){ this.appendRainbow(); this.drawScoreboard(); this.drawRainbow(); this.drawNyanCat(status); this.tick = !this.tick; }; /** * Draw the "scoreboard" showing the number * of passes, failures and pending tests. * * @api private */ NyanCat.prototype.drawScoreboard = function(){ var stats = this.stats; var colors = Base.colors; function draw(color, n) { write(' '); write('\u001b[' + color + 'm' + n + '\u001b[0m'); write('\n'); } draw(colors.green, stats.passes); draw(colors.fail, stats.failures); draw(colors.pending, stats.pending); write('\n'); this.cursorUp(this.numberOfLines); }; /** * Append the rainbow. * * @api private */ NyanCat.prototype.appendRainbow = function(){ var segment = this.tick ? '_' : '-'; var rainbowified = this.rainbowify(segment); for (var index = 0; index < this.numberOfLines; index++) { var trajectory = this.trajectories[index]; if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); trajectory.push(rainbowified); } }; /** * Draw the rainbow. * * @api private */ NyanCat.prototype.drawRainbow = function(){ var self = this; this.trajectories.forEach(function(line, index) { write('\u001b[' + self.scoreboardWidth + 'C'); write(line.join('')); write('\n'); }); this.cursorUp(this.numberOfLines); }; /** * Draw the nyan cat with `status`. * * @param {String} status * @api private */ NyanCat.prototype.drawNyanCat = function(status) { var self = this; var startWidth = this.scoreboardWidth + this.trajectories[0].length; [0, 1, 2, 3].forEach(function(index) { write('\u001b[' + startWidth + 'C'); switch (index) { case 0: write('_,------,'); write('\n'); break; case 1: var padding = self.tick ? ' ' : ' '; write('_|' + padding + '/\\_/\\ '); write('\n'); break; case 2: var padding = self.tick ? '_' : '__'; var tail = self.tick ? '~' : '^'; var face; switch (status) { case 'pass': face = '( ^ .^)'; break; case 'fail': face = '( o .o)'; break; default: face = '( - .-)'; } write(tail + '|' + padding + face + ' '); write('\n'); break; case 3: var padding = self.tick ? ' ' : ' '; write(padding + '"" "" '); write('\n'); break; } }); this.cursorUp(this.numberOfLines); }; /** * Move cursor up `n`. * * @param {Number} n * @api private */ NyanCat.prototype.cursorUp = function(n) { write('\u001b[' + n + 'A'); }; /** * Move cursor down `n`. * * @param {Number} n * @api private */ NyanCat.prototype.cursorDown = function(n) { write('\u001b[' + n + 'B'); }; /** * Generate rainbow colors. * * @return {Array} * @api private */ NyanCat.prototype.generateColors = function(){ var colors = []; for (var i = 0; i < (6 * 7); i++) { var pi3 = Math.floor(Math.PI / 3); var n = (i * (1.0 / 6)); var r = Math.floor(3 * Math.sin(n) + 3); var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); colors.push(36 * r + 6 * g + b + 16); } return colors; }; /** * Apply rainbow to the given `str`. * * @param {String} str * @return {String} * @api private */ NyanCat.prototype.rainbowify = function(str){ var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; this.colorIndex += 1; return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; }; /** * Stdout helper. */ function write(string) { process.stdout.write(string); } /** * Inherit from `Base.prototype`. */ NyanCat.prototype = new Base; NyanCat.prototype.constructor = NyanCat; }); // module: reporters/nyan.js require.register("reporters/progress.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Progress`. */ exports = module.exports = Progress; /** * General progress bar color. */ Base.colors.progress = 90; /** * Initialize a new `Progress` bar test reporter. * * @param {Runner} runner * @param {Object} options * @api public */ function Progress(runner, options) { Base.call(this, runner); var self = this , options = options || {} , stats = this.stats , width = Base.window.width * .50 | 0 , total = runner.total , complete = 0 , max = Math.max; // default chars options.open = options.open || '['; options.complete = options.complete || '▬'; options.incomplete = options.incomplete || '⋅'; options.close = options.close || ']'; options.verbose = false; // tests started runner.on('start', function(){ console.log(); cursor.hide(); }); // tests complete runner.on('test end', function(){ complete++; var incomplete = total - complete , percent = complete / total , n = width * percent | 0 , i = width - n; cursor.CR(); process.stdout.write('\u001b[J'); process.stdout.write(color('progress', ' ' + options.open)); process.stdout.write(Array(n).join(options.complete)); process.stdout.write(Array(i).join(options.incomplete)); process.stdout.write(color('progress', options.close)); if (options.verbose) { process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); } }); // tests are complete, output some stats // and the failures if any runner.on('end', function(){ cursor.show(); console.log(); self.epilogue(); }); } /** * Inherit from `Base.prototype`. */ Progress.prototype = new Base; Progress.prototype.constructor = Progress; }); // module: reporters/progress.js require.register("reporters/spec.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `Spec`. */ exports = module.exports = Spec; /** * Initialize a new `Spec` test reporter. * * @param {Runner} runner * @api public */ function Spec(runner) { Base.call(this, runner); var self = this , stats = this.stats , indents = 0 , n = 0; function indent() { return Array(indents).join(' ') } runner.on('start', function(){ console.log(); }); runner.on('suite', function(suite){ ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); runner.on('suite end', function(suite){ --indents; if (1 == indents) console.log(); }); runner.on('test', function(test){ process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': ')); }); runner.on('pending', function(test){ var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); runner.on('pass', function(test){ if ('fast' == test.speed) { var fmt = indent() + color('checkmark', ' ✓') + color('pass', ' %s '); cursor.CR(); console.log(fmt, test.title); } else { var fmt = indent() + color('checkmark', ' ✓') + color('pass', ' %s ') + color(test.speed, '(%dms)'); cursor.CR(); console.log(fmt, test.title, test.duration); } }); runner.on('fail', function(test, err){ cursor.CR(); console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); runner.on('end', self.epilogue.bind(self)); } /** * Inherit from `Base.prototype`. */ Spec.prototype = new Base; Spec.prototype.constructor = Spec; }); // module: reporters/spec.js require.register("reporters/tap.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `TAP`. */ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , n = 1; runner.on('start', function(){ var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pending', function(test){ console.log('ok %d %s # SKIP -', n, title(test)); }); runner.on('pass', function(test){ console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ console.log('not ok %d %s', n, title(test)); console.log(err.stack.replace(/^/gm, ' ')); }); } /** * Return a TAP-safe title of `test` * * @param {Object} test * @return {String} * @api private */ function title(test) { return test.fullTitle().replace(/#/g, ''); } }); // module: reporters/tap.js require.register("reporters/teamcity.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base'); /** * Expose `Teamcity`. */ exports = module.exports = Teamcity; /** * Initialize a new `Teamcity` reporter. * * @param {Runner} runner * @api public */ function Teamcity(runner) { Base.call(this, runner); var stats = this.stats; runner.on('start', function() { console.log("##teamcity[testSuiteStarted name='mocha.suite']"); }); runner.on('test', function(test) { console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); }); runner.on('fail', function(test, err) { console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); }); runner.on('pending', function(test) { console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); }); runner.on('test end', function(test) { console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); }); runner.on('end', function() { console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); }); } /** * Escape the given `str`. */ function escape(str) { return str .replace(/\|/g, "||") .replace(/\n/g, "|n") .replace(/\r/g, "|r") .replace(/\[/g, "|[") .replace(/\]/g, "|]") .replace(/\u0085/g, "|x") .replace(/\u2028/g, "|l") .replace(/\u2029/g, "|p") .replace(/'/g, "|'"); } }); // module: reporters/teamcity.js require.register("reporters/xunit.js", function(module, exports, require){ /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils') , escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `XUnit`. */ exports = module.exports = XUnit; /** * Initialize a new `XUnit` reporter. * * @param {Runner} runner * @api public */ function XUnit(runner) { Base.call(this, runner); var stats = this.stats , tests = [] , self = this; runner.on('pass', function(test){ tests.push(test); }); runner.on('fail', function(test){ tests.push(test); }); runner.on('end', function(){ console.log(tag('testsuite', { name: 'Mocha Tests' , tests: stats.tests , failures: stats.failures , errors: stats.failures , skip: stats.tests - stats.failures - stats.passes , timestamp: (new Date).toUTCString() , time: stats.duration / 1000 }, false)); tests.forEach(test); console.log(''); }); } /** * Inherit from `Base.prototype`. */ XUnit.prototype = new Base; XUnit.prototype.constructor = XUnit; /** * Output tag for the given `test.` */ function test(test) { var attrs = { classname: test.parent.fullTitle() , name: test.title , time: test.duration / 1000 }; if ('failed' == test.state) { var err = test.err; attrs.message = escape(err.message); console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); } else if (test.pending) { console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); } else { console.log(tag('testcase', attrs, true) ); } } /** * HTML tag helper. */ function tag(name, attrs, close, content) { var end = close ? '/>' : '>' , pairs = [] , tag; for (var key in attrs) { pairs.push(key + '="' + escape(attrs[key]) + '"'); } tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; if (content) tag += content + ''; } }); // module: reporters/xunit.js require.register("runnable.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:runnable'); /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `Runnable`. */ module.exports = Runnable; /** * Initialize a new `Runnable` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Runnable(title, fn) { this.title = title; this.fn = fn; this.async = fn && fn.length; this.sync = ! this.async; this._timeout = 2000; this._slow = 75; this.timedOut = false; } /** * Inherit from `EventEmitter.prototype`. */ Runnable.prototype = new EventEmitter; Runnable.prototype.constructor = Runnable; /** * Set & get timeout `ms`. * * @param {Number} ms * @return {Runnable|Number} ms or self * @api private */ Runnable.prototype.timeout = function(ms){ if (0 == arguments.length) return this._timeout; debug('timeout %d', ms); this._timeout = ms; if (this.timer) this.resetTimeout(); return this; }; /** * Set & get slow `ms`. * * @param {Number} ms * @return {Runnable|Number} ms or self * @api private */ Runnable.prototype.slow = function(ms){ if (0 === arguments.length) return this._slow; debug('timeout %d', ms); this._slow = ms; return this; }; /** * Return the full title generated by recursively * concatenating the parent's full title. * * @return {String} * @api public */ Runnable.prototype.fullTitle = function(){ return this.parent.fullTitle() + ' ' + this.title; }; /** * Clear the timeout. * * @api private */ Runnable.prototype.clearTimeout = function(){ clearTimeout(this.timer); }; /** * Inspect the runnable void of private properties. * * @return {String} * @api private */ Runnable.prototype.inspect = function(){ return JSON.stringify(this, function(key, val){ if ('_' == key[0]) return; if ('parent' == key) return '#'; if ('ctx' == key) return '#'; return val; }, 2); }; /** * Reset the timeout. * * @api private */ Runnable.prototype.resetTimeout = function(){ var self = this , ms = this.timeout(); this.clearTimeout(); if (ms) { this.timer = setTimeout(function(){ self.callback(new Error('timeout of ' + ms + 'ms exceeded')); self.timedOut = true; }, ms); } }; /** * Run the test and invoke `fn(err)`. * * @param {Function} fn * @api private */ Runnable.prototype.run = function(fn){ var self = this , ms = this.timeout() , start = new Date , ctx = this.ctx , finished , emitted; if (ctx) ctx.runnable(this); // timeout if (this.async) { if (ms) { this.timer = setTimeout(function(){ done(new Error('timeout of ' + ms + 'ms exceeded')); self.timedOut = true; }, ms); } } // called multiple times function multiple(err) { if (emitted) return; emitted = true; self.emit('error', err || new Error('done() called multiple times')); } // finished function done(err) { if (self.timedOut) return; if (finished) return multiple(err); self.clearTimeout(); self.duration = new Date - start; finished = true; fn(err); } // for .resetTimeout() this.callback = done; // async if (this.async) { try { this.fn.call(ctx, function(err){ if (err instanceof Error) return done(err); if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); done(); }); } catch (err) { done(err); } return; } // sync try { if (!this.pending) this.fn.call(ctx); this.duration = new Date - start; fn(); } catch (err) { fn(err); } }; }); // module: runnable.js require.register("runner.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:runner') , Test = require('./test') , utils = require('./utils') , filter = utils.filter , keys = utils.keys , noop = function(){}; /** * Expose `Runner`. */ module.exports = Runner; /** * Initialize a `Runner` for the given `suite`. * * Events: * * - `start` execution started * - `end` execution complete * - `suite` (suite) test suite execution started * - `suite end` (suite) all tests (and sub-suites) have finished * - `test` (test) test execution started * - `test end` (test) test completed * - `hook` (hook) hook execution started * - `hook end` (hook) hook complete * - `pass` (test) test passed * - `fail` (test, err) test failed * * @api public */ function Runner(suite) { var self = this; this._globals = []; this.suite = suite; this.total = suite.total(); this.failures = 0; this.on('test end', function(test){ self.checkGlobals(test); }); this.on('hook end', function(hook){ self.checkGlobals(hook); }); this.grep(/.*/); this.globals(utils.keys(global).concat(['errno'])); } /** * Inherit from `EventEmitter.prototype`. */ Runner.prototype = new EventEmitter; Runner.prototype.constructor = Runner; /** * Run tests with full titles matching `re`. Updates runner.total * with number of tests matched. * * @param {RegExp} re * @param {Boolean} invert * @return {Runner} for chaining * @api public */ Runner.prototype.grep = function(re, invert){ debug('grep %s', re); this._grep = re; this._invert = invert; this.total = this.grepTotal(this.suite); return this; }; /** * Returns the number of tests matching the grep search for the * given suite. * * @param {Suite} suite * @return {Number} * @api public */ Runner.prototype.grepTotal = function(suite) { var self = this; var total = 0; suite.eachTest(function(test){ var match = self._grep.test(test.fullTitle()); if (self._invert) match = !match; if (match) total++; }); return total; }; /** * Allow the given `arr` of globals. * * @param {Array} arr * @return {Runner} for chaining * @api public */ Runner.prototype.globals = function(arr){ if (0 == arguments.length) return this._globals; debug('globals %j', arr); utils.forEach(arr, function(arr){ this._globals.push(arr); }, this); return this; }; /** * Check for global variable leaks. * * @api private */ Runner.prototype.checkGlobals = function(test){ if (this.ignoreLeaks) return; var ok = this._globals; var globals = keys(global); var isNode = process.kill; var leaks; // check length - 2 ('errno' and 'location' globals) if (isNode && 1 == ok.length - globals.length) return else if (2 == ok.length - globals.length) return; leaks = filterLeaks(ok, globals); this._globals = this._globals.concat(leaks); if (leaks.length > 1) { this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); } else if (leaks.length) { this.fail(test, new Error('global leak detected: ' + leaks[0])); } }; /** * Fail the given `test`. * * @param {Test} test * @param {Error} err * @api private */ Runner.prototype.fail = function(test, err){ ++this.failures; test.state = 'failed'; if ('string' == typeof err) { err = new Error('the string "' + err + '" was thrown, throw an Error :)'); } this.emit('fail', test, err); }; /** * Fail the given `hook` with `err`. * * Hook failures (currently) hard-end due * to that fact that a failing hook will * surely cause subsequent tests to fail, * causing jumbled reporting. * * @param {Hook} hook * @param {Error} err * @api private */ Runner.prototype.failHook = function(hook, err){ this.fail(hook, err); this.emit('end'); }; /** * Run hook `name` callbacks and then invoke `fn()`. * * @param {String} name * @param {Function} function * @api private */ Runner.prototype.hook = function(name, fn){ var suite = this.suite , hooks = suite['_' + name] , self = this , timer; function next(i) { var hook = hooks[i]; if (!hook) return fn(); self.currentRunnable = hook; self.emit('hook', hook); hook.on('error', function(err){ self.failHook(hook, err); }); hook.run(function(err){ hook.removeAllListeners('error'); var testError = hook.error(); if (testError) self.fail(self.test, testError); if (err) return self.failHook(hook, err); self.emit('hook end', hook); next(++i); }); } process.nextTick(function(){ next(0); }); }; /** * Run hook `name` for the given array of `suites` * in order, and callback `fn(err)`. * * @param {String} name * @param {Array} suites * @param {Function} fn * @api private */ Runner.prototype.hooks = function(name, suites, fn){ var self = this , orig = this.suite; function next(suite) { self.suite = suite; if (!suite) { self.suite = orig; return fn(); } self.hook(name, function(err){ if (err) { self.suite = orig; return fn(err); } next(suites.pop()); }); } next(suites.pop()); }; /** * Run hooks from the top level down. * * @param {String} name * @param {Function} fn * @api private */ Runner.prototype.hookUp = function(name, fn){ var suites = [this.suite].concat(this.parents()).reverse(); this.hooks(name, suites, fn); }; /** * Run hooks from the bottom up. * * @param {String} name * @param {Function} fn * @api private */ Runner.prototype.hookDown = function(name, fn){ var suites = [this.suite].concat(this.parents()); this.hooks(name, suites, fn); }; /** * Return an array of parent Suites from * closest to furthest. * * @return {Array} * @api private */ Runner.prototype.parents = function(){ var suite = this.suite , suites = []; while (suite = suite.parent) suites.push(suite); return suites; }; /** * Run the current test and callback `fn(err)`. * * @param {Function} fn * @api private */ Runner.prototype.runTest = function(fn){ var test = this.test , self = this; try { test.on('error', function(err){ self.fail(test, err); }); test.run(fn); } catch (err) { fn(err); } }; /** * Run tests in the given `suite` and invoke * the callback `fn()` when complete. * * @param {Suite} suite * @param {Function} fn * @api private */ Runner.prototype.runTests = function(suite, fn){ var self = this , tests = suite.tests , test; function next(err) { // if we bail after first err if (self.failures && suite._bail) return fn(); // next test test = tests.shift(); // all done if (!test) return fn(); // grep var match = self._grep.test(test.fullTitle()); if (self._invert) match = !match; if (!match) return next(); // pending if (test.pending) { self.emit('pending', test); self.emit('test end', test); return next(); } // execute test and hook(s) self.emit('test', self.test = test); self.hookDown('beforeEach', function(){ self.currentRunnable = self.test; self.runTest(function(err){ test = self.test; if (err) { self.fail(test, err); self.emit('test end', test); return self.hookUp('afterEach', next); } test.state = 'passed'; self.emit('pass', test); self.emit('test end', test); self.hookUp('afterEach', next); }); }); } this.next = next; next(); }; /** * Run the given `suite` and invoke the * callback `fn()` when complete. * * @param {Suite} suite * @param {Function} fn * @api private */ Runner.prototype.runSuite = function(suite, fn){ var total = this.grepTotal(suite) , self = this , i = 0; debug('run suite %s', suite.fullTitle()); if (!total) return fn(); this.emit('suite', this.suite = suite); function next() { var curr = suite.suites[i++]; if (!curr) return done(); self.runSuite(curr, next); } function done() { self.suite = suite; self.hook('afterAll', function(){ self.emit('suite end', suite); fn(); }); } this.hook('beforeAll', function(){ self.runTests(suite, next); }); }; /** * Handle uncaught exceptions. * * @param {Error} err * @api private */ Runner.prototype.uncaught = function(err){ debug('uncaught exception %s', err.message); var runnable = this.currentRunnable; if (!runnable || 'failed' == runnable.state) return; runnable.clearTimeout(); err.uncaught = true; this.fail(runnable, err); // recover from test if ('test' == runnable.type) { this.emit('test end', runnable); this.hookUp('afterEach', this.next); return; } // bail on hooks this.emit('end'); }; /** * Run the root suite and invoke `fn(failures)` * on completion. * * @param {Function} fn * @return {Runner} for chaining * @api public */ Runner.prototype.run = function(fn){ var self = this , fn = fn || function(){}; debug('start'); // uncaught callback function uncaught(err) { self.uncaught(err); } // callback this.on('end', function(){ debug('end'); process.removeListener('uncaughtException', uncaught); fn(self.failures); }); // run suites this.emit('start'); this.runSuite(this.suite, function(){ debug('finished running'); self.emit('end'); }); // uncaught exception process.on('uncaughtException', uncaught); return this; }; /** * Filter leaks with the given globals flagged as `ok`. * * @param {Array} ok * @param {Array} globals * @return {Array} * @api private */ function filterLeaks(ok, globals) { return filter(globals, function(key){ var matched = filter(ok, function(ok){ if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); return key == ok; }); return matched.length == 0 && (!global.navigator || 'onerror' !== key); }); } }); // module: runner.js require.register("suite.js", function(module, exports, require){ /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:suite') , milliseconds = require('./ms') , utils = require('./utils') , Hook = require('./hook'); /** * Expose `Suite`. */ exports = module.exports = Suite; /** * Create a new `Suite` with the given `title` * and parent `Suite`. When a suite with the * same title is already present, that suite * is returned to provide nicer reporter * and more flexible meta-testing. * * @param {Suite} parent * @param {String} title * @return {Suite} * @api public */ exports.create = function(parent, title){ var suite = new Suite(title, parent.ctx); suite.parent = parent; if (parent.pending) suite.pending = true; title = suite.fullTitle(); parent.addSuite(suite); return suite; }; /** * Initialize a new `Suite` with the given * `title` and `ctx`. * * @param {String} title * @param {Context} ctx * @api private */ function Suite(title, ctx) { this.title = title; this.ctx = ctx; this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = !title; this._timeout = 2000; this._slow = 75; this._bail = false; } /** * Inherit from `EventEmitter.prototype`. */ Suite.prototype = new EventEmitter; Suite.prototype.constructor = Suite; /** * Return a clone of this `Suite`. * * @return {Suite} * @api private */ Suite.prototype.clone = function(){ var suite = new Suite(this.title); debug('clone'); suite.ctx = this.ctx; suite.timeout(this.timeout()); suite.slow(this.slow()); suite.bail(this.bail()); return suite; }; /** * Set timeout `ms` or short-hand such as "2s". * * @param {Number|String} ms * @return {Suite|Number} for chaining * @api private */ Suite.prototype.timeout = function(ms){ if (0 == arguments.length) return this._timeout; if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._timeout = parseInt(ms, 10); return this; }; /** * Set slow `ms` or short-hand such as "2s". * * @param {Number|String} ms * @return {Suite|Number} for chaining * @api private */ Suite.prototype.slow = function(ms){ if (0 === arguments.length) return this._slow; if ('string' == typeof ms) ms = milliseconds(ms); debug('slow %d', ms); this._slow = ms; return this; }; /** * Sets whether to bail after first error. * * @parma {Boolean} bail * @return {Suite|Number} for chaining * @api private */ Suite.prototype.bail = function(bail){ if (0 == arguments.length) return this._bail; debug('bail %s', bail); this._bail = bail; return this; }; /** * Run `fn(test[, done])` before running tests. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.beforeAll = function(fn){ if (this.pending) return this; var hook = new Hook('"before all" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeAll.push(hook); this.emit('beforeAll', hook); return this; }; /** * Run `fn(test[, done])` after running tests. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.afterAll = function(fn){ if (this.pending) return this; var hook = new Hook('"after all" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._afterAll.push(hook); this.emit('afterAll', hook); return this; }; /** * Run `fn(test[, done])` before each test case. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.beforeEach = function(fn){ if (this.pending) return this; var hook = new Hook('"before each" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeEach.push(hook); this.emit('beforeEach', hook); return this; }; /** * Run `fn(test[, done])` after each test case. * * @param {Function} fn * @return {Suite} for chaining * @api private */ Suite.prototype.afterEach = function(fn){ if (this.pending) return this; var hook = new Hook('"after each" hook', fn); hook.parent = this; hook.timeout(this.timeout()); hook.slow(this.slow()); hook.ctx = this.ctx; this._afterEach.push(hook); this.emit('afterEach', hook); return this; }; /** * Add a test `suite`. * * @param {Suite} suite * @return {Suite} for chaining * @api private */ Suite.prototype.addSuite = function(suite){ suite.parent = this; suite.timeout(this.timeout()); suite.slow(this.slow()); suite.bail(this.bail()); this.suites.push(suite); this.emit('suite', suite); return this; }; /** * Add a `test` to this suite. * * @param {Test} test * @return {Suite} for chaining * @api private */ Suite.prototype.addTest = function(test){ test.parent = this; test.timeout(this.timeout()); test.slow(this.slow()); test.ctx = this.ctx; this.tests.push(test); this.emit('test', test); return this; }; /** * Return the full title generated by recursively * concatenating the parent's full title. * * @return {String} * @api public */ Suite.prototype.fullTitle = function(){ if (this.parent) { var full = this.parent.fullTitle(); if (full) return full + ' ' + this.title; } return this.title; }; /** * Return the total number of tests. * * @return {Number} * @api public */ Suite.prototype.total = function(){ return utils.reduce(this.suites, function(sum, suite){ return sum + suite.total(); }, 0) + this.tests.length; }; /** * Iterates through each suite recursively to find * all tests. Applies a function in the format * `fn(test)`. * * @param {Function} fn * @return {Suite} * @api private */ Suite.prototype.eachTest = function(fn){ utils.forEach(this.tests, fn); utils.forEach(this.suites, function(suite){ suite.eachTest(fn); }); return this; }; }); // module: suite.js require.register("test.js", function(module, exports, require){ /** * Module dependencies. */ var Runnable = require('./runnable'); /** * Expose `Test`. */ module.exports = Test; /** * Initialize a new `Test` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Test(title, fn) { Runnable.call(this, title, fn); this.pending = !fn; this.type = 'test'; } /** * Inherit from `Runnable.prototype`. */ Test.prototype = new Runnable; Test.prototype.constructor = Test; }); // module: test.js require.register("utils.js", function(module, exports, require){ /** * Module dependencies. */ var fs = require('browser/fs') , path = require('browser/path') , join = path.join , debug = require('browser/debug')('mocha:watch'); /** * Ignored directories. */ var ignore = ['node_modules', '.git']; /** * Escape special characters in the given string of html. * * @param {String} html * @return {String} * @api private */ exports.escape = function(html){ return String(html) .replace(/&/g, '&') .replace(/"/g, '"') .replace(//g, '>'); }; /** * Array#forEach (<=IE8) * * @param {Array} array * @param {Function} fn * @param {Object} scope * @api private */ exports.forEach = function(arr, fn, scope){ for (var i = 0, l = arr.length; i < l; i++) fn.call(scope, arr[i], i); }; /** * Array#indexOf (<=IE8) * * @parma {Array} arr * @param {Object} obj to find index of * @param {Number} start * @api private */ exports.indexOf = function(arr, obj, start){ for (var i = start || 0, l = arr.length; i < l; i++) { if (arr[i] === obj) return i; } return -1; }; /** * Array#reduce (<=IE8) * * @param {Array} array * @param {Function} fn * @param {Object} initial value * @api private */ exports.reduce = function(arr, fn, val){ var rval = val; for (var i = 0, l = arr.length; i < l; i++) { rval = fn(rval, arr[i], i, arr); } return rval; }; /** * Array#filter (<=IE8) * * @param {Array} array * @param {Function} fn * @api private */ exports.filter = function(arr, fn){ var ret = []; for (var i = 0, l = arr.length; i < l; i++) { var val = arr[i]; if (fn(val, i, arr)) ret.push(val); } return ret; }; /** * Object.keys (<=IE8) * * @param {Object} obj * @return {Array} keys * @api private */ exports.keys = Object.keys || function(obj) { var keys = [] , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Watch the given `files` for changes * and invoke `fn(file)` on modification. * * @param {Array} files * @param {Function} fn * @api private */ exports.watch = function(files, fn){ var options = { interval: 100 }; files.forEach(function(file){ debug('file %s', file); fs.watchFile(file, options, function(curr, prev){ if (prev.mtime < curr.mtime) fn(file); }); }); }; /** * Ignored files. */ function ignored(path){ return !~ignore.indexOf(path); } /** * Lookup files in the given `dir`. * * @return {Array} * @api private */ exports.files = function(dir, ret){ ret = ret || []; fs.readdirSync(dir) .filter(ignored) .forEach(function(path){ path = join(dir, path); if (fs.statSync(path).isDirectory()) { exports.files(path, ret); } else if (path.match(/\.(js|coffee)$/)) { ret.push(path); } }); return ret; }; /** * Compute a slug from the given `str`. * * @param {String} str * @return {String} * @api private */ exports.slug = function(str){ return str .toLowerCase() .replace(/ +/g, '-') .replace(/[^-\w]/g, ''); }; /** * Strip the function definition from `str`, * and re-indent for pre whitespace. */ exports.clean = function(str) { str = str .replace(/^function *\(.*\) *{/, '') .replace(/\s+\}$/, ''); var spaces = str.match(/^\n?( *)/)[1].length , re = new RegExp('^ {' + spaces + '}', 'gm'); str = str.replace(re, ''); return exports.trim(str); }; /** * Escape regular expression characters in `str`. * * @param {String} str * @return {String} * @api private */ exports.escapeRegexp = function(str){ return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); }; /** * Trim the given `str`. * * @param {String} str * @return {String} * @api private */ exports.trim = function(str){ return str.replace(/^\s+|\s+$/g, ''); }; /** * Parse the given `qs`. * * @param {String} qs * @return {Object} * @api private */ exports.parseQuery = function(qs){ return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ var i = pair.indexOf('=') , key = pair.slice(0, i) , val = pair.slice(++i); obj[key] = decodeURIComponent(val); return obj; }, {}); }; /** * Highlight the given string of `js`. * * @param {String} js * @return {String} * @api private */ function highlight(js) { return js .replace(//g, '>') .replace(/\/\/(.*)/gm, '//$1') .replace(/('.*?')/gm, '$1') .replace(/(\d+\.\d+)/gm, '$1') .replace(/(\d+)/gm, '$1') .replace(/\bnew *(\w+)/gm, 'new $1') .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') } /** * Highlight the contents of tag `name`. * * @param {String} name * @api private */ exports.highlightTags = function(name) { var code = document.getElementsByTagName(name); for (var i = 0, len = code.length; i < len; ++i) { code[i].innerHTML = highlight(code[i].innerHTML); } }; }); // module: utils.js /** * Node shims. * * These are meant only to allow * mocha.js to run untouched, not * to allow running node code in * the browser. */ var process = {}; process.exit = function(status){}; process.stdout = {}; var global = window; /** * next tick implementation. */ process.nextTick = (function(){ // postMessage behaves badly on IE8 if (window.ActiveXObject || !window.postMessage) { return function(fn){ fn() }; } // based on setZeroTimeout by David Baron // - http://dbaron.org/log/20100309-faster-timeouts var timeouts = [] , name = 'mocha-zero-timeout' window.addEventListener('message', function(e){ if (e.source == window && e.data == name) { if (e.stopPropagation) e.stopPropagation(); if (timeouts.length) timeouts.shift()(); } }, true); return function(fn){ timeouts.push(fn); window.postMessage(name, '*'); } })(); /** * Remove uncaughtException listener. */ process.removeListener = function(e){ if ('uncaughtException' == e) { window.onerror = null; } }; /** * Implements uncaughtException listener. */ process.on = function(e, fn){ if ('uncaughtException' == e) { window.onerror = fn; } }; // boot ;(function(){ /** * Expose mocha. */ var Mocha = window.Mocha = require('mocha'), mocha = window.mocha = new Mocha({ reporter: 'html' }); /** * Override ui to ensure that the ui functions are initialized. * Normally this would happen in Mocha.prototype.loadFiles. */ mocha.ui = function(ui){ Mocha.prototype.ui.call(this, ui); this.suite.emit('pre-require', window, null, this); return this; }; /** * Setup mocha with the given setting options. */ mocha.setup = function(opts){ if ('string' == typeof opts) opts = { ui: opts }; for (var opt in opts) this[opt](opts[opt]); return this; }; /** * Run mocha, returning the Runner. */ mocha.run = function(fn){ var options = mocha.options; mocha.globals('location'); var query = Mocha.utils.parseQuery(window.location.search || ''); if (query.grep) mocha.grep(query.grep); return Mocha.prototype.run.call(mocha, function(){ Mocha.utils.highlightTags('code'); if (fn) fn(); }); }; })(); })();webpack-4.30.0/test/browsertest/node_modules/000077500000000000000000000000001345416772700212515ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/extra.loader.js000066400000000000000000000001361345416772700241770ustar00rootroot00000000000000module.exports = function(string) { this.cacheable(); return string + " with post loader"; }webpack-4.30.0/test/browsertest/node_modules/library1/000077500000000000000000000000001345416772700227765ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library1/index.js000066400000000000000000000015741345416772700244520ustar00rootroot00000000000000// Single File library var loadTimelibrary1 = typeof window.library1 === "undefined" describe("library1", function() { it("should load library1 only once", function() { expect(loadTimelibrary1).toBe(true); }); it("should load a component", function() { expect(require("./lib/component")).toBe("lib1 component"); }); it("should load async submodules with require.ensure even if single == true", function(done) { var sameTick = true; require.ensure(["submodule1", "submodule2"], function(require) { expect(sameTick).toBe(true); expect(require("submodule1")).toBe("submodule1"); expect(require("submodule2")).toBe("submodule2"); expect(require("submodule3")()).toBe("submodule3"); require.ensure([], function(require) { expect(sameTick).toBe(true); done(); }); }); setImmediate(function() { sameTick = false; }); }); }); module.exports = true; webpack-4.30.0/test/browsertest/node_modules/library1/lib/000077500000000000000000000000001345416772700235445ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library1/lib/comp.js000066400000000000000000000000421345416772700250340ustar00rootroot00000000000000module.exports = "lib1 component";webpack-4.30.0/test/browsertest/node_modules/library1/lib/component.js000066400000000000000000000000461345416772700261040ustar00rootroot00000000000000module.exports = require("./comp.js");webpack-4.30.0/test/browsertest/node_modules/library1/node_modules/000077500000000000000000000000001345416772700254535ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library1/node_modules/submodule1/000077500000000000000000000000001345416772700275335ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library1/node_modules/submodule1/index.js000066400000000000000000000000361345416772700311770ustar00rootroot00000000000000module.exports = "submodule1";webpack-4.30.0/test/browsertest/node_modules/library1/node_modules/submodule2/000077500000000000000000000000001345416772700275345ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library1/node_modules/submodule2/index.js000066400000000000000000000000721345416772700312000ustar00rootroot00000000000000module.exports = (function() { return "submodule2"; }());webpack-4.30.0/test/browsertest/node_modules/library2/000077500000000000000000000000001345416772700227775ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library2/lib/000077500000000000000000000000001345416772700235455ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library2/lib/common.js000066400000000000000000000003211345416772700253670ustar00rootroot00000000000000var typeofLibrary2 = typeof library2; describe("library2", function() { it("should run before main", function() { expect(typeofLibrary2).toBe("undefined"); }); }); exports.library2common = { ok2: true }; webpack-4.30.0/test/browsertest/node_modules/library2/lib/extra.js000066400000000000000000000000361345416772700252250ustar00rootroot00000000000000module.exports = "Lib2 extra";webpack-4.30.0/test/browsertest/node_modules/library2/lib/extra2.js000066400000000000000000000000371345416772700253100ustar00rootroot00000000000000module.exports = "Lib2 extra2";webpack-4.30.0/test/browsertest/node_modules/library2/lib/main.js000066400000000000000000000061331345416772700250320ustar00rootroot00000000000000// Chunked File library var library2commonValue = library2common; describe("library2", function() { var tickExtra, tickEmpty, tickMerged; var extraValue, testValue; beforeAll(function(done) { var asnycOk = false, asnycOk2 = false; var sameTick1 = true; require.ensure(["./extra"], function(require) { asnycOk = true; tickExtra = sameTick1; var sameTick2 = true; require.ensure([], function(require) { asnycOk2 = true; extraValue = require("./extra"); tickEmpty = sameTick2; require.ensure(["./test.js"], function(require) { tickMerged = sameTick2; testValue = require("./test.js"); done(); }); }); Promise.resolve().then(function() {}).then(function() {}).then(function() { sameTick2 = false; }); }); Promise.resolve().then(function() {}).then(function() {}).then(function() { sameTick1 = false; }); }); it("should run after common", function() { expect(library2commonValue).toEqual({ok2: true}); }); it("should load stuff with require.ensure asynchron", function() { expect(tickExtra).toBe(false); }); it("should load not include stuff from parent, remove empty chunks and apply a post loader", function() { expect(tickEmpty).toBe(true); expect(extraValue).toBe("Lib2 extra2 with post loader"); }); it("should merge chunks if maxChunks specified", function() { expect(tickEmpty).toBe(true); expect(testValue).toBe("test module"); }); it("should load require.amd from options", function() { expect(require.amd.fromOptions).toBe(true); }); it("should run empty AMD require", function(done) { var emptyRequire = false; require([], function() { emptyRequire = true; }); Promise.resolve().then(function() {}).then(function() {}).then(function() { expect(emptyRequire).toBe(true); done(); }); }); it("should provide free variables", function() { expect(s3()).toBe("submodule3"); }); it("should define values", function() { expect(CONST_UNDEFINED === undefined).toBe(true); expect(CONST_NULL === null).toBe(true); expect(CONST_TRUE).toBe(true); expect(CONST_FALSE).toBe(false); expect(CONST_FUNCTION()).toBe("ok"); expect(CONST_NUMBER).toBe(123); expect(CONST_NUMBER_EXPR).toBe(123); expect(typeof CONST_TYPEOF).toBe("typeof"); var o = CONST_OBJECT; expect(CONST_OBJECT.A).toBe(1); expect(CONST_OBJECT.B).toBe("B"); expect(CONST_OBJECT.C()).toBe("C"); expect(o.A).toBe(1); expect(o.B).toBe("B"); expect(o.C()).toBe("C"); (function(o) { expect(o.A).toBe(1); expect(o.B).toBe("B"); expect(o.C()).toBe("C"); }(CONST_OBJECT)); if(CONST_FALSE) require("fail"); if(!CONST_TRUE) require("fail"); if(!CONST_NUMBER) require("fail"); if(!CONST_NUMBER_EXPR) require("fail"); if(typeof CONST_TYPEOF !== "typeof") require("fail"); if(typeof CONST_FALSE !== "boolean") require("fail"); if(typeof CONST_FUNCTION !== "function") require("fail"); if(typeof CONST_OBJECT !== "object") require("fail"); if(!CONST_OBJECT.A) require("fail"); if(typeof CONST_OBJECT.A !== "number") require("fail"); }); }); exports.library2 = {ok: true}; // it should not fail if comment in last line webpack-4.30.0/test/browsertest/node_modules/library2/lib/test.js000066400000000000000000000000371345416772700250620ustar00rootroot00000000000000module.exports = "test module";webpack-4.30.0/test/browsertest/node_modules/library2/node_modules/000077500000000000000000000000001345416772700254545ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library2/node_modules/submodule1/000077500000000000000000000000001345416772700275345ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library2/node_modules/submodule1/index.js000066400000000000000000000000361345416772700312000ustar00rootroot00000000000000module.exports = "submodule1";webpack-4.30.0/test/browsertest/node_modules/library2/node_modules/submodule2/000077500000000000000000000000001345416772700275355ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library2/node_modules/submodule2/index.js000066400000000000000000000000721345416772700312010ustar00rootroot00000000000000module.exports = (function() { return "submodule2"; }());webpack-4.30.0/test/browsertest/node_modules/library2/node_modules/submodule3/000077500000000000000000000000001345416772700275365ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/library2/node_modules/submodule3/index.js000066400000000000000000000000661345416772700312050ustar00rootroot00000000000000module.exports = function() { return "submodule3"; };webpack-4.30.0/test/browsertest/node_modules/library2/package.json000066400000000000000000000000321345416772700252600ustar00rootroot00000000000000{ "main": "lib/main.js" }webpack-4.30.0/test/browsertest/node_modules/library2b.js000066400000000000000000000001641345416772700235000ustar00rootroot00000000000000describe("library2b", function() { it("should load this library", function() { expect(true).toBe(true); }); }); webpack-4.30.0/test/browsertest/node_modules/subcontent/000077500000000000000000000000001345416772700234355ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/subcontent/index.js000066400000000000000000000000311345416772700250740ustar00rootroot00000000000000module.exports = "error";webpack-4.30.0/test/browsertest/node_modules/subcontent/test.jade000066400000000000000000000000101345416772700252300ustar00rootroot00000000000000xyz: abcwebpack-4.30.0/test/browsertest/node_modules/subcontent2/000077500000000000000000000000001345416772700235175ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/subcontent2/file.js000066400000000000000000000000341345416772700247710ustar00rootroot00000000000000module.exports = "original";webpack-4.30.0/test/browsertest/node_modules/submodule3/000077500000000000000000000000001345416772700233335ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/node_modules/submodule3/index.js000066400000000000000000000000661345416772700250020ustar00rootroot00000000000000module.exports = function() { return "submodule3"; };webpack-4.30.0/test/browsertest/package.json000066400000000000000000000000671345416772700210650ustar00rootroot00000000000000{ "name": "node-webkit-tests", "main": "tests.html" }webpack-4.30.0/test/browsertest/tests.html000066400000000000000000000020431345416772700206230ustar00rootroot00000000000000 Mocha
    • styling

      • style!css loader

      • style!less loader

      • file loader:

    webpack-4.30.0/test/browsertest/web_modules/000077500000000000000000000000001345416772700211015ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/web_modules/subcontent/000077500000000000000000000000001345416772700232655ustar00rootroot00000000000000webpack-4.30.0/test/browsertest/web_modules/subcontent/index.js000066400000000000000000000000341345416772700247270ustar00rootroot00000000000000module.exports = "replaced";webpack-4.30.0/test/browsertest/webpack.config.js000066400000000000000000000004541345416772700220150ustar00rootroot00000000000000module.exports = { resolve: { modules: ["web_modules", "node_modules"], extensions: [".json", ".web.js", ".js"] }, resolveLoader: { extensions: [ ".json", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js" ], mainFields: ["webpackLoader", "loader", "main"] } }; webpack-4.30.0/test/cases/000077500000000000000000000000001345416772700153075ustar00rootroot00000000000000webpack-4.30.0/test/cases/amd/000077500000000000000000000000001345416772700160505ustar00rootroot00000000000000webpack-4.30.0/test/cases/amd/namedModules/000077500000000000000000000000001345416772700204655ustar00rootroot00000000000000webpack-4.30.0/test/cases/amd/namedModules/index.js000066400000000000000000000012261345416772700221330ustar00rootroot00000000000000define("named1", [], function() { return "named1"; }); define("named2", [], function() { return "named2"; }); define("named3", [], function() { return "named3"; }); define("named4", [], function() { return "named4"; }); define(["named1", "named2"], function(named1, named2) { it("should load the named modules in defined dependencies", function() { expect(named1).toBe("named1"); expect(named2).toBe("named2"); }); it("should load the named modules in require dependencies", function(done) { require(["named3", "named4"], function (named3, named4) { expect(named3).toBe("named3"); expect(named4).toBe("named4"); done(); }); }); }); webpack-4.30.0/test/cases/amd/namedModulesConstArrayDep/000077500000000000000000000000001345416772700231245ustar00rootroot00000000000000webpack-4.30.0/test/cases/amd/namedModulesConstArrayDep/index.js000066400000000000000000000012721345416772700245730ustar00rootroot00000000000000define("named1", [], function() { return "named1"; }); define("named2", [], function() { return "named2"; }); define("named3", [], function() { return "named3"; }); define("named4", [], function() { return "named4"; }); define("named1,named2".split(","), function(named1, named2) { it("should load the named modules in const array defined dependencies", function() { expect(named1).toBe("named1"); expect(named2).toBe("named2"); }); it("should load the named modules in const array require dependencies", function(done) { require("named3,named4".split(","), function (named3, named4) { expect(named3).toBe("named3"); expect(named4).toBe("named4"); done(); }); }); }); webpack-4.30.0/test/cases/chunks/000077500000000000000000000000001345416772700166025ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/circular-correctness/000077500000000000000000000000001345416772700227365ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/circular-correctness/index.js000066400000000000000000000005711345416772700244060ustar00rootroot00000000000000it("should handle circular chunks correctly", function(done) { import(/* webpackChunkName: "a" */"./module-a").then(function(result) { return result.default(); }).then(function(result2) { expect(result2.default()).toBe("x"); done(); }).catch(function(e) { done(e); }); const couldBe = function() { return import(/* webpackChunkName: "b" */"./module-b"); }; }); webpack-4.30.0/test/cases/chunks/circular-correctness/module-a.js000066400000000000000000000001301345416772700247710ustar00rootroot00000000000000export default function() { return import(/* webpackChunkName: "c" */"./module-c"); }; webpack-4.30.0/test/cases/chunks/circular-correctness/module-a2.js000066400000000000000000000000251345416772700250560ustar00rootroot00000000000000export default "a2"; webpack-4.30.0/test/cases/chunks/circular-correctness/module-b.js000066400000000000000000000001561345416772700250020ustar00rootroot00000000000000import "./module-x"; export default function() { return import(/* webpackChunkName: "c" */"./module-c"); }; webpack-4.30.0/test/cases/chunks/circular-correctness/module-b2.js000066400000000000000000000000251345416772700250570ustar00rootroot00000000000000export default "b2"; webpack-4.30.0/test/cases/chunks/circular-correctness/module-c.js000066400000000000000000000003111345416772700247740ustar00rootroot00000000000000import x from "./module-x"; export default function() { if(Math.random() < -1) { import(/* webpackChunkName: "a" */"./module-a"); import(/* webpackChunkName: "b" */"./module-b"); } return x; } webpack-4.30.0/test/cases/chunks/circular-correctness/module-x.js000066400000000000000000000000241345416772700250220ustar00rootroot00000000000000export default "x"; webpack-4.30.0/test/cases/chunks/context-weak/000077500000000000000000000000001345416772700212135ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/context-weak/dir/000077500000000000000000000000001345416772700217715ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/context-weak/dir/four.js000066400000000000000000000000241345416772700232760ustar00rootroot00000000000000module.exports = 4; webpack-4.30.0/test/cases/chunks/context-weak/index.js000066400000000000000000000014411345416772700226600ustar00rootroot00000000000000it("should not bundle context requires with asyncMode === 'weak'", function() { var contextRequire = require.context(".", false, /two/, "weak"); expect(function() { contextRequire("./two") }).toThrowError(/not available/); }); it("should find module with asyncMode === 'weak' when required elsewhere", function() { var contextRequire = require.context(".", false, /.+/, "weak"); expect(contextRequire("./three")).toBe(3); require("./three"); // in a real app would be served as a separate chunk }); it("should find module with asyncMode === 'weak' when required elsewhere (recursive)", function() { var contextRequire = require.context(".", true, /.+/, "weak"); expect(contextRequire("./dir/four")).toBe(4); require("./dir/four"); // in a real app would be served as a separate chunk }); webpack-4.30.0/test/cases/chunks/context-weak/three.js000066400000000000000000000000241345416772700226540ustar00rootroot00000000000000module.exports = 3; webpack-4.30.0/test/cases/chunks/context-weak/two.js000066400000000000000000000000241345416772700223560ustar00rootroot00000000000000module.exports = 2; webpack-4.30.0/test/cases/chunks/context/000077500000000000000000000000001345416772700202665ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/context/index.js000066400000000000000000000004271345416772700217360ustar00rootroot00000000000000it("should also work in a chunk", function(done) { require.ensure([], function(require) { var contextRequire = require.context(".", false, /two/); expect(contextRequire("./two")).toBe(2); var tw = "tw"; expect(require("." + "/" + tw + "o")).toBe(2); done(); }); }); webpack-4.30.0/test/cases/chunks/context/two.js000066400000000000000000000000231345416772700214300ustar00rootroot00000000000000module.exports = 2;webpack-4.30.0/test/cases/chunks/import-circle/000077500000000000000000000000001345416772700213535ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-circle/index.js000066400000000000000000000004001345416772700230120ustar00rootroot00000000000000import leftHelix from './leftHelix'; import rightHelix from './rightHelix'; it("should import generate ensure function for this", () => { return Promise.all([ leftHelix.run(), rightHelix.run() ]); }); export default { leftHelix, rightHelix, }; webpack-4.30.0/test/cases/chunks/import-circle/leftHelix.js000066400000000000000000000001431345416772700236330ustar00rootroot00000000000000import leftHelixPrime, { run } from './leftHelixPrime'; export default { leftHelixPrime, run }; webpack-4.30.0/test/cases/chunks/import-circle/leftHelixPrime.js000066400000000000000000000002611345416772700246310ustar00rootroot00000000000000import rightHelixPrime from './rightHelixPrime'; export function run() { return import(/* webpackChunkName: "left" */ './leftHelix'); } export default { rightHelixPrime, }; webpack-4.30.0/test/cases/chunks/import-circle/rightHelix.js000066400000000000000000000001451345416772700240200ustar00rootroot00000000000000import rightHelixPrime, { run } from './rightHelixPrime'; export default { rightHelixPrime, run } webpack-4.30.0/test/cases/chunks/import-circle/rightHelixPrime.js000066400000000000000000000002621345416772700250150ustar00rootroot00000000000000import leftHelixPrime from './leftHelixPrime'; export function run() { return import(/* webpackChunkName: "right" */ './rightHelix'); } export default { leftHelixPrime }; webpack-4.30.0/test/cases/chunks/import-context-exist-chunk/000077500000000000000000000000001345416772700240365ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-context-exist-chunk/dir-initial-with-fake-map/000077500000000000000000000000001345416772700306735ustar00rootroot00000000000000initialModule.js000066400000000000000000000000471345416772700337520ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-context-exist-chunk/dir-initial-with-fake-mapexport default "initialModuleDefault"; initialModule2.js000066400000000000000000000000331345416772700340270ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-context-exist-chunk/dir-initial-with-fake-mapexports.default = "other"; webpack-4.30.0/test/cases/chunks/import-context-exist-chunk/dir-initial/000077500000000000000000000000001345416772700262435ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-context-exist-chunk/dir-initial/initialModule.js000066400000000000000000000000471345416772700314010ustar00rootroot00000000000000export default "initialModuleDefault"; webpack-4.30.0/test/cases/chunks/import-context-exist-chunk/index.js000066400000000000000000000011161345416772700255020ustar00rootroot00000000000000it("should resolve when import existed chunk (#8626)", function(done) { require.context("./dir-initial/"); const fileName = "initialModule"; import(`./dir-initial/${fileName}`).then(({default:m}) => { expect(m).toBe("initialModuleDefault"); done(); }).catch(done); }); it("should resolve when import existed chunk with fake maps", function(done) { require.context("./dir-initial-with-fake-map/"); const fileName = "initialModule"; import(`./dir-initial-with-fake-map/${fileName}`).then(({default:m}) => { expect(m).toBe("initialModuleDefault"); done(); }).catch(done); }); webpack-4.30.0/test/cases/chunks/import-context/000077500000000000000000000000001345416772700215765ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-context/dir/000077500000000000000000000000001345416772700223545ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-context/dir/one.js000066400000000000000000000000241345416772700234670ustar00rootroot00000000000000module.exports = 1; webpack-4.30.0/test/cases/chunks/import-context/dir/three.js000066400000000000000000000000241345416772700240150ustar00rootroot00000000000000module.exports = 3; webpack-4.30.0/test/cases/chunks/import-context/dir/two.js000066400000000000000000000000241345416772700235170ustar00rootroot00000000000000module.exports = 2; webpack-4.30.0/test/cases/chunks/import-context/dir2/000077500000000000000000000000001345416772700224365ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import-context/dir2/one.js000066400000000000000000000000241345416772700235510ustar00rootroot00000000000000module.exports = 1; webpack-4.30.0/test/cases/chunks/import-context/dir2/three.js000066400000000000000000000000241345416772700240770ustar00rootroot00000000000000module.exports = 3; webpack-4.30.0/test/cases/chunks/import-context/dir2/two.js000066400000000000000000000000241345416772700236010ustar00rootroot00000000000000module.exports = 2; webpack-4.30.0/test/cases/chunks/import-context/index.js000066400000000000000000000014151345416772700232440ustar00rootroot00000000000000function testCase(load, done) { load("two", 2, function() { var sync = true; load("one", 1, function() { expect(sync).toBe(false); load("three", 3, function() { var sync = true; load("two", 2, function() { expect(sync).toBe(true); done(); }); Promise.resolve().then(function() {}).then(function() {}).then(function() { sync = false; }); }); }); Promise.resolve().then(function() { sync = false; }); }); } it("should be able to use expressions in import", function(done) { function load(name, expected, callback) { import("./dir/" + name).then(function(result) { expect(result).toEqual(nsObj({ default: expected })); callback(); }).catch(function(err) { done(err); }); } testCase(load, done); }); webpack-4.30.0/test/cases/chunks/import/000077500000000000000000000000001345416772700201145ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/import/index.js000066400000000000000000000003071345416772700215610ustar00rootroot00000000000000it("should be able to use import", function(done) { import("./two").then(function(two) { expect(two).toEqual(nsObj({ default: 2 })); done(); }).catch(function(err) { done(err); }); }); webpack-4.30.0/test/cases/chunks/import/two.js000066400000000000000000000000231345416772700212560ustar00rootroot00000000000000module.exports = 2;webpack-4.30.0/test/cases/chunks/inline-options/000077500000000000000000000000001345416772700215515ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir1/000077500000000000000000000000001345416772700224105ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir1/a.js000066400000000000000000000000241345416772700231620ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir1/b.js000066400000000000000000000000241345416772700231630ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir1/c.js000066400000000000000000000000241345416772700231640ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir1/d.js000066400000000000000000000000241345416772700231650ustar00rootroot00000000000000export default "d"; webpack-4.30.0/test/cases/chunks/inline-options/dir10/000077500000000000000000000000001345416772700224705ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir10/a.js000066400000000000000000000000241345416772700232420ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir11/000077500000000000000000000000001345416772700224715ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir11/a.js000066400000000000000000000000241345416772700232430ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir2/000077500000000000000000000000001345416772700224115ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir2/a.js000066400000000000000000000000241345416772700231630ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir2/b.js000066400000000000000000000000241345416772700231640ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir2/c.js000066400000000000000000000000241345416772700231650ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir2/d.js000066400000000000000000000000241345416772700231660ustar00rootroot00000000000000export default "d"; webpack-4.30.0/test/cases/chunks/inline-options/dir3/000077500000000000000000000000001345416772700224125ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir3/a.js000066400000000000000000000000241345416772700231640ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir3/b.js000066400000000000000000000000241345416772700231650ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir3/c.js000066400000000000000000000000241345416772700231660ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir3/d.js000066400000000000000000000000241345416772700231670ustar00rootroot00000000000000export default "d"; webpack-4.30.0/test/cases/chunks/inline-options/dir4/000077500000000000000000000000001345416772700224135ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir4/a.js000066400000000000000000000000241345416772700231650ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir4/b.js000066400000000000000000000000241345416772700231660ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir4/c.js000066400000000000000000000000241345416772700231670ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir4/d.js000066400000000000000000000000241345416772700231700ustar00rootroot00000000000000export default "d"; webpack-4.30.0/test/cases/chunks/inline-options/dir5/000077500000000000000000000000001345416772700224145ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir5/a.js000066400000000000000000000000241345416772700231660ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir5/b.js000066400000000000000000000000241345416772700231670ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir5/c.js000066400000000000000000000000241345416772700231700ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir5/d.js000066400000000000000000000000241345416772700231710ustar00rootroot00000000000000export default "d"; webpack-4.30.0/test/cases/chunks/inline-options/dir6/000077500000000000000000000000001345416772700224155ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir6/a.js000066400000000000000000000000241345416772700231670ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir6/b.js000066400000000000000000000000241345416772700231700ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir6/c.js000066400000000000000000000000241345416772700231710ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir6/d.js000066400000000000000000000000241345416772700231720ustar00rootroot00000000000000export default "d"; webpack-4.30.0/test/cases/chunks/inline-options/dir7/000077500000000000000000000000001345416772700224165ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir7/a.js000066400000000000000000000000241345416772700231700ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir7/b.js000066400000000000000000000000241345416772700231710ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir7/c.js000066400000000000000000000000241345416772700231720ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir7/d.js000066400000000000000000000000241345416772700231730ustar00rootroot00000000000000export default "d"; webpack-4.30.0/test/cases/chunks/inline-options/dir8/000077500000000000000000000000001345416772700224175ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir8/a.js000066400000000000000000000000241345416772700231710ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir8/b.js000066400000000000000000000000241345416772700231720ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir8/c.js000066400000000000000000000000241345416772700231730ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/dir9/000077500000000000000000000000001345416772700224205ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/inline-options/dir9/a.js000066400000000000000000000000241345416772700231720ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/chunks/inline-options/dir9/b.js000066400000000000000000000000241345416772700231730ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/chunks/inline-options/dir9/c.js000066400000000000000000000000241345416772700231740ustar00rootroot00000000000000export default "c"; webpack-4.30.0/test/cases/chunks/inline-options/index.js000066400000000000000000000076671345416772700232360ustar00rootroot00000000000000it("should be able to use eager mode", function() { function load(name) { return import(/* webpackMode: "eager" */ "./dir1/" + name); } return testChunkLoading(load, true, true); }); it("should be able to use lazy-once mode", function() { function load(name) { return import(/* webpackMode: "lazy-once" */ "./dir2/" + name); } return testChunkLoading(load, false, true); }); it("should be able to use lazy-once mode with name", function() { function load(name) { return import(/* webpackMode: "lazy-once", webpackChunkName: "name-lazy-once" */ "./dir3/" + name); } return testChunkLoading(load, false, true); }); it("should be able to use lazy mode", function() { function load(name) { return import(/* webpackMode: "lazy" */ "./dir4/" + name); } return testChunkLoading(load, false, false); }); it("should be able to use lazy mode with name", function() { function load(name) { return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy" */ "./dir5/" + name); } return testChunkLoading(load, false, false); }); it("should be able to use lazy mode with name and placeholder", function() { function load(name) { return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy-[request]" */ "./dir6/" + name); } return testChunkLoading(load, false, false); }); it("should be able to combine chunks by name", function() { function load(name) { switch(name) { case "a": return import(/* webpackMode: "eager" */ "./dir7/a"); case "b": return import(/* webpackChunkName: "name-3" */ "./dir7/b"); case "c": return import(/* webpackChunkName: "name-3" */ "./dir7/c"); case "d": return import(/* webpackChunkName: "name-3" */ "./dir7/d"); default: throw new Error("Unexcepted test data"); } } return testChunkLoading(load, false, true); }); it("should be able to use weak mode", function() { function load(name) { return import(/* webpackMode: "weak" */ "./dir8/" + name); } require("./dir8/a") // chunks served manually by the user require("./dir8/b") require("./dir8/c") return testChunkLoading(load, true, true); }); it("should be able to use weak mode (without context)", function() { function load(name) { switch(name) { case "a": return import(/* webpackMode: "weak" */ "./dir9/a"); case "b": return import(/* webpackMode: "weak" */ "./dir9/b"); case "c": return import(/* webpackMode: "weak" */ "./dir9/c"); default: throw new Error("Unexcepted test data"); } } require("./dir9/a") // chunks served manually by the user require("./dir9/b") require("./dir9/c") return testChunkLoading(load, true, true); }); it("should not find module when mode is weak and chunk not served elsewhere", function() { var name = "a"; return import(/* webpackMode: "weak" */ "./dir10/" + name) .catch(function(e) { expect(e).toMatchObject({ message: /not available/, code: /MODULE_NOT_FOUND/ }); }); }); it("should not find module when mode is weak and chunk not served elsewhere (without context)", function() { return import(/* webpackMode: "weak" */ "./dir11/a") .catch(function(e) { expect(e).toMatchObject({ message: /not available/, code: /MODULE_NOT_FOUND/ }); }); }); function testChunkLoading(load, expectedSyncInitial, expectedSyncRequested) { var sync = false; var syncInitial = true; var p = Promise.all([load("a"), load("b")]).then(function() { expect(syncInitial).toBe(expectedSyncInitial); sync = true; var p = Promise.all([ load("a").then(function(a) { expect(a).toEqual(nsObj({ default: "a" })); expect(sync).toBe(true); }), load("c").then(function(c) { expect(c).toEqual(nsObj({ default: "c" })); expect(sync).toBe(expectedSyncRequested); }) ]); Promise.resolve().then(function(){}).then(function(){}).then(function(){}).then(function(){ sync = false; }); return p; }); Promise.resolve().then(function(){}).then(function(){}).then(function(){}).then(function(){ syncInitial = false; }); return p; } webpack-4.30.0/test/cases/chunks/issue-2443/000077500000000000000000000000001345416772700203245ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/issue-2443/dir/000077500000000000000000000000001345416772700211025ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/issue-2443/dir/one/000077500000000000000000000000001345416772700216635ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/issue-2443/dir/one/file.js000066400000000000000000000000241345416772700231340ustar00rootroot00000000000000module.exports = 1; webpack-4.30.0/test/cases/chunks/issue-2443/dir/three/000077500000000000000000000000001345416772700222115ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/issue-2443/dir/three/file.js000066400000000000000000000000241345416772700234620ustar00rootroot00000000000000module.exports = 3; webpack-4.30.0/test/cases/chunks/issue-2443/dir/two/000077500000000000000000000000001345416772700217135ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/issue-2443/dir/two/file.js000066400000000000000000000000241345416772700231640ustar00rootroot00000000000000module.exports = 2; webpack-4.30.0/test/cases/chunks/issue-2443/index.js000066400000000000000000000010071345416772700217670ustar00rootroot00000000000000it("should be able to use expressions in import (directory)", function(done) { function load(name, expected, callback) { import("./dir/" + name + "/file.js").then(function(result) { expect(result).toEqual(nsObj({ default: expected })); callback(); }).catch(function(err) { done(err); }); } require.include("./dir/three/file"); load("one", 1, function() { load("two", 2, function() { load("three", 3, function() { load("two", 2, function() { done(); }); }); }); }); }); webpack-4.30.0/test/cases/chunks/issue-5153/000077500000000000000000000000001345416772700203255ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/issue-5153/index.js000066400000000000000000000002271345416772700217730ustar00rootroot00000000000000import x from "./module"; it("should export the same binding", () => { return import("./module").then(ns => { expect(x).toBe(ns.default); }); }); webpack-4.30.0/test/cases/chunks/issue-5153/module.js000066400000000000000000000000231345416772700221430ustar00rootroot00000000000000export default {}; webpack-4.30.0/test/cases/chunks/named-chunks/000077500000000000000000000000001345416772700211575ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/named-chunks/empty.js000066400000000000000000000000001345416772700226410ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/named-chunks/empty2.js000066400000000000000000000000001345416772700227230ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/named-chunks/empty3.js000066400000000000000000000000001345416772700227240ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/named-chunks/empty4.js000066400000000000000000000000001345416772700227250ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/named-chunks/index.js000066400000000000000000000063231345416772700226300ustar00rootroot00000000000000it("should handle named chunks", function(done) { var sync = false; require.ensure([], function(require) { require("./empty?a"); require("./empty?b"); testLoad(); sync = true; process.nextTick(function() { sync = false; }); }, "named-chunk"); function testLoad() { require.ensure([], function(require) { require("./empty?c"); require("./empty?d"); expect(sync).toBeTruthy(); done(); }, "named-chunk"); } }); it("should handle empty named chunks", function(done) { var sync = false; require.ensure([], function(require) { expect(sync).toBeTruthy(); }, "empty-named-chunk"); require.ensure([], function(require) { expect(sync).toBeTruthy(); done(); }, "empty-named-chunk"); sync = true; setImmediate(function() { sync = false; }); }); it("should handle named chunks when there is an error callback", function(done) { var sync = false; require.ensure([], function(require) { require("./empty?e"); require("./empty?f"); testLoad(); sync = true; process.nextTick(function() { sync = false; }); }, function(error) {}, "named-chunk-for-error-callback"); function testLoad() { require.ensure([], function(require) { require("./empty?g"); require("./empty?h"); expect(sync).toBeTruthy(); done(); }, function(error) {}, "named-chunk-for-error-callback"); } }); it("should handle empty named chunks when there is an error callback", function(done) { var sync = false; require.ensure([], function(require) { expect(sync).toBeTruthy(); }, function(error) {}, "empty-named-chunk-for-error-callback"); require.ensure([], function(require) { expect(sync).toBeTruthy(); done(); }, function(error) {}, "empty-named-chunk-for-error-callback"); sync = true; setImmediate(function() { sync = false; }); }); it("should be able to use named chunks in import()", function(done) { var sync = false; import("./empty?import1-in-chunk1" /* webpackChunkName: "import-named-chunk-1" */).then(function(result){ var i = 0; import("./empty?import2-in-chunk1" /* webpackChunkName: "import-named-chunk-1" */).then(function(result){ expect(sync).toBeTruthy(); if(i++ > 0) done(); }).catch(function(err){ done(err); }); import("./empty?import3-in-chunk2" /* webpackChunkName: "import-named-chunk-2" */).then(function(result){ expect(sync).toBeFalsy(); if(i++ > 0) done(); }).catch(function(err){ done(err); }); sync = true; Promise.resolve().then(function(){}).then(function(){}).then(function(){ sync = false; }); }); }); it("should be able to use named chunk in context import()", function(done) { var mpty = "mpty"; var sync = false; import("./e" + mpty + "2" /* webpackChunkName: "context-named-chunk" */).then(function(result) { var i = 0; import("./e" + mpty + "3" /* webpackChunkName: "context-named-chunk" */).then(function(result){ expect(sync).toBeTruthy(); if(i++ > 0) done(); }).catch(function(err){ done(err); }); import("./e" + mpty + "4" /* webpackChunkName: "context-named-chunk-2" */).then(function(result){ expect(sync).toBeFalsy(); if(i++ > 0) done(); }).catch(function(err){ done(err); }); sync = true; Promise.resolve().then(function(){}).then(function(){}).then(function(){ sync = false; }); }); }); webpack-4.30.0/test/cases/chunks/nested-in-empty/000077500000000000000000000000001345416772700216245ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/nested-in-empty/a.js000066400000000000000000000000001345416772700223700ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/nested-in-empty/b.js000066400000000000000000000000251345416772700224000ustar00rootroot00000000000000module.exports = 42; webpack-4.30.0/test/cases/chunks/nested-in-empty/index.js000066400000000000000000000004451345416772700232740ustar00rootroot00000000000000it("should include a chunk nested in an empty chunk", (done) => { require.ensure(["./a"], () => { require.ensure([], () => { require.ensure(["./a"], () => { require.ensure([], () => { const b = require("./b"); expect(b).toBe(42); done(); }); }); }); }); }); webpack-4.30.0/test/cases/chunks/parsing/000077500000000000000000000000001345416772700202455ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/parsing/empty.js000066400000000000000000000000001345416772700217270ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/parsing/index.js000066400000000000000000000021311345416772700217070ustar00rootroot00000000000000it("should handle bound function expressions", function(done) { require.ensure([], function(require) { expect(this).toEqual({ test: true }); require("./empty?test"); expect(process.nextTick).toBeTypeOf("function"); // check if injection still works require.ensure([], function(require) { expect(this).toEqual({ test: true }); done(); }.bind(this)); }.bind({test: true})); }); it("should handle require.ensure without function expression", function(done) { function f() { done(); } require.ensure([], f); }); it("should parse expression in require.ensure, which isn't a function expression", function(done) { require.ensure([], (function() { expect(require("./empty?require.ensure:test")).toEqual({}); return function f() { done(); }; }())); }); it("should accept a require.include call", function(done) { require.include("./require.include"); var value = null; require.ensure([], function(require) { value = require("./require.include"); }); setImmediate(function() { expect(value).toBe("require.include"); expect(value).toBe("require.include"); done(); }); }); webpack-4.30.0/test/cases/chunks/parsing/require.include.js000066400000000000000000000000431345416772700236760ustar00rootroot00000000000000module.exports = "require.include";webpack-4.30.0/test/cases/chunks/runtime/000077500000000000000000000000001345416772700202655ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/runtime/a.js000066400000000000000000000000251345416772700210400ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/chunks/runtime/acircular.js000066400000000000000000000001211345416772700225620ustar00rootroot00000000000000require.ensure(["./acircular2"], function(require) { require("./acircular2"); })webpack-4.30.0/test/cases/chunks/runtime/acircular2.js000066400000000000000000000001171345416772700226510ustar00rootroot00000000000000require.ensure(["./acircular"], function(require) { require("./acircular"); })webpack-4.30.0/test/cases/chunks/runtime/b.js000066400000000000000000000000401345416772700210360ustar00rootroot00000000000000module.exports = require("./a");webpack-4.30.0/test/cases/chunks/runtime/duplicate.js000066400000000000000000000001221345416772700225700ustar00rootroot00000000000000require.ensure(["./a"], function(require) { expect(require("./a")).toBe("a"); }) webpack-4.30.0/test/cases/chunks/runtime/duplicate2.js000066400000000000000000000001221345416772700226520ustar00rootroot00000000000000require.ensure(["./b"], function(require) { expect(require("./b")).toBe("a"); }) webpack-4.30.0/test/cases/chunks/runtime/empty.js000066400000000000000000000000001345416772700217470ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/runtime/index.js000066400000000000000000000021701345416772700217320ustar00rootroot00000000000000/* globals it */ it("should handle duplicate chunks", function(done) { var firstOne = false, secondOne = false; require.ensure([], function(require) { require("./acircular"); require("./duplicate"); require("./duplicate2"); firstOne = true; if(secondOne) done(); }); require.ensure([], function(require) { require("./acircular2"); require("./duplicate"); require("./duplicate2"); secondOne = true; if(firstOne) done(); }); }); it("should not load a chunk which is included in a already loaded one", function(done) { var asyncFlag = false; require.ensure(["./empty?x", "./empty?y", "./empty?z"], function(require) { try { expect(asyncFlag).toBe(true); loadChunk(); } catch(e) { done(e); } }); Promise.resolve().then(function() {}).then(function() {}).then(function() { asyncFlag = true; }); function loadChunk() { var sync = true; require.ensure(["./empty?x", "./empty?y"], function(require) { try { expect(sync).toBe(true); done(); } catch(e) { done(e); } }); Promise.resolve().then(function() {}).then(function() {}).then(function() { sync = false; }); } }); webpack-4.30.0/test/cases/chunks/runtime/test.filter.js000066400000000000000000000002571345416772700230720ustar00rootroot00000000000000module.exports = function(config) { // This test can't run in development mode as it depends on the flagIncludedChunks optimization return config.mode !== "development"; }; webpack-4.30.0/test/cases/chunks/var-inject-error-handler/000077500000000000000000000000001345416772700234065ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/var-inject-error-handler/empty.js000066400000000000000000000000001345416772700250700ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/var-inject-error-handler/index.js000066400000000000000000000003531345416772700250540ustar00rootroot00000000000000it("should handle var injection in require.ensure with error callback", function(done) { require.ensure([], function(require) { require("./empty"); var x = module.x; done(); }, function(error) {}, "chunk-with-var-inject"); }); webpack-4.30.0/test/cases/chunks/weak-dependencies-context/000077500000000000000000000000001345416772700236375ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies-context/a.js000066400000000000000000000000001345416772700244030ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies-context/b.js000066400000000000000000000000001345416772700244040ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies-context/c.js000066400000000000000000000000001345416772700244050ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies-context/index.js000066400000000000000000000012341345416772700253040ustar00rootroot00000000000000it("should not include a module with a weak dependency using context", function() { var fileA = "a"; var fileB = "b"; var fileC = "c"; var resolveWeakA = require.resolveWeak("./" + fileA); var resolveWeakB = require.resolveWeak("./" + fileB); var resolveWeakC = require.resolveWeak("./" + fileC); var a = !!__webpack_modules__[resolveWeakA]; var b = !!__webpack_modules__[resolveWeakB]; var c = !!__webpack_modules__[resolveWeakC]; require(["./b"]); require("./c"); expect(resolveWeakA).toBeDefined(); expect(resolveWeakB).toBeDefined(); expect(resolveWeakC).toBeDefined(); expect(a).toBe(false); expect(b).toBe(false); expect(c).toBe(true); }); webpack-4.30.0/test/cases/chunks/weak-dependencies/000077500000000000000000000000001345416772700221555ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies/a.js000066400000000000000000000000001345416772700227210ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies/b.js000066400000000000000000000000001345416772700227220ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies/c.js000066400000000000000000000000001345416772700227230ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies/d.js000066400000000000000000000000001345416772700227240ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weak-dependencies/index.js000066400000000000000000000006711345416772700236260ustar00rootroot00000000000000it("should not include a module with a weak dependency", function() { var a = !!__webpack_modules__[require.resolveWeak("./a")]; var b = !!__webpack_modules__[require.resolve("./b")]; var c = !!__webpack_modules__[require.resolveWeak("./c")]; var d = !!__webpack_modules__[require.resolveWeak("./d")]; require(["./c"]); require("./d"); expect(a).toBe(false); expect(b).toBe(true); expect(c).toBe(false); expect(d).toBe(true); }); webpack-4.30.0/test/cases/chunks/weird-reference-to-entry/000077500000000000000000000000001345416772700234275ustar00rootroot00000000000000webpack-4.30.0/test/cases/chunks/weird-reference-to-entry/errors.js000066400000000000000000000002131345416772700252750ustar00rootroot00000000000000module.exports = [ [/It's not allowed to load an initial chunk on demand\. The chunk name "main" is already used by an entrypoint\./], ]; webpack-4.30.0/test/cases/chunks/weird-reference-to-entry/index.js000066400000000000000000000003571345416772700251010ustar00rootroot00000000000000it("should handle reference to entry chunk correctly", function(done) { import(/* webpackChunkName: "main" */"./module-a").then(function(result) { expect(result.default).toBe("ok"); done(); }).catch(function(e) { done(e); }); }); webpack-4.30.0/test/cases/chunks/weird-reference-to-entry/module-a.js000066400000000000000000000000251345416772700254650ustar00rootroot00000000000000export default "ok"; webpack-4.30.0/test/cases/compile/000077500000000000000000000000001345416772700167375ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/deduplication-bundle-loader/000077500000000000000000000000001345416772700242765ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/deduplication-bundle-loader/a/000077500000000000000000000000001345416772700245165ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/deduplication-bundle-loader/a/file.js000066400000000000000000000000251345416772700257700ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/compile/deduplication-bundle-loader/b/000077500000000000000000000000001345416772700245175ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/deduplication-bundle-loader/b/file.js000066400000000000000000000000251345416772700257710ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/cases/compile/deduplication-bundle-loader/index.js000066400000000000000000000005571345416772700257520ustar00rootroot00000000000000it("should load a duplicate module with different dependencies correctly", function(done) { var a = require("bundle-loader!./a/file"); var b = require("bundle-loader!./b/file"); expect((typeof a)).toBe("function"); expect((typeof b)).toBe("function"); a(function(ra) { expect(ra).toBe("a"); b(function(rb) { expect(rb).toBe("b"); done(); }) }); }); webpack-4.30.0/test/cases/compile/deduplication/000077500000000000000000000000001345416772700215635ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/deduplication/d.js000066400000000000000000000000251345416772700223410ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/test/cases/compile/deduplication/dedupe1/000077500000000000000000000000001345416772700231125ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/deduplication/dedupe1/dupdep.js000066400000000000000000000000321345416772700247240ustar00rootroot00000000000000module.exports = "edupe1";webpack-4.30.0/test/cases/compile/deduplication/dedupe1/index.js000066400000000000000000000001371345416772700245600ustar00rootroot00000000000000module.exports = require("../d") + require("./dupdep"); var ep = "ep"; require("./dupd" + ep); webpack-4.30.0/test/cases/compile/deduplication/dedupe2/000077500000000000000000000000001345416772700231135ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/deduplication/dedupe2/dupdep.js000066400000000000000000000000321345416772700247250ustar00rootroot00000000000000module.exports = "edupe2";webpack-4.30.0/test/cases/compile/deduplication/dedupe2/index.js000066400000000000000000000001371345416772700245610ustar00rootroot00000000000000module.exports = require("../d") + require("./dupdep"); var ep = "ep"; require("./dupd" + ep); webpack-4.30.0/test/cases/compile/deduplication/index.js000066400000000000000000000003521345416772700232300ustar00rootroot00000000000000it("should load a duplicate module with different dependencies correctly", function() { var dedupe1 = require("./dedupe1"); var dedupe2 = require("./dedupe2"); expect(dedupe1).toBe("dedupe1"); expect(dedupe2).toBe("dedupe2"); }); webpack-4.30.0/test/cases/compile/error-hide-stack/000077500000000000000000000000001345416772700221025ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/error-hide-stack/errors.js000066400000000000000000000001221345416772700237470ustar00rootroot00000000000000module.exports = [ [/Module build failed( \(from [^)]+\))?:\nMessage\nStack/] ]; webpack-4.30.0/test/cases/compile/error-hide-stack/index.js000066400000000000000000000001671345416772700235530ustar00rootroot00000000000000it("should hide stack in details", function() { expect(function f() { require("./loader!"); }).toThrowError(); }); webpack-4.30.0/test/cases/compile/error-hide-stack/loader.js000066400000000000000000000001731345416772700237070ustar00rootroot00000000000000module.exports = function() { var err = new Error("Message"); err.stack = "Stack"; err.hideStack = true; throw err; }; webpack-4.30.0/test/cases/compile/issue2221/000077500000000000000000000000001345416772700203765ustar00rootroot00000000000000webpack-4.30.0/test/cases/compile/issue2221/exportvar.js000066400000000000000000000000271345416772700227650ustar00rootroot00000000000000export var foo = "bar" webpack-4.30.0/test/cases/compile/issue2221/index.js000066400000000000000000000001571345416772700220460ustar00rootroot00000000000000it("should compile non-immutable exports with missing semicolons", function(){ require("./exportvar"); }); webpack-4.30.0/test/cases/concord/000077500000000000000000000000001345416772700167365ustar00rootroot00000000000000webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/000077500000000000000000000000001345416772700244545ustar00rootroot00000000000000webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/index.js000066400000000000000000000005671345416772700261310ustar00rootroot00000000000000it("should resolve the alias in package.json", function() { expect(require("app/file").default).toBe("file"); }); it("should resolve the alias and extensions in package.json", function() { expect(require("app/file2").default).toBe("correct file2"); }); it("should resolve the alias in package.json", function() { expect(require("thing").default).toBe("the thing"); }); webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/modules/000077500000000000000000000000001345416772700261245ustar00rootroot00000000000000webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/modules/app/000077500000000000000000000000001345416772700267045ustar00rootroot00000000000000webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/modules/app/file.js000066400000000000000000000000271345416772700301600ustar00rootroot00000000000000export default "file"; webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/modules/app/file2.js000066400000000000000000000000361345416772700302420ustar00rootroot00000000000000export default "wrong file2"; webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/modules/app/file2.my-js000066400000000000000000000000401345416772700306600ustar00rootroot00000000000000export default "correct file2"; webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/package.json000066400000000000000000000002171345416772700267420ustar00rootroot00000000000000{ "concord": { "modules": { "app/**": "./modules/app/**", "thing": "./the-thing" }, "extensions": [ ".my-js", ".js" ] } }webpack-4.30.0/test/cases/concord/inner-modules-and-extensions/the-thing.js000066400000000000000000000000331345416772700266750ustar00rootroot00000000000000export default "the thing";webpack-4.30.0/test/cases/context/000077500000000000000000000000001345416772700167735ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/ignore-hidden-files/000077500000000000000000000000001345416772700226075ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/ignore-hidden-files/folder/000077500000000000000000000000001345416772700240625ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/ignore-hidden-files/folder/.file.js000066400000000000000000000000301345416772700254060ustar00rootroot00000000000000module.exports = "fail";webpack-4.30.0/test/cases/context/ignore-hidden-files/index.js000066400000000000000000000002231345416772700242510ustar00rootroot00000000000000it("should ignore hidden files", function() { expect(function() { var name = "./file.js"; require("./folder/" + name); }).toThrowError(); });webpack-4.30.0/test/cases/context/issue-1769/000077500000000000000000000000001345416772700205275ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-1769/folder/000077500000000000000000000000001345416772700220025ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-1769/folder/0.js000066400000000000000000000000001345416772700224650ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-1769/index.js000066400000000000000000000003771345416772700222030ustar00rootroot00000000000000it("should be able the catch a incorrect import", function(done) { var expr = "1"; import("./folder/" + expr).then(function() { done(new Error("should not be called")); }).catch(function(err) { expect(err).toBeInstanceOf(Error); done(); }); }); webpack-4.30.0/test/cases/context/issue-3873/000077500000000000000000000000001345416772700205255ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-3873/index.js000066400000000000000000000002411345416772700221670ustar00rootroot00000000000000function get(name) { return require("./" + name); } it("should automatically infer the index.js file", function() { expect(get("module")).toBe("module"); }); webpack-4.30.0/test/cases/context/issue-3873/module/000077500000000000000000000000001345416772700220125ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-3873/module/index.js000066400000000000000000000000331345416772700234530ustar00rootroot00000000000000module.exports = "module"; webpack-4.30.0/test/cases/context/issue-524/000077500000000000000000000000001345416772700204335ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-524/index.js000066400000000000000000000005001345416772700220730ustar00rootroot00000000000000it("should support an empty context", function() { var c = require.context(".", true, /^nothing$/); expect(typeof c.id === "number" || typeof c.id === "string").toBeTruthy(); expect(function() { c.resolve(""); }).toThrowError(); expect(function() { c(""); }).toThrowError(); expect(c.keys()).toEqual([]); }); webpack-4.30.0/test/cases/context/issue-5750/000077500000000000000000000000001345416772700205215ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-5750/folder/000077500000000000000000000000001345416772700217745ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-5750/folder/a000066400000000000000000000000001345416772700221250ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-5750/index.js000066400000000000000000000003151345416772700221650ustar00rootroot00000000000000it("should not use regexps with the g flag", function() { expect(require.context("./folder", true, /a/).keys().length).toBe(1); expect(require.context("./folder", true, /a/g).keys().length).toBe(0); }); webpack-4.30.0/test/cases/context/issue-5750/warnings.js000066400000000000000000000001461345416772700227100ustar00rootroot00000000000000module.exports = [ [/Critical dependency: Contexts can't use RegExps with the 'g' or 'y' flags/], ]; webpack-4.30.0/test/cases/context/issue-801/000077500000000000000000000000001345416772700204315ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-801/folder/000077500000000000000000000000001345416772700217045ustar00rootroot00000000000000webpack-4.30.0/test/cases/context/issue-801/folder/file.js000066400000000000000000000005771345416772700231720ustar00rootroot00000000000000module.exports = function(arg) { try { var a = require(arg + ".js"); } catch(e) {} try { var b = require("" + arg + ".js"); } catch(e) {} try { var c = require("./" + arg + ".js"); } catch(e) {} try { var d = require("./" + arg); } catch(e) {} return {a: typeof a === "function", b: typeof b === "function", c: typeof c === "function", d: typeof d === "function"} };webpack-4.30.0/test/cases/context/issue-801/index.js000066400000000000000000000006521345416772700221010ustar00rootroot00000000000000it("should emit valid code for dynamic require string with expr", function() { var test = require("./folder/file"); expect(test("file")).toEqual({ a: false, b: false, c: true, d: true }); expect(test("file.js")).toEqual({ a: false, b: false, c: false, d: true }); expect(test("./file")).toEqual({ a: true, b: true, c: false, d: false }); expect(test("./file.js")).toEqual({ a: false, b: false, c: false, d: false }); }); webpack-4.30.0/test/cases/errors/000077500000000000000000000000001345416772700166235ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/case-sensitive/000077500000000000000000000000001345416772700215455ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/case-sensitive/a.js000066400000000000000000000000001345416772700223110ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/case-sensitive/b/000077500000000000000000000000001345416772700217665ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/case-sensitive/b/file.js000066400000000000000000000000001345416772700232310ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/case-sensitive/index.js000066400000000000000000000003611345416772700232120ustar00rootroot00000000000000it("should return different modules with different casing", function() { var a = require("./a"); var A = require("./A"); var b = require("./b/file.js"); var B = require("./B/file.js"); expect(a).not.toBe(A); expect(b).not.toBe(B); }); webpack-4.30.0/test/cases/errors/case-sensitive/test.filter.js000066400000000000000000000002331345416772700243440ustar00rootroot00000000000000var fs = require("fs"); var path = require("path"); module.exports = function(config) { return fs.existsSync(path.join(__dirname, "TEST.FILTER.JS")); }; webpack-4.30.0/test/cases/errors/case-sensitive/warnings.js000066400000000000000000000004151345416772700237330ustar00rootroot00000000000000module.exports = [ [/There are multiple modules with names that only differ in casing/, /case-sensitive.A\.js/, /case-sensitive.a\.js/], [/There are multiple modules with names that only differ in casing/, /case-sensitive.B.file\.js/, /case-sensitive.b.file\.js/] ]; webpack-4.30.0/test/cases/errors/crash-missing-import/000077500000000000000000000000001345416772700227025ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/crash-missing-import/a.js000066400000000000000000000000451345416772700234570ustar00rootroot00000000000000import { x } from "./missing"; x(); webpack-4.30.0/test/cases/errors/crash-missing-import/errors.js000066400000000000000000000000551345416772700245540ustar00rootroot00000000000000module.exports = [ [/Module not found/], ]; webpack-4.30.0/test/cases/errors/crash-missing-import/index.js000066400000000000000000000001411345416772700243430ustar00rootroot00000000000000it("should not crash when imported module is missing", function() { }); require.include("./a"); webpack-4.30.0/test/cases/errors/harmony-import-missing/000077500000000000000000000000001345416772700232575ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/harmony-import-missing/a.js000066400000000000000000000000321345416772700240300ustar00rootroot00000000000000export var test = "test"; webpack-4.30.0/test/cases/errors/harmony-import-missing/errors.js000066400000000000000000000000731345416772700251310ustar00rootroot00000000000000module.exports = [ [ /Can't resolve '.\/missing'/ ] ]; webpack-4.30.0/test/cases/errors/harmony-import-missing/index.js000066400000000000000000000002051345416772700247210ustar00rootroot00000000000000it("should not crash on importing missing modules", function() { expect(function() { require("./module"); }).toThrowError(); }); webpack-4.30.0/test/cases/errors/harmony-import-missing/module.js000066400000000000000000000000601345416772700250760ustar00rootroot00000000000000export * from "./missing"; export * from "./a"; webpack-4.30.0/test/cases/errors/loader-error-warning/000077500000000000000000000000001345416772700226635ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/loader-error-warning/a.js000066400000000000000000000000001345416772700234270ustar00rootroot00000000000000webpack-4.30.0/test/cases/errors/loader-error-warning/error-loader.js000066400000000000000000000001351345416772700256150ustar00rootroot00000000000000module.exports = function(source) { this.emitError(this.query.substr(1)); return source; } webpack-4.30.0/test/cases/errors/loader-error-warning/errors.js000066400000000000000000000003051345416772700245330ustar00rootroot00000000000000module.exports = [ [ /abc/, /Emitted value instead of an instance of Error/, /error-loader\.js/ ], [ /def/, /Emitted value instead of an instance of Error/, /error-loader\.js/ ] ]; webpack-4.30.0/test/cases/errors/loader-error-warning/index.js000066400000000000000000000002611345416772700243270ustar00rootroot00000000000000it("should emit the correct errors and warnings", function() { require("./error-loader?abc!./a"); require("./error-loader?def!./a"); require("./warning-loader?xyz!./a"); }); webpack-4.30.0/test/cases/errors/loader-error-warning/warning-loader.js000066400000000000000000000001371345416772700261330ustar00rootroot00000000000000module.exports = function(source) { this.emitWarning(this.query.substr(1)); return source; } webpack-4.30.0/test/cases/errors/loader-error-warning/warnings.js000066400000000000000000000001571345416772700250540ustar00rootroot00000000000000module.exports = [ [ /xyz/, /Emitted value instead of an instance of Error/, /warning-loader\.js/ ] ]; webpack-4.30.0/test/cases/json/000077500000000000000000000000001345416772700162605ustar00rootroot00000000000000webpack-4.30.0/test/cases/json/data/000077500000000000000000000000001345416772700171715ustar00rootroot00000000000000webpack-4.30.0/test/cases/json/data/a.json000066400000000000000000000000051345416772700202770ustar00rootroot00000000000000null webpack-4.30.0/test/cases/json/data/b.json000066400000000000000000000000041345416772700202770ustar00rootroot00000000000000123 webpack-4.30.0/test/cases/json/data/c.json000066400000000000000000000000151345416772700203020ustar00rootroot00000000000000[1, 2, 3, 4] webpack-4.30.0/test/cases/json/data/d.json000066400000000000000000000000031345416772700203000ustar00rootroot00000000000000{} webpack-4.30.0/test/cases/json/data/e.json000066400000000000000000000000451345416772700203070ustar00rootroot00000000000000{ "1": "x", "bb": 2, "aa": 1 } webpack-4.30.0/test/cases/json/data/f.json000066400000000000000000000001051345416772700203050ustar00rootroot00000000000000{ "named": "named", "default": "default", "__esModule": true } webpack-4.30.0/test/cases/json/data/g.json000066400000000000000000000000221345416772700203040ustar00rootroot00000000000000{ "named": {} } webpack-4.30.0/test/cases/json/data/index.js000066400000000000000000000005371345416772700206430ustar00rootroot00000000000000it("should require json via require", function() { expect({ data: require("./a.json") }).toEqual({ data: null }); expect({ data: require("./b.json") }).toEqual({ data: 123 }); expect({ data: require("./c.json") }).toEqual({ data: [1, 2, 3, 4] }); expect({ data: require("./e.json") }).toEqual({ data: { "aa": 1, "bb": 2, "1": "x" } }); }); webpack-4.30.0/test/cases/json/import-by-name-with-concatenation/000077500000000000000000000000001345416772700247145ustar00rootroot00000000000000webpack-4.30.0/test/cases/json/import-by-name-with-concatenation/index.js000066400000000000000000000000341345416772700263560ustar00rootroot00000000000000import "../import-by-name"; webpack-4.30.0/test/cases/json/import-by-name/000077500000000000000000000000001345416772700211205ustar00rootroot00000000000000webpack-4.30.0/test/cases/json/import-by-name/index.js000066400000000000000000000010471345416772700225670ustar00rootroot00000000000000import * as c from "../data/c.json"; import * as d from "../data/d.json"; import { bb, aa } from "../data/e.json"; import f, { named } from "../data/f.json"; import g, { named as gnamed } from "../data/g.json"; it("should be possible to import json data", function() { expect(c[2]).toBe(3); expect(Object.keys(d)).toEqual(["default"]); expect(aa).toBe(1); expect(bb).toBe(2); expect(named).toBe("named"); (expect({ f })).toEqual({ f: { __esModule: true, default: "default", named: "named" } }); expect(g.named).toBe(gnamed); }); webpack-4.30.0/test/cases/json/import-lazy/000077500000000000000000000000001345416772700205475ustar00rootroot00000000000000webpack-4.30.0/test/cases/json/import-lazy/index.js000066400000000000000000000017011345416772700222130ustar00rootroot00000000000000 it("should be possible to import json data async", function() { return Promise.all([ import("../data/a.json"), import("../data/b.json"), import("../data/c.json"), import("../data/d.json"), import("../data/e.json"), import("../data/f.json"), import("../data/g.json") ]).then(([a, b, c, d, e, f, g]) => { expect(a).toEqual(nsObj({ default: null })); expect(b).toEqual(nsObj({ default: 123 })); expect(c).toEqual(nsObj({ 0: 1, 1: 2, 2: 3, 3: 4, default: [1, 2, 3, 4] })); expect(d).toEqual(nsObj({ default: {} })); expect(e).toEqual(nsObj({ aa: 1, bb: 2, 1: "x", default: { aa: 1, bb: 2, "1": "x" } })); expect(f).toEqual(nsObj({ named: "named", default: { named: "named", "default": "default", __esModule: true } })); expect(g).toEqual(nsObj({ named: {}, default: { named: {} } })); expect(g.named).toBe(g.default.named); }); }); webpack-4.30.0/test/cases/json/import-with-default-with-concatenation/000077500000000000000000000000001345416772700257615ustar00rootroot00000000000000webpack-4.30.0/test/cases/json/import-with-default-with-concatenation/index.js000066400000000000000000000000411345416772700274210ustar00rootroot00000000000000import "../import-with-default"; webpack-4.30.0/test/cases/json/import-with-default/000077500000000000000000000000001345416772700221655ustar00rootroot00000000000000webpack-4.30.0/test/cases/json/import-with-default/index.js000066400000000000000000000007761345416772700236440ustar00rootroot00000000000000import a from "../data/a.json"; import b from "../data/b.json"; import c from "../data/c.json"; import d from "../data/d.json"; import e from "../data/e.json"; import f from "../data/f.json"; it("should be possible to import json data", function() { expect({a}).toEqual({a: null}); expect(b).toBe(123); expect(c).toEqual([1, 2, 3, 4]); expect(d).toEqual({}); expect(e).toEqual({ aa: 1, bb: 2, "1": "x" }); expect(f).toEqual({ named: "named", "default": "default", __esModule: true }); }); webpack-4.30.0/test/cases/loaders/000077500000000000000000000000001345416772700167405ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/_css/000077500000000000000000000000001345416772700176675ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/_css/folder/000077500000000000000000000000001345416772700211425ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/_css/folder/stylesheet-import1.css000066400000000000000000000002471345416772700254410ustar00rootroot00000000000000@import url(~resources-module/stylesheet-import2.css) print, screen; @import url(stylesheet-import3.css) print and screen; .rule-import1 { background: lightgreen; } webpack-4.30.0/test/cases/loaders/_css/folder/stylesheet-import3.css000066400000000000000000000000561345416772700254410ustar00rootroot00000000000000.rule-import2 { background: red !important; }webpack-4.30.0/test/cases/loaders/_css/generateCss.js000066400000000000000000000003341345416772700224700ustar00rootroot00000000000000var fs = require("fs"); var path = require("path"); module.exports = function() { return { code: fs.readFileSync(path.join(path.dirname(__filename), "stylesheet.css"), "utf-8") + "\n.generated { color: red; }" }; }; webpack-4.30.0/test/cases/loaders/_css/node_modules/000077500000000000000000000000001345416772700223445ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/_css/node_modules/resources-module/000077500000000000000000000000001345416772700256415ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/_css/node_modules/resources-module/import2.less000066400000000000000000000000571345416772700301270ustar00rootroot00000000000000.less-rule-import2 { background: lightgreen; }webpack-4.30.0/test/cases/loaders/_css/node_modules/resources-module/stylesheet-import2.css000066400000000000000000000000521345416772700321330ustar00rootroot00000000000000.rule-import2 { background: lightgreen; }webpack-4.30.0/test/cases/loaders/_css/stylesheet.css000066400000000000000000000001261345416772700225710ustar00rootroot00000000000000@import url(folder/stylesheet-import1.css); .rule-direct { background: lightgreen; }webpack-4.30.0/test/cases/loaders/_resources/000077500000000000000000000000001345416772700211115ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/_resources/abc.txt000066400000000000000000000000031345416772700223700ustar00rootroot00000000000000abcwebpack-4.30.0/test/cases/loaders/_resources/included.pug000066400000000000000000000000131345416772700234070ustar00rootroot00000000000000h1 includedwebpack-4.30.0/test/cases/loaders/_resources/parent.pug000066400000000000000000000000421345416772700231130ustar00rootroot00000000000000p block content include included webpack-4.30.0/test/cases/loaders/_resources/script.coffee000066400000000000000000000001251345416772700235640ustar00rootroot00000000000000condition = true obj = text: "coffee test" module.exports = obj.text if condition?webpack-4.30.0/test/cases/loaders/_resources/template.pug000066400000000000000000000001251345416772700234370ustar00rootroot00000000000000extends parent block content = typeof abc === "undefined" ? "self" + self.abc : abcwebpack-4.30.0/test/cases/loaders/async/000077500000000000000000000000001345416772700200555ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/async/a.js000066400000000000000000000000251345416772700206300ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/loaders/async/index.js000066400000000000000000000016041345416772700215230ustar00rootroot00000000000000it("should allow combinations of async and sync loaders", function() { expect(require("./loaders/syncloader!./a")).toBe("a"); expect(require("./loaders/asyncloader!./a")).toBe("a"); expect(require("./loaders/syncloader!./loaders/syncloader!./a")).toBe("a"); expect(require("./loaders/syncloader!./loaders/asyncloader!./a")).toBe("a"); expect(require("./loaders/asyncloader!./loaders/syncloader!./a")).toBe("a"); expect(require("./loaders/asyncloader!./loaders/asyncloader!./a")).toBe("a"); expect(require("./loaders/asyncloader!./loaders/asyncloader!./loaders/asyncloader!./a")).toBe("a"); expect(require("./loaders/asyncloader!./loaders/syncloader!./loaders/asyncloader!./a")).toBe("a"); expect(require("./loaders/syncloader!./loaders/asyncloader!./loaders/syncloader!./a")).toBe("a"); expect(require("./loaders/syncloader!./loaders/syncloader!./loaders/syncloader!./a")).toBe("a"); }); webpack-4.30.0/test/cases/loaders/async/loaders/000077500000000000000000000000001345416772700215065ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/async/loaders/asyncloader.js000066400000000000000000000004321345416772700243470ustar00rootroot00000000000000module.exports = function(content) { var cb = this.async(); if(!cb) throw new Error("Loader should allow async mode"); if(cb !== this.callback) throw new Error("result of this.async() should be equal to this.callback"); process.nextTick(function() { cb(null, content); }); };webpack-4.30.0/test/cases/loaders/async/loaders/syncloader.js000066400000000000000000000000701345416772700242040ustar00rootroot00000000000000module.exports = function(content) { return content; };webpack-4.30.0/test/cases/loaders/coffee-loader/000077500000000000000000000000001345416772700214335ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/coffee-loader/index.js000066400000000000000000000007701345416772700231040ustar00rootroot00000000000000it("should handle the coffee loader correctly", function() { expect(require("!coffee-loader!../_resources/script.coffee")).toBe("coffee test"); expect(require("../_resources/script.coffee")).toBe("coffee test"); }); it("should handle literate coffee script correctly", function() { expect(require("!coffee-loader?literate!./script.coffee.md")).toBe("literate coffee test"); }); it("should generate valid code with cheap-source-map", function() { require("!coffee-loader!./module-only.coffee"); }); webpack-4.30.0/test/cases/loaders/coffee-loader/module-only.coffee000066400000000000000000000000061345416772700250440ustar00rootroot00000000000000modulewebpack-4.30.0/test/cases/loaders/coffee-loader/script.coffee.md000066400000000000000000000003521345416772700245070ustar00rootroot00000000000000# literate coffeescript test Set some `condition` to `true condition = true Create an object with some text obj = text: "literate coffee test" Export the text if the condition is true module.exports = obj.text if condition?webpack-4.30.0/test/cases/loaders/context/000077500000000000000000000000001345416772700204245ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/context/index.js000066400000000000000000000003661345416772700220760ustar00rootroot00000000000000it("should be able to use a context with a loader", function() { var abc = "abc", scr = "script.coffee"; expect(require("../_resources/" + scr)).toBe("coffee test"); expect(require("raw-loader!../_resources/" + abc + ".txt")).toBe("abc"); }); webpack-4.30.0/test/cases/loaders/css-loader/000077500000000000000000000000001345416772700207745ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/css-loader/index.js000066400000000000000000000006371345416772700224470ustar00rootroot00000000000000it("should handle the css loader correctly", function() { expect( (require("!css-loader!../_css/stylesheet.css") + "").indexOf(".rule-direct") ).not.toEqual(-1); expect( (require("!css-loader!../_css/stylesheet.css") + "").indexOf(".rule-import1") ).not.toEqual(-1); expect( (require("!css-loader!../_css/stylesheet.css") + "").indexOf(".rule-import2") ).not.toEqual(-1); }); webpack-4.30.0/test/cases/loaders/issue-2299/000077500000000000000000000000001345416772700204735ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/issue-2299/a.data000066400000000000000000000001431345416772700215440ustar00rootroot00000000000000{ "imports": [ "./subdir_1/b.json", "./subdir_2/c.json" ], "a": true } webpack-4.30.0/test/cases/loaders/issue-2299/index.js000066400000000000000000000004311345416772700221360ustar00rootroot00000000000000it("should be able to use loadModule multiple times within a loader, on files in different directories", function() { const data = require("!./loader/index.js!./a.data"); expect(data).toHaveProperty("a"); expect(data).toHaveProperty("b"); expect(data).toHaveProperty("c"); }); webpack-4.30.0/test/cases/loaders/issue-2299/loader/000077500000000000000000000000001345416772700217415ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/issue-2299/loader/index.js000066400000000000000000000012131345416772700234030ustar00rootroot00000000000000var asyncLib = require("neo-async"); module.exports = function(content) { var cb = this.async(); var json = JSON.parse(content); asyncLib.mapSeries( json.imports, function(url, callback) { this.loadModule(url, function(err, source, map, module) { if(err) { return callback(err); } callback(null, JSON.parse(source)); }); }.bind(this), function(err, results) { if(err) { return cb(err); } // Combine all the results into one object and return it cb(null, "module.exports = " + JSON.stringify(results.reduce(function(prev, result) { return Object.assign({}, prev, result); }, json))); } ); }; webpack-4.30.0/test/cases/loaders/issue-2299/subdir_1/000077500000000000000000000000001345416772700222035ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/issue-2299/subdir_1/b.json000066400000000000000000000000221345416772700233110ustar00rootroot00000000000000{ "b": true } webpack-4.30.0/test/cases/loaders/issue-2299/subdir_2/000077500000000000000000000000001345416772700222045ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/issue-2299/subdir_2/c.json000066400000000000000000000000221345416772700233130ustar00rootroot00000000000000{ "c": true } webpack-4.30.0/test/cases/loaders/issue-4959/000077500000000000000000000000001345416772700205005ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/issue-4959/a.js000066400000000000000000000000261345416772700212540ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/cases/loaders/issue-4959/b.js000066400000000000000000000000371345416772700212570ustar00rootroot00000000000000module.exports = require("c"); webpack-4.30.0/test/cases/loaders/issue-4959/c.js000066400000000000000000000000261345416772700212560ustar00rootroot00000000000000module.exports = "c"; webpack-4.30.0/test/cases/loaders/issue-4959/index.js000066400000000000000000000001701345416772700221430ustar00rootroot00000000000000it("should resolve module dependencies recursively", function() { expect(require("!./loaders/index!a")).toBe("c"); }); webpack-4.30.0/test/cases/loaders/issue-4959/loaders/000077500000000000000000000000001345416772700221315ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/issue-4959/loaders/index.js000066400000000000000000000003161345416772700235760ustar00rootroot00000000000000module.exports = function() { var callback = this.async(); this.loadModule("b", function(error) { if (error) { return callback(error); } callback(null, "module.exports = require('b');"); }); }; webpack-4.30.0/test/cases/loaders/issue-4959/package.json000066400000000000000000000001071345416772700227640ustar00rootroot00000000000000{ "browser": { "a": "./a.js", "b": "./b.js", "c": "./c.js" } } webpack-4.30.0/test/cases/loaders/json-loader/000077500000000000000000000000001345416772700211555ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/json-loader/index.js000066400000000000000000000006411345416772700226230ustar00rootroot00000000000000it("should be able to load JSON files without loader", function() { var someJson = require("./some.json"); expect(someJson).toHaveProperty("it", "works"); expect(someJson).toHaveProperty("number", 42); }); it("should also work when the json extension is omitted", function() { var someJson = require("./some"); expect(someJson).toHaveProperty("it", "works"); expect(someJson).toHaveProperty("number", 42); }); webpack-4.30.0/test/cases/loaders/json-loader/some.json000066400000000000000000000000441345416772700230110ustar00rootroot00000000000000{ "it": "works", "number": 42 } webpack-4.30.0/test/cases/loaders/less-loader/000077500000000000000000000000001345416772700211525ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/less-loader/index.js000066400000000000000000000007261345416772700226240ustar00rootroot00000000000000it("should handle the less loader (piped with raw loader) correctly", function() { expect( require("!raw-loader!less-loader!./less/stylesheet.less").indexOf(".less-rule-direct") ).not.toEqual(-1); expect( require("!raw-loader!less-loader!./less/stylesheet.less").indexOf(".less-rule-import1") ).not.toEqual(-1); expect( require("!raw-loader!less-loader!./less/stylesheet.less").indexOf(".less-rule-import2") ).not.toEqual(-1); }); webpack-4.30.0/test/cases/loaders/less-loader/less/000077500000000000000000000000001345416772700221205ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/less-loader/less/folder/000077500000000000000000000000001345416772700233735ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/less-loader/less/folder/import1.less000066400000000000000000000001751345416772700256610ustar00rootroot00000000000000@import "~resources-module/import2.less"; .less-rule-import1 { background: lightgreen; background-image: url("url.js"); } webpack-4.30.0/test/cases/loaders/less-loader/less/folder/url.js000066400000000000000000000000001345416772700245210ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/less-loader/less/stylesheet.less000066400000000000000000000001111345416772700251720ustar00rootroot00000000000000@import "folder/import1"; .less-rule-direct { background: lightgreen; }webpack-4.30.0/test/cases/loaders/less-loader/node_modules/000077500000000000000000000000001345416772700236275ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/less-loader/node_modules/resources-module/000077500000000000000000000000001345416772700271245ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/less-loader/node_modules/resources-module/import2.less000066400000000000000000000000571345416772700314120ustar00rootroot00000000000000.less-rule-import2 { background: lightgreen; }webpack-4.30.0/test/cases/loaders/less-loader/node_modules/resources-module/stylesheet-import2.css000066400000000000000000000000521345416772700334160ustar00rootroot00000000000000.rule-import2 { background: lightgreen; }webpack-4.30.0/test/cases/loaders/module-description-file/000077500000000000000000000000001345416772700234635ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/module-description-file/index.js000066400000000000000000000012701345416772700251300ustar00rootroot00000000000000it("should run a loader from package.json", function() { expect(require("testloader!../_resources/abc.txt")).toBe("abcwebpack"); expect(require("testloader/lib/loader2!../_resources/abc.txt")).toBe("abcweb"); expect(require("testloader/lib/loader3!../_resources/abc.txt")).toBe("abcloader"); expect(require("testloader/lib/loader-indirect!../_resources/abc.txt")).toBe("abcwebpack"); }); it("should run a loader from .webpack-loader.js extension", function() { expect(require("testloader/lib/loader!../_resources/abc.txt")).toBe("abcwebpack"); }); it("should be able to pipe loaders", function() { expect(require("testloader!./reverseloader!../_resources/abc.txt")).toBe("cbawebpack"); }); webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/000077500000000000000000000000001345416772700261405ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/000077500000000000000000000000001345416772700303065ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/lib/000077500000000000000000000000001345416772700310545ustar00rootroot00000000000000loader-indirect.js000066400000000000000000000000671345416772700344030ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/libmodule.exports = require("./loader.webpack-loader.js");webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/lib/loader.js000066400000000000000000000002011345416772700326510ustar00rootroot00000000000000module.exports = function(content) { var content = contents[0]; callback(null, "module.exports=" + JSON.stringify(content)); } loader.webpack-loader.js000066400000000000000000000001461345416772700354610ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/libmodule.exports = function(content) { return "module.exports=" + JSON.stringify(content+"webpack"); } loader2.web-loader.js000066400000000000000000000001601345416772700347000ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/libmodule.exports = function(content) { this.callback(null, "module.exports=" + JSON.stringify(content+"web")); } loader3.loader.js000066400000000000000000000002141345416772700341260ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/libmodule.exports = function(content) { var callback = this.async(); callback(null, "module.exports=" + JSON.stringify(content+"loader")); } webpack-4.30.0/test/cases/loaders/module-description-file/node_modules/testloader/package.json000066400000000000000000000001131345416772700325670ustar00rootroot00000000000000{ "name": "testloader", "webpackLoader": "lib/loader.webpack-loader.js" }webpack-4.30.0/test/cases/loaders/module-description-file/reverseloader.js000066400000000000000000000001251345416772700266610ustar00rootroot00000000000000module.exports = function(content) { return content.split("").reverse().join(""); } webpack-4.30.0/test/cases/loaders/no-string/000077500000000000000000000000001345416772700206605ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/no-string/errors.js000066400000000000000000000010221345416772700225250ustar00rootroot00000000000000module.exports = [ [ /\.\/loaders\/no-string\/file\.js \(\.\/loaders\/no-string\/loader\.js!\.\/loaders\/no-string\/file\.js\)/, /Module build failed: Error: Final loader \(\.\/loaders\/no-string\/loader\.js\) didn't return a Buffer or String/ ], [ /\.\/loaders\/no-string\/file\.js \(\.\/loaders\/no-string\/loader\.js!\.\/loaders\/no-string\/pitch-loader\.js!\.\/loaders\/no-string\/file\.js\)/, /Module build failed: Error: Final loader \(\.\/loaders\/no-string\/loader\.js\) didn't return a Buffer or String/ ] ]; webpack-4.30.0/test/cases/loaders/no-string/file.js000066400000000000000000000000041345416772700221270ustar00rootroot00000000000000123 webpack-4.30.0/test/cases/loaders/no-string/index.js000066400000000000000000000004461345416772700223310ustar00rootroot00000000000000it("should emit the correct error for loaders not returning buffer or string", function() { expect(() => require("./loader.js!./file.js")).toThrowError( /Module build failed/ ); expect(() => require("./loader.js!./pitch-loader.js!./file.js")).toThrowError( /Module build failed/ ); }); webpack-4.30.0/test/cases/loaders/no-string/loader.js000066400000000000000000000000511345416772700224600ustar00rootroot00000000000000module.exports = () => { return 123; }; webpack-4.30.0/test/cases/loaders/no-string/pitch-loader.js000066400000000000000000000000511345416772700235650ustar00rootroot00000000000000module.exports = () => { return 123; }; webpack-4.30.0/test/cases/loaders/pug-loader/000077500000000000000000000000001345416772700207775ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/pug-loader/index.js000066400000000000000000000004331345416772700224440ustar00rootroot00000000000000it("should handle the pug loader correctly", function() { expect(require("!pug-loader?self!../_resources/template.pug")({ abc: "abc" })).toBe("

    selfabc

    included

    "); expect(require("../_resources/template.pug")({ abc: "abc" })).toBe("

    abc

    included

    "); }); webpack-4.30.0/test/cases/loaders/query/000077500000000000000000000000001345416772700201055ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/query/a.js000066400000000000000000000000251345416772700206600ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/loaders/query/context-query-test/000077500000000000000000000000001345416772700237115ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/query/context-query-test/test.js000066400000000000000000000000141345416772700252210ustar00rootroot00000000000000test contentwebpack-4.30.0/test/cases/loaders/query/index.js000066400000000000000000000026411345416772700215550ustar00rootroot00000000000000it("should pass query to loader", function() { var result = require("./loaders/queryloader?query!./a?resourcequery"); expect(result).toEqual({ resourceQuery: "?resourcequery", query: "?query", prev: "module.exports = \"a\";" }); }); it("should pass query to loader without resource with resource query", function() { var result = require("./loaders/queryloader?query!?resourcequery"); expect(result).toEqual({ resourceQuery: "?resourcequery", query: "?query", prev: null }); }); it("should pass query to loader without resource", function() { var result = require("./loaders/queryloader?query!"); expect(result).toEqual({ query: "?query", prev: null }); }); it("should pass query to multiple loaders", function() { var result = require("./loaders/queryloader?query1!./loaders/queryloader?query2!./a?resourcequery"); expect(result).toBeTypeOf("object"); expect(result).toHaveProperty("resourceQuery", "?resourcequery"); expect(result).toHaveProperty("query", "?query1"); expect(result).toHaveProperty("prev", "module.exports = " + JSON.stringify({ resourceQuery: "?resourcequery", query: "?query2", prev: "module.exports = \"a\";" })); }); it("should pass query to loader over context", function() { var test = "test"; var result = require("./loaders/queryloader?query!./context-query-test/" + test); expect(result).toEqual({ resourceQuery: "", query: "?query", prev: "test content" }); }); webpack-4.30.0/test/cases/loaders/query/loaders/000077500000000000000000000000001345416772700215365ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/query/loaders/queryloader.js000066400000000000000000000002451345416772700244310ustar00rootroot00000000000000module.exports = function(content) { return "module.exports = " + JSON.stringify({ resourceQuery: this.resourceQuery, query: this.query, prev: content }); } webpack-4.30.0/test/cases/loaders/raw-loader/000077500000000000000000000000001345416772700207755ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/raw-loader/index.js000066400000000000000000000002001345416772700224320ustar00rootroot00000000000000it("should handle the raw loader correctly", function() { expect(require("raw-loader!../_resources/abc.txt")).toBe("abc"); }); webpack-4.30.0/test/cases/loaders/resolve/000077500000000000000000000000001345416772700204175ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/resolve/index.js000066400000000000000000000002711345416772700220640ustar00rootroot00000000000000it("should be possible to create resolver with different options", () => { const result = require("./loader!"); expect(result).toEqual({ one: "index.js", two: "index.xyz" }); }) webpack-4.30.0/test/cases/loaders/resolve/index.xyz000066400000000000000000000000001345416772700222700ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/resolve/loader.js000066400000000000000000000006221345416772700222230ustar00rootroot00000000000000const path = require("path"); module.exports = function() { const resolve1 = this.getResolve(); const resolve2 = this.getResolve({ extensions: [".xyz", ".js"] }); return Promise.all([ resolve1(__dirname, "./index"), resolve2(__dirname, "./index") ]).then(([one, two]) => { return `module.exports = ${JSON.stringify({ one: path.basename(one), two: path.basename(two), })}`; }); }; webpack-4.30.0/test/cases/loaders/val-loader/000077500000000000000000000000001345416772700207665ustar00rootroot00000000000000webpack-4.30.0/test/cases/loaders/val-loader/index.js000066400000000000000000000007101345416772700224310ustar00rootroot00000000000000it("should handle the val loader (piped with css loader) correctly", function() { expect( (require("!css-loader!val-loader!../_css/generateCss") + "").indexOf("generated") ).not.toEqual(-1); expect( (require("!css-loader!val-loader!../_css/generateCss") + "").indexOf(".rule-import2") ).not.toEqual(-1); expect( (require("!raw-loader!val-loader!../_css/generateCss") + "").indexOf("generated") ).not.toEqual(-1); }); webpack-4.30.0/test/cases/mjs/000077500000000000000000000000001345416772700161005ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/cjs-import-default/000077500000000000000000000000001345416772700216115ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/cjs-import-default/cjs.js000066400000000000000000000000671345416772700227310ustar00rootroot00000000000000module.exports = { data: "ok", default: "default" }; webpack-4.30.0/test/cases/mjs/cjs-import-default/errors.js000066400000000000000000000012601345416772700234620ustar00rootroot00000000000000module.exports = [ [ /Can't import the namespace object from non EcmaScript module \(only default export is available\)/ ], [ /Can't import the namespace object from non EcmaScript module \(only default export is available\)/ ], [ /Can't import the named export 'data' from non EcmaScript module \(only default export is available\)/ ], [ /Can't import the named export 'data' from non EcmaScript module \(only default export is available\)/ ], [ /Can't reexport the namespace object from non EcmaScript module \(only default export is available\)/ ], [ /Can't reexport the named export 'data' from non EcmaScript module \(only default export is available\)/ ] ]; webpack-4.30.0/test/cases/mjs/cjs-import-default/index.mjs000066400000000000000000000024741345416772700234420ustar00rootroot00000000000000import { data } from "./cjs.js"; import * as star from "./cjs.js"; import def from "./cjs.js"; import { ns, default as def1, def as def2, data as data2 } from "./reexport.mjs"; import * as reexport from "./reexport.mjs"; it("should get correct values when importing named exports from a CommonJs module from mjs", function() { expect(typeof data).toBe("undefined"); expect({ data }).toEqual({ data: undefined }); expect(def).toEqual({ data: "ok", default: "default" }); expect({ def }).toEqual({ def: { data: "ok", default: "default" } }); expect(star).toEqual(nsObj({ default: { data: "ok", default: "default" } })); expect({ star }).toEqual({ star: nsObj({ default: { data: "ok", default: "default" } }) }); expect(star.default).toEqual({ data: "ok", default: "default" }); expect(ns).toEqual(nsObj({ default: { data: "ok", default: "default" } })); expect(def1).toEqual({ data: "ok", default: "default" }); expect(def2).toEqual({ data: "ok", default: "default" }); expect((typeof data2)).toBe("undefined"); expect(reexport).toEqual(nsObj({ ns: nsObj({ default: { data: "ok", default: "default" } }), default: { data: "ok", default: "default" }, def: { data: "ok", default: "default" }, data: undefined })); }); webpack-4.30.0/test/cases/mjs/cjs-import-default/reexport.mjs000066400000000000000000000002471345416772700241770ustar00rootroot00000000000000import * as ns from "./cjs.js"; export { ns }; export { default } from "./cjs.js"; export { default as def } from "./cjs.js"; export { data as data } from "./cjs.js"; webpack-4.30.0/test/cases/mjs/esm-by-default/000077500000000000000000000000001345416772700207165ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/esm-by-default/index.mjs000066400000000000000000000006011345416772700225350ustar00rootroot00000000000000it("should not have commonjs stuff available", function() { if(typeof module !== "undefined") { // If module is available expect(module).toHaveProperty("webpackTestSuiteModule"); // it must be the node.js module } if(typeof require !== "undefined") { // If require is available expect(require).toHaveProperty("webpackTestSuiteRequire"); // it must be the node.js require } }); webpack-4.30.0/test/cases/mjs/namespace-object-lazy/000077500000000000000000000000001345416772700222555ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/namespace-object-lazy/cjs-esmodule.js000066400000000000000000000001211345416772700251770ustar00rootroot00000000000000exports.__esModule = true; exports.default = "default"; exports.named = "named"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/cjs.js000066400000000000000000000000661345416772700233740ustar00rootroot00000000000000exports.default = "default"; exports.named = "named"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-cjs/000077500000000000000000000000001345416772700236105ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-cjs/null.js000066400000000000000000000000271345416772700251170ustar00rootroot00000000000000module.exports = null; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-cjs/one.js000066400000000000000000000000661345416772700247310ustar00rootroot00000000000000exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-cjs/three.js000066400000000000000000000000661345416772700252570ustar00rootroot00000000000000exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-cjs/two.js000066400000000000000000000001221345416772700247520ustar00rootroot00000000000000exports.__esModule = true; exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-harmony/000077500000000000000000000000001345416772700245065ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-harmony/one.js000066400000000000000000000000661345416772700256270ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-harmony/three.js000066400000000000000000000000661345416772700261550ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-harmony/two.js000066400000000000000000000000661345416772700256570ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-mixed/000077500000000000000000000000001345416772700241375ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-mixed/json.json000066400000000000000000000000621345416772700260010ustar00rootroot00000000000000{ "default": "default", "named": "named" }webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-mixed/null.js000066400000000000000000000000271345416772700254460ustar00rootroot00000000000000module.exports = null; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-mixed/one.js000066400000000000000000000000661345416772700252600ustar00rootroot00000000000000exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-mixed/three.js000066400000000000000000000000661345416772700256060ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/dir-mixed/two.js000066400000000000000000000001221345416772700253010ustar00rootroot00000000000000exports.__esModule = true; exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/namespace-object-lazy/index.mjs000066400000000000000000000063401345416772700241020ustar00rootroot00000000000000it("should receive a namespace object when importing commonjs", function(done) { import("./cjs.js").then(function(result) { expect(result).toEqual(nsObj({ default: { named: "named", default: "default" } })); done(); }).catch(done); }); it("should receive a namespace object when importing commonjs with __esModule", function(done) { import("./cjs-esmodule.js").then(function(result) { expect(result).toEqual(nsObj({ default: { __esModule: true, named: "named", default: "default" } })); done(); }).catch(done); }); function contextCJS(name) { return Promise.all([ import(`./dir-cjs/${name}.js`), import(/* webpackMode: "lazy-once" */`./dir-cjs?1/${name}.js`), import(/* webpackMode: "eager" */`./dir-cjs?2/${name}.js`) ]).then(function(results) { return import(/* webpackMode: "weak" */`./dir-cjs/${name}.js`).then(function(r) { results.push(r); return results; }); }); } function contextHarmony(name) { return Promise.all([ import(`./dir-harmony/${name}.js`), import(/* webpackMode: "lazy-once" */`./dir-harmony?1/${name}.js`), import(/* webpackMode: "eager" */`./dir-harmony?2/${name}.js`) ]).then(function(results) { return import(/* webpackMode: "weak" */`./dir-harmony/${name}.js`).then(function(r) { results.push(r); return results; }); }); } function contextMixed(name) { return Promise.all([ import(`./dir-mixed/${name}`), import(/* webpackMode: "lazy-once" */`./dir-mixed?1/${name}`), import(/* webpackMode: "eager" */`./dir-mixed?2/${name}`) ]).then(function(results) { return import(/* webpackMode: "weak" */`./dir-mixed/${name}`).then(function(r) { results.push(r); return results; }); }); } function promiseTest(promise, equalsTo) { return promise.then(function(results) { for(const result of results) expect(result).toEqual(equalsTo); }); } it("should receive a namespace object when importing commonjs via context", function() { return Promise.all([ promiseTest(contextCJS("one"), nsObj({ default: { named: "named", default: "default" } })), promiseTest(contextCJS("two"), nsObj({ default: { __esModule: true, named: "named", default: "default" } })), promiseTest(contextCJS("three"), nsObj({ default: { named: "named", default: "default" } })), promiseTest(contextCJS("null"), nsObj({ default: null })) ]); }); it("should receive a namespace object when importing harmony via context", function() { return Promise.all([ promiseTest(contextHarmony("one"), nsObj({ named: "named", default: "default" })), promiseTest(contextHarmony("two"), nsObj({ named: "named", default: "default" })), promiseTest(contextHarmony("three"), nsObj({ named: "named", default: "default" })) ]); }); it("should receive a namespace object when importing mixed content via context", function() { return Promise.all([ promiseTest(contextMixed("one"), nsObj({ default: { named: "named", default: "default" } })), promiseTest(contextMixed("two"), nsObj({ default: { __esModule: true, named: "named", default: "default" } })), promiseTest(contextMixed("three"), nsObj({ named: "named", default: "default" })), promiseTest(contextMixed("null"), nsObj({ default: null })), promiseTest(contextMixed("json.json"), nsObj({ named: "named", default: { named: "named", default: "default" } })) ]); }); webpack-4.30.0/test/cases/mjs/namespace-object-lazy/test.filter.js000066400000000000000000000001011345416772700250460ustar00rootroot00000000000000module.exports = function(config) { return !config.minimize; }; webpack-4.30.0/test/cases/mjs/no-module-main-field/000077500000000000000000000000001345416772700220025ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/no-module-main-field/index.mjs000066400000000000000000000001601345416772700236210ustar00rootroot00000000000000import result from "m"; it("should use the correct entry point", function() { expect(result).toBe("yep"); }); webpack-4.30.0/test/cases/mjs/no-module-main-field/node_modules/000077500000000000000000000000001345416772700244575ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/no-module-main-field/node_modules/m/000077500000000000000000000000001345416772700247135ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/no-module-main-field/node_modules/m/a.js000066400000000000000000000000301345416772700254620ustar00rootroot00000000000000export default "nope1"; webpack-4.30.0/test/cases/mjs/no-module-main-field/node_modules/m/a.mjs000066400000000000000000000000261345416772700256440ustar00rootroot00000000000000export default "yep"; webpack-4.30.0/test/cases/mjs/no-module-main-field/node_modules/m/b.js000066400000000000000000000000301345416772700254630ustar00rootroot00000000000000export default "nope2"; webpack-4.30.0/test/cases/mjs/no-module-main-field/node_modules/m/b.mjs000066400000000000000000000000301345416772700256400ustar00rootroot00000000000000export default "nope3"; webpack-4.30.0/test/cases/mjs/no-module-main-field/node_modules/m/package.json000066400000000000000000000000431345416772700271760ustar00rootroot00000000000000{ "main": "a", "module": "b" } webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/000077500000000000000000000000001345416772700236345ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/cjs-esmodule.js000066400000000000000000000001211345416772700265560ustar00rootroot00000000000000exports.__esModule = true; exports.default = "default"; exports.named = "named"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/cjs.js000066400000000000000000000000661345416772700247530ustar00rootroot00000000000000exports.default = "default"; exports.named = "named"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-cjs/000077500000000000000000000000001345416772700251675ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-cjs/null.js000066400000000000000000000000271345416772700264760ustar00rootroot00000000000000module.exports = null; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-cjs/one.js000066400000000000000000000000661345416772700263100ustar00rootroot00000000000000exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-cjs/three.js000066400000000000000000000000661345416772700266360ustar00rootroot00000000000000exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-cjs/two.js000066400000000000000000000001221345416772700263310ustar00rootroot00000000000000exports.__esModule = true; exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-harmony/000077500000000000000000000000001345416772700260655ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-harmony/one.js000066400000000000000000000000661345416772700272060ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-harmony/three.js000066400000000000000000000000661345416772700275340ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-harmony/two.js000066400000000000000000000000661345416772700272360ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-mixed/000077500000000000000000000000001345416772700255165ustar00rootroot00000000000000webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-mixed/json.json000066400000000000000000000000621345416772700273600ustar00rootroot00000000000000{ "default": "default", "named": "named" }webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-mixed/null.js000066400000000000000000000000271345416772700270250ustar00rootroot00000000000000module.exports = null; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-mixed/one.js000066400000000000000000000000661345416772700266370ustar00rootroot00000000000000exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-mixed/three.js000066400000000000000000000000661345416772700271650ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/dir-mixed/two.js000066400000000000000000000001221345416772700266600ustar00rootroot00000000000000exports.__esModule = true; exports.named = "named"; exports.default = "default"; webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/index.js000066400000000000000000000063061345416772700253060ustar00rootroot00000000000000it("should receive a namespace object when importing commonjs", function(done) { import("./cjs").then(function(result) { expect(result).toEqual(nsObj({ named: "named", default: { named: "named", default: "default" } })); done(); }).catch(done); }); it("should receive a namespace object when importing commonjs with __esModule", function(done) { import("./cjs-esmodule").then(function(result) { expect(result).toEqual({ __esModule: true, named: "named", default: "default" }); done(); }).catch(done); }); function contextCJS(name) { return Promise.all([ import(`./dir-cjs/${name}`), import(/* webpackMode: "lazy-once" */`./dir-cjs?1/${name}`), import(/* webpackMode: "eager" */`./dir-cjs?2/${name}`) ]).then(function(results) { return import(/* webpackMode: "weak" */`./dir-cjs/${name}`).then(function(r) { results.push(r); return results; }); }); } function contextHarmony(name) { return Promise.all([ import(`./dir-harmony/${name}`), import(/* webpackMode: "lazy-once" */`./dir-harmony?1/${name}`), import(/* webpackMode: "eager" */`./dir-harmony?2/${name}`) ]).then(function(results) { return import(/* webpackMode: "weak" */`./dir-harmony/${name}`).then(function(r) { results.push(r); return results; }); }); } function contextMixed(name) { return Promise.all([ import(`./dir-mixed/${name}`), import(/* webpackMode: "lazy-once" */`./dir-mixed?1/${name}`), import(/* webpackMode: "eager" */`./dir-mixed?2/${name}`) ]).then(function(results) { return import(/* webpackMode: "weak" */`./dir-mixed/${name}`).then(function(r) { results.push(r); return results; }); }); } function promiseTest(promise, equalsTo) { return promise.then(function(results) { for(const result of results) expect(result).toEqual(equalsTo); }); } it("should receive a namespace object when importing commonjs via context", function() { return Promise.all([ promiseTest(contextCJS("one"), nsObj({ named: "named", default: { named: "named", default: "default" } })), promiseTest(contextCJS("two"), { __esModule: true, named: "named", default: "default" }), promiseTest(contextCJS("three"), nsObj({ named: "named", default: { named: "named", default: "default" } })), promiseTest(contextCJS("null"), nsObj({ default: null })) ]); }); it("should receive a namespace object when importing harmony via context", function() { return Promise.all([ promiseTest(contextHarmony("one"), nsObj({ named: "named", default: "default" })), promiseTest(contextHarmony("two"), nsObj({ named: "named", default: "default" })), promiseTest(contextHarmony("three"), nsObj({ named: "named", default: "default" })) ]); }); it("should receive a namespace object when importing mixed content via context", function() { return Promise.all([ promiseTest(contextMixed("one"), nsObj({ named: "named", default: { named: "named", default: "default" } })), promiseTest(contextMixed("two"), { __esModule: true, named: "named", default: "default" }), promiseTest(contextMixed("three"), nsObj({ named: "named", default: "default" })), promiseTest(contextMixed("null"), nsObj({ default: null })), promiseTest(contextMixed("json.json"), nsObj({ named: "named", default: { named: "named", default: "default" } })) ]); }); webpack-4.30.0/test/cases/mjs/non-mjs-namespace-object-lazy/test.filter.js000066400000000000000000000001011345416772700264250ustar00rootroot00000000000000module.exports = function(config) { return !config.minimize; }; webpack-4.30.0/test/cases/nonce/000077500000000000000000000000001345416772700164115ustar00rootroot00000000000000webpack-4.30.0/test/cases/nonce/set-nonce/000077500000000000000000000000001345416772700203045ustar00rootroot00000000000000webpack-4.30.0/test/cases/nonce/set-nonce/empty.js000066400000000000000000000000001345416772700217660ustar00rootroot00000000000000webpack-4.30.0/test/cases/nonce/set-nonce/index.js000066400000000000000000000016451345416772700217570ustar00rootroot00000000000000it("should load script with nonce 'nonce1234'", function(done) { __webpack_nonce__ = 'nonce1234'; require.ensure([], function(require) { require("./empty?a"); }, "chunk-with-nonce"); __webpack_nonce__ = undefined; // if in browser context, test that nonce was added. if (typeof document !== 'undefined') { var script = document.querySelector('script[src="js/chunk-with-nonce.web.js"]'); expect(script.getAttribute('nonce')).toBe('nonce1234'); } __webpack_nonce__ = undefined; done(); }); it("should load script without nonce", function(done) { require.ensure([], function(require) { require("./empty?b"); }, "chunk-without-nonce"); // if in browser context, test that nonce was added. if (typeof document !== 'undefined') { var script = document.querySelector('script[src="js/chunk-without-nonce.web.js"]'); expect(script.hasAttribute('nonce')).toBe(false); } __webpack_nonce__ = undefined; done(); }); webpack-4.30.0/test/cases/optimize/000077500000000000000000000000001345416772700171475ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/node_modules/000077500000000000000000000000001345416772700216245ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/node_modules/pmodule/000077500000000000000000000000001345416772700232715ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/node_modules/pmodule/a.js000066400000000000000000000001571345416772700240520ustar00rootroot00000000000000var a = "a"; var b = "b"; var c = "c"; export { a, b, c }; import { track } from "./tracker"; track("a.js"); webpack-4.30.0/test/cases/optimize/node_modules/pmodule/b.js000066400000000000000000000001701345416772700240460ustar00rootroot00000000000000var x = "x"; var y = "y"; export { x, y }; export { z } from "./c"; import { track } from "./tracker"; track("b.js"); webpack-4.30.0/test/cases/optimize/node_modules/pmodule/c.js000066400000000000000000000001171345416772700240500ustar00rootroot00000000000000var z = "z"; export { z }; import { track } from "./tracker"; track("c.js"); webpack-4.30.0/test/cases/optimize/node_modules/pmodule/index.js000066400000000000000000000002021345416772700247300ustar00rootroot00000000000000export * from "./a"; export { x, y, z } from "./b"; import { track } from "./tracker"; track("index.js"); export default "def"; webpack-4.30.0/test/cases/optimize/node_modules/pmodule/package.json000066400000000000000000000000351345416772700255550ustar00rootroot00000000000000{ "sideEffects": false } webpack-4.30.0/test/cases/optimize/node_modules/pmodule/tracker.js000066400000000000000000000002021345416772700252540ustar00rootroot00000000000000export function track(file) { log.push(file); log.sort(); } export var log = []; export function reset() { log.length = 0; } webpack-4.30.0/test/cases/optimize/side-effects-all-chain-unused/000077500000000000000000000000001345416772700246375ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-all-chain-unused/index.js000066400000000000000000000002711345416772700263040ustar00rootroot00000000000000import { log } from "pmodule/tracker"; import { a } from "pmodule"; it("should not evaluate a chain of modules", function() { expect(a).toBe("a"); expect(log).toEqual(["a.js"]); }); webpack-4.30.0/test/cases/optimize/side-effects-all-chain-unused/test.filter.js000066400000000000000000000001161345416772700274360ustar00rootroot00000000000000module.exports = function(config) { return config.mode !== "development"; }; webpack-4.30.0/test/cases/optimize/side-effects-all-used/000077500000000000000000000000001345416772700232145ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-all-used/index.js000066400000000000000000000004611345416772700246620ustar00rootroot00000000000000import { log } from "pmodule/tracker"; import { a, x, z } from "pmodule"; import def from "pmodule"; it("should evaluate all modules", function() { expect(def).toBe("def"); expect(a).toBe("a"); expect(x).toBe("x"); expect(z).toBe("z"); expect(log).toEqual(["a.js", "b.js", "c.js", "index.js"]); }); webpack-4.30.0/test/cases/optimize/side-effects-all-used/test.filter.js000066400000000000000000000001161345416772700260130ustar00rootroot00000000000000module.exports = function(config) { return config.mode !== "development"; }; webpack-4.30.0/test/cases/optimize/side-effects-immediate-unused/000077500000000000000000000000001345416772700247455ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-immediate-unused/index.js000066400000000000000000000003331345416772700264110ustar00rootroot00000000000000import { log } from "pmodule/tracker"; import { a, z } from "pmodule"; it("should not evaluate an immediate module", function() { expect(a).toBe("a"); expect(z).toBe("z"); expect(log).toEqual(["a.js", "c.js"]); }); webpack-4.30.0/test/cases/optimize/side-effects-immediate-unused/test.filter.js000066400000000000000000000001161345416772700275440ustar00rootroot00000000000000module.exports = function(config) { return config.mode !== "development"; }; webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/000077500000000000000000000000001345416772700262065ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/index.js000066400000000000000000000002121345416772700276460ustar00rootroot00000000000000import * as m from "m"; it("should handle unknown exports fine", function() { var x = m; expect(x).toEqual(nsObj({ foo: "foo" })); }); webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/node_modules/000077500000000000000000000000001345416772700306635ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/node_modules/m/000077500000000000000000000000001345416772700311175ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/node_modules/m/a.js000066400000000000000000000000301345416772700316660ustar00rootroot00000000000000export var foo = "foo"; webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/node_modules/m/b.js000066400000000000000000000000111345416772700316660ustar00rootroot00000000000000// empty webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/node_modules/m/index.js000066400000000000000000000000521345416772700325610ustar00rootroot00000000000000export * from "./a"; export * from "./b"; webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/node_modules/m/package.json000066400000000000000000000000351345416772700334030ustar00rootroot00000000000000{ "sideEffects": false } webpack-4.30.0/test/cases/optimize/side-effects-reexport-start-unknown/test.filter.js000066400000000000000000000001161345416772700310050ustar00rootroot00000000000000module.exports = function(config) { return config.mode !== "development"; }; webpack-4.30.0/test/cases/optimize/side-effects-root-unused/000077500000000000000000000000001345416772700237725ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-root-unused/index.js000066400000000000000000000003601345416772700254360ustar00rootroot00000000000000import { log } from "pmodule/tracker"; import { a, x, z } from "pmodule"; it("should evaluate all modules", function() { expect(a).toBe("a"); expect(x).toBe("x"); expect(z).toBe("z"); expect(log).toEqual(["a.js", "b.js", "c.js"]); }); webpack-4.30.0/test/cases/optimize/side-effects-root-unused/test.filter.js000066400000000000000000000001161345416772700265710ustar00rootroot00000000000000module.exports = function(config) { return config.mode !== "development"; }; webpack-4.30.0/test/cases/optimize/side-effects-scope-hoisting/000077500000000000000000000000001345416772700244415ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-scope-hoisting/index.js000066400000000000000000000003001345416772700260770ustar00rootroot00000000000000import { a } from "pmodule"; it("should not crash with null id", function() { expect(a).toBe("a"); }); if(Math === undefined) console.log(module); // prevent scope hoisting of this module webpack-4.30.0/test/cases/optimize/side-effects-simple-unused/000077500000000000000000000000001345416772700243005ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-simple-unused/index.js000066400000000000000000000004371345416772700257510ustar00rootroot00000000000000import { log } from "pmodule/tracker"; import { x, z } from "pmodule"; import def from "pmodule"; it("should not evaluate a simple unused module", function() { expect(def).toBe("def"); expect(x).toBe("x"); expect(z).toBe("z"); expect(log).toEqual(["b.js", "c.js", "index.js"]); }); webpack-4.30.0/test/cases/optimize/side-effects-simple-unused/test.filter.js000066400000000000000000000001161345416772700270770ustar00rootroot00000000000000module.exports = function(config) { return config.mode !== "development"; }; webpack-4.30.0/test/cases/optimize/side-effects-transitive-unused/000077500000000000000000000000001345416772700251775ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/side-effects-transitive-unused/index.js000066400000000000000000000003471345416772700266500ustar00rootroot00000000000000import { log } from "pmodule/tracker"; import { a, y } from "pmodule"; it("should not evaluate a reexporting transitive module", function() { expect(a).toBe("a"); expect(y).toBe("y"); expect(log).toEqual(["a.js", "b.js"]); }); webpack-4.30.0/test/cases/optimize/side-effects-transitive-unused/test.filter.js000066400000000000000000000001161345416772700277760ustar00rootroot00000000000000module.exports = function(config) { return config.mode !== "development"; }; webpack-4.30.0/test/cases/optimize/tree-shaking-commonjs/000077500000000000000000000000001345416772700233535ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/tree-shaking-commonjs/a.js000066400000000000000000000000311345416772700241230ustar00rootroot00000000000000export {test} from "./b";webpack-4.30.0/test/cases/optimize/tree-shaking-commonjs/b.js000066400000000000000000000000401345416772700241240ustar00rootroot00000000000000module.exports = require("./c");webpack-4.30.0/test/cases/optimize/tree-shaking-commonjs/c.js000066400000000000000000000000241345416772700241270ustar00rootroot00000000000000export * from "./d";webpack-4.30.0/test/cases/optimize/tree-shaking-commonjs/d.js000066400000000000000000000000401345416772700241260ustar00rootroot00000000000000module.exports = require("./e");webpack-4.30.0/test/cases/optimize/tree-shaking-commonjs/e.js000066400000000000000000000000261345416772700241330ustar00rootroot00000000000000export var test = 123;webpack-4.30.0/test/cases/optimize/tree-shaking-commonjs/index.js000066400000000000000000000001661345416772700250230ustar00rootroot00000000000000import { test } from "./a"; it("should correctly tree shake star exports", function() { expect(test).toBe(123); }); webpack-4.30.0/test/cases/optimize/tree-shaking-star/000077500000000000000000000000001345416772700224775ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/tree-shaking-star/a.js000066400000000000000000000000241345416772700232510ustar00rootroot00000000000000export * from "./b";webpack-4.30.0/test/cases/optimize/tree-shaking-star/b.js000066400000000000000000000000241345416772700232520ustar00rootroot00000000000000export * from "./c";webpack-4.30.0/test/cases/optimize/tree-shaking-star/c.js000066400000000000000000000000241345416772700232530ustar00rootroot00000000000000export * from "./d";webpack-4.30.0/test/cases/optimize/tree-shaking-star/d.js000066400000000000000000000000261345416772700232560ustar00rootroot00000000000000export var test = 123;webpack-4.30.0/test/cases/optimize/tree-shaking-star/index.js000066400000000000000000000003321345416772700241420ustar00rootroot00000000000000import { test } from "./a"; import { func1, func3 } from "./x"; it("should correctly tree shake star exports", function() { expect(test).toBe(123); expect(func1()).toBe("func1"); expect(func3()).toBe("func3"); }); webpack-4.30.0/test/cases/optimize/tree-shaking-star/x.js000066400000000000000000000000541345416772700233030ustar00rootroot00000000000000export * from "./x1"; export * from "./x2"; webpack-4.30.0/test/cases/optimize/tree-shaking-star/x1.js000066400000000000000000000001301345416772700233570ustar00rootroot00000000000000export function func1() { return "func1"; } export function func2() { return "func2"; } webpack-4.30.0/test/cases/optimize/tree-shaking-star/x2.js000066400000000000000000000001301345416772700233600ustar00rootroot00000000000000export function func3() { return "func3"; } export function func4() { return "func4"; } webpack-4.30.0/test/cases/optimize/tree-shaking-star2/000077500000000000000000000000001345416772700225615ustar00rootroot00000000000000webpack-4.30.0/test/cases/optimize/tree-shaking-star2/a.js000066400000000000000000000000261345416772700233350ustar00rootroot00000000000000export * from "./aa"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/aa.js000066400000000000000000000000261345416772700234760ustar00rootroot00000000000000export var aa = "aa"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/b.js000066400000000000000000000000251345416772700233350ustar00rootroot00000000000000export * from "./bb";webpack-4.30.0/test/cases/optimize/tree-shaking-star2/bb.js000066400000000000000000000000261345416772700235000ustar00rootroot00000000000000export var bb = "bb"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/c.js000066400000000000000000000000241345416772700233350ustar00rootroot00000000000000export var c = "c"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/d.js000066400000000000000000000000211345416772700233330ustar00rootroot00000000000000exports.d = "d"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/index.js000066400000000000000000000004471345416772700242330ustar00rootroot00000000000000import { aa } from "./root"; import { aa as aa2, d } from "./root3"; var root6 = require("./root6"); it("should correctly tree shake star exports", function() { expect(aa).toBe("aa"); expect(aa2).toBe("aa"); expect(d).toBe("d"); expect(root6).toEqual(nsObj({ aa: "aa", c: "c" })); }); webpack-4.30.0/test/cases/optimize/tree-shaking-star2/root.js000066400000000000000000000000771345416772700241060ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/root2.js000066400000000000000000000001241345416772700241610ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; export * from "./d"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/root3.js000066400000000000000000000000311345416772700241570ustar00rootroot00000000000000export * from "./root2"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/root4.js000066400000000000000000000000521345416772700241630ustar00rootroot00000000000000export * from "./a"; export * from "./c"; webpack-4.30.0/test/cases/optimize/tree-shaking-star2/root5.js000066400000000000000000000000441345416772700241650ustar00rootroot00000000000000module.exports = require("./root4");webpack-4.30.0/test/cases/optimize/tree-shaking-star2/root6.js000066400000000000000000000000311345416772700241620ustar00rootroot00000000000000export * from "./root5"; webpack-4.30.0/test/cases/parsing/000077500000000000000000000000001345416772700167525ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/amd-rename/000077500000000000000000000000001345416772700207605ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/amd-rename/index.js000066400000000000000000000002321345416772700224220ustar00rootroot00000000000000it("should name require in define correctly", function() { define(["require"], function(require) { expect((typeof require)).toBe("function"); }); }); webpack-4.30.0/test/cases/parsing/bom/000077500000000000000000000000001345416772700175275ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/bom/bomfile.css000066400000000000000000000000231345416772700216510ustar00rootroot00000000000000body{color:#abc}webpack-4.30.0/test/cases/parsing/bom/bomfile.js000066400000000000000000000000311345416772700214740ustar00rootroot00000000000000module.exports = "ok";webpack-4.30.0/test/cases/parsing/bom/bomfile.json000066400000000000000000000000261345416772700220350ustar00rootroot00000000000000{ "message": "ok" }webpack-4.30.0/test/cases/parsing/bom/index.js000066400000000000000000000006321345416772700211750ustar00rootroot00000000000000it("should load a utf-8 file with BOM", function() { var result = require("./bomfile"); expect(result).toEqual("ok"); }); it("should load a css file with BOM", function() { var css = require("!css-loader!./bomfile.css") + ""; expect(css).toBe("body{color:#abc}"); }); it("should load a json file with BOM", function() { var result = require("./bomfile.json"); expect(result.message).toEqual("ok"); }); webpack-4.30.0/test/cases/parsing/bom/typeof.js000066400000000000000000000000401345416772700213650ustar00rootroot00000000000000module.exports = typeof require;webpack-4.30.0/test/cases/parsing/browserify/000077500000000000000000000000001345416772700211455ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/browserify/index.js000066400000000000000000000026471345416772700226230ustar00rootroot00000000000000it("should be able to parse browserified modules", function(done) { (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o { expect(require("./file")).toBe("ok"); done(); }); }); it("should parse a string in require.ensure with arrow function array expression", function(done) { require.ensure("./file", require => (expect(require("./file")).toBe("ok"), done())); }); webpack-4.30.0/test/cases/parsing/chunks/test.filter.js000066400000000000000000000002161345416772700230450ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/parsing/class/000077500000000000000000000000001345416772700200575ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/class/a.js000066400000000000000000000000271345416772700206340ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/cases/parsing/class/index.js000066400000000000000000000004271345416772700215270ustar00rootroot00000000000000import X, { A, B } from "./module"; it("should parse classes", function() { expect(new X().a).toBe("ok"); expect(new A().a).toBe("ok"); expect(new B().a).toBe("ok"); }); it("should parse methods", function() { expect(new X().b()).toBe("ok"); expect(X.c()).toBe("ok"); }); webpack-4.30.0/test/cases/parsing/class/module.js000066400000000000000000000004531345416772700217040ustar00rootroot00000000000000class A { constructor() { this.a = require("./a"); } } const B = class { constructor() { this.a = require("./a"); } }; export default class { constructor() { this.a = require("./a"); } b() { return require("./a"); } static c() { return require("./a"); } }; export { A, B }; webpack-4.30.0/test/cases/parsing/class/test.filter.js000066400000000000000000000002161345416772700226570ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/parsing/comment-in-import/000077500000000000000000000000001345416772700223305ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/comment-in-import/index.js000066400000000000000000000003371345416772700240000ustar00rootroot00000000000000it("should allow random comments in import()", () => { return Promise.all([ import(/* hello world */ "./module"), import(/* }); */ "./module"), import(/* test */ "./module"), import(/* 1234 */ "./module") ]); }); webpack-4.30.0/test/cases/parsing/comment-in-import/module.js000066400000000000000000000000001345416772700241410ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/complex-require/000077500000000000000000000000001345416772700220735ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/complex-require/abc/000077500000000000000000000000001345416772700226205ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/complex-require/abc/abcTest.js000066400000000000000000000000251345416772700245400ustar00rootroot00000000000000export default "ok"; webpack-4.30.0/test/cases/parsing/complex-require/amd.js000066400000000000000000000016401345416772700231730ustar00rootroot00000000000000 it("should parse template strings in amd requires", function(done) { var name = "abc"; var suffix = "Test"; var pending = [ require([`./abc/abcTest`], test), require([`./abc/${name}Test`], test), require([`./${name}/${name}Test`], test), require([`./abc/${name}${suffix}`], test), require([String.raw`./${name}/${name}${suffix}`], test) ].length; function test (result) { expect(result.default).toEqual("ok") if (--pending <= 0) { done() } } }) it("should parse .concat strings in amd requires", function(done) { var name = "abc"; var suffix = "Test"; var pending = [ require(["./abc/abcTest"], test), require(["./abc/".concat(name, "Test")], test), require(["./".concat(name, "/").concat(name, "Test")], test), require(["./abc/".concat(name).concat(suffix)], test) ].length; function test (result) { expect(result.default).toEqual("ok") if (--pending <= 0) { done() } } }) webpack-4.30.0/test/cases/parsing/complex-require/cjs.js000066400000000000000000000043311345416772700232110ustar00rootroot00000000000000 it("should parse template strings in require.ensure requires", function(done) { var name = "abc"; var suffix = "Test"; require.ensure([], function(require) { var imports = [ require(`./abc/${name}Test`), require(`./${name}/${name}Test`), require(`./abc/${name}${suffix}`), require(String.raw`./${name}/${name}${suffix}`) ]; for (var i = 0; i < imports.length; i++) { expect(imports[i].default).toEqual("ok"); } done() }) }) it("should parse template strings in sync requires", function() { var name = "sync"; var suffix = "Test"; var imports = [ require(`./sync/${name}Test`), require(`./sync/${name}${suffix}`), require(String.raw`./sync/${name.slice(0, 1)}y${name.slice(2)}${suffix}`), require(`./sync/sync${"Test"}`), require(String.raw`./sync/${"sync"}Test`) ]; for (var i = 0; i < imports.length; i++) { expect(imports[i].default).toEqual("sync"); } }) it("should parse template strings in require.resolve", function() { var name = "sync"; // Arbitrary assertion; can't use .ok() as it could be 0, // can't use typeof as that depends on webpack config. expect(require.resolve(`./sync/${name}Test`)).toBeDefined(); }) it("should parse .concat strings in require.ensure requires", function(done) { var name = "abc"; var suffix = "Test"; require.ensure([], function(require) { var imports = [ require("./abc/".concat(name, "Test")), require("./".concat(name, "/").concat(name, "Test")), require("./abc/".concat(name).concat(suffix)) ]; for (var i = 0; i < imports.length; i++) { expect(imports[i].default).toEqual("ok"); } done() }) }) it("should parse .concat strings in sync requires", function() { var name = "sync"; var suffix = "Test"; var imports = [ require("./sync/".concat(name, "Test")), require("./sync/".concat(name).concat(suffix)), require("./sync/sync".concat("Test")) ]; for (var i = 0; i < imports.length; i++) { expect(imports[i].default).toEqual("sync"); } }) it("should parse .concat strings in require.resolve", function() { var name = "sync"; // Arbitrary assertion; can't use .ok() as it could be 0, // can't use typeof as that depends on webpack config. expect(require.resolve("./sync/".concat(name, "Test"))).toBeDefined(); }) webpack-4.30.0/test/cases/parsing/complex-require/index.js000066400000000000000000000014541345416772700235440ustar00rootroot00000000000000it("should parse template strings in import", function(done) { var name = "abc".split(""); var suffix = "Test"; Promise.all([ import(`./abc/${name[0]}${name[1]}${name[2]}Test`), import(String.raw`./${name.join("")}/${name.join("")}Test`), import(String.raw`./abc/${name.join("")}${suffix}`) ]) .then(function (imports) { for (var i = 0; i < imports.length; i++) { expect(imports[i].default).toEqual("ok"); } }) .then(function () { done(); }, done) }); it("should parse .concat strings in import", function(done) { var name = "abc".split(""); var suffix = "Test"; import("./abc/".concat(name[0]).concat(name[1]).concat(name[2], "Test")) .then(function (imported) { expect(imported.default).toEqual("ok"); }) .then(function () { done(); }, done) }); require("./cjs") require("./amd") webpack-4.30.0/test/cases/parsing/complex-require/sync/000077500000000000000000000000001345416772700230475ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/complex-require/sync/syncTest.js000066400000000000000000000000271345416772700252200ustar00rootroot00000000000000export default "sync"; webpack-4.30.0/test/cases/parsing/complex-require/test.filter.js000066400000000000000000000002621345416772700246740ustar00rootroot00000000000000var supportsTemplateStrings = require("../../../helpers/supportsTemplateStrings"); module.exports = function(config) { return !config.minimize && supportsTemplateStrings(); }; webpack-4.30.0/test/cases/parsing/context/000077500000000000000000000000001345416772700204365ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/context/index.js000066400000000000000000000037041345416772700221070ustar00rootroot00000000000000it("should be able to load a file with the require.context method", function() { expect(require.context("./templates")("./tmpl")).toBe("test template"); expect((require.context("./././templates"))("./tmpl")).toBe("test template"); expect((require.context("././templates/.")("./tmpl"))).toBe("test template"); expect(require.context("./loaders/queryloader?dog=bark!./templates?cat=meow")("./tmpl")).toEqual({ resourceQuery: "?cat=meow", query: "?dog=bark", prev: "module.exports = \"test template\";" }); expect(require . context ( "." + "/." + "/" + "templ" + "ates" ) ( "./subdir/tmpl.js" )).toBe("subdir test template"); expect(require.context("./templates", true, /./)("xyz")).toBe("xyz"); }); it("should automatically create contexts", function() { var template = "tmpl", templateFull = "./tmpl.js"; var mp = "mp", tmp = "tmp", mpl = "mpl"; expect(require("./templates/" + template)).toBe("test template"); expect(require("./templates/" + tmp + "l")).toBe("test template"); expect(require("./templates/t" + mpl)).toBe("test template"); expect(require("./templates/t" + mp + "l")).toBe("test template"); }); it("should be able to require.resolve with automatical context", function() { var template = "tmpl"; expect(require.resolve("./templates/" + template)).toBe(require.resolve("./templates/tmpl")); }); it("should be able to use renaming combined with a context", function() { var renamedRequire = require; require = function () {}; require("fail"); var template = "tmpl"; expect(renamedRequire("./templates/" + template)).toBe("test template"); }); it("should compile an empty context", function() { var x = "xxx"; expect(function() { require("./templates/notExisting" + x); }).toThrowError(/xxx/); }); it("should execute an empty context", function() { var context; expect(function() { context = require.context("./templates/", true, /^\.\/notExisting/); }).not.toThrowError(); expect(function() { context(""); }).toThrowError(); }); webpack-4.30.0/test/cases/parsing/context/loaders/000077500000000000000000000000001345416772700220675ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/context/loaders/queryloader.js000066400000000000000000000002461345416772700247630ustar00rootroot00000000000000module.exports = function(content) { return "module.exports = " + JSON.stringify({ resourceQuery: this.resourceQuery, query: this.query, prev: content }); }; webpack-4.30.0/test/cases/parsing/context/templates/000077500000000000000000000000001345416772700224345ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/context/templates/dump-file.txt000066400000000000000000000000761345416772700250620ustar00rootroot00000000000000This is a file! with some content it should break webpack :)webpack-4.30.0/test/cases/parsing/context/templates/node_modules/000077500000000000000000000000001345416772700251115ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/context/templates/node_modules/xyz.js000066400000000000000000000000271345416772700263000ustar00rootroot00000000000000module.exports = "xyz";webpack-4.30.0/test/cases/parsing/context/templates/subdir/000077500000000000000000000000001345416772700237245ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/context/templates/subdir/tmpl.js000066400000000000000000000000501345416772700252310ustar00rootroot00000000000000module.exports = "subdir test template";webpack-4.30.0/test/cases/parsing/context/templates/templateLoader.js000066400000000000000000000000721345416772700257330ustar00rootroot00000000000000module.exports = function(name) { return require(name); }webpack-4.30.0/test/cases/parsing/context/templates/templateLoaderIndirect.js000066400000000000000000000003251345416772700274160ustar00rootroot00000000000000module.exports = function(name) { var a = load(require, name); var r = require; var b = r(name); if(a !== b) return "FAIL"; return a; } function load(requireFunction, name) { return requireFunction(name); }webpack-4.30.0/test/cases/parsing/context/templates/tmpl.js000066400000000000000000000000411345416772700237410ustar00rootroot00000000000000module.exports = "test template";webpack-4.30.0/test/cases/parsing/context/warnings.js000066400000000000000000000004051345416772700226230ustar00rootroot00000000000000module.exports = [ [/Module parse failed/, /dump-file\.txt/, /templates sync \^\\\.\\\/\.\*\$/], [/Critical dependency/, /templateLoader\.js/], [/Critical dependency/, /templateLoaderIndirect\.js/], [/Critical dependency/, /templateLoaderIndirect\.js/], ]; webpack-4.30.0/test/cases/parsing/es6.nominimize/000077500000000000000000000000001345416772700216245ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/es6.nominimize/a.js000066400000000000000000000000261345416772700224000ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/cases/parsing/es6.nominimize/array.js000066400000000000000000000000341345416772700232750ustar00rootroot00000000000000module.exports = [1, 2, 3]; webpack-4.30.0/test/cases/parsing/es6.nominimize/async.js000066400000000000000000000000321345416772700232720ustar00rootroot00000000000000module.exports = "async"; webpack-4.30.0/test/cases/parsing/es6.nominimize/b.js000066400000000000000000000000261345416772700224010ustar00rootroot00000000000000module.exports = "b"; webpack-4.30.0/test/cases/parsing/es6.nominimize/c.js000066400000000000000000000000261345416772700224020ustar00rootroot00000000000000module.exports = "c"; webpack-4.30.0/test/cases/parsing/es6.nominimize/index.js000066400000000000000000000024731345416772700232770ustar00rootroot00000000000000"use strict"; import a from "./a"; it("should parse classes", function() { class MyClass { constructor() { this.a = require("./a"); } func() { return require("./b"); } [require("./c")]() { return "c"; } } var x = new MyClass(); expect(x.a).toBe("a"); expect(x.func()).toBe("b"); expect(x.c()).toBe("c"); }); it("should parse spread operator"/*, function() { expect([0, ...require("./array")]).toEqual([0, 1, 2, 3]); expect(({z: 0, ...require("./object")})).toEqual({z: 0, a: 1, b: 2, c: 3}); }*/); it("should parse arrow function", function() { expect((() => require("./a"))()).toBe("a"); expect((() => { return require("./a"); })()).toBe("a"); require.ensure([], () => { require("./a"); }); require.ensure([], () => { require("./async"); }); if(module.hot) { module.hot.accept("./a", () => { var x = 1; }); } }); it("should parse template literals", function() { function tag(strings, value) { return value; } var x = `a${require("./b")}c`; var y = tag`a${require("./b")}c`; expect(x).toBe("abc"); expect(y).toBe("b"); }) it("should parse generators and yield", function() { function* gen() { yield require("./a"); yield require("./b"); } var x = gen(); expect(x.next().value).toBe("a"); expect(x.next().value).toBe("b"); expect(x.next().done).toBe(true); }) webpack-4.30.0/test/cases/parsing/es6.nominimize/object.js000066400000000000000000000000451345416772700234270ustar00rootroot00000000000000module.exports = {a: 1, b: 2, c: 3}; webpack-4.30.0/test/cases/parsing/es6.nominimize/test.filter.js000066400000000000000000000002161345416772700244240ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/parsing/evaluate/000077500000000000000000000000001345416772700205605ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/evaluate/a.js000066400000000000000000000000251345416772700213330ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/parsing/evaluate/index.js000066400000000000000000000023721345416772700222310ustar00rootroot00000000000000it("should evaluate null", function() { var y = null ? require("fail") : require("./a"); if(null) require("fail"); }); it("should evaluate logical expression", function() { var value1 = "hello" || require("fail"); var value2 = typeof require === "function" || require("fail"); var value3 = "" && require("fail"); var value4 = typeof require !== "function" && require("fail"); var value5 = "hello" && (() => "value5")(); var value6 = "" || (() => "value6")(); var value7 = (function () { return'value7'===typeof 'value7'&&'value7'})(); expect(value1).toBe("hello"); expect(value2).toBe(true); expect(value3).toBe(""); expect(value4).toBe(false); expect(value5).toBe("value5"); expect(value6).toBe("value6"); expect(value7).toBe(false); }); if("shouldn't evaluate expression", function() { var value = ""; var x = (value + "") ? "fail" : "ok"; expect(x).toBe("ok"); }); it("should short-circuit evaluating", function() { var expr; var a = false && expr ? require("fail") : require("./a"); var b = true || expr ? require("./a") : require("fail"); }); it("should evaluate __dirname and __resourceQuery with replace and substr", function() { var result = require("./resourceQuery/index?" + __dirname); expect(result).toEqual("?resourceQuery"); }); webpack-4.30.0/test/cases/parsing/evaluate/resourceQuery/000077500000000000000000000000001345416772700234355ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/evaluate/resourceQuery/index.js000066400000000000000000000001671345416772700251060ustar00rootroot00000000000000module.exports = require((__resourceQuery.substr(1) + "/resourceQuery/returnRQ?XXXQuery").replace(/XXX/g, "resource"));webpack-4.30.0/test/cases/parsing/evaluate/resourceQuery/returnRQ.js000066400000000000000000000000411345416772700255500ustar00rootroot00000000000000module.exports = __resourceQuery;webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/000077500000000000000000000000001345416772700233405ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/a.js000066400000000000000000000000251345416772700241130ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/amdmodule.js000066400000000000000000000000621345416772700256430ustar00rootroot00000000000000define((require) => { return require("./a"); }); webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/c.js000066400000000000000000000000251345416772700241150ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/circular.js000066400000000000000000000000731345416772700255020ustar00rootroot00000000000000module.exports = 1; module.exports = require("./circular");webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/constructor.js000066400000000000000000000000711345416772700262610ustar00rootroot00000000000000module.exports = function(value) { this.value = value; }webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/d.js000066400000000000000000000000251345416772700241160ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/index.js000066400000000000000000000072531345416772700250140ustar00rootroot00000000000000it("should parse fancy function calls with arrow functions", function() { ("function"==typeof define && define.amd ? define : (e,t) => {return t()} )(["./constructor"], (c) => { return new c(1324); }); expect(module.exports).toHaveProperty("value", 1324); (("function"==typeof define && define.amd ? define : (e,t) => {return t()} )(["./constructor"], (c) => { return new c(4231); })); expect(module.exports).toHaveProperty("value", 4231); }); it("should parse fancy AMD calls with arrow functions", function() { require("./constructor ./a".split(" ")); require("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), (require, module, exports, constructor, a) => { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); expect((typeof require("./constructor"))).toBe("function"); expect((typeof constructor)).toBe("function"); expect(a).toBe("a"); }); define("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), (require, module, exports, constructor, a) => { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); expect((typeof require("./constructor"))).toBe("function"); expect((typeof constructor)).toBe("function"); expect(a).toBe("a"); }); }); it("should be able to use AMD-style require with arrow functions", function(done) { var template = "b"; require(["./circular", "./templates/" + template, true ? "./circular" : "fail"], (circular, testTemplate, circular2) => { expect(circular).toBe(1); expect(circular2).toBe(1); expect(testTemplate).toBe("b"); done(); }); }); it("should be able to use require.js-style define with arrow functions", function(done) { define("name", ["./circular"], (circular) => { expect(circular).toBe(1); done(); }); }); it("should be able to use require.js-style define, optional dependencies, not exist, with arrow function", function(done) { define("name", ["./optional"], (optional) => { expect(optional.b).toBeFalsy(); done(); }); }); it("should be able to use require.js-style define, special string, with arrow function", function(done) { define(["require"], (require) => { expect(require("./circular")).toBe(1); done(); }); }); it("should be able to use require.js-style define, without name, with arrow function", function(done) { true && define(["./circular"], (circular) => { expect(circular).toBe(1); done(); }); }); it("should be able to use require.js-style define, with empty dependencies, with arrow function", function(done) { define("name", [], () => { done(); }); }); it("should be able to use require.js-style define, without dependencies, with arrow function", function(done) { true && define("name", () => { done(); }); }); it("should offer AMD-style define for CommonJs with arrow function", function(done) { var _test_exports = exports; var _test_module = module; define((require, exports, module) => { expect((typeof require)).toBe("function"); expect(exports).toBe(_test_exports); expect(module).toBe(_test_module); expect(require("./circular")).toBe(1); done(); }); }); it("should pull in all dependencies of an AMD module with arrow function", function(done) { define((require) => { expect(require("./amdmodule")).toBe("a"); done(); }); }); it("should create a chunk for require.js require, with arrow function", function(done) { var sameTick = true; require(["./c"], (c) => { expect(sameTick).toBe(false); expect(c).toBe("c"); expect(require("./d")).toBe("d"); done(); }); sameTick = false; }); webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/optional.js000066400000000000000000000002061345416772700255210ustar00rootroot00000000000000module.exports = 2; try { module.exports.a = require("./a"); } catch (e) {}; try { module.exports.b = require("./b"); } catch (e) {}; webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/templates/000077500000000000000000000000001345416772700253365ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/templates/a.js000066400000000000000000000000251345416772700261110ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/templates/b.js000066400000000000000000000000251345416772700261120ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/templates/c.js000066400000000000000000000000251345416772700261130ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/test.filter.js000066400000000000000000000002161345416772700261400ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/parsing/extract-amd.nominimize/warnings.js000066400000000000000000000001171345416772700255250ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/b' /, /b\.js/] ]; webpack-4.30.0/test/cases/parsing/extract-amd/000077500000000000000000000000001345416772700211635ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/extract-amd/a.js000066400000000000000000000000251345416772700217360ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/parsing/extract-amd/c.js000066400000000000000000000000251345416772700217400ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/cases/parsing/extract-amd/circular.js000066400000000000000000000000731345416772700233250ustar00rootroot00000000000000module.exports = 1; module.exports = require("./circular");webpack-4.30.0/test/cases/parsing/extract-amd/constructor.js000066400000000000000000000000711345416772700241040ustar00rootroot00000000000000module.exports = function(value) { this.value = value; }webpack-4.30.0/test/cases/parsing/extract-amd/d.js000066400000000000000000000000251345416772700217410ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/test/cases/parsing/extract-amd/index.js000066400000000000000000000146171345416772700226410ustar00rootroot00000000000000it("should parse fancy function calls", function() { ("function"==typeof define && define.amd ? define : function(e,t){return t()} )(["./constructor"], function(c) { return new c(1324); }); expect(module.exports).toHaveProperty("value", 1324); (("function"==typeof define && define.amd ? define : function(e,t){return t()} )(["./constructor"], function(c) { return new c(4231); })); expect(module.exports).toHaveProperty("value", 4231); }); it("should parse fancy AMD calls", function() { require("./constructor ./a".split(" ")); require("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), function(require, module, exports, constructor, a) { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); expect((typeof require("./constructor"))).toBe("function"); expect((typeof constructor)).toBe("function"); expect(a).toBe("a"); }); define("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), function(require, module, exports, constructor, a) { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); expect((typeof require("./constructor"))).toBe("function"); expect((typeof constructor)).toBe("function"); expect(a).toBe("a"); }); }); it("should be able to use AMD-style require", function(done) { var template = "b"; require(["./circular", "./templates/" + template, true ? "./circular" : "fail"], function(circular, testTemplate, circular2) { expect(circular).toBe(1); expect(circular2).toBe(1); expect(testTemplate).toBe("b"); done(); }); }); it("should be able to use require.js-style define", function(done) { define("name", ["./circular"], function(circular) { expect(circular).toBe(1); done(); }); }); it("should be able to use require.js-style define, optional dependencies, not exist", function(done) { define("name", ["./optional"], function(optional) { expect(optional.b).toBeFalsy(); done(); }); }); it("should be able to use require.js-style define, special string", function(done) { define(["require"], function(require) { expect(require("./circular")).toBe(1); done(); }); }); it("should be able to use require.js-style define, without name", function(done) { true && define(["./circular"], function(circular) { expect(circular).toBe(1); done(); }); }); it("should be able to use require.js-style define, with empty dependencies", function(done) { define("name", [], function() { done(); }); }); it("should be able to use require.js-style define, with empty dependencies, with a expression", function(done) { define([], ok); function ok() { done() }; }); it("should be able to use require.js-style define, with empty dependencies, with a expression and name", function(done) { define("name", [], done); }); it("should be able to use require.js-style define, without dependencies", function(done) { true && define("name", function() { done(); }); }); it("should be able to use require.js-style define, without dependencies, with a expression", function(done) { true && define("name", ok); function ok() { done() }; }); var obj = {}; it("should be able to use require.js-style define, with an object", function() { module.exports = null; true && define("blaaa", obj); expect(module.exports).toBe(obj); module.exports = null; define("blaaa", obj); expect(module.exports).toBe(obj); module.exports = null; }); it("should offer AMD-style define for CommonJs", function(done) { var _test_exports = exports; var _test_module = module; define(function(require, exports, module) { expect((typeof require)).toBe("function"); expect(exports).toBe(_test_exports); expect(module).toBe(_test_module); expect(require("./circular")).toBe(1); done(); }); }); it("should not crash on require.js require only with array", function() { require(["./circular"]); }); it("should be able to use AMD require without function expression (empty array)", function(done) { require([], ok); function ok() { done() }; }); it("should be able to use AMD require without function expression", function(done) { require(["./circular"], fn); function fn(c) { expect(c).toBe(1); done(); } }); it("should create a chunk for require.js require", function(done) { var sameTick = true; require(["./c"], function(c) { expect(sameTick).toBe(false); expect(c).toBe("c"); expect(require("./d")).toBe("d"); done(); }); sameTick = false; }); it("should not fail #138", function(done) { (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(); // Node } else { factory(); // Browser global } }(function () { done() })); }); it("should parse a bound function expression 1", function(done) { define(function(a, require, exports, module) { expect(a).toBe(123); expect((typeof require)).toBe("function"); expect(require("./a")).toBe("a"); done(); }.bind(null, 123)); }); it("should parse a bound function expression 2", function(done) { define("name", function(a, require, exports, module) { expect(a).toBe(123); expect((typeof require)).toBe("function"); expect(require("./a")).toBe("a"); done(); }.bind(null, 123)); }); it("should parse a bound function expression 3", function(done) { define(["./a"], function(number, a) { expect(number).toBe(123); expect(a).toBe("a"); done(); }.bind(null, 123)); }); it("should parse a bound function expression 4", function(done) { define("name", ["./a"], function(number, a) { expect(number).toBe(123); expect(a).toBe("a"); done(); }.bind(null, 123)); }); it("should not fail issue #138 second", function() { (function(define, global) { 'use strict'; define(function (require) { expect((typeof require)).toBe("function"); expect(require("./a")).toBe("a"); return "#138 2."; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }, this); expect(module.exports).toBe("#138 2."); }); it("should parse an define with empty array and object", function() { var obj = {ok: 95476}; define([], obj); expect(module.exports).toBe(obj); }); it("should parse an define with object", function() { var obj = {ok: 76243}; define(obj); expect(module.exports).toBe(obj); }); webpack-4.30.0/test/cases/parsing/extract-amd/optional.js000066400000000000000000000002061345416772700233440ustar00rootroot00000000000000module.exports = 2; try { module.exports.a = require("./a"); } catch (e) {}; try { module.exports.b = require("./b"); } catch (e) {}; webpack-4.30.0/test/cases/parsing/extract-amd/templates/000077500000000000000000000000001345416772700231615ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/extract-amd/templates/a.js000066400000000000000000000000251345416772700237340ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/parsing/extract-amd/templates/b.js000066400000000000000000000000251345416772700237350ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/cases/parsing/extract-amd/templates/c.js000066400000000000000000000000251345416772700237360ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/cases/parsing/extract-amd/warnings.js000066400000000000000000000001171345416772700233500ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/b' /, /b\.js/] ]; webpack-4.30.0/test/cases/parsing/extract-require/000077500000000000000000000000001345416772700220765ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/extract-require/constructor.js000066400000000000000000000000711345416772700250170ustar00rootroot00000000000000module.exports = function(value) { this.value = value; }webpack-4.30.0/test/cases/parsing/extract-require/errors.js000066400000000000000000000001561345416772700237520ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /, /extract-require\/index.js/] ];webpack-4.30.0/test/cases/parsing/extract-require/folder/000077500000000000000000000000001345416772700233515ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/extract-require/folder/file1.js000066400000000000000000000000311345416772700247010ustar00rootroot00000000000000module.exports = "file1";webpack-4.30.0/test/cases/parsing/extract-require/folder/file2.js000066400000000000000000000000311345416772700247020ustar00rootroot00000000000000module.exports = "file2";webpack-4.30.0/test/cases/parsing/extract-require/folder/file3.js000066400000000000000000000000311345416772700247030ustar00rootroot00000000000000module.exports = "file3";webpack-4.30.0/test/cases/parsing/extract-require/index.js000066400000000000000000000023451345416772700235470ustar00rootroot00000000000000function testCase(number) { expect(require(number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule")).toBe("file" + number); expect(require( number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule" )).toBe("file" + number); } it("should parse complex require calls", function() { // "Parse require in new(...) should work" expect(new(require("./constructor"))(1234).value).toBe(1234); // "Parse require in new(...) should work, with spaces" expect(new ( require ( "./constructor" ) ) ( 1234 ) .value).toBe(1234); }); it("should let the user hide the require function", function() { expect((function(require) { return require; })(1234)).toBe(1234); function testFunc(abc, require) { return require; } expect(testFunc(333, 678)).toBe(678); (function() { var require = 123; expect(require).toBe(123); }()); (function() { function require() { return 123; }; expect(require("error")).toBe(123); }()); (function() { var module = 1233; expect(module).toBe(1233); }()); }); it("should not create a context for the ?: operator", function() { testCase(1); testCase(2); testCase(3); }); webpack-4.30.0/test/cases/parsing/filename/000077500000000000000000000000001345416772700205325ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/filename/index.js000066400000000000000000000004541345416772700222020ustar00rootroot00000000000000it("should be a string (__filename)", function() { expect(__filename).toBeTypeOf("string"); var f = __filename; expect(f).toBeTypeOf("string"); }); it("should be a string (__dirname)", function() { expect(__dirname).toBeTypeOf("string"); var d = __dirname; expect(d).toBeTypeOf("string"); }); webpack-4.30.0/test/cases/parsing/harmony-commonjs-mix/000077500000000000000000000000001345416772700230455ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-commonjs-mix/index.js000066400000000000000000000002561345416772700245150ustar00rootroot00000000000000it("should result in a warning when using module.exports in harmony module", function() { var x = require("./module1"); expect(x).toEqual(nsObj({ default: 1234 })); }); webpack-4.30.0/test/cases/parsing/harmony-commonjs-mix/module.js000066400000000000000000000000221345416772700246620ustar00rootroot00000000000000export default 1; webpack-4.30.0/test/cases/parsing/harmony-commonjs-mix/module1.js000066400000000000000000000006501345416772700247520ustar00rootroot00000000000000import "./module"; expect(function() { module.exports = 1; }).toThrowError(); expect((typeof module.exports)).toBe("undefined"); expect((typeof define)).toBe("undefined"); expect(function() { define(function() {}) }).toThrowError(/define is not defined/); export default 1234; if(eval("typeof exports !== \"undefined\"")) { // exports is node.js exports and not webpacks expect(Object.keys(exports)).toEqual([]); } webpack-4.30.0/test/cases/parsing/harmony-commonjs/000077500000000000000000000000001345416772700222525ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-commonjs/a.js000066400000000000000000000000611345416772700230250ustar00rootroot00000000000000export default function test() { return "OK"; } webpack-4.30.0/test/cases/parsing/harmony-commonjs/b.js000066400000000000000000000000531345416772700230270ustar00rootroot00000000000000export * from "./c"; export * from "./c2"; webpack-4.30.0/test/cases/parsing/harmony-commonjs/c.js000066400000000000000000000000251345416772700230270ustar00rootroot00000000000000export * from "./d"; webpack-4.30.0/test/cases/parsing/harmony-commonjs/c2.js000066400000000000000000000000241345416772700231100ustar00rootroot00000000000000export var x = "x"; webpack-4.30.0/test/cases/parsing/harmony-commonjs/d.js000066400000000000000000000000211345416772700230240ustar00rootroot00000000000000exports.y = "y"; webpack-4.30.0/test/cases/parsing/harmony-commonjs/e.js000066400000000000000000000000421345416772700230300ustar00rootroot00000000000000exports.a = "a"; exports.b = "b"; webpack-4.30.0/test/cases/parsing/harmony-commonjs/index.js000066400000000000000000000016451345416772700237250ustar00rootroot00000000000000import { x, y } from "./b"; it("should pass when required by CommonJS module", function () { var test1 = require('./a').default; expect(test1()).toBe("OK"); }); it("should pass when use babeljs transpiler", function() { //the following are generated code by use babeljs. // use it this way will save trouble to setup babel-loader // the babeljs transpiled code depends on the __esModule to be set var _test = require('./a'); var _test2 = _interopRequireDefault(_test); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var test2 = (0, _test2.default)(); expect(test2).toBe("OK"); }); it("should double reexport from non-harmony modules correctly", function() { expect(y).toBe("y"); expect(x).toBe("x"); }); import { a, b } from "./reexport" it("should be possible to reexport a module with unknown exports", function() { expect(a).toBe("a"); expect(b).toBe("b"); }); webpack-4.30.0/test/cases/parsing/harmony-commonjs/reexport.js000066400000000000000000000000431345416772700244550ustar00rootroot00000000000000export * from "./e"; import "./e"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/000077500000000000000000000000001345416772700237165ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/1.js000066400000000000000000000000511345416772700244100ustar00rootroot00000000000000export var x = "1"; export * from "./a"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/2.js000066400000000000000000000000511345416772700244110ustar00rootroot00000000000000export * from "./a"; export var x = "1"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/3.js000066400000000000000000000000521345416772700244130ustar00rootroot00000000000000export * from "./a"; export * from "./b"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/4.js000066400000000000000000000000521345416772700244140ustar00rootroot00000000000000export * from "./b"; export * from "./a"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/5.js000066400000000000000000000000521345416772700244150ustar00rootroot00000000000000export * from "./c"; export * from "./d"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/6.js000066400000000000000000000001241345416772700244160ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; export * from "./d"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/7.js000066400000000000000000000001241345416772700244170ustar00rootroot00000000000000export * from "./d"; export * from "./b"; export * from "./c"; export * from "./a"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/a.js000066400000000000000000000000241345416772700244700ustar00rootroot00000000000000export var x = "a"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/b.js000066400000000000000000000000241345416772700244710ustar00rootroot00000000000000export var x = "b"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/c.js000066400000000000000000000000211345416772700244670ustar00rootroot00000000000000exports.x = "c"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/d.js000066400000000000000000000000211345416772700244700ustar00rootroot00000000000000exports.x = "d"; webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/index.js000066400000000000000000000016371345416772700253720ustar00rootroot00000000000000import { x as x1 } from "./1?a"; import { x as x2 } from "./2?a"; import { x as x3 } from "./3?a"; import { x as x4 } from "./4?a"; import { x as x5 } from "./5?a"; import { x as x6 } from "./6?a"; import { x as x7 } from "./7?a"; var y1 = require("./1?b").x; var y2 = require("./2?b").x; var y3 = require("./3?b").x; var y4 = require("./4?b").x; var y5 = require("./5?b").x; var y6 = require("./6?b").x; var y7 = require("./7?b").x; it("should not overwrite when using star export (known exports)", function() { expect(x1).toBe("1"); expect(x2).toBe("1"); expect(x3).toBe("a"); expect(x4).toBe("b"); expect(x5).toBe("c"); expect(x6).toBe("a"); expect(x7).toBe("d"); }); it("should not overwrite when using star export (unknown exports)", function() { expect(y1).toBe("1"); expect(y2).toBe("1"); expect(y3).toBe("a"); expect(y4).toBe("b"); expect(y5).toBe("c"); expect(y6).toBe("a"); expect(y7).toBe("d"); }); webpack-4.30.0/test/cases/parsing/harmony-duplicate-export/reexport.js000066400000000000000000000000251345416772700261210ustar00rootroot00000000000000export * from "./a"; webpack-4.30.0/test/cases/parsing/harmony-edge-cases/000077500000000000000000000000001345416772700224255ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-edge-cases/a.js000066400000000000000000000001171345416772700232020ustar00rootroot00000000000000export default function test() { return "ok"; } var a = test(); export { a };webpack-4.30.0/test/cases/parsing/harmony-edge-cases/b.js000066400000000000000000000001171345416772700232030ustar00rootroot00000000000000export default function test() { return "ok"; } var b = test(); export { b };webpack-4.30.0/test/cases/parsing/harmony-edge-cases/c.js000066400000000000000000000000241345416772700232010ustar00rootroot00000000000000export var c = "ok";webpack-4.30.0/test/cases/parsing/harmony-edge-cases/d.js000066400000000000000000000000251345416772700232030ustar00rootroot00000000000000export default "ok"; webpack-4.30.0/test/cases/parsing/harmony-edge-cases/fake-reexport.js000066400000000000000000000001011345416772700255270ustar00rootroot00000000000000import { c } from "./c"; import d from "./d"; export { c, d }; webpack-4.30.0/test/cases/parsing/harmony-edge-cases/index.js000066400000000000000000000004221345416772700240700ustar00rootroot00000000000000import { a } from "./a"; import x, { b } from "./b"; import { c, d } from "./fake-reexport"; it("should be able to use exported function", function() { expect(a).toBe("ok"); expect(b).toBe("ok"); expect(x()).toBe("ok"); expect(c).toBe("ok"); expect(d).toBe("ok"); }); webpack-4.30.0/test/cases/parsing/harmony-export-hoist/000077500000000000000000000000001345416772700230725ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-export-hoist/bar.js000066400000000000000000000001171345416772700241730ustar00rootroot00000000000000import { foo, foo2 } from "./foo"; export default { foo: foo, foo2: foo2 }; webpack-4.30.0/test/cases/parsing/harmony-export-hoist/foo.js000066400000000000000000000002311345416772700242070ustar00rootroot00000000000000import {bar} from "./bar"; export function foo() { return "ok"; } function foo2() { return "ok"; } export { foo2 } export { default } from "./bar"; webpack-4.30.0/test/cases/parsing/harmony-export-hoist/index.js000066400000000000000000000004111345416772700245330ustar00rootroot00000000000000"use strict"; it("should hoist exports", function() { var result = require("./foo").default; expect(typeof result.foo).toEqual("function"); expect(typeof result.foo2).toEqual("function"); expect(result.foo()).toBe("ok"); expect(result.foo2()).toBe("ok"); }); webpack-4.30.0/test/cases/parsing/harmony-export-import-specifier/000077500000000000000000000000001345416772700252255ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-export-import-specifier/a.js000066400000000000000000000000511345416772700257770ustar00rootroot00000000000000export var x = 1; export * from "./cjs"; webpack-4.30.0/test/cases/parsing/harmony-export-import-specifier/cjs.js000066400000000000000000000000411345416772700263350ustar00rootroot00000000000000module.exports = { x: 2, y: 3 }; webpack-4.30.0/test/cases/parsing/harmony-export-import-specifier/index.js000066400000000000000000000002521345416772700266710ustar00rootroot00000000000000"use strict"; import { x, y } from "./a"; it("namespace export as from commonjs should override named export", function() { expect(x).toBe(1); expect(y).toBe(3); }); webpack-4.30.0/test/cases/parsing/harmony-export-precedence/000077500000000000000000000000001345416772700240415ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-export-precedence/a.js000066400000000000000000000002011345416772700246100ustar00rootroot00000000000000export function a() { return "a1"; } export { b } from "./b"; export * from "./c"; export { d } from "./b"; export var e = "e1"; webpack-4.30.0/test/cases/parsing/harmony-export-precedence/b.js000066400000000000000000000001511345416772700246150ustar00rootroot00000000000000export var a = "a2"; export var b = "b2"; export var c = "c2"; export var d = "d2"; export var e = "e2"; webpack-4.30.0/test/cases/parsing/harmony-export-precedence/c.js000066400000000000000000000002031345416772700246140ustar00rootroot00000000000000export var a = "a3"; export var b = "b3"; export var c = "c3"; export var e = "e3"; export var f = "f3"; export default "default"; webpack-4.30.0/test/cases/parsing/harmony-export-precedence/d.js000066400000000000000000000000321345416772700246150ustar00rootroot00000000000000export default "default"; webpack-4.30.0/test/cases/parsing/harmony-export-precedence/index.js000066400000000000000000000007361345416772700255140ustar00rootroot00000000000000import { a, b, c, d, e } from "./a"; import defaultImport from "./a"; it("should prefer local exports", function() { expect(a()).toBe("a1"); expect(e).toBe("e1"); }); it("should prefer indirect exports over star exports", function() { expect(b).toBe("b2"); expect(d).toBe("d2"); }); it("should use star exports", function() { expect(c).toBe("c3"); }); it("should not export default via star export", function() { expect((typeof defaultImport)).toBe("undefined"); }); webpack-4.30.0/test/cases/parsing/harmony-export-precedence/warnings.js000066400000000000000000000001441345416772700262260ustar00rootroot00000000000000module.exports = [ [/export 'default' \(imported as 'defaultImport'\) was not found in '.\/a'/] ]; webpack-4.30.0/test/cases/parsing/harmony-import-export-order/000077500000000000000000000000001345416772700243675ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-import-export-order/a.js000066400000000000000000000001011345416772700251350ustar00rootroot00000000000000import { add } from "./tracker"; add("a"); export var ax = "ax"; webpack-4.30.0/test/cases/parsing/harmony-import-export-order/b.js000066400000000000000000000001311345416772700251410ustar00rootroot00000000000000import { ax } from "./c"; import { add } from "./tracker"; add("b"); export var bx = ax; webpack-4.30.0/test/cases/parsing/harmony-import-export-order/c.js000066400000000000000000000002041345416772700251430ustar00rootroot00000000000000export * from "./a"; export * from "./b"; import { bx } from "./b"; export { bx as cx } import { add } from "./tracker"; add("c"); webpack-4.30.0/test/cases/parsing/harmony-import-export-order/index.js000066400000000000000000000005301345416772700260320ustar00rootroot00000000000000it("should process imports of star exports in the correct order", function() { var tracker = require("./tracker"); tracker.list.length = 0; delete require.cache[require.resolve("./c")]; var c = require("./c"); expect(tracker.list).toEqual(["a", "b", "c"]); expect(c.ax).toBe("ax"); expect(c.bx).toBe("ax"); expect(c.cx).toBe("ax"); }); webpack-4.30.0/test/cases/parsing/harmony-import-export-order/tracker.js000066400000000000000000000001041345416772700263530ustar00rootroot00000000000000export var list = []; export function add(str) { list.push(str); } webpack-4.30.0/test/cases/parsing/harmony-import-targets/000077500000000000000000000000001345416772700234065ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-import-targets/index.js000066400000000000000000000011561345416772700250560ustar00rootroot00000000000000import {x, f} from "./x"; it("should import into object literal", function() { (expect({ x: x })).toEqual({x: 1}); var obj = { x: x }; expect(obj).toEqual({x: 1}); }); function func(z) { return z; } it("should import into function argument", function() { expect(func(x)).toBe(1); expect(f(x)).toBe(1); expect(func({x:x})).toEqual({x:1}); expect(f({x:x})).toEqual({x:1}); var y = f(x); expect(y).toBe(1); y = function() { return x; }; expect(y()).toBe(1); }); it("should import into array literal", function() { expect([x, f(2)]).toEqual([1, 2]); expect([{ value: x }]).toEqual([{ value: x }]); }); webpack-4.30.0/test/cases/parsing/harmony-import-targets/x.js000066400000000000000000000000651345416772700242140ustar00rootroot00000000000000export var x = 1; export function f(x) { return x; }webpack-4.30.0/test/cases/parsing/harmony-info/000077500000000000000000000000001345416772700213605ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-info/commonjs.js000066400000000000000000000000001345416772700235310ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-info/index.js000066400000000000000000000002541345416772700230260ustar00rootroot00000000000000import def, { a as aa, b, c, d, e } from "./module"; import f, { g } from "./commonjs"; it("should emit the correct warnings", function() { def, aa, b, c, d, e, f, g }); webpack-4.30.0/test/cases/parsing/harmony-info/module.js000066400000000000000000000001141345416772700231770ustar00rootroot00000000000000function b() {} export { b } export var c = 123; export function d() {} webpack-4.30.0/test/cases/parsing/harmony-info/warnings.js000066400000000000000000000003231345416772700235440ustar00rootroot00000000000000module.exports = [ [/export 'default' \(imported as 'def'\) was not found in '\.\/module'/], [/export 'e' was not found in '\.\/module'/], [/export 'a' \(imported as 'aa'\) was not found in '\.\/module'/] ]; webpack-4.30.0/test/cases/parsing/harmony-injecting-order/000077500000000000000000000000001345416772700235105ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-injecting-order/file.js000066400000000000000000000000751345416772700247670ustar00rootroot00000000000000export function f() { return __webpack_amd_options__; }; webpack-4.30.0/test/cases/parsing/harmony-injecting-order/index.js000066400000000000000000000001541345416772700251550ustar00rootroot00000000000000it("should inject variables before exporting", function() { expect(require("./file").f()).toEqual({}); }); webpack-4.30.0/test/cases/parsing/harmony-spec/000077500000000000000000000000001345416772700213575ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-spec/eval.js000066400000000000000000000001051345416772700226400ustar00rootroot00000000000000export var value = 0; export function evalInModule(x) { eval(x); }; webpack-4.30.0/test/cases/parsing/harmony-spec/export-cycle-a.js000066400000000000000000000001731345416772700245520ustar00rootroot00000000000000function fun() { return true; }; import { callFun } from "./export-cycle-b"; export default callFun(); export { fun }; webpack-4.30.0/test/cases/parsing/harmony-spec/export-cycle-b.js000066400000000000000000000001261345416772700245510ustar00rootroot00000000000000import { fun } from "./export-cycle-a"; export function callFun() { return fun(); } webpack-4.30.0/test/cases/parsing/harmony-spec/index.js000066400000000000000000000020271345416772700230250ustar00rootroot00000000000000import { value, add } from "./live"; import { value as value2, add as add2 } from "./live-es5"; import { getLog } from "./order-tracker"; import "./order-c"; import cycleValue from "./export-cycle-a"; import { data } from "./self-cycle"; it("should establish live binding of values", function() { expect(value).toBe(0); add(2); expect(value).toBe(2); }); it("should establish live binding of values with transpiled es5 module", function() { expect(value2).toBe(0); add2(5); expect(value2).toBe(5); }); it("should allow to use eval with exports", function() { expect(valueEval).toBe(0); evalInModule("value = 5"); expect(valueEval).toBe(5); }); it("should execute modules in the correct order", function() { expect(getLog()).toEqual(["a", "b", "c"]); }); it("should bind exports before the module executes", function() { expect(cycleValue).toBe(true); }); it("should allow to import live variables from itself", function() { expect(data).toEqual([undefined, 1, 2]); }); import { value as valueEval, evalInModule } from "./eval"; webpack-4.30.0/test/cases/parsing/harmony-spec/live-es5.js000066400000000000000000000001461345416772700233470ustar00rootroot00000000000000exports.__esModule = true; exports.value = 0; exports.add = function add(x) { exports.value += x; }; webpack-4.30.0/test/cases/parsing/harmony-spec/live.js000066400000000000000000000000771345416772700226600ustar00rootroot00000000000000export var value = 0; export function add(x) { value += x; }; webpack-4.30.0/test/cases/parsing/harmony-spec/order-a.js000066400000000000000000000000611345416772700232430ustar00rootroot00000000000000import { log } from "./order-tracker"; log("a"); webpack-4.30.0/test/cases/parsing/harmony-spec/order-b.js000066400000000000000000000000611345416772700232440ustar00rootroot00000000000000import { log } from "./order-tracker"; log("b"); webpack-4.30.0/test/cases/parsing/harmony-spec/order-c.js000066400000000000000000000001311345416772700232430ustar00rootroot00000000000000import { log } from "./order-tracker"; import "./order-a"; log("c"); import "./order-b"; webpack-4.30.0/test/cases/parsing/harmony-spec/order-tracker.js000066400000000000000000000001461345416772700244620ustar00rootroot00000000000000var data = []; export function log(x) { data.push(x); }; export function getLog() { return data; }; webpack-4.30.0/test/cases/parsing/harmony-spec/self-cycle.js000066400000000000000000000002071345416772700237420ustar00rootroot00000000000000import { a as b } from "./self-cycle"; var data = []; data.push(b); var a = 1; data.push(b); a = 2; data.push(b); export { a, data } webpack-4.30.0/test/cases/parsing/harmony-tdz/000077500000000000000000000000001345416772700212265ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-tdz/index.js000066400000000000000000000004351345416772700226750ustar00rootroot00000000000000import value, { exception } from "./module"; it("should have a TDZ for exported const values", function() { expect((typeof exception)).toBe("object"); expect(exception).toBeInstanceOf(Error); expect(exception.message).toMatch(/ is not defined$/); expect(value).toBe("value"); }); webpack-4.30.0/test/cases/parsing/harmony-tdz/module.js000066400000000000000000000002261345416772700230510ustar00rootroot00000000000000import { f } from "./module2"; export let exception; try { f(); } catch(e) { exception = e; } export const value = "value"; export default f(); webpack-4.30.0/test/cases/parsing/harmony-tdz/module2.js000066400000000000000000000001121345416772700231250ustar00rootroot00000000000000import { value } from "./module"; export function f() { return value; } webpack-4.30.0/test/cases/parsing/harmony-tdz/test.filter.js000066400000000000000000000002511345416772700240250ustar00rootroot00000000000000var supportsBlockScoping = require("../../../helpers/supportsBlockScoping"); module.exports = function(config) { return !config.minimize && supportsBlockScoping(); }; webpack-4.30.0/test/cases/parsing/harmony-this/000077500000000000000000000000001345416772700213745ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony-this/abc.js000066400000000000000000000002651345416772700224620ustar00rootroot00000000000000function returnThis() { if(typeof this === "undefined") return "undefined"; return this; } var a = returnThis; var b = returnThis; export { a, b } export default returnThis; webpack-4.30.0/test/cases/parsing/harmony-this/index.js000066400000000000000000000011141345416772700230360ustar00rootroot00000000000000"use strict"; import d, {a, b as B} from "./abc"; import * as abc from "./abc"; function x() { throw new Error("should not be executed"); } it("should have this = undefined on imported non-strict functions", function() { x expect(d()).toBe("undefined"); x expect(a()).toBe("undefined"); x expect(B()).toBe("undefined"); }); import C2, { C } from "./new"; import * as New from "./new"; it("should be possible to use new correctly", function() { x expect(new C()).toEqual({ok: true}); x expect(new C2()).toEqual({ok: true}); x expect(new New.C()).toEqual({ok: true}); }); webpack-4.30.0/test/cases/parsing/harmony-this/new.js000066400000000000000000000001411345416772700225170ustar00rootroot00000000000000function C() { this.ok = this.pok; } C.prototype.pok = true; export default C; export { C }; webpack-4.30.0/test/cases/parsing/harmony/000077500000000000000000000000001345416772700204275ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony/index.js000066400000000000000000000060051345416772700220750ustar00rootroot00000000000000import {a, b as B} from "abc"; import * as abc from "abc"; import { fn } from "exportKinds"; import { one, two } from "exportKinds"; import { test1, test2 } from "exportKinds"; import { a as rea, b as reb, c as rec, o as reo, two as retwo, def as Thing3 } from "reexport"; import { a as rea2 } from "reexport2"; import threeIsOdd, { even } from "circularEven"; import { specA, specB } from "exports-specifier"; import Thing, { Other } from "commonjs"; import * as commonjs from "commonjs"; import Thing2, { Other as Other2 } from "commonjs-trans"; import * as commonjsTrans from "commonjs-trans"; import defaultExport from "def"; import "unused"; it("should import a default export from a module", function() { expect(defaultExport).toBe("def"); }); it("should import an identifier from a module", function() { expect(a).toBe("a"); expect(B).toBe("b"); }); it("should import a whole module", function() { expect(abc.a).toBe("a"); expect(abc.b).toBe("b"); expect(abc.c).toBe("c"); expect(abc.d.c).toBe("c"); expect(abc.e).toBe("c"); var copy = (function(a) { return a; }(abc)); expect(copy.a).toBe("a"); expect(copy.b).toBe("b"); expect(copy.c).toBe("c"); expect(copy.d.c).toBe("c"); expect(copy.e).toBe("c"); expect((typeof abc)).toBe("object"); expect("" + abc).toBe("[object Module]"); }); it("should export functions", function() { expect(fn).toBeTypeOf("function"); expect(fn()).toBe("fn"); expect((fn === fn)).toBe(true); }); it("should multiple variables with one statement", function() { expect(one).toBe("one"); expect(two).toBe("two"); }); it("should still be able to use exported stuff", function() { expect(test1).toBe("fn"); expect(test2).toBe("two"); }); it("should reexport a module", function() { expect(rea).toBe("a"); expect(reb).toBe("b"); expect(rec).toBe("c"); expect(reo).toBe("one"); expect(retwo).toBe("two"); expect(rea2).toBe("a"); }); it("should support circular dependencies", function() { expect(threeIsOdd).toBe(true); expect(even(4)).toBe(true); }); it("should support export specifier", function() { expect(specA).toBe(1); expect(specB).toBe(2); }); it("should be able to import commonjs", function() { function x() { throw new Error("should not be executed"); } // next line doesn't end with semicolon x expect(Thing).toBeTypeOf("function"); x expect(Thing()).toBe("thing"); x expect(Other).toBe("other"); expect(Thing2).toBeTypeOf("function"); expect(new Thing2().value).toBe("thing"); expect(Other2).toBe("other"); expect(Thing3()).toBe("thing"); }); it("should be able to import commonjs with star import", function() { var copyOfCommonjs = commonjs; expect(commonjs()).toBe("thing"); expect(commonjs.Other).toBe("other"); expect(copyOfCommonjs()).toBe("thing"); expect(copyOfCommonjs.Other).toBe("other"); var copyOfCommonjsTrans = commonjsTrans; expect(new commonjsTrans.default().value).toBe("thing"); expect(commonjsTrans.Other).toBe("other"); expect(new copyOfCommonjsTrans.default().value).toBe("thing"); expect(copyOfCommonjsTrans.Other).toBe("other"); }); webpack-4.30.0/test/cases/parsing/harmony/node_modules/000077500000000000000000000000001345416772700231045ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/harmony/node_modules/abc.js000066400000000000000000000002461345416772700241710ustar00rootroot00000000000000export var a = "a"; export var b = "b"; export {c} from "./abc_c"; import * as temp from "./abc_c"; export {temp as d}; import {c} from "./abc_c"; export {c as e}; webpack-4.30.0/test/cases/parsing/harmony/node_modules/abc_c.js000066400000000000000000000000241345416772700244650ustar00rootroot00000000000000export var c = "c"; webpack-4.30.0/test/cases/parsing/harmony/node_modules/circularEven.js000066400000000000000000000002051345416772700260610ustar00rootroot00000000000000import { odd } from "circularOdd"; export default odd(3); export function even(n) { if(n == 0) return true; return odd(n - 1); } webpack-4.30.0/test/cases/parsing/harmony/node_modules/circularOdd.js000066400000000000000000000001601345416772700256720ustar00rootroot00000000000000import { even } from "circularEven"; export function odd(n) { if(n == 0) return false; return even(n - 1); } webpack-4.30.0/test/cases/parsing/harmony/node_modules/commonjs-trans.js000066400000000000000000000001651345416772700264160ustar00rootroot00000000000000exports.__esModule = true; exports.default = function Thing() { this.value = "thing"; }; exports.Other = "other"; webpack-4.30.0/test/cases/parsing/harmony/node_modules/commonjs.js000066400000000000000000000001271345416772700252670ustar00rootroot00000000000000module.exports = function Thing() { return "thing"; } module.exports.Other = "other";webpack-4.30.0/test/cases/parsing/harmony/node_modules/def.js000066400000000000000000000000251345416772700241750ustar00rootroot00000000000000export default "def";webpack-4.30.0/test/cases/parsing/harmony/node_modules/exportKinds.js000066400000000000000000000001761345416772700257600ustar00rootroot00000000000000export function fn() { return "fn"; } export var one = "one", two = "two"; export var test1 = fn(); export var test2 = two; webpack-4.30.0/test/cases/parsing/harmony/node_modules/exports-specifier.js000066400000000000000000000000631345416772700271140ustar00rootroot00000000000000var specA = 1, b = 2; export { specA, b as specB } webpack-4.30.0/test/cases/parsing/harmony/node_modules/reexport.js000066400000000000000000000001541345416772700253120ustar00rootroot00000000000000export * from "abc"; export { one as o, two } from "exportKinds"; export { default as def } from "commonjs";webpack-4.30.0/test/cases/parsing/harmony/node_modules/reexport2.js000066400000000000000000000000421345416772700253700ustar00rootroot00000000000000"use strict"; export * from "abc";webpack-4.30.0/test/cases/parsing/harmony/node_modules/unused.js000066400000000000000000000001511345416772700247420ustar00rootroot00000000000000export var a = "a"; var b = "b"; export {b as d}; export {c as e} from "./abc_c"; export * from "./abc"; webpack-4.30.0/test/cases/parsing/hot-api/000077500000000000000000000000001345416772700203135ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/hot-api/a.js000066400000000000000000000000251345416772700210660ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/parsing/hot-api/b.js000066400000000000000000000000251345416772700210670ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/cases/parsing/hot-api/index.js000066400000000000000000000005411345416772700217600ustar00rootroot00000000000000if(module.hot) { it("should run module.hot.accept(…)", function() { module.hot.accept("./a", function() {}); }); it("should run module.hot.accept()", function() { module.hot.accept(); }); it("should run module.hot.decline", function() { module.hot.decline("./b"); }); } else { it("should run module.hot.* (disabled)", function() { }); } webpack-4.30.0/test/cases/parsing/hot-error-handler/000077500000000000000000000000001345416772700223065ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/hot-error-handler/index.js000066400000000000000000000002061345416772700237510ustar00rootroot00000000000000it("should parse a self accept with error handler", function() { if(module.hot) { module.hot.accept(function(err) { }); } });webpack-4.30.0/test/cases/parsing/hot-hash/000077500000000000000000000000001345416772700204655ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/hot-hash/index.js000066400000000000000000000004011345416772700221250ustar00rootroot00000000000000if(module.hot) { it("should have __webpack_hash__", function() { expect(typeof __webpack_hash__).toBeTypeOf("string"); expect(__webpack_hash__).toMatch(/^[0-9a-f]{20}$/); }); } else { it("should have __webpack_hash__ (disabled)", function() { }); } webpack-4.30.0/test/cases/parsing/inject-free-vars/000077500000000000000000000000001345416772700221165ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/inject-free-vars/fail.js000066400000000000000000000000301345416772700233600ustar00rootroot00000000000000throw new Error("Fail");webpack-4.30.0/test/cases/parsing/inject-free-vars/index.js000066400000000000000000000010021345416772700235540ustar00rootroot00000000000000it("should inject the module object into a chunk (AMD1)", function(done) { require([], function() { expect(module.webpackPolyfill).toBe(1); done(); }); }); it("should inject the module object into a chunk (AMD2)", function() { require([module.webpackPolyfill ? "./x1" : "./fail"]); expect(module.webpackPolyfill).toBe(1); }); it("should inject the module object into a chunk (ensure)", function(done) { require.ensure([], function(require) { expect(module.webpackPolyfill).toBe(1); done(); }); }); webpack-4.30.0/test/cases/parsing/inject-free-vars/x1.js000066400000000000000000000000001345416772700227720ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-1044/000077500000000000000000000000001345416772700204705ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-1044/index.js000066400000000000000000000002171345416772700221350ustar00rootroot00000000000000it("should not crash on missing spaces", function() { (function() { return"function"==typeof define&&define.amd?"hello":"world"; })(); }); webpack-4.30.0/test/cases/parsing/issue-1600/000077500000000000000000000000001345416772700204665ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-1600/file.js000066400000000000000000000000721345416772700217420ustar00rootroot00000000000000// module.js export default(function () { return 1; }); webpack-4.30.0/test/cases/parsing/issue-1600/index.js000066400000000000000000000001411345416772700221270ustar00rootroot00000000000000import fn from './file'; it("should compile correctly", function() { expect(fn()).toBe(1); }); webpack-4.30.0/test/cases/parsing/issue-2006/000077500000000000000000000000001345416772700204675ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2006/errors.js000066400000000000000000000000531345416772700223370ustar00rootroot00000000000000module.exports = [ [/Empty dependency/] ];webpack-4.30.0/test/cases/parsing/issue-2006/index.js000066400000000000000000000001041345416772700221270ustar00rootroot00000000000000it("should compile", function() {}); if(/./.test("")) require(""); webpack-4.30.0/test/cases/parsing/issue-2019/000077500000000000000000000000001345416772700204735ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2019/file.js000066400000000000000000000001251345416772700217460ustar00rootroot00000000000000var CONSTANT = "const"; var def = "default"; export default def; export { CONSTANT };webpack-4.30.0/test/cases/parsing/issue-2019/index.js000066400000000000000000000002561345416772700221430ustar00rootroot00000000000000it("should not fail on default export before export", function() { expect(require("./file").default).toBe("default"); expect(require("./file").CONSTANT).toBe("const"); }); webpack-4.30.0/test/cases/parsing/issue-2050/000077500000000000000000000000001345416772700204665ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2050/a.js000066400000000000000000000000341345416772700212410ustar00rootroot00000000000000var xa = "a"; export { xa };webpack-4.30.0/test/cases/parsing/issue-2050/b.js000066400000000000000000000000341345416772700212420ustar00rootroot00000000000000var xb = "b"; export { xb };webpack-4.30.0/test/cases/parsing/issue-2050/c.js000066400000000000000000000000341345416772700212430ustar00rootroot00000000000000var xc = "c"; export { xc };webpack-4.30.0/test/cases/parsing/issue-2050/d.js000066400000000000000000000000361345416772700212460ustar00rootroot00000000000000var xd = "d"; exports.xd = xd;webpack-4.30.0/test/cases/parsing/issue-2050/index.js000066400000000000000000000002221345416772700221270ustar00rootroot00000000000000it("should support multiple reexports", function() { expect(require("./x")).toEqual(nsObj({ xa: "a", xb: "b", xc: "c", xd: "d" })); }); webpack-4.30.0/test/cases/parsing/issue-2050/module.js000066400000000000000000000001231345416772700223050ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; export * from "./d";webpack-4.30.0/test/cases/parsing/issue-2050/x.js000066400000000000000000000001261345416772700212720ustar00rootroot00000000000000import { xa, xb, xc, xd } from "./module"; export { xa, xb, xc as xc, xd as xd } webpack-4.30.0/test/cases/parsing/issue-2084/000077500000000000000000000000001345416772700204755ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2084/file.js000066400000000000000000000000311345416772700217440ustar00rootroot00000000000000module.exports = "file"; webpack-4.30.0/test/cases/parsing/issue-2084/index.js000066400000000000000000000043131345416772700221430ustar00rootroot00000000000000function runWithThis(obj, fn) { fn.call(obj); } it("should bind this context on require callback", function(done) { require("./file"); runWithThis({ok: true}, function() { require([], function() { try { expect(require("./file")).toBe("file"); expect(this).toEqual({ok: true}); done(); } catch(e) { done(e); } }.bind(this)); }); }); it("should bind this context on require callback (loaded)", function(done) { runWithThis({ok: true}, function() { require(["./load.js"], function(load) { try { expect(require("./file")).toBe("file"); expect(load).toBe("load"); expect(this).toEqual({ok: true}); done(); } catch(e) { done(e); } }.bind(this)); }); }); it("should bind this context on require callback (foo)", function(done) { var foo = {ok: true}; require([], function(load) { try { expect(require("./file")).toBe("file"); expect(this).toEqual({ok: true}); done(); } catch(e) { done(e); } }.bind(foo)); }); it("should bind this context on require callback (foo, loaded)", function(done) { var foo = {ok: true}; require(["./load.js"], function(load) { try { expect(require("./file")).toBe("file"); expect(load).toBe("load"); expect(this).toEqual({ok: true}); done(); } catch(e) { done(e); } }.bind(foo)); }); it("should bind this context on require callback (foo)", function(done) { runWithThis({ok: true}, function() { require([], function(load) { try { expect(require("./file")).toBe("file"); expect(this).toEqual({ok: {ok: true}}); done(); } catch(e) { done(e); } }.bind({ok: this})); }); }); it("should bind this context on require.ensure callback", function(done) { runWithThis({ok: true}, function() { require.ensure([], function(require) { try { expect(require("./file")).toBe("file"); expect(this).toEqual({ok: true}); done(); } catch(e) { done(e); } }.bind(this)); }); }); it("should bind this context on require.ensure callback (loaded)", function(done) { runWithThis({ok: true}, function() { require.ensure(["./load.js"], function(require) { try { expect(require("./file")).toBe("file"); expect(this).toEqual({ok: true}); done(); } catch(e) { done(e); } }.bind(this)); }); }); webpack-4.30.0/test/cases/parsing/issue-2084/load.js000066400000000000000000000000311345416772700217440ustar00rootroot00000000000000module.exports = "load"; webpack-4.30.0/test/cases/parsing/issue-2349/000077500000000000000000000000001345416772700205015ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2349/a.js000066400000000000000000000001031345416772700212510ustar00rootroot00000000000000export var x = 1 // named export export default 0 // default exportwebpack-4.30.0/test/cases/parsing/issue-2349/index.js000066400000000000000000000002141345416772700221430ustar00rootroot00000000000000import {x} from './a' // named imported cases an errors it("should be able to import a named export", function() { expect(x).toBe(1); }); webpack-4.30.0/test/cases/parsing/issue-2522/000077500000000000000000000000001345416772700204725ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2522/index.js000066400000000000000000000004441345416772700221410ustar00rootroot00000000000000import { a, a as aa } from "./module"; import b from "./module"; import * as c from "./module"; it("should import into object shorthand", function() { var o = { a, aa, b, c }; expect(o).toEqual({ a: 123, aa: 123, b: 456, c: nsObj({ a: 123, default: 456 }) }); }) webpack-4.30.0/test/cases/parsing/issue-2522/module.js000066400000000000000000000000471345416772700223160ustar00rootroot00000000000000export var a = 123; export default 456;webpack-4.30.0/test/cases/parsing/issue-2522/test.filter.js000066400000000000000000000002161345416772700232720ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/parsing/issue-2523/000077500000000000000000000000001345416772700204735ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2523/index.js000066400000000000000000000003561345416772700221440ustar00rootroot00000000000000import A from "./module"; import { B } from "./module"; import { c } from "./module"; it("should allow to export a class", function() { expect((typeof A)).toBe("function"); expect((typeof B)).toBe("function"); expect(c).toBe("c"); }) webpack-4.30.0/test/cases/parsing/issue-2523/module.js000066400000000000000000000001021345416772700223070ustar00rootroot00000000000000export default class A {} export class B {} export const c = 'c';webpack-4.30.0/test/cases/parsing/issue-2523/test.filter.js000066400000000000000000000002161345416772700232730ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/parsing/issue-2528-2/000077500000000000000000000000001345416772700206375ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2528-2/index.js000066400000000000000000000000501345416772700222770ustar00rootroot00000000000000foo(); import { foo } from './module'; webpack-4.30.0/test/cases/parsing/issue-2528-2/module.js000066400000000000000000000000741345416772700224630ustar00rootroot00000000000000export function foo() { it("should run", function() {}); } webpack-4.30.0/test/cases/parsing/issue-2528/000077500000000000000000000000001345416772700205005ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2528/helperA.js000066400000000000000000000000531345416772700224140ustar00rootroot00000000000000module.exports = function(a) { return a; } webpack-4.30.0/test/cases/parsing/issue-2528/helperB.js000066400000000000000000000000701345416772700224140ustar00rootroot00000000000000module.exports = { mark: function(a) { return a(); } } webpack-4.30.0/test/cases/parsing/issue-2528/helperC.js000066400000000000000000000003121345416772700224140ustar00rootroot00000000000000module.exports = { wrap: function(fn) { return function() { var context = { prev: 0, next: 0, stop: function() { this.next = "end"; } }; while(context.next !== "end") fn(context); } } } webpack-4.30.0/test/cases/parsing/issue-2528/index.js000066400000000000000000000022251345416772700221460ustar00rootroot00000000000000import { foo } from './module'; import impA from "./helperA"; import impB from "./helperB"; import impC from "./helperC"; var notExportedAsync = function () { var ref = impA(impB.mark(function _callee2() { return impC.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: foo(); case 1: case 'end': return _context2.stop(); } } }, _callee2, this); })); return function notExportedAsync() { return ref.apply(this, arguments); }; }(); export var exportedAsync = function () { var ref = impA(impB.mark(function _callee() { return impC.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return foo(); case 2: case 'end': return _context.stop(); } } }, _callee, this); })); return function exportedAsync() { return ref.apply(this, arguments); }; }(); import { count } from "./module"; it("should run async functions", function() { var org = count; notExportedAsync(); expect(count).toBe(org + 1); exportedAsync(); expect(count).toBe(org + 2); }); webpack-4.30.0/test/cases/parsing/issue-2528/module.js000066400000000000000000000001071345416772700223210ustar00rootroot00000000000000export function foo() { count++; return; } export var count = 0; webpack-4.30.0/test/cases/parsing/issue-2570/000077500000000000000000000000001345416772700204755ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2570/fn.js000066400000000000000000000000771345416772700214420ustar00rootroot00000000000000export default function() { return [].slice.call(arguments); } webpack-4.30.0/test/cases/parsing/issue-2570/index.js000066400000000000000000000004701345416772700221430ustar00rootroot00000000000000import fn from "./fn"; it("should generate valid code when calling a harmony import function with brackets", function() { var a = fn((1)); var b = fn(2); var c = fn((3), (4)); var d = fn(5, (6)); expect(a).toEqual([1]); expect(b).toEqual([2]); expect(c).toEqual([3, 4]); expect(d).toEqual([5, 6]); }); webpack-4.30.0/test/cases/parsing/issue-2600/000077500000000000000000000000001345416772700204675ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2600/errors.js000066400000000000000000000000621345416772700223370ustar00rootroot00000000000000module.exports = [ [/Can't resolve 'missing'/] ];webpack-4.30.0/test/cases/parsing/issue-2600/index.js000066400000000000000000000001151345416772700221310ustar00rootroot00000000000000if(Math.sin(1) > 1000) import("missing"); it("should run", function() {}); webpack-4.30.0/test/cases/parsing/issue-2618/000077500000000000000000000000001345416772700205005ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2618/index.js000066400000000000000000000004361345416772700221500ustar00rootroot00000000000000import defaultValue, { value, value2, value3, value4 } from "./module"; it("should be possible to redefine Object in a module", function() { expect(value).toBe(123); expect(value2).toBe(123); expect(value3).toBe(123); expect(value4).toBe(123); expect(defaultValue).toBe(123); }); webpack-4.30.0/test/cases/parsing/issue-2618/module.js000066400000000000000000000002541345416772700223240ustar00rootroot00000000000000var Object = 123; export const value = Object; export var value2 = Object; export default Object; export * from "./module2"; export { value3 as value4 } from "./module2"; webpack-4.30.0/test/cases/parsing/issue-2618/module2.js000066400000000000000000000000311345416772700223770ustar00rootroot00000000000000export var value3 = 123; webpack-4.30.0/test/cases/parsing/issue-2618/test.filter.js000066400000000000000000000002161345416772700233000ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/parsing/issue-2622/000077500000000000000000000000001345416772700204735ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2622/index.js000066400000000000000000000005341345416772700221420ustar00rootroot00000000000000import { a, b } from "./module"; function func(x = a, y = b) { return [x, y]; } var func2 = function(x = a, y = b) { return [x, y]; } it("should import into default parameters", function() { expect(func()).toEqual(["a", "b"]); expect(func2()).toEqual(["a", "b"]); expect(func(1)).toEqual([1, "b"]); expect(func2(2)).toEqual([2, "b"]); }); webpack-4.30.0/test/cases/parsing/issue-2622/module.js000066400000000000000000000000501345416772700223110ustar00rootroot00000000000000export var a = "a"; export var b = "b"; webpack-4.30.0/test/cases/parsing/issue-2622/test.filter.js000066400000000000000000000002461345416772700232760ustar00rootroot00000000000000var supportsDefaultArgs = require("../../../helpers/supportsDefaultArgs"); module.exports = function(config) { return !config.minimize && supportsDefaultArgs(); }; webpack-4.30.0/test/cases/parsing/issue-2641/000077500000000000000000000000001345416772700204745ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2641/errors.js000066400000000000000000000001221345416772700223410ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /] ]; webpack-4.30.0/test/cases/parsing/issue-2641/file.js000066400000000000000000000000501345416772700217440ustar00rootroot00000000000000define(function() { return "file"; }); webpack-4.30.0/test/cases/parsing/issue-2641/index.js000066400000000000000000000027511345416772700221460ustar00rootroot00000000000000it("should require existing module with supplied error callback", function(done) { require(['./file'], function(file){ try { expect(file).toBe("file"); done(); } catch(e) { done(e); } }, function(error) { done(error); }); }); it("should call error callback on missing module", function(done) { require(['./file', './missingModule'], function(file){}, function(error) { try { expect(error).toBeInstanceOf(Error); expect(error.message).toBe("Cannot find module './missingModule'"); done(); } catch(e) { done(e); } }); }); it("should call error callback on missing module in context", function(done) { (function(module) { require(['./' + module], function(file){}, function(error) { try { expect(error).toBeInstanceOf(Error); expect(error.message).toBe("Cannot find module './missingModule'"); done(); } catch(e) { done(e); } }); })('missingModule'); }); it("should call error callback on exception thrown in loading module", function(done) { require(['./throwing'], function(){}, function(error) { try { expect(error).toBeInstanceOf(Error); expect(error.message).toBe('message'); done(); } catch(e) { done(e); } }); }); it("should not call error callback on exception thrown in require callback", function(done) { require(['./throwing'], function() { throw new Error('message'); }, function(error) { try { expect(error).toBeInstanceOf(Error); expect(error.message).toBe('message'); done(); } catch(e) { done(e); } }); }); webpack-4.30.0/test/cases/parsing/issue-2641/throwing.js000066400000000000000000000000651345416772700226740ustar00rootroot00000000000000define(function() { throw new Error('message'); }); webpack-4.30.0/test/cases/parsing/issue-2895/000077500000000000000000000000001345416772700205075ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2895/a.js000066400000000000000000000000521345416772700212620ustar00rootroot00000000000000export const a = { x: 1 }, b = { x: 2 } webpack-4.30.0/test/cases/parsing/issue-2895/index.js000066400000000000000000000002321345416772700221510ustar00rootroot00000000000000import { a, b } from "./a"; it("should export a const value without semicolon", function() { expect(a).toEqual({x: 1}); expect(b).toEqual({x: 2}); }); webpack-4.30.0/test/cases/parsing/issue-2895/test.filter.js000066400000000000000000000002511345416772700233060ustar00rootroot00000000000000var supportsBlockScoping = require("../../../helpers/supportsBlockScoping"); module.exports = function(config) { return !config.minimize && supportsBlockScoping(); }; webpack-4.30.0/test/cases/parsing/issue-2942/000077500000000000000000000000001345416772700205005ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-2942/index.js000066400000000000000000000007071345416772700221510ustar00rootroot00000000000000it("should polyfill System", function() { if (typeof System === "object" && typeof System.register === "function") { require("fail"); } expect((typeof System)).toBe("object"); expect((typeof System.register)).toBe("undefined"); expect((typeof System.get)).toBe("undefined"); expect((typeof System.set)).toBe("undefined"); expect((typeof System.anyNewItem)).toBe("undefined"); var x = System.anyNewItem; expect((typeof x)).toBe("undefined"); }) webpack-4.30.0/test/cases/parsing/issue-2942/warnings.js000066400000000000000000000002421345416772700226640ustar00rootroot00000000000000module.exports = [ [/System.register is not supported by webpack/], [/System.get is not supported by webpack/], [/System.set is not supported by webpack/], ]; webpack-4.30.0/test/cases/parsing/issue-3116/000077500000000000000000000000001345416772700204725ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-3116/file.js000066400000000000000000000000621345416772700217450ustar00rootroot00000000000000export default "default"; export var abc = "abc"; webpack-4.30.0/test/cases/parsing/issue-3116/file2.js000066400000000000000000000000621345416772700220270ustar00rootroot00000000000000export default "default"; export var abc = "abc"; webpack-4.30.0/test/cases/parsing/issue-3116/index.js000066400000000000000000000006451345416772700221440ustar00rootroot00000000000000import * as file from "./file"; import * as file2 from "./file2"; it("should translate indexed access to harmony import correctly", function() { expect(file["default"]).toBe("default"); expect(file["abc"]).toBe("abc"); }); it("should translate dynamic indexed access to harmony import correctly", function() { var fault = "fault"; expect(file2["de" + fault]).toBe("default"); expect(file2["abc"]).toBe("abc"); }); webpack-4.30.0/test/cases/parsing/issue-3238/000077500000000000000000000000001345416772700204775ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-3238/index.js000066400000000000000000000002031345416772700221370ustar00rootroot00000000000000it("supports empty element in destructuring", function() { const second = ([, x]) => x; expect(second([1, 2])).toEqual(2); }); webpack-4.30.0/test/cases/parsing/issue-3238/test.filter.js000066400000000000000000000003041345416772700232750ustar00rootroot00000000000000var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); module.exports = function(config) { return !config.minimize && supportsIteratorDestructuring(); }; webpack-4.30.0/test/cases/parsing/issue-3252/000077500000000000000000000000001345416772700204735ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-3252/a.js000066400000000000000000000002561345416772700212540ustar00rootroot00000000000000export class V6Engine { toString() { return 'V6'; } } export class V8Engine { toString() { return 'V8'; } } export function getVersion() { return '1.0'; } webpack-4.30.0/test/cases/parsing/issue-3252/index.js000066400000000000000000000003361345416772700221420ustar00rootroot00000000000000import * as E from './a'; function fooBar({some, bar = E.V6Engine}) { return new bar().toString(); } it("supports default argument assignment in import", function () { expect(fooBar({some:"test"})).toEqual('V6'); }); webpack-4.30.0/test/cases/parsing/issue-3252/test.filter.js000066400000000000000000000002671345416772700233010ustar00rootroot00000000000000var supportsDefaultAssignment = require("../../../helpers/supportDefaultAssignment"); module.exports = function(config) { return !config.minimize && supportsDefaultAssignment(); }; webpack-4.30.0/test/cases/parsing/issue-3273/000077500000000000000000000000001345416772700204765ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-3273/file.js000066400000000000000000000000321345416772700217460ustar00rootroot00000000000000export var test = "test"; webpack-4.30.0/test/cases/parsing/issue-3273/index.js000066400000000000000000000016301345416772700221430ustar00rootroot00000000000000import { test } from "./file"; it("should hide import by local var", function() { var test = "ok"; expect(test).toBe("ok"); }); it("should hide import by object pattern", function() { var { test } = { test: "ok" }; expect(test).toBe("ok"); }); it("should hide import by array pattern", function() { var [test] = ["ok"]; expect(test).toBe("ok"); }); it("should hide import by array pattern (nested)", function() { var [[test]] = [["ok"]]; expect(test).toBe("ok"); }); it("should hide import by pattern in function", function() { (function({test}) { expect(test).toBe("ok"); }({ test: "ok" })); }); it("should allow import in default (incorrect)", function() { var { other = test, test } = { test: "ok" }; expect(test).toBe("ok"); expect((typeof other)).toBe("undefined"); }); it("should allow import in default", function() { var { other = test } = { test: "ok" }; expect(other).toBe("test"); }); webpack-4.30.0/test/cases/parsing/issue-3273/test.filter.js000066400000000000000000000004631345416772700233020ustar00rootroot00000000000000var supportsDefaultAssignment = require("../../../helpers/supportDefaultAssignment"); var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); module.exports = function(config) { return !config.minimize && supportsDefaultAssignment() && supportsObjectDestructuring(); }; webpack-4.30.0/test/cases/parsing/issue-345/000077500000000000000000000000001345416772700204135ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-345/abc/000077500000000000000000000000001345416772700211405ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-345/abc/abcTest.js000066400000000000000000000000261345416772700230610ustar00rootroot00000000000000module.exports = "ok";webpack-4.30.0/test/cases/parsing/issue-345/index.js000066400000000000000000000003001345416772700220510ustar00rootroot00000000000000it("should parse multiple expressions in a require", function(done) { var name = "abc"; require(["./" + name + "/" + name + "Test"], function(x) { expect(x).toBe("ok"); done(); }); }); webpack-4.30.0/test/cases/parsing/issue-3769/000077500000000000000000000000001345416772700205105ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-3769/a.js000066400000000000000000000000321345416772700212610ustar00rootroot00000000000000export const thing = 123; webpack-4.30.0/test/cases/parsing/issue-3769/b.js000066400000000000000000000000241345416772700212630ustar00rootroot00000000000000export default 123; webpack-4.30.0/test/cases/parsing/issue-3769/c.js000066400000000000000000000000241345416772700212640ustar00rootroot00000000000000export default 123; webpack-4.30.0/test/cases/parsing/issue-3769/cjs.js000066400000000000000000000000571345416772700216270ustar00rootroot00000000000000exports.__esModule = true; exports.test = 123; webpack-4.30.0/test/cases/parsing/issue-3769/d.js000066400000000000000000000000241345416772700212650ustar00rootroot00000000000000export default 123; webpack-4.30.0/test/cases/parsing/issue-3769/imported.js000066400000000000000000000000271345416772700226700ustar00rootroot00000000000000exports.test = "test"; webpack-4.30.0/test/cases/parsing/issue-3769/index.js000066400000000000000000000001441345416772700221540ustar00rootroot00000000000000it("should generate valid code", function() { expect(require("./module").myTest).toBe("test"); }); webpack-4.30.0/test/cases/parsing/issue-3769/module.js000066400000000000000000000013101345416772700223260ustar00rootroot00000000000000import { thing } from './a' import user_settings_main from './c' import user_settings_change_password from './d' export { test as myTest } from "./imported"; export { default as preload } from './d?1' export { default as snackbar } from './d?2' export { default as authentication } from './d?3' export { default as navigator } from './d?4' export { default as locale } from './d?5' export { default as example_users } from './d?6' export { default as user_profile } from './d?7' export { default as block_user } from './d?8' export { default as log } from './d?9' export const user_settings = (thing, user_settings_main, user_settings_change_password) webpack-4.30.0/test/cases/parsing/issue-387/000077500000000000000000000000001345416772700204215ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-387/file.js000066400000000000000000000000261345416772700216740ustar00rootroot00000000000000module.exports = 4321;webpack-4.30.0/test/cases/parsing/issue-387/index.js000066400000000000000000000024001345416772700220620ustar00rootroot00000000000000it("should parse cujojs UMD modules", function() { (function (define) { // using the define signature that triggers AMD-wrapped CommonJS define(function (require) { return 123; }); }( typeof define == 'function' && define.amd ? define : function (factory) { module.exports = factory(require); } )); expect(module.exports).toBe(123); }); it("should parse cujojs UMD modules with deps", function() { (function (define) { // dependencies are listed in the dependency array define(['./file'], function (file) { return 1234; }); }( typeof define == 'function' && define.amd ? define : function (ids, factory) { // note: the lambda function cannot be removed in some CJS environments var deps = ids.map(function (id) { return require(id); }); module.exports = factory.apply(null, deps); } )); expect(module.exports).toBe(1234); }); it("should parse cujojs UMD modules with inlined deps", function() { (function (define) { // using the define signature that triggers AMD-wrapped CommonJS define(function (require) { return require("./file"); }); }( typeof define == 'function' && define.amd ? define : function (factory) { module.exports = factory(require); } )); expect(module.exports).toBe(4321); }); webpack-4.30.0/test/cases/parsing/issue-3917/000077500000000000000000000000001345416772700205035ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-3917/index.js000066400000000000000000000005231345416772700221500ustar00rootroot00000000000000it("should be able to compile a module with UMD", function() { var x = require("./module"); expect(x.default).toBe(global); }); it("should not find a free exports", function() { var x = require("./module2"); if(typeof exports !== "undefined") expect(x.default).toBe(exports); else expect((x.default)).toBe(false); }); export {} webpack-4.30.0/test/cases/parsing/issue-3917/module.js000066400000000000000000000005161345416772700223300ustar00rootroot00000000000000var root; if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (typeof module !== 'undefined') { root = module; } else { root = Function('return this')(); } var result = root; export default result; webpack-4.30.0/test/cases/parsing/issue-3917/module2.js000066400000000000000000000001651345416772700224120ustar00rootroot00000000000000var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; export default freeExports; webpack-4.30.0/test/cases/parsing/issue-3964/000077500000000000000000000000001345416772700205055ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-3964/index.js000066400000000000000000000002311345416772700221460ustar00rootroot00000000000000it("should be possible to export default an imported name", function() { var x = require("./module"); expect(x).toEqual(nsObj({ default: 1234 })); }); webpack-4.30.0/test/cases/parsing/issue-3964/module.js000066400000000000000000000000451345416772700223270ustar00rootroot00000000000000import X from "./x" export default X webpack-4.30.0/test/cases/parsing/issue-3964/x.js000066400000000000000000000000251345416772700213070ustar00rootroot00000000000000export default 1234; webpack-4.30.0/test/cases/parsing/issue-4179/000077500000000000000000000000001345416772700205045ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4179/index.js000066400000000000000000000004151345416772700221510ustar00rootroot00000000000000import def from "./module?harmony"; import * as mod from "./module?harmony-start" it("should export a sequence expression correctly", function() { expect(require("./module?cjs")).toEqual(nsObj({ default: 2 })); expect(def).toBe(2); expect(mod.default).toBe(2); }); webpack-4.30.0/test/cases/parsing/issue-4179/module.js000066400000000000000000000000271345416772700223260ustar00rootroot00000000000000export default (1, 2); webpack-4.30.0/test/cases/parsing/issue-4357/000077500000000000000000000000001345416772700205025ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4357/a.js000066400000000000000000000000261345416772700212560ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/cases/parsing/issue-4357/b.js000066400000000000000000000000241345416772700212550ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/cases/parsing/issue-4357/index.js000066400000000000000000000006761345416772700221600ustar00rootroot00000000000000import b from "./b"; it("should parse dynamic property names", function() { var o = { [require("./a")]: "a", [b]: "b" }; expect(o).toEqual({ a: "a", b: "b" }); }); it("should match dynamic property names", function() { const { [require("./a")]: aa, [b]: bb } = { a: "a", b: "b" }; const [x,, ...[{ [b]: { [b]: cc } }]] = [0, 1, {b: {b: "c"}}]; expect(aa).toBe("a"); expect(bb).toBe("b"); expect(cc).toBe("c"); }); webpack-4.30.0/test/cases/parsing/issue-4357/test.filter.js000066400000000000000000000005001345416772700232760ustar00rootroot00000000000000var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); module.exports = function(config) { return !config.minimize && supportsIteratorDestructuring() && supportsObjectDestructuring(); }; webpack-4.30.0/test/cases/parsing/issue-4596/000077500000000000000000000000001345416772700205075ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4596/index.js000066400000000000000000000006521345416772700221570ustar00rootroot00000000000000it("should evaluate require.resolve as truthy value", function() { var id; if(require.resolve) id = require.resolve("./module.js"); expect(typeof id === "number" || typeof id === "string").toBeTruthy(); }); it("should evaluate require.resolve in ?: expression", function() { var id = require.resolve ? require.resolve("./module.js") : null; expect(typeof id === "number" || typeof id === "string").toBeTruthy(); }); webpack-4.30.0/test/cases/parsing/issue-4596/module.js000066400000000000000000000000001345416772700223200ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4608-1/000077500000000000000000000000001345416772700206375ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4608-1/index.js000066400000000000000000000040211345416772700223010ustar00rootroot00000000000000it("should find var declaration later in code", function() { expect((typeof require)).toBe("undefined"); var require; }); it("should find var declaration in same statement", function() { var fn = (function() { require("fail"); }), require; require = (function(x) { expect(x).toBe("fail"); }); fn(); }); it("should find a catch block declaration", function() { try { var f = (function(x) { expect(x).toBe("fail"); }); throw f; } catch(require) { require("fail"); } }); it("should find var declaration in control statements", function() { var f = (function(x) { expect(x).toBe("fail"); }); (function() { { var require = f; } require("fail"); }()); (function() { var i = 1; while(i--) { var require = f; } require("fail"); }()); (function() { do { var require = f; } while(false); require("fail"); }()); (function() { for(var i = 0; i < 1; i++) { var require = f; } require("fail"); }()); (function() { for(var i in {a:1}) { var require = f; } require("fail"); }()); (function() { with({ a: 1 }) { var require = f; } require("fail"); }()); }); it("should find var declaration in control statements after usage", function() { var f = (function(x) { expect(x).toBe("fail"); }); (function() { var test = (function() { require("fail"); }); { var require = f; } test(); }()); (function() { var test = (function() { require("fail"); }); var i = 1; while(i--) { var require = f; } test(); }()); (function() { var test = (function() { require("fail"); }); do { var require = f; } while(false); test(); }()); (function() { var test = (function() { require("fail"); }); for(var i = 0; i < 1; i++) { var require = f; } test(); }()); (function() { var test = (function() { require("fail"); }); for(var i in {a:1}) { var require = f; } test(); }()); (function() { var test = (function() { require("fail"); }); with({ a: 1 }) { var require = f; } test(); }()); }); webpack-4.30.0/test/cases/parsing/issue-4608-2/000077500000000000000000000000001345416772700206405ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4608-2/index.js000066400000000000000000000007721345416772700223130ustar00rootroot00000000000000"use strict"; it("should find var declaration in control statements", function() { var f = (function(x) { expect(x).toBe("fail"); }); (function() { for(let x of ["a"]) { var require = f; } require("fail"); }()); }); it("should find var declaration in control statements after usage", function() { var f = (function(x) { expect(x).toBe("fail"); }); (function() { var test = (function() { require("fail"); }); for(let x of ["a"]) { var require = f; } test(); }()); }); webpack-4.30.0/test/cases/parsing/issue-4608-2/test.filter.js000066400000000000000000000002241345416772700234370ustar00rootroot00000000000000var supportsForOf = require("../../../helpers/supportsForOf"); module.exports = function(config) { return !config.minimize && supportsForOf(); }; webpack-4.30.0/test/cases/parsing/issue-4709/000077500000000000000000000000001345416772700205035ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4709/index.js000066400000000000000000000007011345416772700221460ustar00rootroot00000000000000function getDirectiveRequire(directive) { var require = directive.require || (directive.controller && directive.name); if (!isArray(require) && isObject(require)) { forEach(require, function(value, key) { var match = value.match(REQUIRE_PREFIX_REGEXP); var name = value.substring(match[0].length); if (!name) require[key] = match[0] + key; }); } return require; } it("should parse these snippets successfully", function() { }); webpack-4.30.0/test/cases/parsing/issue-4870/000077500000000000000000000000001345416772700205025ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4870/file.js000066400000000000000000000000321345416772700217520ustar00rootroot00000000000000export var test = "test"; webpack-4.30.0/test/cases/parsing/issue-4870/index.js000066400000000000000000000004421345416772700221470ustar00rootroot00000000000000import { test } from "./file"; it("should allow import in array destructing", function() { var other; [other = test] = []; expect(other).toBe("test"); }); it("should allow import in object destructing", function() { var other; ({other = test} = {}); expect(other).toBe("test"); }); webpack-4.30.0/test/cases/parsing/issue-4870/test.filter.js000066400000000000000000000005001345416772700232760ustar00rootroot00000000000000var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); module.exports = function(config) { return !config.minimize && supportsObjectDestructuring() && supportsIteratorDestructuring(); }; webpack-4.30.0/test/cases/parsing/issue-494/000077500000000000000000000000001345416772700204205ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-494/index.js000066400000000000000000000002101345416772700220560ustar00rootroot00000000000000it("should replace a free var in a IIFE", function() { (function(md) { expect(md).toBeTypeOf("function"); }(module.deprecate)); }); webpack-4.30.0/test/cases/parsing/issue-4940/000077500000000000000000000000001345416772700205005ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-4940/index.js000066400000000000000000000035061345416772700221510ustar00rootroot00000000000000define("local-module-object", function() { return { foo: "bar" }; }); define("local-side-effect", function() { return { foo: null }; }); define("local-module-non-object", ["local-side-effect"], function(sideEffect) { sideEffect.foo = "bar"; return 1; }); it("should create dependency when require is called with 'new' (object export)", function() { const result = new require("./object-export"); expect(result.foo).toBe("bar"); expect(result).toEqual(require("./object-export")); }); it("should create dependency when require is called with 'new' (non-object export)", function() { const sideEffect = require("./sideEffect"); const result = new require("./non-object-export"); expect(result instanceof __webpack_require__).toBe(true); expect(sideEffect.foo).toBe("bar"); expect(result).not.toEqual(require("./non-object-export")); }); it("should create dependency with 'new' on a local dependency (object export)", function() { const result = new require("local-module-object"); expect(result.foo).toBe("bar"); expect(result).toEqual(require("local-module-object")); }); it("shouldn't fail with a local dependency (non-object export)", function() { const sideEffect = require("local-side-effect"); const result = new require("local-module-non-object"); expect(result).not.toBe(1); expect(sideEffect.foo).toBe("bar"); expect(result).not.toEqual(require("local-module-non-object")); }); it("should work with 'require' in parentheses", function() { const result = new require("./object-export"); expect(result.foo).toBe("bar"); }); it("should work with local module 'require' in parentheses", function() { const result = new require("local-module-object"); expect(result.foo).toBe("bar"); }); it("shouldn't fail with non-object local module 'require' in parentheses", function() { new require("local-module-non-object"); }); webpack-4.30.0/test/cases/parsing/issue-4940/non-object-export.js000066400000000000000000000001341345416772700244110ustar00rootroot00000000000000const sideEffect = require("./sideEffect"); sideEffect.foo = "bar"; module.exports = "foo"; webpack-4.30.0/test/cases/parsing/issue-4940/object-export.js000066400000000000000000000000421345416772700236170ustar00rootroot00000000000000module.exports = { foo: "bar" }; webpack-4.30.0/test/cases/parsing/issue-4940/sideEffect.js000066400000000000000000000000411345416772700230720ustar00rootroot00000000000000module.exports = { foo: null }; webpack-4.30.0/test/cases/parsing/issue-551/000077500000000000000000000000001345416772700204125ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-551/index.js000066400000000000000000000012101345416772700220510ustar00rootroot00000000000000var window = {}; it("should be able to set the public path", function() { var originalValue = __webpack_public_path__; global.xyz = "xyz"; __webpack_public_path__ = global.xyz; expect(__webpack_require__.p).toBe("xyz"); delete global.xyz; window.something = "something"; __webpack_public_path__ = window.something; expect(__webpack_require__.p).toBe("something"); delete window.something; __webpack_public_path__ = "abc"; expect(__webpack_require__.p).toBe("abc"); __webpack_public_path__ = func(); expect(__webpack_require__.p).toBe("func"); __webpack_public_path__ = originalValue; function func() { return "func"; } }); webpack-4.30.0/test/cases/parsing/issue-5624/000077500000000000000000000000001345416772700205005ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-5624/index.js000066400000000000000000000002171345416772700221450ustar00rootroot00000000000000import { fn } from "./module"; it("should allow conditionals as callee", function() { var x = (true ? fn : fn)(); expect(x).toBe("ok"); }); webpack-4.30.0/test/cases/parsing/issue-5624/module.js000066400000000000000000000000471345416772700223240ustar00rootroot00000000000000export function fn() { return "ok"; } webpack-4.30.0/test/cases/parsing/issue-5889/000077500000000000000000000000001345416772700205155ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-5889/index.js000066400000000000000000000001771345416772700221670ustar00rootroot00000000000000const result = require("./module"); it("should correctly replace 'require' bindings", () => { expect(result).toBe(true); }); webpack-4.30.0/test/cases/parsing/issue-5889/module.js000066400000000000000000000001201345416772700223310ustar00rootroot00000000000000let result = false; if (require) { result = true; } module.exports = result; webpack-4.30.0/test/cases/parsing/issue-627/000077500000000000000000000000001345416772700204165ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-627/dir/000077500000000000000000000000001345416772700211745ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-627/dir/test.js000066400000000000000000000001651345416772700225130ustar00rootroot00000000000000expect(function() { var expr1 = "a", expr2 = "b"; require(Math.random() < 0.5 ? expr1 : expr2); }).toThrowError(); webpack-4.30.0/test/cases/parsing/issue-627/index.js000066400000000000000000000001221345416772700220560ustar00rootroot00000000000000it("should compile expr in ?: operator", function() { require("./dir/test"); }); webpack-4.30.0/test/cases/parsing/issue-627/warnings.js000066400000000000000000000000571345416772700226060ustar00rootroot00000000000000module.exports = [ [/Critical dependency/] ]; webpack-4.30.0/test/cases/parsing/issue-6867/000077500000000000000000000000001345416772700205125ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-6867/a.js000066400000000000000000000000351345416772700212660ustar00rootroot00000000000000export default function() {} webpack-4.30.0/test/cases/parsing/issue-6867/b.js000066400000000000000000000000371345416772700212710ustar00rootroot00000000000000export default (function() {}) webpack-4.30.0/test/cases/parsing/issue-6867/c.js000066400000000000000000000000411345416772700212650ustar00rootroot00000000000000export default function foo() {} webpack-4.30.0/test/cases/parsing/issue-6867/d.js000066400000000000000000000000431345416772700212700ustar00rootroot00000000000000export default (function bar() {}) webpack-4.30.0/test/cases/parsing/issue-6867/e.js000066400000000000000000000000301345416772700212650ustar00rootroot00000000000000export default class {} webpack-4.30.0/test/cases/parsing/issue-6867/f.js000066400000000000000000000000321345416772700212700ustar00rootroot00000000000000export default (class {}) webpack-4.30.0/test/cases/parsing/issue-6867/g.js000066400000000000000000000000321345416772700212710ustar00rootroot00000000000000export default class A {} webpack-4.30.0/test/cases/parsing/issue-6867/h.js000066400000000000000000000000341345416772700212740ustar00rootroot00000000000000export default (class A {}) webpack-4.30.0/test/cases/parsing/issue-6867/index.js000066400000000000000000000025711345416772700221640ustar00rootroot00000000000000it("should compile default export unnamed function declaration", function() { return import(/* webpackChunkName: "a" */ "./a") .then(({ default: a }) => { a() }); }); it("should compile default export unnamed function expression", function() { return import(/* webpackChunkName: "b" */ "./b") .then(({ default: b }) => { b() }); }); it("should compile default export named function declaration", function() { return import(/* webpackChunkName: "c" */ "./c") .then(({ default: c }) => { c() }); }); it("should compile default export named function expression", function() { return import(/* webpackChunkName: "d" */ "./d") .then(({ default: d }) => { d() }); }); it("should compile default export unnamed class declaration", function() { return import(/* webpackChunkName: "e" */ "./e") .then(({ default: E }) => { new E() }); }); it("should compile default export unnamed class expression", function() { return import(/* webpackChunkName: "f" */ "./f") .then(({ default: F }) => { new F() }); }); it("should compile default export named class declaration", function() { return import(/* webpackChunkName: "g" */ "./g") .then(({ default: G }) => { new G() }); }); it("should compile default export named class expression", function() { return import(/* webpackChunkName: "h" */ "./h") .then(({ default: H }) => { new H() }); }); webpack-4.30.0/test/cases/parsing/issue-7318/000077500000000000000000000000001345416772700205025ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-7318/index.js000066400000000000000000000001621345416772700221460ustar00rootroot00000000000000const type = require("./typeof"); it("should not output invalid code", () => { expect(type).toBe("number"); }); webpack-4.30.0/test/cases/parsing/issue-7318/typeof.js000066400000000000000000000000431345416772700223430ustar00rootroot00000000000000typeof 1 module.exports = "number" webpack-4.30.0/test/cases/parsing/issue-7335/000077500000000000000000000000001345416772700205015ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-7335/a.js000066400000000000000000000000221345416772700212510ustar00rootroot00000000000000export default 9; webpack-4.30.0/test/cases/parsing/issue-7335/index.js000066400000000000000000000012031345416772700221420ustar00rootroot00000000000000import x from "./a"; const sum1 = (x, y, total = x + y) => total; const id1 = (a = x) => a; function sum2(x, y, total = x + y) { return total; } function id2(a = x) { return a; } const sum3 = function(x, y, total = x + y) { return total; } const id3 = function(a = x) { return a; } it("should shadow imported bindings", () => { // Arrow functions expect(sum1(2, 3)).toBe(5); expect(id1(1)).toBe(1); expect(id1()).toBe(9); // Function declarations expect(sum2(2, 3)).toBe(5); expect(id2(1)).toBe(1); expect(id2()).toBe(9); // Function expressions expect(sum3(2, 3)).toBe(5); expect(id3(1)).toBe(1); expect(id3()).toBe(9); }); webpack-4.30.0/test/cases/parsing/issue-758/000077500000000000000000000000001345416772700204235ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-758/errors.js000066400000000000000000000001221345416772700222700ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /] ]; webpack-4.30.0/test/cases/parsing/issue-758/file.js000066400000000000000000000000501345416772700216730ustar00rootroot00000000000000define(function() { return "file"; }); webpack-4.30.0/test/cases/parsing/issue-758/index.js000066400000000000000000000036221345416772700220730ustar00rootroot00000000000000it("should require existing module with supplied error callback", function(done) { require.ensure(['./file'], function(){ try { var file = require('./file'); expect(file).toBe("file"); done(); } catch(e) { done(e); } }, function(error) {}); }); it("should call error callback on missing module", function(done) { require.ensure(['./missingModule'], function(){ require('./missingModule'); }, function(error) { expect(error).toBeInstanceOf(Error); expect(error.message).toBe("Cannot find module './missingModule'"); done(); }); }); it("should call error callback on missing module in context", function(done) { (function(module) { require.ensure([], function(){ require('./' + module); }, function(error) { expect(error).toBeInstanceOf(Error); expect(error.message).toBe("Cannot find module './missingModule'"); done(); }); })('missingModule'); }); it("should call error callback on exception thrown in loading module", function(done) { require.ensure(['./throwing'], function(){ require('./throwing'); }, function(error) { expect(error).toBeInstanceOf(Error); expect(error.message).toBe('message'); done(); }); }); it("should not call error callback on exception thrown in require callback", function(done) { require.ensure(['./throwing'], function() { throw new Error('message'); }, function(error) { expect(error).toBeInstanceOf(Error); expect(error.message).toBe('message'); done(); }); }); it("should call error callback when there is an error loading the chunk", function(done) { var temp = __webpack_require__.e; __webpack_require__.e = function() { return Promise.resolve().then(function() { throw 'fake chunk load error'; }); }; require.ensure(['./file'], function(){ try { var file = require('./file'); } catch(e) { done(e); } }, function(error) { expect(error).toBe('fake chunk load error'); done(); }); __webpack_require__.e = temp; }); webpack-4.30.0/test/cases/parsing/issue-758/throwing.js000066400000000000000000000000651345416772700226230ustar00rootroot00000000000000define(function() { throw new Error('message'); }); webpack-4.30.0/test/cases/parsing/issue-7728/000077500000000000000000000000001345416772700205075ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-7728/a.js000066400000000000000000000000621345416772700212630ustar00rootroot00000000000000export default function test() { return "OK"; } webpack-4.30.0/test/cases/parsing/issue-7728/index.js000066400000000000000000000002111345416772700221460ustar00rootroot00000000000000it("should detect module.require dependency", function () { var test1 = module.require('./a').default; expect(test1()).toBe("OK"); }); webpack-4.30.0/test/cases/parsing/issue-7778/000077500000000000000000000000001345416772700205145ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-7778/a.js000066400000000000000000000001011345416772700212620ustar00rootroot00000000000000export default function a() { return 'a' + __resourceQuery } webpack-4.30.0/test/cases/parsing/issue-7778/abc.js000066400000000000000000000001051345416772700215730ustar00rootroot00000000000000export default function abc() { return 'abc' + __resourceQuery } webpack-4.30.0/test/cases/parsing/issue-7778/index.js000066400000000000000000000032401345416772700221600ustar00rootroot00000000000000it("should detect query strings in dynamic import as a static value 1 ", function() { return Promise.all([ import("./a").then(({ default: a }) => { expect(a()).toBe("a"); }), import("./abc").then(({ default: a }) => { expect(a()).toBe("abc"); }), import("./a?queryString").then(({ default: a }) => { expect(a()).toBe("a?queryString"); }), import("./abc?query?String").then(({ default: a }) => { expect(a()).toBe("abc?query?String"); }), ]); }); it("should detect query strings in dynamic import as a static value 2", function() { var testFileName = "a"; return Promise.all([ import(`./${testFileName}`).then(({ default: a }) => { expect(a()).toBe("a"); }), import(`./${testFileName}bc`).then(({ default: a }) => { expect(a()).toBe("abc"); }), import(`./${testFileName}?queryString`).then(({ default: a }) => { expect(a()).toBe("a?queryString"); }), import(`./${testFileName}bc?query?String`).then(({ default: a }) => { expect(a()).toBe("abc?query?String"); }) ]); }); it("should detect query strings in dynamic import as a static value 3", function() { var testFileName = "a"; return Promise.all([ import("./" + testFileName).then(({ default: a }) => { expect(a()).toBe("a"); }), import("./" + testFileName + "").then(({ default: a }) => { expect(a()).toBe("a"); }), import("./" + testFileName + "bc").then(({ default: a }) => { expect(a()).toBe("abc"); }), import("./" + testFileName + "?queryString").then(({ default: a }) => { expect(a()).toBe("a?queryString"); }), import("./" + testFileName + "bc?query?String").then(({ default: a }) => { expect(a()).toBe("abc?query?String"); }) ]); }); webpack-4.30.0/test/cases/parsing/issue-8874/000077500000000000000000000000001345416772700205125ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/issue-8874/index.js000066400000000000000000000014741345416772700221650ustar00rootroot00000000000000import myFunction from './module'; import myFunctionDefaultParameter from './moduleDefaultParameter'; import myFunctionExportedFunctionExpression from './moduleExportedFunctionExpression'; import myFunctionExportedFunctionExpressionDefaultParameter from './moduleExportedFunctionExpressionDefaultParameter'; it('should execute IIFE twice', () => { expect(myFunction()).toBe(2); }); it('should execute IIFE twice when using IIFE function name as default parameter', () => { expect(myFunctionDefaultParameter()).toBe(2); }); it('should execute Function Expression twice', () => { expect(myFunctionExportedFunctionExpression()).toBe(2); }); it('should execute Function Expression twice when using IIFE function name as default parameter', () => { expect(myFunctionExportedFunctionExpressionDefaultParameter()).toBe(2); }); webpack-4.30.0/test/cases/parsing/issue-8874/module.js000066400000000000000000000004051345416772700223340ustar00rootroot00000000000000import someFunction from './someFunction'; export default function myFunction() { let iifeExecutionCount = 0; (function someFunction (recurse) { iifeExecutionCount++; if (recurse) { someFunction(false); } })(true); return iifeExecutionCount; } webpack-4.30.0/test/cases/parsing/issue-8874/moduleDefaultParameter.js000066400000000000000000000003741345416772700255070ustar00rootroot00000000000000export default function myFunction() { let iifeExecutionCount = 0; (function someFunction (recurse, recurseFunction = someFunction) { iifeExecutionCount++; if (recurse) { recurseFunction(false); } })(true); return iifeExecutionCount; } webpack-4.30.0/test/cases/parsing/issue-8874/moduleExportedFunctionExpression.js000066400000000000000000000002521345416772700276350ustar00rootroot00000000000000import someFunction from './someFunction'; export default (function someFunction (recurse = true) { if (recurse) { return 1 + someFunction(false); } return 1; }); webpack-4.30.0/test/cases/parsing/issue-8874/moduleExportedFunctionExpressionDefaultParameter.js000066400000000000000000000003161345416772700330040ustar00rootroot00000000000000 import someFunction from './someFunction'; export default (function someFunction (recurse = true, recurseFunction = someFunction) { if (recurse) { return 1 + recurseFunction(false); } return 1; }); webpack-4.30.0/test/cases/parsing/issue-8874/someFunction.js000066400000000000000000000000701345416772700235160ustar00rootroot00000000000000export default function someFunction () { return -1; } webpack-4.30.0/test/cases/parsing/javascript/000077500000000000000000000000001345416772700211205ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/javascript/index.js000066400000000000000000000002041345416772700225610ustar00rootroot00000000000000it("should parse sparse arrays", function() { // issue #136 expect([,null]).toHaveLength(2); expect([0,,,0]).toHaveLength(4); }); webpack-4.30.0/test/cases/parsing/local-modules/000077500000000000000000000000001345416772700215125ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/local-modules/dep.js000066400000000000000000000000271345416772700226170ustar00rootroot00000000000000module.exports = "dep";webpack-4.30.0/test/cases/parsing/local-modules/index.js000066400000000000000000000032611345416772700231610ustar00rootroot00000000000000it("should define and require a local module", function() { module.exports = "not set"; define("my-module", function() { return 1234; }); expect(module.exports).toBe("not set"); define(["my-module"], function(myModule) { expect(myModule).toBe(1234); return 2345; }); expect(module.exports).toBe(2345); expect(require("my-module")).toBe(1234); require(["my-module"]); }); it("should not create a chunk for a AMD require to a local module", function(done) { define("my-module2", function() { return 1235; }); var sync = false; require(["my-module2"], function(myModule2) { expect(myModule2).toBe(1235); sync = true; }); setImmediate(function() { expect(sync).toBe(true); done(); }); }); it("should define and require a local module with deps", function() { module.exports = "not set"; define("my-module3", ["./dep"], function(dep) { expect(dep).toBe("dep"); return 1234; }); expect(module.exports).toBe("not set"); define("my-module4", ["my-module3", "./dep"], function(myModule, dep) { expect(dep).toBe("dep"); expect(myModule).toBe(1234); return 2345; }); expect(module.exports).toBe("not set"); expect(require("my-module3")).toBe(1234); expect(require("my-module4")).toBe(2345); }); it("should define and require a local module that is relative", function () { define("my-dir/my-module3", function() { return 1234; }); define("my-dir/my-other-dir/my-module4", function() { return 2345; }); define("my-dir/my-other-dir/my-module5", ["./my-module4", "../my-module3"], function(myModule4, myModule3) { expect(myModule3).toBe(1234); expect(myModule4).toBe(2345); return 3456; }); expect(require("my-dir/my-other-dir/my-module5")).toBe(3456); }) webpack-4.30.0/test/cases/parsing/optional-catch-binding/000077500000000000000000000000001345416772700232675ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/optional-catch-binding/index.js000066400000000000000000000001541345416772700247340ustar00rootroot00000000000000import f from "./module"; it("should support optional catch binding", () => { expect(f()).toBe(true); }); webpack-4.30.0/test/cases/parsing/optional-catch-binding/module.js000066400000000000000000000001301345416772700251040ustar00rootroot00000000000000export default function() { try { throw new Error(); } catch { return true; } }; webpack-4.30.0/test/cases/parsing/optional-catch-binding/test.filter.js000066400000000000000000000004701345416772700260710ustar00rootroot00000000000000const supportsOptionalCatchBinding = require("../../../helpers/supportsOptionalCatchBinding"); module.exports = function(config) { // XXX: Disable this test if Terser is used because it does not support ES 2019 if (config.mode === "production") { return false; } return supportsOptionalCatchBinding(); }; webpack-4.30.0/test/cases/parsing/pattern-in-for/000077500000000000000000000000001345416772700216175ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/pattern-in-for/index.js000066400000000000000000000006721345416772700232710ustar00rootroot00000000000000it("should parse patterns in for in/of statements", () => { var message; for({ message = require("./module")} of [{}]) { expect(message).toBe("ok"); } for({ message = require("./module") } in { "string": "value" }) { expect(message).toBe("ok"); } for(var { value = require("./module")} of [{}]) { expect(value).toBe("ok"); } for(var { value = require("./module") } in { "string": "value" }) { expect(value).toBe("ok"); } }); webpack-4.30.0/test/cases/parsing/pattern-in-for/module.js000066400000000000000000000000271345416772700234410ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/cases/parsing/precreated-ast/000077500000000000000000000000001345416772700216555ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/precreated-ast/ast-loader.js000066400000000000000000000011241345416772700242440ustar00rootroot00000000000000"use strict"; const acorn = require("acorn"); const acornParser = acorn.Parser.extend(require("acorn-dynamic-import").default); module.exports = function(source) { const comments = []; const ast = acornParser.parse(source, { ranges: true, locations: true, ecmaVersion: 2017, sourceType: "module", onComment: comments }); // change something to test if it's really used ast.body[0].expression.right.arguments[0].value = "./ok"; ast.body[0].expression.right.arguments[0].raw = "\"./ok\""; ast.comments = comments; this.callback(null, source, null, { webpackAST: ast }); }; webpack-4.30.0/test/cases/parsing/precreated-ast/index.js000066400000000000000000000001671345416772700233260ustar00rootroot00000000000000it("should be able to process AST from loader", function() { expect(require("./ast-loader!./module")).toBe("ok"); }); webpack-4.30.0/test/cases/parsing/precreated-ast/module.js000066400000000000000000000000451345416772700234770ustar00rootroot00000000000000module.exports = require("./wrong"); webpack-4.30.0/test/cases/parsing/precreated-ast/ok.js000066400000000000000000000000271345416772700226230ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/cases/parsing/precreated-ast/wrong.js000066400000000000000000000000321345416772700233420ustar00rootroot00000000000000module.exports = "wrong"; webpack-4.30.0/test/cases/parsing/renaming/000077500000000000000000000000001345416772700205525ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/renaming/file.js000066400000000000000000000000261345416772700220250ustar00rootroot00000000000000module.exports = "ok";webpack-4.30.0/test/cases/parsing/renaming/index.js000066400000000000000000000051751345416772700222270ustar00rootroot00000000000000it("should be able to rename require by var", function() { var cjsRequire; // just to make it difficult var cjsRequire = require, cjsRequire2 = typeof require !== "undefined" && require; expect(cjsRequire("./file")).toBe("ok"); expect(cjsRequire2("./file")).toBe("ok"); }); it("should be able to rename require by assign", function() { var cjsRequire, cjsRequire2; (function() { cjsRequire = require; cjsRequire2 = typeof require === "function" && require; expect(cjsRequire("./file")).toBe("ok"); expect(cjsRequire2("./file")).toBe("ok"); }()); }); it("should be able to rename require by IIFE", function() { (function(cjsRequire) { expect(cjsRequire("./file")).toBe("ok"); }(require)); }); it("should be able to rename require by IIFE call", function() { (function(somethingElse, cjsRequire) { expect(cjsRequire("./file")).toBe("ok"); expect(somethingElse).toBe(123); }.call(this, 123, typeof require === "function" ? require : "error")); }); it("should be able to rename stuff by IIFE call", function() { (function(_exports, _exports2, _module, _module2, _define, _define2, _require, _require2) { _define(function(R, E, M) { expect(R("./file")).toBe("ok"); expect(_require("./file")).toBe("ok"); expect(_require2("./file")).toBe("ok"); expect(E).toBe(exports); expect(_exports).toBe(exports); expect(_exports2).toBe(exports); expect(M).toBe(module); expect(_module).toBe(module); expect(_module2).toBe(module); }); _define2(["./file"], function(file) { expect(file).toBe("ok"); }); }).call(this, typeof exports !== 'undefined' ? exports : null, exports, typeof module !== 'undefined' ? module : null, module, typeof define !== 'undefined' ? define : null, define, typeof require !== 'undefined' ? require : null, require); }); it("should accept less parameters in a IIFE call", function() { (function(r, require) { expect(r("./file")).toBe("ok"); expect((typeof require)).toBe("undefined"); }(require)); }); it("should accept more parameters in a IIFE call", function() { (function() { }(require)); }); it("should be able to rename stuff by IIFE call", function() { (function(_exports, _module, _define, _require) { _define(function(R, E, M) { expect(R("./file")).toBe("ok"); expect(_require("./file")).toBe("ok"); expect(E).toBe(exports); expect(_exports).toBe(exports); expect(M).toBe(module); expect(_module).toBe(module); }); }).call(this, typeof exports !== 'undefined' ? exports : null, typeof module !== 'undefined' ? module : null, typeof define !== 'undefined' ? define : null, typeof require !== 'undefined' ? require : null); }); webpack-4.30.0/test/cases/parsing/requirejs/000077500000000000000000000000001345416772700207635ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/requirejs/file.js000066400000000000000000000000001345416772700222260ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/requirejs/index.js000066400000000000000000000010001345416772700224170ustar00rootroot00000000000000it("should ignore require.config", function() { require.config({ }); requirejs.config({ }); }); it("should have a require.version", function() { expect(require.version).toBeTypeOf("string"); }); it("should have a requirejs.onError function", function() { function f(){} expect(requirejs.onError).toBeTypeOf("function"); // has default handler var org = requirejs.onError; requirejs.onError = f; expect(requirejs.onError).toBe(f); requirejs.onError = org; require(["./file.js"], function() {}); }); webpack-4.30.0/test/cases/parsing/resolve-weak-context/000077500000000000000000000000001345416772700230405ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/resolve-weak-context/dir/000077500000000000000000000000001345416772700236165ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/resolve-weak-context/dir/file.js000066400000000000000000000000341345416772700250700ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/cases/parsing/resolve-weak-context/index.js000066400000000000000000000003021345416772700245000ustar00rootroot00000000000000it("should be able to use require.resolveWeak with expression", function() { var expr = "file"; var id = require.resolveWeak("./dir/" + expr); expect(id).toBe(require("./dir/file.js")); }); webpack-4.30.0/test/cases/parsing/spread/000077500000000000000000000000001345416772700202305ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/spread/a.js000066400000000000000000000000271345416772700210050ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/cases/parsing/spread/index.js000066400000000000000000000005331345416772700216760ustar00rootroot00000000000000import X, { A, B } from "./module"; import * as M from "./module"; it("should support spread operator", function() { var o1 = { ...X }; expect(o1).toEqual({ A: "A", B: "B" }); var o2 = { ...({ X }) }; expect(o2).toEqual({ X: { A: "A", B: "B" } }); var o3 = { ...M }; expect(o3).toEqual({ default: { A: "A", B: "B" }, A: "A", B: "B" }); }); webpack-4.30.0/test/cases/parsing/spread/module.js000066400000000000000000000001121345416772700220450ustar00rootroot00000000000000const A = "A"; const B = "B"; export default { A, B }; export { A, B }; webpack-4.30.0/test/cases/parsing/spread/test.filter.js000066400000000000000000000002031345416772700230240ustar00rootroot00000000000000var supportsSpread = require("../../../helpers/supportsSpread"); module.exports = function(config) { return supportsSpread(); }; webpack-4.30.0/test/cases/parsing/strict-mode/000077500000000000000000000000001345416772700212045ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/strict-mode/abc.js000066400000000000000000000000631345416772700222660ustar00rootroot00000000000000export default function() { return typeof this; };webpack-4.30.0/test/cases/parsing/strict-mode/index.js000066400000000000000000000006361345416772700226560ustar00rootroot00000000000000"use strict"; define(["./abc"], function(abc) { // AMD is used here, because it adds stuff to the top of the code // we make sure to keep strict mode var a = abc.default; it("should keep strict mode", function() { var x = (function() { return this; })(); expect((typeof x)).toBe("undefined"); }); it("should import modules in strict mode", function() { expect(a()).toBe("undefined"); }); }); webpack-4.30.0/test/cases/parsing/typeof/000077500000000000000000000000001345416772700202605ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/typeof/errorfile.js000066400000000000000000000000651345416772700226100ustar00rootroot00000000000000))) This results in a syntax error loading this file.webpack-4.30.0/test/cases/parsing/typeof/index.js000066400000000000000000000045231345416772700217310ustar00rootroot00000000000000it("should not create a context for typeof require", function() { expect(require("./typeof")).toBe("function"); }); it("should answer typeof require correctly", function() { expect((typeof require)).toBe("function"); }); it("should answer typeof define correctly", function() { expect((typeof define)).toBe("function"); }); it("should answer typeof require.amd correctly", function() { expect((typeof require.amd)).toBe("object"); }); it("should answer typeof define.amd correctly", function() { expect((typeof define.amd)).toBe("object"); }); it("should answer typeof module correctly", function() { expect((typeof module)).toBe("object"); }); it("should answer typeof exports correctly", function() { expect((typeof exports)).toBe("object"); }); it("should answer typeof require.include correctly", function() { expect((typeof require.include)).toBe("function"); }); it("should answer typeof require.ensure correctly", function() { expect((typeof require.ensure)).toBe("function"); }); it("should answer typeof require.resolve correctly", function() { expect((typeof require.resolve)).toBe("function"); }); it("should answer typeof __non_webpack_require__ correctly", function() { var oldValue; eval("oldValue = require;"); expect((typeof __non_webpack_require__)).toBe("function"); eval("require = undefined;"); expect((typeof __non_webpack_require__)).toBe("undefined"); eval("require = oldValue;"); expect((typeof __non_webpack_require__)).toBe("function"); }); it("should not parse filtered stuff", function() { if(typeof require != "function") require("fail"); if(typeof require !== "function") require("fail"); if(!(typeof require == "function")) require("fail"); if(!(typeof require === "function")) require("fail"); if(typeof require == "undefined") require = require("fail"); if(typeof require === "undefined") require = require("fail"); if(typeof require.resolve !== "function") require("fail"); if(typeof module == "undefined") module = require("fail"); if(typeof module === "undefined") module = require("fail"); if(typeof module != "object") module = require("fail"); if(typeof exports == "undefined") exports = require("fail"); if(typeof System !== "object") exports = require("fail"); if(typeof require.include !== "function") require.include("fail"); if(typeof require.ensure !== "function") require.ensure(["fail"], function(){}); }); webpack-4.30.0/test/cases/parsing/typeof/typeof.js000066400000000000000000000000401345416772700221160ustar00rootroot00000000000000module.exports = typeof require;webpack-4.30.0/test/cases/parsing/unsupported-amd/000077500000000000000000000000001345416772700221015ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/unsupported-amd/errors.js000066400000000000000000000001571345416772700237560ustar00rootroot00000000000000module.exports = [ [/Cannot statically analyse/, /in line 12/], [/Cannot statically analyse/, /in line 4/] ];webpack-4.30.0/test/cases/parsing/unsupported-amd/index.js000066400000000000000000000005451345416772700235520ustar00rootroot00000000000000it("should fail on unsupported use of AMD require 1", function() { expect(function() { var abc = ["./a", "./b"]; require(abc, function(a, b) {}); }).toThrowError(); }); it("should fail on unsupported use of AMD require 2", function() { expect(function() { var abc = ["./a", "./b"]; function f(a, b) {} require(abc, f); }).toThrowError(); }); webpack-4.30.0/test/cases/parsing/var-hiding/000077500000000000000000000000001345416772700210025ustar00rootroot00000000000000webpack-4.30.0/test/cases/parsing/var-hiding/index.js000066400000000000000000000003521345416772700224470ustar00rootroot00000000000000var fn = function(module) { if (typeof module !== 'number') { throw new Error("module should be a number"); } expect((typeof module)).toBe("number"); }; it("should hide a free var by function argument", function() { fn(1); }); webpack-4.30.0/test/cases/resolving/000077500000000000000000000000001345416772700173175ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/000077500000000000000000000000001345416772700220635ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/errors.js000066400000000000000000000004541345416772700237400ustar00rootroot00000000000000module.exports = [ [/Module not found/, /recursive-file\/a/, /Recursion in resolving/], [/Module not found/, /recursive-file\/b/, /Recursion in resolving/], [/Module not found/, /recursive-file\/c/, /Recursion in resolving/], [/Module not found/, /recursive-file\/d/, /Recursion in resolving/] ];webpack-4.30.0/test/cases/resolving/browser-field/index.js000066400000000000000000000030641345416772700235330ustar00rootroot00000000000000it("should replace a module with a module", function() { expect(require("replacing-module1")).toBe("new-module"); }); it("should replace a module with a file in a module", function() { expect(require("replacing-module2")).toBe("new-module/inner"); }); it("should replace a module with file in the same module", function() { expect(require("replacing-module3")).toBe("new-module/inner"); }); it("should replace a module with a file in the current module", function() { expect(require("replacing-module4")).toBe("replacing-module4/module"); }); it("should replace a file with another file", function() { expect(require("replacing-file1")).toBe("new-file"); }); it("should replace a file with a module", function() { expect(require("replacing-file2")).toBe("new-module"); }); it("should replace a file with a file in a module", function() { expect(require("replacing-file3")).toBe("new-module/inner"); }); it("should replace a file in a directory with another file", function() { expect(require("replacing-file4")).toBe("new-file"); }); it("should ignore recursive module mappings", function() { expect(require("recursive-module")).toBe("new-module"); }); it("should use empty modules for ignored modules", function() { expect(require("ignoring-module").module).toEqual({}); expect(require("ignoring-module").file).toEqual({}); expect(require("ignoring-module").module).not.toBe(require("ignoring-module").file); }); // Errors require.include("recursive-file/a"); require.include("recursive-file/b"); require.include("recursive-file/c"); require.include("recursive-file/d"); webpack-4.30.0/test/cases/resolving/browser-field/node_modules/000077500000000000000000000000001345416772700245405ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/ignoring-module/000077500000000000000000000000001345416772700276375ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/ignoring-module/file.js000066400000000000000000000000301345416772700311050ustar00rootroot00000000000000throw new Error("Fail");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/ignoring-module/index.js000066400000000000000000000001131345416772700312770ustar00rootroot00000000000000exports.module = require("wrong-module"); exports.file = require("./file");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/ignoring-module/package.json000066400000000000000000000001021345416772700321160ustar00rootroot00000000000000{ "browser": { "wrong-module": false, "./file.js": false } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/new-module/000077500000000000000000000000001345416772700266145ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/new-module/index.js000066400000000000000000000000361345416772700302600ustar00rootroot00000000000000module.exports = "new-module";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/new-module/inner.js000066400000000000000000000000441345416772700302630ustar00rootroot00000000000000module.exports = "new-module/inner";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-file/000077500000000000000000000000001345416772700274645ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-file/a.js000066400000000000000000000000251345416772700302370ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-file/b.js000066400000000000000000000000251345416772700302400ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-file/c.js000066400000000000000000000000251345416772700302410ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-file/d.js000066400000000000000000000000251345416772700302420ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-file/package.json000066400000000000000000000001411345416772700317460ustar00rootroot00000000000000{ "browser": { "a.js": "./a", "./b.js": "./b", "c.js": "./d.js", "./d.js": "./c.js" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-module/000077500000000000000000000000001345416772700300325ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-module/index.js000066400000000000000000000000471345416772700315000ustar00rootroot00000000000000module.exports = require("new-module");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/recursive-module/package.json000066400000000000000000000000611345416772700323150ustar00rootroot00000000000000{ "browser": { "new-module": "new-module" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file1/000077500000000000000000000000001345416772700275025ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file1/file.js000066400000000000000000000000301345416772700307500ustar00rootroot00000000000000module.exports = "file";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file1/index.js000066400000000000000000000000431345416772700311440ustar00rootroot00000000000000module.exports = require("./file");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file1/new-file.js000066400000000000000000000000341345416772700315430ustar00rootroot00000000000000module.exports = "new-file";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file1/package.json000066400000000000000000000000631345416772700317670ustar00rootroot00000000000000{ "browser": { "./file.js": "./new-file.js" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file2/000077500000000000000000000000001345416772700275035ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file2/file.js000066400000000000000000000000301345416772700307510ustar00rootroot00000000000000module.exports = "file";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file2/index.js000066400000000000000000000000431345416772700311450ustar00rootroot00000000000000module.exports = require("./file");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file2/package.json000066400000000000000000000000601345416772700317650ustar00rootroot00000000000000{ "browser": { "./file.js": "new-module" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file3/000077500000000000000000000000001345416772700275045ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file3/file.js000066400000000000000000000000301345416772700307520ustar00rootroot00000000000000module.exports = "file";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file3/index.js000066400000000000000000000000431345416772700311460ustar00rootroot00000000000000module.exports = require("./file");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file3/package.json000066400000000000000000000000661345416772700317740ustar00rootroot00000000000000{ "browser": { "./file.js": "new-module/inner" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file4/000077500000000000000000000000001345416772700275055ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/000077500000000000000000000000001345416772700302635ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/file.js000066400000000000000000000000301345416772700315310ustar00rootroot00000000000000module.exports = "file";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/index.js000066400000000000000000000000431345416772700317250ustar00rootroot00000000000000module.exports = require("./file");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/new-file.js000066400000000000000000000000341345416772700323240ustar00rootroot00000000000000module.exports = "new-file";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file4/index.js000066400000000000000000000000421345416772700311460ustar00rootroot00000000000000module.exports = require("./dir");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-file4/package.json000066400000000000000000000000701345416772700317700ustar00rootroot00000000000000{ "browser": { "./dir/file.js": "./dir/new-file" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module1/000077500000000000000000000000001345416772700300505ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module1/index.js000066400000000000000000000000511345416772700315110ustar00rootroot00000000000000module.exports = require("wrong-module");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module1/package.json000066400000000000000000000000631345416772700323350ustar00rootroot00000000000000{ "browser": { "wrong-module": "new-module" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module2/000077500000000000000000000000001345416772700300515ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module2/index.js000066400000000000000000000000511345416772700315120ustar00rootroot00000000000000module.exports = require("wrong-module");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module2/package.json000066400000000000000000000000711345416772700323350ustar00rootroot00000000000000{ "browser": { "wrong-module": "new-module/inner" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module3/000077500000000000000000000000001345416772700300525ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module3/index.js000066400000000000000000000000471345416772700315200ustar00rootroot00000000000000module.exports = require("new-module");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module3/package.json000066400000000000000000000000671345416772700323430ustar00rootroot00000000000000{ "browser": { "new-module": "new-module/inner" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module4/000077500000000000000000000000001345416772700300535ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module4/index.js000066400000000000000000000000511345416772700315140ustar00rootroot00000000000000module.exports = require("wrong-module");webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module4/module.js000066400000000000000000000000541345416772700316750ustar00rootroot00000000000000module.exports = "replacing-module4/module";webpack-4.30.0/test/cases/resolving/browser-field/node_modules/replacing-module4/package.json000066400000000000000000000000641345416772700323410ustar00rootroot00000000000000{ "browser": { "wrong-module": "./module.js" } }webpack-4.30.0/test/cases/resolving/browser-field/node_modules/wrong-module.js000066400000000000000000000000401345416772700275070ustar00rootroot00000000000000module.exports = "wrong-module";webpack-4.30.0/test/cases/resolving/commomjs-local-module/000077500000000000000000000000001345416772700235165ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/commomjs-local-module/index.js000066400000000000000000000012071345416772700251630ustar00rootroot00000000000000define("regular", function(require, exports, module) { module.exports = "regular-module"; }); define("override-exports", function(require, exports, module) { exports = "this one overrides exports reference"; }); define("return-module", function(require, exports, module) { return "module is returned"; }); it("should make different modules for query", function() { expect(require("regular")).toBe("regular-module"); expect(require("return-module")).toBe("module is returned"); const overrideExports = require("override-exports"); expect(typeof overrideExports).toBe("object"); expect(Object.keys(overrideExports)).toHaveLength(0); }); webpack-4.30.0/test/cases/resolving/context/000077500000000000000000000000001345416772700210035ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/context/index.js000066400000000000000000000007101345416772700224460ustar00rootroot00000000000000it("should resolve loaders relative to require", function() { var index = "index", test = "test"; expect(require("./loaders/queryloader?query!!!!./node_modules/subcontent/" + index + ".js")).toEqual({ resourceQuery: "", query: "?query", prev: "module.exports = \"error\";" }); expect(require("!./loaders/queryloader?query!./node_modules/subcontent/" + test + ".pug")).toEqual({ resourceQuery: "", query: "?query", prev: "xyz: abc" }); }); webpack-4.30.0/test/cases/resolving/context/loaders/000077500000000000000000000000001345416772700224345ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/context/loaders/queryloader.js000066400000000000000000000002451345416772700253270ustar00rootroot00000000000000module.exports = function(content) { return "module.exports = " + JSON.stringify({ resourceQuery: this.resourceQuery, query: this.query, prev: content }); } webpack-4.30.0/test/cases/resolving/context/node_modules/000077500000000000000000000000001345416772700234605ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/context/node_modules/subcontent/000077500000000000000000000000001345416772700256445ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/context/node_modules/subcontent/index.js000066400000000000000000000000311345416772700273030ustar00rootroot00000000000000module.exports = "error";webpack-4.30.0/test/cases/resolving/context/node_modules/subcontent/test.pug000066400000000000000000000000101345416772700273270ustar00rootroot00000000000000xyz: abcwebpack-4.30.0/test/cases/resolving/issue-2986/000077500000000000000000000000001345416772700210555ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/issue-2986/errors.js000066400000000000000000000001621345416772700227260ustar00rootroot00000000000000module.exports = [ [/Can't resolve 'any' in/, /BREAKING CHANGE/, /any-loader/], [/Can't resolve 'other' in/] ]; webpack-4.30.0/test/cases/resolving/issue-2986/index.js000066400000000000000000000001451345416772700225220ustar00rootroot00000000000000require.include("any!"); require.include("other!"); it("should have correct errors", function() {}) webpack-4.30.0/test/cases/resolving/issue-2986/node_modules/000077500000000000000000000000001345416772700235325ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/issue-2986/node_modules/any-loader.js000066400000000000000000000000651345416772700261240ustar00rootroot00000000000000module.exports = function(source) { return source; } webpack-4.30.0/test/cases/resolving/query/000077500000000000000000000000001345416772700204645ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/query/empty.js000066400000000000000000000000001345416772700221460ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/query/index.js000066400000000000000000000005111345416772700221260ustar00rootroot00000000000000it("should make different modules for query", function() { var a = require("./empty"); var b = require("./empty?1"); var c = require("./empty?2"); expect(typeof a).toBe("object"); expect(typeof b).toBe("object"); expect(typeof c).toBe("object"); expect(a).not.toBe(b); expect(a).not.toBe(c); expect(b).not.toBe(c); }); webpack-4.30.0/test/cases/resolving/single-file-module/000077500000000000000000000000001345416772700230005ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/single-file-module/index.js000066400000000000000000000001601345416772700244420ustar00rootroot00000000000000it("should load single file modules", function() { expect(require("subfilemodule")).toBe("subfilemodule"); }); webpack-4.30.0/test/cases/resolving/single-file-module/node_modules/000077500000000000000000000000001345416772700254555ustar00rootroot00000000000000webpack-4.30.0/test/cases/resolving/single-file-module/node_modules/subfilemodule.js000066400000000000000000000000411345416772700306450ustar00rootroot00000000000000module.exports = "subfilemodule";webpack-4.30.0/test/cases/runtime/000077500000000000000000000000001345416772700167725ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/chunk-callback-order/000077500000000000000000000000001345416772700227455ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/chunk-callback-order/a.js000066400000000000000000000000251345416772700235200ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/cases/runtime/chunk-callback-order/b.js000066400000000000000000000000401345416772700235160ustar00rootroot00000000000000module.exports = require("./a");webpack-4.30.0/test/cases/runtime/chunk-callback-order/duplicate.js000066400000000000000000000001221345416772700252500ustar00rootroot00000000000000require.ensure(["./a"], function(require) { expect(require("./a")).toBe("a"); }) webpack-4.30.0/test/cases/runtime/chunk-callback-order/duplicate2.js000066400000000000000000000001221345416772700253320ustar00rootroot00000000000000require.ensure(["./b"], function(require) { expect(require("./b")).toBe("a"); }) webpack-4.30.0/test/cases/runtime/chunk-callback-order/index.js000066400000000000000000000005721345416772700244160ustar00rootroot00000000000000it("should fire multiple code load callbacks in the correct order", function(done) { var calls = []; require.ensure([], function(require) { require("./duplicate"); require("./duplicate2"); calls.push(1); }); require.ensure([], function(require) { require("./duplicate"); require("./duplicate2"); calls.push(2); expect(calls).toEqual([1,2]); done(); }); }); webpack-4.30.0/test/cases/runtime/circular-dependencies/000077500000000000000000000000001345416772700232225ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/circular-dependencies/circular.js000066400000000000000000000000731345416772700253640ustar00rootroot00000000000000module.exports = 1; module.exports = require("./circular");webpack-4.30.0/test/cases/runtime/circular-dependencies/circular2.js000066400000000000000000000000741345416772700254470ustar00rootroot00000000000000module.exports = 2; module.exports = require("./circular2");webpack-4.30.0/test/cases/runtime/circular-dependencies/index.js000066400000000000000000000001531345416772700246660ustar00rootroot00000000000000it("should load circular dependencies correctly", function() { expect(require("./circular")).toBe(1); }); webpack-4.30.0/test/cases/runtime/error-handling/000077500000000000000000000000001345416772700217055ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/error-handling/errors.js000066400000000000000000000001551345416772700235600ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /, /error-handling\/index.js/] ];webpack-4.30.0/test/cases/runtime/error-handling/folder/000077500000000000000000000000001345416772700231605ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/error-handling/folder/file1.js000066400000000000000000000000311345416772700245100ustar00rootroot00000000000000module.exports = "file1";webpack-4.30.0/test/cases/runtime/error-handling/folder/file2.js000066400000000000000000000000311345416772700245110ustar00rootroot00000000000000module.exports = "file2";webpack-4.30.0/test/cases/runtime/error-handling/folder/file3.js000066400000000000000000000000311345416772700245120ustar00rootroot00000000000000module.exports = "file3";webpack-4.30.0/test/cases/runtime/error-handling/index.js000066400000000000000000000013351345416772700233540ustar00rootroot00000000000000function testCase(number) { expect(require(number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule")).toBe("file" + number); expect(require( number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule" )).toBe("file" + number); } it("should throw an error on missing module at runtime, but not at compile time if in try block", function() { var error = null; try { testCase(4); // indirect } catch(e) { error = e; } expect(error).toBeInstanceOf(Error); error = null; try { require("./missingModule2"); // direct } catch(e) { error = e; } expect(error).toBeInstanceOf(Error); }); webpack-4.30.0/test/cases/runtime/error-handling/warnings.js000066400000000000000000000001561345416772700240750ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule2' /, /error-handling\/index.js/] ];webpack-4.30.0/test/cases/runtime/issue-1650/000077500000000000000000000000001345416772700205135ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/issue-1650/file.js000066400000000000000000000000401345416772700217620ustar00rootroot00000000000000__webpack_public_path__ = "ok"; webpack-4.30.0/test/cases/runtime/issue-1650/index.js000066400000000000000000000003131345416772700221550ustar00rootroot00000000000000it("should be able to set the public path globally", function() { var org = __webpack_public_path__; require("./file"); expect(__webpack_public_path__).toBe("ok"); __webpack_public_path__ = org; }); webpack-4.30.0/test/cases/runtime/issue-1788/000077500000000000000000000000001345416772700205275ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/issue-1788/a.js000066400000000000000000000002111345416772700212770ustar00rootroot00000000000000import b from './b'; export default 'a-default'; export { btest } from "./b"; export function atest() { expect(b).toBe("b-default"); } webpack-4.30.0/test/cases/runtime/issue-1788/b.js000066400000000000000000000001541345416772700213060ustar00rootroot00000000000000import a from './a'; export default 'b-default'; export function btest() { expect(a).toBe("a-default"); } webpack-4.30.0/test/cases/runtime/issue-1788/index.js000066400000000000000000000001571345416772700221770ustar00rootroot00000000000000import { atest, btest } from "./a"; it("should have the correct values", function() { atest(); btest(); }); webpack-4.30.0/test/cases/runtime/issue-2391-chunk/000077500000000000000000000000001345416772700216245ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/issue-2391-chunk/file.js000066400000000000000000000000001345416772700230670ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/issue-2391-chunk/index.js000066400000000000000000000002231345416772700232660ustar00rootroot00000000000000it("should have a require.onError function by default", function() { expect((typeof require.onError)).toBe("function"); require(["./file"]); }); webpack-4.30.0/test/cases/runtime/issue-2391/000077500000000000000000000000001345416772700205165ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/issue-2391/index.js000066400000000000000000000002461345416772700221650ustar00rootroot00000000000000it("should not have a require.onError function by default", function() { expect((typeof require.onError)).toBe("undefined"); // expected to fail in browsertests }); webpack-4.30.0/test/cases/runtime/missing-module-exception/000077500000000000000000000000001345416772700237225ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/missing-module-exception/index.js000066400000000000000000000002161345416772700253660ustar00rootroot00000000000000it("should have correct error code", function() { try { require("./fail"); } catch(e) { expect(e.code).toBe("MODULE_NOT_FOUND"); } }); webpack-4.30.0/test/cases/runtime/missing-module-exception/warnings.js000066400000000000000000000001101345416772700261000ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/fail' /] ];webpack-4.30.0/test/cases/runtime/module-caching/000077500000000000000000000000001345416772700216515ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/module-caching/index.js000066400000000000000000000021031345416772700233120ustar00rootroot00000000000000it("should cache modules correctly", function(done) { delete require.cache[require.resolve("./singular.js")]; expect(require("./singular.js").value).toBe(1); expect((require("./singular.js")).value).toBe(1); require("./sing" + "ular.js").value = 2; expect(require("./singular.js").value).toBe(2); require.ensure(["./two.js"], function(require) { expect(require("./singular.js").value).toBe(2); done(); }); }); it("should be able the remove modules from cache with require.cache and require.resolve", function() { var singularObj = require("./singular2"); var singularId = require.resolve("./singular2"); var singularIdInConditional = require.resolve(true ? "./singular2" : "./singular"); if(typeof singularId !== "number" && typeof singularId !== "string") throw new Error("require.resolve should return a number or string"); expect(singularIdInConditional).toBe(singularId); expect(require.cache).toBeTypeOf("object"); expect(require.cache[singularId]).toBeTypeOf("object"); delete require.cache[singularId]; expect(require("./singular2")).not.toBe(singularObj); }); webpack-4.30.0/test/cases/runtime/module-caching/singular.js000066400000000000000000000000311345416772700240250ustar00rootroot00000000000000module.exports.value = 1;webpack-4.30.0/test/cases/runtime/module-caching/singular2.js000066400000000000000000000000001345416772700241030ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/module-caching/two.js000066400000000000000000000000231345416772700230130ustar00rootroot00000000000000module.exports = 2;webpack-4.30.0/test/cases/runtime/require-function/000077500000000000000000000000001345416772700222715ustar00rootroot00000000000000webpack-4.30.0/test/cases/runtime/require-function/fail.js000066400000000000000000000000371345416772700235420ustar00rootroot00000000000000This file should not load! }][{webpack-4.30.0/test/cases/runtime/require-function/index.js000066400000000000000000000003551345416772700237410ustar00rootroot00000000000000it("should have correct properties on the require function", function() { expect(__webpack_require__.c).toBeTypeOf("object"); expect(__webpack_require__.m).toBeTypeOf("object"); expect(__webpack_require__.p).toBeTypeOf("string"); }); webpack-4.30.0/test/cases/scope-hoisting/000077500000000000000000000000001345416772700202425ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/async-keyword-5615/000077500000000000000000000000001345416772700234375ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/async-keyword-5615/async.js000066400000000000000000000000321345416772700251050ustar00rootroot00000000000000export default "default"; webpack-4.30.0/test/cases/scope-hoisting/async-keyword-5615/index.js000066400000000000000000000001641345416772700251050ustar00rootroot00000000000000import value from "./async"; it("should have the correct values", function() { expect(value).toBe("default"); }); webpack-4.30.0/test/cases/scope-hoisting/chained-reexport/000077500000000000000000000000001345416772700235035ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/chained-reexport/a.js000066400000000000000000000000341345416772700242560ustar00rootroot00000000000000export var named = "named"; webpack-4.30.0/test/cases/scope-hoisting/chained-reexport/b.js000066400000000000000000000000251345416772700242570ustar00rootroot00000000000000export * from "./a"; webpack-4.30.0/test/cases/scope-hoisting/chained-reexport/c.js000066400000000000000000000000351345416772700242610ustar00rootroot00000000000000export { named } from "./b"; webpack-4.30.0/test/cases/scope-hoisting/chained-reexport/index.js000066400000000000000000000001621345416772700251470ustar00rootroot00000000000000import { named } from "./c"; it("should have the correct values", function() { expect(named).toBe("named"); }); webpack-4.30.0/test/cases/scope-hoisting/circular-external/000077500000000000000000000000001345416772700236665ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/circular-external/a1.js000066400000000000000000000000361345416772700245240ustar00rootroot00000000000000import "./a2"; import "./b1"; webpack-4.30.0/test/cases/scope-hoisting/circular-external/a2.js000066400000000000000000000000121345416772700245170ustar00rootroot00000000000000export {} webpack-4.30.0/test/cases/scope-hoisting/circular-external/b1.js000066400000000000000000000000361345416772700245250ustar00rootroot00000000000000import "./b2"; import "./c1"; webpack-4.30.0/test/cases/scope-hoisting/circular-external/b2.js000066400000000000000000000000121345416772700245200ustar00rootroot00000000000000export {} webpack-4.30.0/test/cases/scope-hoisting/circular-external/c1.js000066400000000000000000000000361345416772700245260ustar00rootroot00000000000000import "./c2"; import "./a1"; webpack-4.30.0/test/cases/scope-hoisting/circular-external/c2.js000066400000000000000000000000121345416772700245210ustar00rootroot00000000000000export {} webpack-4.30.0/test/cases/scope-hoisting/circular-external/index.js000066400000000000000000000002351345416772700253330ustar00rootroot00000000000000it("should compile and run fine", function(done) { Promise.all([ import("./a1"), import("./b1"), import("./c1") ]).then(function() { done(); }); }); webpack-4.30.0/test/cases/scope-hoisting/circular-namespace-object/000077500000000000000000000000001345416772700252445ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/circular-namespace-object/index.js000066400000000000000000000002121345416772700267040ustar00rootroot00000000000000import value from "./module"; it("should have access to namespace object before evaluation", function() { expect(value).toBe("ok"); }); webpack-4.30.0/test/cases/scope-hoisting/circular-namespace-object/module.js000066400000000000000000000001161345416772700270650ustar00rootroot00000000000000export { default } from "./module2" export function func() { return "ok"; } webpack-4.30.0/test/cases/scope-hoisting/circular-namespace-object/module2.js000066400000000000000000000001271345416772700271510ustar00rootroot00000000000000import * as module from "./module"; var f = Object(module).func; export default f(); webpack-4.30.0/test/cases/scope-hoisting/esModule/000077500000000000000000000000001345416772700220175ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/esModule/index.js000066400000000000000000000002431345416772700234630ustar00rootroot00000000000000it("should have the __esModule flag", () => { return import("./module").then(mod => { expect(mod.__esModule).toBe(true); expect(mod.default).toBe(84); }) }) webpack-4.30.0/test/cases/scope-hoisting/esModule/module.js000066400000000000000000000000701345416772700236370ustar00rootroot00000000000000import other from "./other"; export default other * 2; webpack-4.30.0/test/cases/scope-hoisting/esModule/other.js000066400000000000000000000000231345416772700234710ustar00rootroot00000000000000export default 42; webpack-4.30.0/test/cases/scope-hoisting/export-namespace/000077500000000000000000000000001345416772700235155ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/export-namespace/index.js000066400000000000000000000005211345416772700251600ustar00rootroot00000000000000import { ns as ns1 } from "./module1"; const ns2 = require("./module2").ns; it("should allow to export a namespace object (concated)", function() { expect(ns1).toEqual(nsObj({ a: "a", b: "b" })); }); it("should allow to export a namespace object (exposed)", function() { expect(ns2).toEqual(nsObj({ a: "a", b: "b" })); }); webpack-4.30.0/test/cases/scope-hoisting/export-namespace/module1.js000066400000000000000000000000541345416772700254200ustar00rootroot00000000000000import * as ns from "./ns1"; export { ns }; webpack-4.30.0/test/cases/scope-hoisting/export-namespace/module2.js000066400000000000000000000000541345416772700254210ustar00rootroot00000000000000import * as ns from "./ns2"; export { ns }; webpack-4.30.0/test/cases/scope-hoisting/export-namespace/ns1.js000066400000000000000000000000501345416772700245470ustar00rootroot00000000000000export var a = "a"; export var b = "b"; webpack-4.30.0/test/cases/scope-hoisting/export-namespace/ns2.js000066400000000000000000000000501345416772700245500ustar00rootroot00000000000000export var a = "a"; export var b = "b"; webpack-4.30.0/test/cases/scope-hoisting/import-order/000077500000000000000000000000001345416772700226655ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/import-order/commonjs.js000066400000000000000000000000741345416772700250510ustar00rootroot00000000000000var track = require("./tracker").track; track("commonjs"); webpack-4.30.0/test/cases/scope-hoisting/import-order/index.js000066400000000000000000000002731345416772700243340ustar00rootroot00000000000000import "./commonjs"; import "./module"; import { log } from "./tracker"; it("should evaluate import in the correct order", function() { expect(log).toEqual(["commonjs", "module"]); }); webpack-4.30.0/test/cases/scope-hoisting/import-order/module.js000066400000000000000000000000651345416772700245110ustar00rootroot00000000000000import { track } from "./tracker"; track("module"); webpack-4.30.0/test/cases/scope-hoisting/import-order/tracker.js000066400000000000000000000001071345416772700246540ustar00rootroot00000000000000export var log = []; export function track(name) { log.push(name); } webpack-4.30.0/test/cases/scope-hoisting/indirect-reexport/000077500000000000000000000000001345416772700237115ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/indirect-reexport/a.js000066400000000000000000000000301345416772700244600ustar00rootroot00000000000000export default "named"; webpack-4.30.0/test/cases/scope-hoisting/indirect-reexport/b.js000066400000000000000000000000521345416772700244650ustar00rootroot00000000000000import named from "./a"; export { named } webpack-4.30.0/test/cases/scope-hoisting/indirect-reexport/c.js000066400000000000000000000000561345416772700244720ustar00rootroot00000000000000import { named } from "./b"; export { named } webpack-4.30.0/test/cases/scope-hoisting/indirect-reexport/index.js000066400000000000000000000001571345416772700253610ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { expect(c.named).toBe("named"); }); webpack-4.30.0/test/cases/scope-hoisting/inside-class/000077500000000000000000000000001345416772700226205ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/inside-class/first.js000066400000000000000000000002231345416772700243020ustar00rootroot00000000000000export class Foo { test() { return Foo.value; } } Foo.value = 1; export class Bar { test() { return Bar.value; } } Bar.value = 1; webpack-4.30.0/test/cases/scope-hoisting/inside-class/index.js000066400000000000000000000005251345416772700242670ustar00rootroot00000000000000import { Foo, Bar as FirstBar } from "./first" import { Foo as SecondFoo, Bar } from "./second" it("should renamed class reference in inner scope", function() { var a = new Foo().test(); var b = new SecondFoo().test(); expect(a).toBe(1); expect(b).toBe(2); expect(new FirstBar().test()).toBe(1); expect(new Bar().test()).toBe(2); }); webpack-4.30.0/test/cases/scope-hoisting/inside-class/second.js000066400000000000000000000002231345416772700244260ustar00rootroot00000000000000export class Foo { test() { return Foo.value; } } Foo.value = 2; export class Bar { test() { return Bar.value; } } Bar.value = 2; webpack-4.30.0/test/cases/scope-hoisting/inside-class/test.filter.js000066400000000000000000000002161345416772700254200ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-4.30.0/test/cases/scope-hoisting/intra-references/000077500000000000000000000000001345416772700234765ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/intra-references/a.js000066400000000000000000000000371345416772700242540ustar00rootroot00000000000000export { default } from "./b"; webpack-4.30.0/test/cases/scope-hoisting/intra-references/b.js000066400000000000000000000000371345416772700242550ustar00rootroot00000000000000export { default } from "./c"; webpack-4.30.0/test/cases/scope-hoisting/intra-references/c.js000066400000000000000000000000251345416772700242530ustar00rootroot00000000000000export default "ok"; webpack-4.30.0/test/cases/scope-hoisting/intra-references/index.js000066400000000000000000000002341345416772700251420ustar00rootroot00000000000000import value from "./a"; it("should have the correct values", function() { expect(value).toBe("ok"); }); // prevent scope hoisting of b require("./b"); webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/000077500000000000000000000000001345416772700234025ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/index.js000066400000000000000000000003201345416772700250420ustar00rootroot00000000000000var testData = require("./src/index.js"); it("should export the correct values", function() { expect(testData).toEqual( nsObj({ icon: nsObj({ svg: nsObj({ default: 1 }) }) }) ); }); webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/src/000077500000000000000000000000001345416772700241715ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/src/icon/000077500000000000000000000000001345416772700251215ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/src/icon/index.js000066400000000000000000000000631345416772700265650ustar00rootroot00000000000000import * as svg from "./svg"; export { svg }; webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/src/icon/svg/000077500000000000000000000000001345416772700257205ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/src/icon/svg/index.js000066400000000000000000000000221345416772700273570ustar00rootroot00000000000000export default 1; webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/src/icon/svg/svg1.js000066400000000000000000000000271345416772700271350ustar00rootroot00000000000000export const svg1 = 1; webpack-4.30.0/test/cases/scope-hoisting/issue-5020-minimal/src/index.js000066400000000000000000000000651345416772700256370ustar00rootroot00000000000000import * as icon from "./icon"; export { icon } webpack-4.30.0/test/cases/scope-hoisting/issue-5020/000077500000000000000000000000001345416772700217565ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020/index.js000066400000000000000000000006121345416772700234220ustar00rootroot00000000000000var testData = require("./src/index.js"); it("should export the correct values", function() { expect(testData).toEqual( nsObj({ svg5: nsObj({ svg: nsObj({ clinical1: { svg1: 1 }, clinical2: { svg2: 2 } }) }), svg6: nsObj({ svg: nsObj({ test: { svg1: 10 }, clinical2: { svg2: 20 } }) }) }) ); }) webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/000077500000000000000000000000001345416772700225455ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon/000077500000000000000000000000001345416772700234755ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon/index.js000066400000000000000000000000631345416772700251410ustar00rootroot00000000000000import * as svg from "./svg"; export { svg }; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon/svg/000077500000000000000000000000001345416772700242745ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon/svg/index.js000066400000000000000000000002511345416772700257370ustar00rootroot00000000000000import { svg1 } from "./svg1"; import { svg2 } from "./svg2"; const clinical1 = { svg1 }; const clinical2 = { svg2 }; export { clinical1, clinical2 }; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon/svg/svg1.js000066400000000000000000000000271345416772700255110ustar00rootroot00000000000000export const svg1 = 1; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon/svg/svg2.js000066400000000000000000000000271345416772700255120ustar00rootroot00000000000000export const svg2 = 2; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon1/000077500000000000000000000000001345416772700235565ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon1/index.js000066400000000000000000000000631345416772700252220ustar00rootroot00000000000000import * as svg from "./svg"; export { svg }; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon1/svg/000077500000000000000000000000001345416772700243555ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon1/svg/index.js000066400000000000000000000002371345416772700260240ustar00rootroot00000000000000import { svg1 } from "./svg1"; import { svg2 } from "./svg2"; const test = { svg1 }; const clinical2 = { svg2 }; export { test, clinical2 }; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon1/svg/svg1.js000066400000000000000000000000301345416772700255640ustar00rootroot00000000000000export const svg1 = 10; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/icon1/svg/svg2.js000066400000000000000000000000301345416772700255650ustar00rootroot00000000000000export const svg2 = 20; webpack-4.30.0/test/cases/scope-hoisting/issue-5020/src/index.js000066400000000000000000000001401345416772700242050ustar00rootroot00000000000000import * as svg5 from "./icon"; import * as svg6 from "./icon1"; export { svg5, svg6 } webpack-4.30.0/test/cases/scope-hoisting/issue-5096/000077500000000000000000000000001345416772700217735ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5096/b.js000066400000000000000000000000641345416772700225520ustar00rootroot00000000000000import { a } from './index'; export const b = a(); webpack-4.30.0/test/cases/scope-hoisting/issue-5096/index.js000066400000000000000000000003051345416772700234360ustar00rootroot00000000000000import { b } from './b'; export function a() { return "a"; }; // Inject a variable if(Math.random() < -1) console.log(module); it("should compile fine", function() { expect(b).toBe("a"); }); webpack-4.30.0/test/cases/scope-hoisting/issue-5314/000077500000000000000000000000001345416772700217645ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5314/index.js000066400000000000000000000002531345416772700234310ustar00rootroot00000000000000import a from "./module"; var obj = {}; it("should allow access to the default export of the root module", function() { expect(a()).toBe(obj); }); export default obj; webpack-4.30.0/test/cases/scope-hoisting/issue-5314/module.js000066400000000000000000000001021345416772700236000ustar00rootroot00000000000000import b from "./index"; export default function() { return b; }; webpack-4.30.0/test/cases/scope-hoisting/issue-5443/000077500000000000000000000000001345416772700217675ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5443/index.js000066400000000000000000000002511345416772700234320ustar00rootroot00000000000000import { module } from "./reexport"; it("should have the correct values", function() { expect(module).toEqual(nsObj({ default: "default", named: "named" })); }); webpack-4.30.0/test/cases/scope-hoisting/issue-5443/module.js000066400000000000000000000000661345416772700236140ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/scope-hoisting/issue-5443/reexport.js000066400000000000000000000000701345416772700241720ustar00rootroot00000000000000import * as module from "./module" export { module } webpack-4.30.0/test/cases/scope-hoisting/issue-5481/000077500000000000000000000000001345416772700217715ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-5481/cjs.js000066400000000000000000000000271345416772700231050ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/cases/scope-hoisting/issue-5481/index.js000066400000000000000000000002011345416772700234270ustar00rootroot00000000000000import value from "./module"; it("should not cause name conflicts", function() { expect((typeof value)).toBe("undefined"); }); webpack-4.30.0/test/cases/scope-hoisting/issue-5481/module.js000066400000000000000000000001061345416772700236110ustar00rootroot00000000000000import a from "./cjs"; var cjs_default; export default cjs_default; webpack-4.30.0/test/cases/scope-hoisting/issue-6407/000077500000000000000000000000001345416772700217705ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-6407/import-one.js000066400000000000000000000000741345416772700244200ustar00rootroot00000000000000function foo(n) { return 'bar'; } export default [, foo]; webpack-4.30.0/test/cases/scope-hoisting/issue-6407/import-two.js000066400000000000000000000000741345416772700244500ustar00rootroot00000000000000function foo(n) { return 'bar'; } export default [, foo]; webpack-4.30.0/test/cases/scope-hoisting/issue-6407/index.js000066400000000000000000000006521345416772700234400ustar00rootroot00000000000000import importOne from './import-one'; import importTwo from './import-two'; it("should concatenate modules default exports and empty array values", function() { expect(importOne.length).toBe(2); expect(typeof importOne[0]).toBe('undefined'); expect(typeof importOne[1]).toBe('function'); expect(importTwo.length).toBe(2); expect(typeof importTwo[0]).toBe('undefined'); expect(typeof importTwo[1]).toBe('function'); }); webpack-4.30.0/test/cases/scope-hoisting/issue-7930/000077500000000000000000000000001345416772700217725ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/issue-7930/export.js000066400000000000000000000000661345416772700236530ustar00rootroot00000000000000export var a = 1; var value = 42; export { value }; webpack-4.30.0/test/cases/scope-hoisting/issue-7930/index.js000066400000000000000000000002751345416772700234430ustar00rootroot00000000000000import { value } from "./module"; it("should export the correct value", () => { expect(value).toBe(42); }); // prevent scope hoisting if(Math.random() < -1) { console.log(module.id); } webpack-4.30.0/test/cases/scope-hoisting/issue-7930/module.js000066400000000000000000000000321345416772700236100ustar00rootroot00000000000000export * from "./export"; webpack-4.30.0/test/cases/scope-hoisting/json-reexport-6700/000077500000000000000000000000001345416772700234535ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/json-reexport-6700/a.json000066400000000000000000000000171345416772700245640ustar00rootroot00000000000000{ "a": "A" } webpack-4.30.0/test/cases/scope-hoisting/json-reexport-6700/b.json000066400000000000000000000000171345416772700245650ustar00rootroot00000000000000{ "b": "B" } webpack-4.30.0/test/cases/scope-hoisting/json-reexport-6700/index.js000066400000000000000000000003171345416772700251210ustar00rootroot00000000000000import { a, b, aa, bb } from './json.js' it("should reexport json data correctly", () => { expect(aa).toEqual({ a: "A" }); expect(bb).toEqual({ b: "B" }); expect(a).toBe("A"); expect(b).toBe("B"); }); webpack-4.30.0/test/cases/scope-hoisting/json-reexport-6700/json.js000066400000000000000000000002431345416772700247610ustar00rootroot00000000000000import aa from './a.json'; export { aa }; export { default as bb } from './b.json'; import { a } from './a.json'; export { a }; export { b } from './b.json'; webpack-4.30.0/test/cases/scope-hoisting/name-conflicts/000077500000000000000000000000001345416772700231445ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/name-conflicts/index.js000066400000000000000000000006431345416772700246140ustar00rootroot00000000000000import value1 from "./module?("; import value2 from "./module?)"; import value3 from "./module?["; import value4 from "./module?]"; import value5 from "./module?{"; import value6 from "./module?}"; it("should not break on name conflicts", function() { expect(value1).toBe("a"); expect(value2).toBe("a"); expect(value3).toBe("a"); expect(value4).toBe("a"); expect(value5).toBe("a"); expect(value6).toBe("a"); }); webpack-4.30.0/test/cases/scope-hoisting/name-conflicts/module.js000066400000000000000000000000241345416772700247630ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/cases/scope-hoisting/order-without-side-effects/000077500000000000000000000000001345416772700254155ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/order-without-side-effects/a.js000066400000000000000000000001061345416772700261700ustar00rootroot00000000000000import { array } from "./tracker"; array.push("a"); export var a = 1; webpack-4.30.0/test/cases/scope-hoisting/order-without-side-effects/b.js000066400000000000000000000001061345416772700261710ustar00rootroot00000000000000import { array } from "./tracker"; array.push("b"); export var b = 2; webpack-4.30.0/test/cases/scope-hoisting/order-without-side-effects/index.js000066400000000000000000000003351345416772700270630ustar00rootroot00000000000000import { array } from "./tracker"; import { a } from "./a"; import { b } from "./b"; it("should concatenate in correct order", function() { expect(b).toBe(2); expect(a).toBe(1); expect(array).toEqual(["a", "b"]); }); webpack-4.30.0/test/cases/scope-hoisting/order-without-side-effects/package.json000066400000000000000000000000331345416772700276770ustar00rootroot00000000000000{ "sideEffects": false } webpack-4.30.0/test/cases/scope-hoisting/order-without-side-effects/tracker.js000066400000000000000000000000271345416772700274050ustar00rootroot00000000000000export var array = []; webpack-4.30.0/test/cases/scope-hoisting/reexport-cjs/000077500000000000000000000000001345416772700226675ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/reexport-cjs/a.js000066400000000000000000000000311345416772700234370ustar00rootroot00000000000000exports.named = "named"; webpack-4.30.0/test/cases/scope-hoisting/reexport-cjs/b.js000066400000000000000000000000351345416772700234440ustar00rootroot00000000000000export { named } from "./a"; webpack-4.30.0/test/cases/scope-hoisting/reexport-cjs/c.js000066400000000000000000000000351345416772700234450ustar00rootroot00000000000000export { named } from "./b"; webpack-4.30.0/test/cases/scope-hoisting/reexport-cjs/index.js000066400000000000000000000001621345416772700243330ustar00rootroot00000000000000import { named } from "./c"; it("should have the correct values", function() { expect(named).toBe("named"); }); webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-cjs/000077500000000000000000000000001345416772700243345ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-cjs/a.js000066400000000000000000000000311345416772700251040ustar00rootroot00000000000000exports.named = "named"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-cjs/b.js000066400000000000000000000000351345416772700251110ustar00rootroot00000000000000export { named } from "./a"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-cjs/c.js000066400000000000000000000000351345416772700251120ustar00rootroot00000000000000export { named } from "./b"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-cjs/index.js000066400000000000000000000001571345416772700260040ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { expect(c.named).toBe("named"); }); webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-default-cjs/000077500000000000000000000000001345416772700257565ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-default-cjs/a.js000066400000000000000000000000341345416772700265310ustar00rootroot00000000000000module.exports = "default"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-default-cjs/b.js000066400000000000000000000000371345416772700265350ustar00rootroot00000000000000export { default } from "./a"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-default-cjs/c.js000066400000000000000000000000371345416772700265360ustar00rootroot00000000000000export { default } from "./b"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-default-cjs/index.js000066400000000000000000000001631345416772700274230ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { expect(c.default).toBe("default"); }); webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-harmony/000077500000000000000000000000001345416772700252325ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-harmony/a.js000066400000000000000000000000341345416772700260050ustar00rootroot00000000000000export var named = "named"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-harmony/b.js000066400000000000000000000000251345416772700260060ustar00rootroot00000000000000export * from "./a"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-harmony/c.js000066400000000000000000000000351345416772700260100ustar00rootroot00000000000000export { named } from "./b"; webpack-4.30.0/test/cases/scope-hoisting/reexport-exposed-harmony/index.js000066400000000000000000000001571345416772700267020ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { expect(c.named).toBe("named"); }); webpack-4.30.0/test/cases/scope-hoisting/renaming-4967/000077500000000000000000000000001345416772700224515ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/renaming-4967/file1.js000066400000000000000000000004241345416772700240070ustar00rootroot00000000000000export function a() { return "ok"; } export function test() { function file1_js_a() { return "fail"; } function file1_a() { return "fail"; } return a(); } function renaming_4967_file1_js_a() { return "fail"; } function renaming_4967_file1_a() { return "fail"; } webpack-4.30.0/test/cases/scope-hoisting/renaming-4967/index.js000066400000000000000000000003231345416772700241140ustar00rootroot00000000000000it("should check existing variables when renaming", function() { expect(require("./module").d.x()).toBe("ok"); expect(require("./module").c.a()).toBe("ok"); expect(require("./module").test()).toBe("ok"); }); webpack-4.30.0/test/cases/scope-hoisting/renaming-4967/module.js000066400000000000000000000003451345416772700242760ustar00rootroot00000000000000import { a as b, test } from './file1'; var c = { a: function a() { return b(); }, }; var d = { x: function x() { function a() { return "fail"; } return b(); }, }; export { c, d, test }; webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/000077500000000000000000000000001345416772700244255ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/file1.js000066400000000000000000000000331345416772700257570ustar00rootroot00000000000000export var test = "test1"; webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/file2.js000066400000000000000000000000541345416772700257630ustar00rootroot00000000000000var [ test ] = [ "test2" ]; export { test } webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/file3.js000066400000000000000000000000621345416772700257630ustar00rootroot00000000000000var { test } = { test: "test3" }; export { test } webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/file4.js000066400000000000000000000000761345416772700257710ustar00rootroot00000000000000var {o:[{ test }]} = {o:[{ test: "test4" }]}; export { test } webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/index.js000066400000000000000000000006671345416772700261030ustar00rootroot00000000000000import m from "./module"; it("should apply shorthand properties correctly when renaming", function() { expect(m).toEqual({ obj: { test: "test1", test2: "test2", test3: "test3", test4: "test4" }, nested: { array: [{ test: "test1", test2: "test2", test3: "test3", test4: "test4" }] }, test: "test1", test2: "test2", test3: "test3", test4: "test4", f: ["test2", "test2", "test3"] }) }); webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/module.js000066400000000000000000000006571345416772700262600ustar00rootroot00000000000000import { test } from './file1'; import { test as test2 } from './file2'; import { test as test3 } from './file3'; import { test as test4 } from './file4'; var obj = { test, test2, test3, test4 }; var nested = { array: [ { test, test2, test3, test4 }]}; function f(test = test2, { test2: t2 } = { test2 }, { t3 = test3 } = {}) { return [test, t2, t3]; } export default { obj, nested, test, test2, test3, test4, f: f() }; webpack-4.30.0/test/cases/scope-hoisting/renaming-shorthand-5027/test.filter.js000066400000000000000000000010071345416772700272240ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); var supportDefaultAssignment = require("../../../helpers/supportDefaultAssignment"); var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); module.exports = function(config) { return !config.minimize && supportsES6() && supportDefaultAssignment() && supportsObjectDestructuring() && supportsIteratorDestructuring(); }; webpack-4.30.0/test/cases/scope-hoisting/require-root-5604/000077500000000000000000000000001345416772700232735ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/require-root-5604/index.js000066400000000000000000000003551345416772700247430ustar00rootroot00000000000000import value, { self as moduleSelf } from "./module"; export var self = require("./"); it("should have the correct values", function() { expect(value).toBe("default"); expect(moduleSelf).toBe(self); expect(self.self).toBe(self); }); webpack-4.30.0/test/cases/scope-hoisting/require-root-5604/module.js000066400000000000000000000000731345416772700251160ustar00rootroot00000000000000export default "default"; export var self = require("./"); webpack-4.30.0/test/cases/scope-hoisting/simple/000077500000000000000000000000001345416772700215335ustar00rootroot00000000000000webpack-4.30.0/test/cases/scope-hoisting/simple/index.js000066400000000000000000000002361345416772700232010ustar00rootroot00000000000000import value, { named } from "./module"; it("should have the correct values", function() { expect(value).toBe("default"); expect(named).toBe("named"); }); webpack-4.30.0/test/cases/scope-hoisting/simple/module.js000066400000000000000000000000661345416772700233600ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-4.30.0/test/cases/side-effects/000077500000000000000000000000001345416772700176505ustar00rootroot00000000000000webpack-4.30.0/test/cases/side-effects/missing-module-7499/000077500000000000000000000000001345416772700232165ustar00rootroot00000000000000webpack-4.30.0/test/cases/side-effects/missing-module-7499/example/000077500000000000000000000000001345416772700246515ustar00rootroot00000000000000webpack-4.30.0/test/cases/side-effects/missing-module-7499/example/constants.js000066400000000000000000000000351345416772700272210ustar00rootroot00000000000000export const hello = 'world' webpack-4.30.0/test/cases/side-effects/missing-module-7499/example/index.js000066400000000000000000000000761345416772700263210ustar00rootroot00000000000000import * as constants from './constants' export { constants } webpack-4.30.0/test/cases/side-effects/missing-module-7499/example/package.json000066400000000000000000000000331345416772700271330ustar00rootroot00000000000000{ "sideEffects": false } webpack-4.30.0/test/cases/side-effects/missing-module-7499/index.js000066400000000000000000000002561345416772700246660ustar00rootroot00000000000000import './example' it("should run correctly", function() { return import('./lazy').then(lazy => { expect(lazy.default()).toEqual(nsObj({ hello: "world" })); }) }); webpack-4.30.0/test/cases/side-effects/missing-module-7499/lazy.js000066400000000000000000000001451345416772700245330ustar00rootroot00000000000000import { constants } from './example' export default function getConstants() { return constants; } webpack-4.30.0/test/cases/side-effects/order-issue-7665/000077500000000000000000000000001345416772700225165ustar00rootroot00000000000000webpack-4.30.0/test/cases/side-effects/order-issue-7665/index.js000066400000000000000000000002711345416772700241630ustar00rootroot00000000000000import array from "./tracker"; import { b } from "./module"; it("should evaulate modules in the correct order", () => { expect(b).toEqual("b"); expect(array).toEqual(["b", "a"]); }) webpack-4.30.0/test/cases/side-effects/order-issue-7665/module/000077500000000000000000000000001345416772700240035ustar00rootroot00000000000000webpack-4.30.0/test/cases/side-effects/order-issue-7665/module/a.js000066400000000000000000000001071345416772700245570ustar00rootroot00000000000000import array from "../tracker"; array.push("a"); export default "a"; webpack-4.30.0/test/cases/side-effects/order-issue-7665/module/b.js000066400000000000000000000001071345416772700245600ustar00rootroot00000000000000import array from "../tracker"; array.push("b"); export default "b"; webpack-4.30.0/test/cases/side-effects/order-issue-7665/module/index.js000066400000000000000000000000621345416772700254460ustar00rootroot00000000000000import b from './b'; import './a'; export { b }; webpack-4.30.0/test/cases/side-effects/order-issue-7665/module/package.json000066400000000000000000000000721345416772700262700ustar00rootroot00000000000000{ "sideEffects": [ "./index.js", "./a.js" ] } webpack-4.30.0/test/cases/side-effects/order-issue-7665/tracker.js000066400000000000000000000000231345416772700245020ustar00rootroot00000000000000export default []; webpack-4.30.0/test/cases/wasm/000077500000000000000000000000001345416772700162565ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/decoding/000077500000000000000000000000001345416772700200325ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/decoding/index.js000066400000000000000000000007671345416772700215110ustar00rootroot00000000000000it("should support wasm compiled from c++", function() { return import("./memory3.wasm").then(function(wasm) { expect(wasm._Z3getv()).toBe(0); wasm._Z3seti(42); expect(wasm._Z3getv()).toBe(42); }); }); it("should raw memory export without data", function() { return import("./memory2.wasm").then(function(wasm) { expect(wasm.memory).toBeInstanceOf(WebAssembly.Memory); expect(wasm.memory.buffer).toBeInstanceOf(ArrayBuffer); expect(wasm.memory.buffer.byteLength).toBe(1 << 16); }); }); webpack-4.30.0/test/cases/wasm/decoding/memory2.wasm000066400000000000000000000000431345416772700223120ustar00rootroot00000000000000asm memorynamewebpack-4.30.0/test/cases/wasm/decoding/memory3.wasm000066400000000000000000000002171345416772700223160ustar00rootroot00000000000000asm``pmemory_Z3seti_Z3getv A 6 A( A webpack-4.30.0/test/cases/wasm/decoding/test.filter.js000066400000000000000000000002221345416772700226270ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/export-imported-global/000077500000000000000000000000001345416772700226565ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/export-imported-global/env.js000066400000000000000000000000521345416772700240010ustar00rootroot00000000000000export const n = 1; export const m = 1.25 webpack-4.30.0/test/cases/wasm/export-imported-global/index.js000066400000000000000000000007441345416772700243300ustar00rootroot00000000000000it("should export imported global", function() { return import("./module").then(function({ v, w, x, test }) { if (WebAssembly.Global) { expect(v.constructor).toBe(WebAssembly.Global); expect(w.constructor).toBe(WebAssembly.Global); expect(x.constructor).toBe(WebAssembly.Global); expect(+v).toBe(1); expect(+w).toBe(1); expect(+x).toBe(1.25); } else { expect(v).toBe(1); expect(w).toBe(1); expect(x).toBe(1.25); } expect(test()).toBe(2); }); }); webpack-4.30.0/test/cases/wasm/export-imported-global/module.js000066400000000000000000000000361345416772700245000ustar00rootroot00000000000000export * from "./module.wat"; webpack-4.30.0/test/cases/wasm/export-imported-global/module.wat000066400000000000000000000005211345416772700246560ustar00rootroot00000000000000(module (import "./env.js" "n" (global i32)) (import "./env.js" "m" (global $g2 f64)) (export "v" (global 0)) (global $g i32 (get_global 0)) (export "w" (global $g)) (export "x" (global $g2)) (func (export "test") (result i32) get_global $g2 get_global $g2 f64.add drop get_global 0 get_global $g i32.add ) ) webpack-4.30.0/test/cases/wasm/export-imported-global/test.filter.js000066400000000000000000000002221345416772700254530ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/000077500000000000000000000000001345416772700233055ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/index.js000066400000000000000000000002051345416772700247470ustar00rootroot00000000000000it("should not throw when no dependency reference", function() { return expect(() => import("side-effect-free")).not.toThrow(); }); webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/node_modules/000077500000000000000000000000001345416772700257625ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/node_modules/side-effect-free/000077500000000000000000000000001345416772700310575ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/node_modules/side-effect-free/index.js000066400000000000000000000000361345416772700325230ustar00rootroot00000000000000export * from "./module.wat"; webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/node_modules/side-effect-free/module.wat000066400000000000000000000000401345416772700330530ustar00rootroot00000000000000(module (func (export "a")) ) package.json000066400000000000000000000000331345416772700332620ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/node_modules/side-effect-free{ "sideEffects": false } webpack-4.30.0/test/cases/wasm/finalize-exports-issue-8261/test.filter.js000066400000000000000000000002221345416772700261020ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/global-refs-imported-global/000077500000000000000000000000001345416772700235325ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/global-refs-imported-global/env.js000066400000000000000000000000251345416772700246550ustar00rootroot00000000000000export const n = 33; webpack-4.30.0/test/cases/wasm/global-refs-imported-global/index.js000066400000000000000000000002461345416772700252010ustar00rootroot00000000000000it("should allow global with imported global as initilizer", function() { return import("./module.wat").then(function({get}) { expect(get()).toEqual(33); }); }); webpack-4.30.0/test/cases/wasm/global-refs-imported-global/module.wat000066400000000000000000000002141345416772700255310ustar00rootroot00000000000000(module (import "./env.js" "n" (global i32)) (global i32 (get_global 0)) (func (export "get") (result i32) (get_global 1) ) ) webpack-4.30.0/test/cases/wasm/global-refs-imported-global/test.filter.js000066400000000000000000000002221345416772700263270ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/import-wasm-wasm/000077500000000000000000000000001345416772700215025ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/import-wasm-wasm/index.js000066400000000000000000000003101345416772700231410ustar00rootroot00000000000000it("should allow to run a WebAssembly module with imports", function() { return import("./wasm.wat").then(function(wasm) { const result = wasm.addNumber(20); expect(result).toEqual(42); }); }); webpack-4.30.0/test/cases/wasm/import-wasm-wasm/test.filter.js000066400000000000000000000002221345416772700242770ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/import-wasm-wasm/wasm.wat000066400000000000000000000005011345416772700231620ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (type $t1 (func (param i32) (result i32))) (import "./wasm2.wat" "getNumber" (func $./wasm2.wasm.getNumber (type $t0))) (func $addNumber (export "addNumber") (type $t1) (param $p0 i32) (result i32) (i32.add (get_local $p0) (call $./wasm2.wasm.getNumber)))) webpack-4.30.0/test/cases/wasm/import-wasm-wasm/wasm2.wat000066400000000000000000000001771345416772700232550ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (func $getNumber (export "getNumber") (type $t0) (result i32) (i32.const 22))) webpack-4.30.0/test/cases/wasm/imported-global-preserve-ordering/000077500000000000000000000000001345416772700247775ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/imported-global-preserve-ordering/env.js000066400000000000000000000000501345416772700261200ustar00rootroot00000000000000export const a = 1; export const b = 2; webpack-4.30.0/test/cases/wasm/imported-global-preserve-ordering/index.js000066400000000000000000000005561345416772700264520ustar00rootroot00000000000000it("should preserve the ordering of globals", function() { return import("./module.wat").then(function(e) { if (WebAssembly.Global) { expect(e.c.constructor).toBe(WebAssembly.Global); expect(e.d.constructor).toBe(WebAssembly.Global); expect(+e.c).toBe(3); expect(+e.d).toBe(4); } else { expect(e.c).toBe(3); expect(e.d).toBe(4); } }); }); webpack-4.30.0/test/cases/wasm/imported-global-preserve-ordering/module.wat000066400000000000000000000003201345416772700267740ustar00rootroot00000000000000(module (import "./env.js" "a" (global i32)) (import "./env.js" "b" (global i32)) (global $c i32 (i32.const 3)) (global $d i32 (i32.const 4)) (export "c" (global $c)) (export "d" (global $d)) ) webpack-4.30.0/test/cases/wasm/imported-global-preserve-ordering/test.filter.js000066400000000000000000000002221345416772700275740ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/imported-global-preserve-type/000077500000000000000000000000001345416772700241475ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/imported-global-preserve-type/env.js000066400000000000000000000000441345416772700252730ustar00rootroot00000000000000export const number = 0xFFFFFFFFFF; webpack-4.30.0/test/cases/wasm/imported-global-preserve-type/index.js000066400000000000000000000002511345416772700256120ustar00rootroot00000000000000it("should preserve the valtype of the imported global", function() { return import("./module.wat").then(function({get}) { expect(get()).toBe(0xFFFFFFFFFF); }); }); webpack-4.30.0/test/cases/wasm/imported-global-preserve-type/module.wat000066400000000000000000000001621345416772700261500ustar00rootroot00000000000000(module (import "./env.js" "number" (global f64)) (func (export "get") (result f64) (get_global 0) ) ) webpack-4.30.0/test/cases/wasm/imported-global-preserve-type/test.filter.js000066400000000000000000000002221345416772700267440ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/imports-circular/000077500000000000000000000000001345416772700215555ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/imports-circular/index.js000066400000000000000000000002521345416772700232210ustar00rootroot00000000000000it("should allow to run a WebAssembly module importing JS circular", function() { return import("./module").then(function(mod) { expect(mod.result).toBe(42); }); }); webpack-4.30.0/test/cases/wasm/imports-circular/module.js000066400000000000000000000001711345416772700233770ustar00rootroot00000000000000import { addNumber } from "./wasm.wat"; export var result = addNumber(22); export function getNumber() { return 20; } webpack-4.30.0/test/cases/wasm/imports-circular/test.filter.js000066400000000000000000000002221345416772700243520ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/imports-circular/wasm.wat000066400000000000000000000004661345416772700232470ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (type $t1 (func (param i32) (result i32))) (import "./module" "getNumber" (func $./module.getNumber (type $t0))) (func $addNumber (export "addNumber") (type $t1) (param $p0 i32) (result i32) (i32.add (get_local $p0) (call $./module.getNumber)))) webpack-4.30.0/test/cases/wasm/imports-complex-types/000077500000000000000000000000001345416772700225625ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/imports-complex-types/index.js000066400000000000000000000003271345416772700242310ustar00rootroot00000000000000it("should allow to run a WebAssembly module with non-js-compatible imports", function() { return import("./wasm.wasm").then(function(wasm) { const result = wasm.testI64(); expect(result).toEqual(42); }); }); webpack-4.30.0/test/cases/wasm/imports-complex-types/other.wasm000066400000000000000000000001041345416772700245670ustar00rootroot00000000000000asm`~~ getI64  B*| name getI64webpack-4.30.0/test/cases/wasm/imports-complex-types/test.filter.js000066400000000000000000000002221345416772700253570ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/imports-complex-types/wasm.wasm000066400000000000000000000001671345416772700244260ustar00rootroot00000000000000asm `~~` ./other.wasmgetI64 testI64 BB} name getI64webpack-4.30.0/test/cases/wasm/imports-many-direct/000077500000000000000000000000001345416772700221655ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/imports-many-direct/index.js000066400000000000000000000003321345416772700236300ustar00rootroot00000000000000it("should allow to run a WebAssembly module with many direct wasm dependencies", function() { return import("./wasm.wat").then(function(wasm) { const result = wasm.testI64(); expect(result).toEqual(42); }); }); webpack-4.30.0/test/cases/wasm/imports-many-direct/other1.wat000066400000000000000000000003011345416772700240760ustar00rootroot00000000000000(module (type $t0 (func (param i64) (result i64))) (func $getI64 (type $t0) (param $p0 i64) (result i64) get_local $p0 i64.const 20 i64.add) (export "getI64" (func $getI64))) webpack-4.30.0/test/cases/wasm/imports-many-direct/other2.wat000066400000000000000000000003011345416772700240770ustar00rootroot00000000000000(module (type $t0 (func (param i64) (result i64))) (func $getI64 (type $t0) (param $p0 i64) (result i64) get_local $p0 i64.const 22 i64.add) (export "getI64" (func $getI64))) webpack-4.30.0/test/cases/wasm/imports-many-direct/test.filter.js000066400000000000000000000002221345416772700247620ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/imports-many-direct/wasm.wat000066400000000000000000000006471345416772700236600ustar00rootroot00000000000000(module (type $t0 (func (param i64) (result i64))) (type $t1 (func (result i32))) (import "./other1.wat" "getI64" (func $getI641 (type $t0))) (import "./other2.wat" "getI64" (func $getI642 (type $t0))) (func $testI64 (type $t1) (result i32) i64.const 1152921504606846976 call $getI641 call $getI642 i64.const 1152921504606846976 i64.sub i32.wrap/i64) (export "testI64" (func $testI64))) webpack-4.30.0/test/cases/wasm/imports-multiple/000077500000000000000000000000001345416772700216045ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/imports-multiple/index.js000066400000000000000000000002641345416772700232530ustar00rootroot00000000000000it("should allow to run a WebAssembly module importing from multiple modules", function() { return import("./module").then(function(mod) { expect(mod.result).toBe(42); }); }); webpack-4.30.0/test/cases/wasm/imports-multiple/module.js000066400000000000000000000001711345416772700234260ustar00rootroot00000000000000import { getResult } from "./wasm.wasm"; export var result = getResult(1); export function getNumber() { return 20; } webpack-4.30.0/test/cases/wasm/imports-multiple/module2.js000066400000000000000000000001421345416772700235060ustar00rootroot00000000000000import { getNumber as getN } from "./wasm.wasm"; export function getNumber() { return getN(); } webpack-4.30.0/test/cases/wasm/imports-multiple/test.filter.js000066400000000000000000000002221345416772700244010ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/imports-multiple/wasm.wasm000066400000000000000000000003121345416772700234400ustar00rootroot00000000000000asm ``,./module getNumber ./module2 getNumber getNumber getResult A j Vname@./module.getNumber./module.getNumber2 getNumber addNumber p0webpack-4.30.0/test/cases/wasm/imports/000077500000000000000000000000001345416772700177535ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/imports/index.js000066400000000000000000000003111345416772700214130ustar00rootroot00000000000000it("should allow to run a WebAssembly module with imports", function() { return import("./wasm.wat?1").then(function(wasm) { const result = wasm.addNumber(3); expect(result).toEqual(11); }); }); webpack-4.30.0/test/cases/wasm/imports/module.js000066400000000000000000000000531345416772700215740ustar00rootroot00000000000000export function getNumber() { return 8; } webpack-4.30.0/test/cases/wasm/imports/test.filter.js000066400000000000000000000002221345416772700225500ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/imports/wasm.wat000066400000000000000000000004661345416772700214450ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (type $t1 (func (param i32) (result i32))) (import "./module" "getNumber" (func $./module.getNumber (type $t0))) (func $addNumber (export "addNumber") (type $t1) (param $p0 i32) (result i32) (i32.add (get_local $p0) (call $./module.getNumber)))) webpack-4.30.0/test/cases/wasm/js-incompatible-type/000077500000000000000000000000001345416772700223155ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/js-incompatible-type/env.js000066400000000000000000000000241345416772700234370ustar00rootroot00000000000000export const n = 1; webpack-4.30.0/test/cases/wasm/js-incompatible-type/errors.js000066400000000000000000000007561345416772700241770ustar00rootroot00000000000000module.exports = [ [ /export-i64-param\.wat/, /Export "a" with i64 as parameter can only be used for direct wasm to wasm dependencies/, /export-i64-param\.js/ ], [ /export-i64-result\.wat/, /Export "a" with i64 as result can only be used for direct wasm to wasm dependencies/, /export-i64-result\.js/ ], [ /import-i64\.wat/, /Import "n" from "\.\/env.js" with Non-JS-compatible Global Type \(i64\) can only be used for direct wasm to wasm dependencies/, /index\.js/ ] ] webpack-4.30.0/test/cases/wasm/js-incompatible-type/export-i64-param.js000066400000000000000000000000541345416772700256710ustar00rootroot00000000000000export { a } from "./export-i64-param.wat"; webpack-4.30.0/test/cases/wasm/js-incompatible-type/export-i64-param.wat000066400000000000000000000000621345416772700260470ustar00rootroot00000000000000(module (func (export "a") (param i64) (nop)) ) webpack-4.30.0/test/cases/wasm/js-incompatible-type/export-i64-result.js000066400000000000000000000000551345416772700261100ustar00rootroot00000000000000export { a } from "./export-i64-result.wat"; webpack-4.30.0/test/cases/wasm/js-incompatible-type/export-i64-result.wat000066400000000000000000000001021345416772700262600ustar00rootroot00000000000000(module (func (export "a") (result i64) (i64.const 1) ) ) webpack-4.30.0/test/cases/wasm/js-incompatible-type/import-i64.wat000066400000000000000000000000611345416772700247410ustar00rootroot00000000000000(module (import "./env.js" "n" (global i64)) ) webpack-4.30.0/test/cases/wasm/js-incompatible-type/index.js000066400000000000000000000011131345416772700237560ustar00rootroot00000000000000const errorRegex = /wasm function signature contains illegal type|invalid type/; it("should disallow exporting a func signature with result i64", function() { return import("./export-i64-result").then(({a}) => { expect(() => a()).toThrow(errorRegex); }); }); it("should disallow exporting a func signature with param i64", function() { return import("./export-i64-param").then(({a}) => { expect(() => a()).toThrow(errorRegex); }); }); it("should disallow importing a value type of i64", function() { return expect(import("./import-i64.wat")).rejects.toThrow(errorRegex); }); webpack-4.30.0/test/cases/wasm/js-incompatible-type/test.filter.js000066400000000000000000000002621345416772700251160ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly() && config.mode === "production"; }; webpack-4.30.0/test/cases/wasm/memory/000077500000000000000000000000001345416772700175665ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/memory/index.js000066400000000000000000000003771345416772700212420ustar00rootroot00000000000000it("should allow direct memory connection between wasm modules", function() { return import("./run").then(function(module) { expect(module.x1).toBe(42); expect(module.x2).toBe(42); expect(module.y1).toBe(11); expect(module.y2).toBe(11); }); }); webpack-4.30.0/test/cases/wasm/memory/mem-access.wat000066400000000000000000000005261345416772700223230ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (type $t1 (func (param i32))) (import "./memory.wat" "memory" (memory $./memory.wasm.memory 1)) (func $get (export "get") (type $t0) (result i32) (i32.load (i32.const 0))) (func $set (export "set") (type $t1) (param $p i32) (i32.store (i32.const 0) (get_local $p)))) webpack-4.30.0/test/cases/wasm/memory/memory.wat000066400000000000000000000001301345416772700216050ustar00rootroot00000000000000(module (memory $memory (export "memory") 1) (data (i32.const 12) "\00\00\00\00")) webpack-4.30.0/test/cases/wasm/memory/run.js000066400000000000000000000003351345416772700207310ustar00rootroot00000000000000import * as a1 from "./mem-access.wat?1"; import * as a2 from "./mem-access.wat?2"; a1.set(42); export const x1 = a1.get(); export const x2 = a2.get(); a2.set(11); export const y1 = a1.get(); export const y2 = a2.get(); webpack-4.30.0/test/cases/wasm/memory/test.filter.js000066400000000000000000000002221345416772700223630ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/order/000077500000000000000000000000001345416772700173715ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/order/a.js000066400000000000000000000001671345416772700201530ustar00rootroot00000000000000import { trackA, results } from "./tracker"; import "./b.js"; import "./wasm.wat"; trackA(); export default results; webpack-4.30.0/test/cases/wasm/order/b.js000066400000000000000000000000571345416772700201520ustar00rootroot00000000000000import { trackB } from "./tracker"; trackB(); webpack-4.30.0/test/cases/wasm/order/c.js000066400000000000000000000001171345416772700201500ustar00rootroot00000000000000import { trackC } from "./tracker"; trackC(); export const magicNumber = 42; webpack-4.30.0/test/cases/wasm/order/index.js000066400000000000000000000004331345416772700210360ustar00rootroot00000000000000it("should be evaluated in the correct order", () => { return import("./a").then(({ default: results }) => { return Promise.resolve().then(() => { // wait an extra tick to get the tick from the tracker expect(results).toEqual(["b", "c", "wasm42", "a", "tick"]); }); }); }); webpack-4.30.0/test/cases/wasm/order/test.filter.js000066400000000000000000000002221345416772700221660ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/order/tracker.js000066400000000000000000000004441345416772700213640ustar00rootroot00000000000000export let results = []; export function trackA() { results.push("a"); } export function trackB() { results.push("b"); } export function trackC() { results.push("c"); } export function trackWasm(number) { results.push("wasm" + number); } Promise.resolve().then(() => results.push("tick")); webpack-4.30.0/test/cases/wasm/order/wasm.wat000066400000000000000000000003331345416772700210540ustar00rootroot00000000000000(module (func $trackWasm (import "./tracker" "trackWasm") (param i32)) (global $magicNumber (import "./c.js" "magicNumber") i32) (func $start get_global $magicNumber call $trackWasm ) (start $start) ) webpack-4.30.0/test/cases/wasm/simple/000077500000000000000000000000001345416772700175475ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/simple/index.js000066400000000000000000000006221345416772700212140ustar00rootroot00000000000000it("should allow to run a WebAssembly module (indirect)", function() { return import("./module").then(function(module) { const result = module.run(); expect(result).toEqual(42); }); }); it("should allow to run a WebAssembly module (direct)", function() { return import("./wasm.wat?2").then(function(wasm) { const result = wasm.add(wasm.getNumber(), 2); expect(result).toEqual(42); }); }); webpack-4.30.0/test/cases/wasm/simple/module.js000066400000000000000000000001471345416772700213740ustar00rootroot00000000000000import { add, getNumber } from "./wasm.wat?1"; export function run() { return add(getNumber(), 2); } webpack-4.30.0/test/cases/wasm/simple/test.filter.js000066400000000000000000000002221345416772700223440ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/simple/wasm.wat000066400000000000000000000004771345416772700212430ustar00rootroot00000000000000(module (type $t0 (func (param i32 i32) (result i32))) (type $t1 (func (result i32))) (func $add (export "add") (type $t0) (param $p0 i32) (param $p1 i32) (result i32) (i32.add (get_local $p0) (get_local $p1))) (func $getNumber (export "getNumber") (type $t1) (result i32) (i32.const 40))) webpack-4.30.0/test/cases/wasm/table/000077500000000000000000000000001345416772700173455ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/table/index.js000066400000000000000000000021211345416772700210060ustar00rootroot00000000000000// the message is inconsistency between some nodejs versions const UNKNOWN_FUNCTION_TABLE = /invalid index into function table|invalid function/; it("should support tables", function() { return import("./wasm-table.wat").then(function(wasm) { expect(wasm.callByIndex(0)).toEqual(42); expect(wasm.callByIndex(1)).toEqual(13); expect(() => wasm.callByIndex(2)).toThrow(UNKNOWN_FUNCTION_TABLE); }); }); it("should support exported tables", function() { return import("./wasm-table-export.wat").then(function(wasm) { expect(wasm.table).toBeInstanceOf(WebAssembly.Table); expect(wasm.table.length).toBe(2); const e0 = wasm.table.get(0); const e1 = wasm.table.get(1); expect(e0).toBeInstanceOf(Function); expect(e1).toBeInstanceOf(Function); expect(e0()).toEqual(42); expect(e1()).toEqual(13); }); }); it("should support imported tables", function() { return import("./wasm-table-imported.wat").then(function(wasm) { expect(wasm.callByIndex(0)).toEqual(42); expect(wasm.callByIndex(1)).toEqual(13); expect(() => wasm.callByIndex(2)).toThrow(UNKNOWN_FUNCTION_TABLE); }); }); webpack-4.30.0/test/cases/wasm/table/test.filter.js000066400000000000000000000002221345416772700221420ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/table/wasm-table-export.wat000066400000000000000000000003461345416772700234400ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (func $f1 (type $t0) (result i32) (i32.const 42)) (func $f2 (type $t0) (result i32) (i32.const 13)) (table $table (export "table") 2 anyfunc) (elem (i32.const 0) $f1 $f2)) webpack-4.30.0/test/cases/wasm/table/wasm-table-imported.wat000066400000000000000000000004771345416772700237470ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (type $t1 (func (param i32) (result i32))) (import "./wasm-table-export.wat" "table" (table $./wasm-table-export.wasm.table 2 anyfunc)) (func $callByIndex (export "callByIndex") (type $t1) (param $i i32) (result i32) (call_indirect (type $t0) (get_local $i)))) webpack-4.30.0/test/cases/wasm/table/wasm-table.wat000066400000000000000000000006521345416772700221210ustar00rootroot00000000000000(module (type $t0 (func (result i32))) (type $t1 (func (result i32))) (type $t2 (func (param i32) (result i32))) (func $f0 (type $t0) (result i32) (i32.const 42)) (func $f1 (type $t0) (result i32) (i32.const 13)) (func $callByIndex (export "callByIndex") (type $t2) (param $p0 i32) (result i32) (call_indirect (type $t1) (get_local $p0))) (table $T0 2 anyfunc) (elem (i32.const 0) $f0 $f1)) webpack-4.30.0/test/cases/wasm/two-files-loader/000077500000000000000000000000001345416772700214335ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/two-files-loader/index.js000066400000000000000000000006531345416772700231040ustar00rootroot00000000000000it("should be able to create two modules from loader", function() { return import("./wrapper-loader!./src/wasm.dat").then(function(wasm) { expect(wasm.getString()).toEqual("Hello World"); }); }); it("should be able to create two modules from loader with remaining request", function() { return import("./wrapper-loader2!./src/wasm.dat?2").then(function(wasm) { expect(wasm.getString()).toEqual("Hello World"); }); }); webpack-4.30.0/test/cases/wasm/two-files-loader/src/000077500000000000000000000000001345416772700222225ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/two-files-loader/src/wasm.dat000066400000000000000000000002161345416772700236620ustar00rootroot00000000000000(module (memory (export "memory") 1) (data (i32.const 16) "Hello World\00") (func (export "getString") (result i32) (i32.const 16) ) ) webpack-4.30.0/test/cases/wasm/two-files-loader/test.filter.js000066400000000000000000000002221345416772700242300ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/two-files-loader/wrapper-loader.js000066400000000000000000000007721345416772700247230ustar00rootroot00000000000000const stringifyRequest = require("loader-utils").stringifyRequest; module.exports.pitch = function(remainingRequest) { return ` import { getString as _getString, memory } from ${stringifyRequest(this, `${this.resourcePath}.wat!=!${remainingRequest}` )}; export function getString() { const strBuf = new Uint8Array(memory.buffer, _getString()); const idx = strBuf.indexOf(0); const strBuf2 = strBuf.slice(0, idx); const str = Buffer.from(strBuf2).toString("utf-8"); return str; }; `; }; webpack-4.30.0/test/cases/wasm/two-files-loader/wrapper-loader2.js000066400000000000000000000010121345416772700247710ustar00rootroot00000000000000const stringifyRequest = require("loader-utils").stringifyRequest; module.exports.pitch = function(remainingRequest) { return ` import { getString as _getString, memory } from ${stringifyRequest( this, `${this.resourcePath}.wasm!=!wast-loader!${remainingRequest}` )}; export function getString() { const strBuf = new Uint8Array(memory.buffer, _getString()); const idx = strBuf.indexOf(0); const strBuf2 = strBuf.slice(0, idx); const str = Buffer.from(strBuf2).toString("utf-8"); return str; }; `; }; webpack-4.30.0/test/cases/wasm/unused-export/000077500000000000000000000000001345416772700211005ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/unused-export/index.js000066400000000000000000000002621345416772700225450ustar00rootroot00000000000000it("should allow wasm with unused exports", function() { return import("./module").then(function(module) { const result = module.run(); expect(result).toEqual(42); }); }); webpack-4.30.0/test/cases/wasm/unused-export/module.js000066400000000000000000000001301345416772700227150ustar00rootroot00000000000000import { getNumber } from "./wasm.wat"; export function run() { return getNumber(); } webpack-4.30.0/test/cases/wasm/unused-export/test.filter.js000066400000000000000000000002221345416772700236750ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/unused-export/wasm.wat000066400000000000000000000004771345416772700225740ustar00rootroot00000000000000(module (type $t0 (func (param i32 i32) (result i32))) (type $t1 (func (result i32))) (func $add (export "add") (type $t0) (param $p0 i32) (param $p1 i32) (result i32) (i32.add (get_local $p0) (get_local $p1))) (func $getNumber (export "getNumber") (type $t1) (result i32) (i32.const 42))) webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/000077500000000000000000000000001345416772700240125ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/Q_rsqrt.wasm000066400000000000000000000002341345416772700263350ustar00rootroot00000000000000asm`}}pmemory _Z7Q_rsqrtf €}C? C?"A߳ Auk" "C?  webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/duff.wasm000066400000000000000000000010231345416772700256230ustar00rootroot00000000000000asm`pmemory _Z4sendPcS_m  AjAv!@@@@@@@@@ AqAj"AK  A!  A!  A!  A!  A!  A!  A!  A! @@@@@@@@@@@@@   -: Aj! Aj!A! -: Aj! Aj!A! -: Aj! Aj!A! -: Aj! Aj!A!  -: Aj! Aj!A!  -: Aj! Aj!A!  -: Aj! Aj!A!  -: Aj"E A!  Aj! Aj!   A!  A ! webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/fact.wasm000066400000000000000000000002321345416772700256150ustar00rootroot00000000000000asm`|pmemory_Z4facti À~@ AH B|!B!@  B|"~! BU  D? webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/fast-math.wasm000066400000000000000000000004421345416772700265670ustar00rootroot00000000000000asm`|||`||`||||env_Z3powddpЀmemory_Z3food_Z9maybe_mindd _Z8call_powd _Z6do_powd _Z6factorddd 退 D@  c D @    webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/index.js000066400000000000000000000030521345416772700254570ustar00rootroot00000000000000it("Q_rsqrt should work", function() { return import("./Q_rsqrt.wasm").then(function(wasm) { const result = wasm._Z7Q_rsqrtf(1/1764); expect(result).toBeGreaterThan(41.9); expect(result).toBeLessThan(42.1); }); }); it("testFunction should work", function() { return import("./testFunction.wasm").then(function(wasm) { const view = new Int32Array(wasm.memory.buffer); view[0] = 123; view[1] = 1; view[2] = 2; view[3] = 3; const result = wasm._Z12testFunctionPii(4, 3); expect(result).toEqual(6); }); }); it("fact should work", function() { return import("./fact.wasm").then(function(wasm) { const result = wasm._Z4facti(11); expect(result).toEqual(39916800); }); }); it("popcnt should work", function() { return import("./popcnt.wasm").then(function(wasm) { expect(wasm.main(0xF0F)).toEqual(16); expect(wasm._Z5countj(0xF0F)).toEqual(8); }); }); it("fast-math should work", function() { return import("./fast-math.wasm").then(function(wasm) { expect(wasm._Z3food(42)).toEqual(14); expect(wasm._Z9maybe_mindd(42, 24)).toEqual(24); expect(wasm._Z8call_powd(42)).toEqual(9682651996416); expect(wasm._Z6do_powd(42)).toEqual(9682651996416); expect(wasm._Z6factorddd(42, 42, 42)).toEqual(3528); }); }); it("duff should work", function() { return import("./duff.wasm").then(function(wasm) { const view = new Uint8Array(wasm.memory.buffer); view[0] = 123; for(let i = 1; i < 100; i++) view[i] = i; const result = wasm._Z4sendPcS_m(200, 1, 100); for(let i = 1; i < 100; i++) expect(view[199 + i]).toEqual(i); }); }); webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/node_modules/000077500000000000000000000000001345416772700264675ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/node_modules/env.js000066400000000000000000000000421345416772700276110ustar00rootroot00000000000000export const _Z3powdd = Math.pow; webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/popcnt.wasm000066400000000000000000000001701345416772700262040ustar00rootroot00000000000000asm`pmemorymain _Z5countj  iAt i webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/test.filter.js000066400000000000000000000002221345416772700266070ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-async/testFunction.wasm000066400000000000000000000002321345416772700273650ustar00rootroot00000000000000asm`pmemory_Z12testFunctionPii A!@ AH @ ( j! Aj! Aj"  webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/000077500000000000000000000000001345416772700236515ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/Q_rsqrt.wasm000066400000000000000000000002341345416772700261740ustar00rootroot00000000000000asm`}}pmemory _Z7Q_rsqrtf €}C? C?"A߳ Auk" "C?  webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/duff.wasm000066400000000000000000000010231345416772700254620ustar00rootroot00000000000000asm`pmemory _Z4sendPcS_m  AjAv!@@@@@@@@@ AqAj"AK  A!  A!  A!  A!  A!  A!  A!  A! @@@@@@@@@@@@@   -: Aj! Aj!A! -: Aj! Aj!A! -: Aj! Aj!A! -: Aj! Aj!A!  -: Aj! Aj!A!  -: Aj! Aj!A!  -: Aj! Aj!A!  -: Aj"E A!  Aj! Aj!   A!  A ! webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/fact.wasm000066400000000000000000000002321345416772700254540ustar00rootroot00000000000000asm`|pmemory_Z4facti À~@ AH B|!B!@  B|"~! BU  D? webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/fast-math.wasm000066400000000000000000000004421345416772700264260ustar00rootroot00000000000000asm`|||`||`||||env_Z3powddpЀmemory_Z3food_Z9maybe_mindd _Z8call_powd _Z6do_powd _Z6factorddd 退 D@  c D @    webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/index.js000066400000000000000000000011121345416772700253110ustar00rootroot00000000000000it("Q_rsqrt should work", function() { return import("./tests").then(t => t.run_Q_rsqrt()); }); it("testFunction should work", function() { return import("./tests").then(t => t.run_testFunction()); }); it("fact should work", function() { return import("./tests").then(t => t.run_fact()); }); it("popcnt should work", function() { return import("./tests").then(t => t.run_popcnt()); }); it("fast-math should work", function() { return import("./tests").then(t => t.run_fastMath()); }); it("duff should work", function() { return import("./tests").then(t => t.run_duff()); }); webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/node_modules/000077500000000000000000000000001345416772700263265ustar00rootroot00000000000000webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/node_modules/env.js000066400000000000000000000000421345416772700274500ustar00rootroot00000000000000export const _Z3powdd = Math.pow; webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/popcnt.wasm000066400000000000000000000001701345416772700260430ustar00rootroot00000000000000asm`pmemorymain _Z5countj  iAt i webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/test.filter.js000066400000000000000000000002221345416772700264460ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/testFunction.wasm000066400000000000000000000002321345416772700272240ustar00rootroot00000000000000asm`pmemory_Z12testFunctionPii A!@ AH @ ( j! Aj! Aj"  webpack-4.30.0/test/cases/wasm/wasm-explorer-examples-sync/tests.js000066400000000000000000000026361345416772700253600ustar00rootroot00000000000000import * as Q_rsqrt from "./Q_rsqrt.wasm"; import * as testFunction from "./testFunction.wasm"; import * as fact from "./fact.wasm"; import * as popcnt from "./popcnt.wasm"; import * as fastMath from "./fast-math.wasm"; import * as duff from "./duff.wasm"; export function run_Q_rsqrt() { const result = Q_rsqrt._Z7Q_rsqrtf(1/1764); expect(result).toBeGreaterThan(41.9); expect(result).toBeLessThan(42.1); } export function run_testFunction() { const view = new Int32Array(testFunction.memory.buffer); view[0] = 123; view[1] = 1; view[2] = 2; view[3] = 3; const result = testFunction._Z12testFunctionPii(4, 3); expect(result).toEqual(6); } export function run_fact() { const result = fact._Z4facti(11); expect(result).toEqual(39916800); } export function run_popcnt() { expect(popcnt.main(0xF0F)).toEqual(16); expect(popcnt._Z5countj(0xF0F)).toEqual(8); } export function run_fastMath() { expect(fastMath._Z3food(42)).toEqual(14); expect(fastMath._Z9maybe_mindd(42, 24)).toEqual(24); expect(fastMath._Z8call_powd(42)).toEqual(9682651996416); expect(fastMath._Z6do_powd(42)).toEqual(9682651996416); expect(fastMath._Z6factorddd(42, 42, 42)).toEqual(3528); } export function run_duff() { const view = new Uint8Array(duff.memory.buffer); view[0] = 123; for(let i = 1; i < 100; i++) view[i] = i; const result = duff._Z4sendPcS_m(200, 1, 100); for(let i = 1; i < 100; i++) expect(view[199 + i]).toEqual(i); } webpack-4.30.0/test/checkArrayExpectation.js000066400000000000000000000034431345416772700210330ustar00rootroot00000000000000"use strict"; const fs = require("fs"); const path = require("path"); module.exports = function checkArrayExpectation( testDirectory, object, kind, filename, upperCaseKind, done ) { if (!done) { done = upperCaseKind; upperCaseKind = filename; filename = `${kind}s`; } let array = object[`${kind}s`].slice().sort(); if (kind === "warning") array = array.filter(item => !/from Terser/.test(item)); if (fs.existsSync(path.join(testDirectory, `${filename}.js`))) { const expectedFilename = path.join(testDirectory, `${filename}.js`); const expected = require(expectedFilename); if (expected.length < array.length) return ( done( new Error( `More ${kind}s while compiling than expected:\n\n${array.join( "\n\n" )}. Check expected warnings: ${filename}` ) ), true ); else if (expected.length > array.length) return ( done( new Error( `Less ${kind}s while compiling than expected:\n\n${array.join( "\n\n" )}. Check expected warnings: ${filename}` ) ), true ); for (let i = 0; i < array.length; i++) { if (Array.isArray(expected[i])) { for (let j = 0; j < expected[i].length; j++) { if (!expected[i][j].test(array[i])) return ( done( new Error( `${upperCaseKind} ${i}: ${array[i]} doesn't match ${expected[ i ][j].toString()}` ) ), true ); } } else if (!expected[i].test(array[i])) return ( done( new Error( `${upperCaseKind} ${i}: ${array[i]} doesn't match ${expected[ i ].toString()}` ) ), true ); } } else if (array.length > 0) { return ( done( new Error(`${upperCaseKind}s while compiling:\n\n${array.join("\n\n")}`) ), true ); } }; webpack-4.30.0/test/compareLocations.unittest.js000066400000000000000000000075331345416772700217370ustar00rootroot00000000000000"use strict"; const compareLocations = require("../lib/compareLocations"); const createPosition = overrides => { return Object.assign( { line: 10, column: 5 }, overrides ); }; const createLocation = (start, end, index) => { return { start: createPosition(start), end: createPosition(end), index: index || 3 }; }; describe("compareLocations", () => { describe("string location comparison", () => { it("returns -1 when the first string comes before the second string", () => { expect(compareLocations("alpha", "beta")).toBe(-1); }); it("returns 1 when the first string comes after the second string", () => { expect(compareLocations("beta", "alpha")).toBe(1); }); it("returns 0 when the first string is the same as the second string", () => { expect(compareLocations("charlie", "charlie")).toBe(0); }); }); describe("object location comparison", () => { let a, b; describe("location line number", () => { beforeEach(() => { a = createLocation({ line: 10 }); b = createLocation({ line: 20 }); }); it("returns -1 when the first location line number comes before the second location line number", () => { expect(compareLocations(a, b)).toBe(-1); }); it("returns 1 when the first location line number comes after the second location line number", () => { expect(compareLocations(b, a)).toBe(1); }); }); describe("location column number", () => { beforeEach(() => { a = createLocation({ column: 10 }); b = createLocation({ column: 20 }); }); it("returns -1 when the first location column number comes before the second location column number", () => { expect(compareLocations(a, b)).toBe(-1); }); it("returns 1 when the first location column number comes after the second location column number", () => { expect(compareLocations(b, a)).toBe(1); }); }); describe("location index number", () => { beforeEach(() => { a = createLocation(null, null, 10); b = createLocation(null, null, 20); }); it("returns -1 when the first location index number comes before the second location index number", () => { expect(compareLocations(a, b)).toBe(-1); }); it("returns 1 when the first location index number comes after the second location index number", () => { expect(compareLocations(b, a)).toBe(1); }); }); describe("same location", () => { beforeEach(() => { a = createLocation(); b = createLocation(); }); it("returns 0", () => { expect(compareLocations(a, b)).toBe(0); }); }); }); describe("string and object location comparison", () => { it("returns 1 when the first parameter is a string and the second parameter is an object", () => { expect(compareLocations("alpha", createLocation())).toBe(1); }); it("returns -1 when the first parameter is an object and the second parameter is a string", () => { expect(compareLocations(createLocation(), "alpha")).toBe(-1); }); }); describe("unknown location type comparison", () => { it("returns 0 when the first parameter is an object and the second parameter is a number", () => { expect(compareLocations(createLocation(), 123)).toBe(0); }); it("returns undefined when the first parameter is a number and the second parameter is an object", () => { expect(compareLocations(123, createLocation())).toBe(undefined); }); it("returns 0 when the first parameter is a string and the second parameter is a number", () => { expect(compareLocations("alpha", 123)).toBe(0); }); it("returns undefined when the first parameter is a number and the second parameter is a string", () => { expect(compareLocations(123, "alpha")).toBe(undefined); }); it("returns undefined when both the first parameter and the second parameter is a number", () => { expect(compareLocations(123, 456)).toBe(undefined); }); }); }); webpack-4.30.0/test/configCases/000077500000000000000000000000001345416772700164355ustar00rootroot00000000000000webpack-4.30.0/test/configCases/additional-pass/000077500000000000000000000000001345416772700215115ustar00rootroot00000000000000webpack-4.30.0/test/configCases/additional-pass/simple/000077500000000000000000000000001345416772700230025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/additional-pass/simple/index.js000066400000000000000000000000631345416772700244460ustar00rootroot00000000000000it("should compile", function(done) { done(); }); webpack-4.30.0/test/configCases/additional-pass/simple/webpack.config.js000066400000000000000000000004371345416772700262240ustar00rootroot00000000000000var testPlugin = function() { var counter = 1; this.hooks.compilation.tap("TestPlugin", compilation => { var nr = counter++; compilation.hooks.needAdditionalPass.tap("TestPlugin", function() { if (nr < 5) return true; }); }); }; module.exports = { plugins: [testPlugin] }; webpack-4.30.0/test/configCases/amd/000077500000000000000000000000001345416772700171765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/amd/disabled/000077500000000000000000000000001345416772700207455ustar00rootroot00000000000000webpack-4.30.0/test/configCases/amd/disabled/index.js000066400000000000000000000002251345416772700224110ustar00rootroot00000000000000it("should compile", function(done) { done(); }); it("should disable define", function(done) { expect(typeof define).toBe('undefined') done() }) webpack-4.30.0/test/configCases/amd/disabled/webpack.config.js000066400000000000000000000000421345416772700241570ustar00rootroot00000000000000module.exports = { amd: false }; webpack-4.30.0/test/configCases/async-commons-chunk/000077500000000000000000000000001345416772700223315ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/all-selected/000077500000000000000000000000001345416772700246675ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/all-selected/a.js000066400000000000000000000000251345416772700254420ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/configCases/async-commons-chunk/all-selected/b.js000066400000000000000000000000251345416772700254430ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/configCases/async-commons-chunk/all-selected/c.js000066400000000000000000000000251345416772700254440ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/configCases/async-commons-chunk/all-selected/index.js000066400000000000000000000010411345416772700263300ustar00rootroot00000000000000it("should load the full async commons", function(done) { require.ensure(["./a"], function(require) { expect(require("./a")).toBe("a"); done(); }); }); it("should load a chunk with async commons (AMD)", function(done) { require(["./a", "./b"], function(a, b) { expect(a).toBe("a"); expect(b).toBe("b"); done(); }); }); it("should load a chunk with async commons (require.ensure)", function(done) { require.ensure([], function(require) { expect(require("./a")).toBe("a"); expect(require("./c")).toBe("c"); done(); }); }); webpack-4.30.0/test/configCases/async-commons-chunk/all-selected/webpack.config.js000066400000000000000000000001151345416772700301020ustar00rootroot00000000000000module.exports = { optimization: { splitChunks: { minSize: 1 } } }; webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/000077500000000000000000000000001345416772700243035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/a.js000066400000000000000000000000251345416772700250560ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/b.js000066400000000000000000000000251345416772700250570ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/c.js000066400000000000000000000000251345416772700250600ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/d.js000066400000000000000000000000251345416772700250610ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/e.js000066400000000000000000000000251345416772700250620ustar00rootroot00000000000000module.exports = "e";webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/index.js000066400000000000000000000016061345416772700257530ustar00rootroot00000000000000it("should load nested commons chunk", function(done) { var counter = 0; require.ensure(["./a"], function(require) { expect(require("./a")).toBe("a"); require.ensure(["./c", "./d"], function(require) { expect(require("./c")).toBe("c"); expect(require("./d")).toBe("d"); if(++counter == 4) done(); }); require.ensure(["./c", "./e"], function(require) { expect(require("./c")).toBe("c"); expect(require("./e")).toBe("e"); if(++counter == 4) done(); }); }); require.ensure(["./b"], function(require) { expect(require("./b")).toBe("b"); require.ensure(["./c", "./d"], function(require) { expect(require("./c")).toBe("c"); expect(require("./d")).toBe("d"); if(++counter == 4) done(); }); require.ensure(["./c", "./e"], function(require) { expect(require("./c")).toBe("c"); expect(require("./e")).toBe("e"); if(++counter == 4) done(); }); }); }); webpack-4.30.0/test/configCases/async-commons-chunk/duplicate/webpack.config.js000066400000000000000000000001151345416772700275160ustar00rootroot00000000000000module.exports = { optimization: { splitChunks: { minSize: 1 } } }; webpack-4.30.0/test/configCases/async-commons-chunk/existing-name/000077500000000000000000000000001345416772700251015ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/existing-name/a.js000066400000000000000000000000251345416772700256540ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/configCases/async-commons-chunk/existing-name/b.js000066400000000000000000000000251345416772700256550ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/configCases/async-commons-chunk/existing-name/c.js000066400000000000000000000000251345416772700256560ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/configCases/async-commons-chunk/existing-name/index.js000066400000000000000000000022611345416772700265470ustar00rootroot00000000000000const chunkLoadingSpy = jest.spyOn(__webpack_require__, "e"); it("should not have duplicate chunks in blocks", function(done) { // This split point should contain: a require.ensure( [], function(require) { expect(require("./a")).toBe("a"); }, "a" ); // This split point should contain: a and b - we use CommonsChunksPlugin to // have it only contain b and make chunk a be an async dependency. require.ensure( [], function(require) { expect(require("./a")).toBe("a"); expect(require("./b")).toBe("b"); }, "a+b" ); // This split point should contain: a, b and c - we use CommonsChunksPlugin to // have it only contain c and make chunks a and a+b be async dependencies. require.ensure( [], function(require) { expect(require("./a")).toBe("a"); expect(require("./b")).toBe("b"); expect(require("./c")).toBe("c"); }, "a+b+c" ); // Each of the require.ensures above should end up resolving chunks: // - a // - a, a+b // - a, a+b, a+b+c expect(chunkLoadingSpy.mock.calls.length).toBe(6); expect(chunkLoadingSpy.mock.calls).toEqual([ ["a"], ["a"], ["a+b" /* == b */], ["a"], ["a+b" /* == b */], ["a+b+c" /* == c */] ]); done(); }); webpack-4.30.0/test/configCases/async-commons-chunk/existing-name/webpack.config.js000066400000000000000000000003241345416772700303160ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { performance: { hints: false }, optimization: { splitChunks: { minSize: 1, name: true } }, plugins: [new webpack.NamedChunksPlugin()] }; webpack-4.30.0/test/configCases/async-commons-chunk/nested/000077500000000000000000000000001345416772700236135ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/nested/a.js000066400000000000000000000000251345416772700243660ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/configCases/async-commons-chunk/nested/b.js000066400000000000000000000000251345416772700243670ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/configCases/async-commons-chunk/nested/c.js000066400000000000000000000000251345416772700243700ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/configCases/async-commons-chunk/nested/d.js000066400000000000000000000000251345416772700243710ustar00rootroot00000000000000module.exports = "d";webpack-4.30.0/test/configCases/async-commons-chunk/nested/index.js000066400000000000000000000011421345416772700252560ustar00rootroot00000000000000it("should load nested commons chunk", function(done) { require.ensure(["./a"], function(require) { expect(require("./a")).toBe("a"); var counter = 0; require.ensure(["./b", "./c"], function(require) { expect(require("./b")).toBe("b"); expect(require("./c")).toBe("c"); if(++counter == 3) done(); }); require.ensure(["./b", "./d"], function(require) { expect(require("./b")).toBe("b"); expect(require("./d")).toBe("d"); if(++counter == 3) done(); }); require.ensure(["./b"], function(require) { expect(require("./b")).toBe("b"); if(++counter == 3) done(); }); }); }); webpack-4.30.0/test/configCases/async-commons-chunk/nested/webpack.config.js000066400000000000000000000001151345416772700270260ustar00rootroot00000000000000module.exports = { optimization: { splitChunks: { minSize: 1 } } }; webpack-4.30.0/test/configCases/async-commons-chunk/node/000077500000000000000000000000001345416772700232565ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/node/index.js000066400000000000000000000002201345416772700247150ustar00rootroot00000000000000import "./modules/a"; it("should load", done => { Promise.all([import("./modules/b"), import("./modules/c")]).then(() => { done(); }); }); webpack-4.30.0/test/configCases/async-commons-chunk/node/modules/000077500000000000000000000000001345416772700247265ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/node/modules/a.js000066400000000000000000000000431345416772700255010ustar00rootroot00000000000000import "./b"; export default "a"; webpack-4.30.0/test/configCases/async-commons-chunk/node/modules/b.js000066400000000000000000000000241345416772700255010ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/configCases/async-commons-chunk/node/modules/c.js000066400000000000000000000000441345416772700255040ustar00rootroot00000000000000import("./a"); export default "c"; webpack-4.30.0/test/configCases/async-commons-chunk/node/webpack.config.js000066400000000000000000000002241345416772700264720ustar00rootroot00000000000000module.exports = { mode: "none", entry: { "foo/bar": "./" }, target: "node", optimization: { namedChunks: true, namedModules: true } }; webpack-4.30.0/test/configCases/async-commons-chunk/simple/000077500000000000000000000000001345416772700236225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/async-commons-chunk/simple/a.js000066400000000000000000000000251345416772700243750ustar00rootroot00000000000000module.exports = "a";webpack-4.30.0/test/configCases/async-commons-chunk/simple/b.js000066400000000000000000000000251345416772700243760ustar00rootroot00000000000000module.exports = "b";webpack-4.30.0/test/configCases/async-commons-chunk/simple/c.js000066400000000000000000000000251345416772700243770ustar00rootroot00000000000000module.exports = "c";webpack-4.30.0/test/configCases/async-commons-chunk/simple/index.js000066400000000000000000000010411345416772700252630ustar00rootroot00000000000000it("should load the full async commons", function(done) { require.ensure(["./a"], function(require) { expect(require("./a")).toBe("a"); done(); }); }); it("should load a chunk with async commons (AMD)", function(done) { require(["./a", "./b"], function(a, b) { expect(a).toBe("a"); expect(b).toBe("b"); done(); }); }); it("should load a chunk with async commons (require.ensure)", function(done) { require.ensure([], function(require) { expect(require("./a")).toBe("a"); expect(require("./c")).toBe("c"); done(); }); }); webpack-4.30.0/test/configCases/async-commons-chunk/simple/webpack.config.js000066400000000000000000000001151345416772700270350ustar00rootroot00000000000000module.exports = { optimization: { splitChunks: { minSize: 1 } } }; webpack-4.30.0/test/configCases/chunk-index/000077500000000000000000000000001345416772700206525ustar00rootroot00000000000000webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/000077500000000000000000000000001345416772700252655ustar00rootroot00000000000000webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/a.js000066400000000000000000000000221345416772700260350ustar00rootroot00000000000000import "./shared";webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/async.js000066400000000000000000000000001345416772700267260ustar00rootroot00000000000000webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/b.js000066400000000000000000000000221345416772700260360ustar00rootroot00000000000000import "./shared";webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/c.js000066400000000000000000000000001345416772700260330ustar00rootroot00000000000000webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/entry1.js000066400000000000000000000001761345416772700270510ustar00rootroot00000000000000import "./a"; import(/* webpackChunkName: "async" */ "./async"); import "./b"; import "./c"; it("should compile", () => {}); webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/entry2.js000066400000000000000000000001761345416772700270520ustar00rootroot00000000000000import "./c"; import(/* webpackChunkName: "async" */ "./async"); import "./b"; import "./a"; it("should compile", () => {}); webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/shared.js000066400000000000000000000000001345416772700270570ustar00rootroot00000000000000webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/test.config.js000066400000000000000000000001421345416772700300430ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return ["entry1.js", "entry2.js"]; } }; webpack-4.30.0/test/configCases/chunk-index/order-multiple-entries/webpack.config.js000066400000000000000000000055061345416772700305110ustar00rootroot00000000000000/** @typedef {import("../../../../lib/Compilation")} Compilation */ /** @typedef {import("../../../../lib/Module")} Module */ module.exports = { entry: { entry1: "./entry1", entry2: "./entry2" }, output: { filename: "[name].js" }, plugins: [ function() { /** * @param {Compilation} compilation compilation * @returns {void} */ const handler = compilation => { compilation.hooks.afterSeal.tap("testcase", () => { const data = {}; for (const [name, group] of compilation.namedChunkGroups) { /** @type {Map} */ const modules = new Map(); const modules2 = new Map(); for (const chunk of group.chunks) { for (const module of chunk.modulesIterable) { modules.set(module, group.getModuleIndex(module)); modules2.set(module, group.getModuleIndex2(module)); } } const sortedModules = Array.from(modules).sort((a, b) => { return a[1] - b[1]; }); const sortedModules2 = Array.from(modules2).sort((a, b) => { return a[1] - b[1]; }); const text = sortedModules .map( ([m, index]) => `${index}: ${m.readableIdentifier( compilation.requestShortener )}` ) .join(", "); const text2 = sortedModules2 .map( ([m, index]) => `${index}: ${m.readableIdentifier( compilation.requestShortener )}` ) .join(", "); data[name + "Index"] = text; data[name + "Index2"] = text2; } expect(data).toEqual({ entry1Index: "0: ./entry1.js, 1: ./a.js, 2: ./shared.js, 3: ./b.js, 4: ./c.js", entry1Index2: "0: ./shared.js, 1: ./a.js, 2: ./b.js, 3: ./c.js, 4: ./entry1.js", entry2Index: "0: ./entry2.js, 1: ./c.js, 2: ./b.js, 3: ./shared.js, 4: ./a.js", entry2Index2: "0: ./c.js, 1: ./shared.js, 2: ./b.js, 3: ./a.js, 4: ./entry2.js", asyncIndex: "0: ./async.js", asyncIndex2: "0: ./async.js" }); const indicies = compilation.modules .slice() .sort((a, b) => a.index - b.index) .map( m => `${m.index}: ${m.readableIdentifier( compilation.requestShortener )}` ) .join(", "); const indicies2 = compilation.modules .slice() .sort((a, b) => a.index2 - b.index2) .map( m => `${m.index2}: ${m.readableIdentifier( compilation.requestShortener )}` ) .join(", "); expect(indicies).toEqual( "0: ./entry1.js, 1: ./a.js, 2: ./shared.js, 3: ./b.js, 4: ./c.js, 5: ./entry2.js, 6: ./async.js" ); expect(indicies2).toEqual( "0: ./shared.js, 1: ./a.js, 2: ./b.js, 3: ./c.js, 4: ./entry1.js, 5: ./entry2.js, 6: ./async.js" ); }); }; this.hooks.compilation.tap("testcase", handler); } ] }; webpack-4.30.0/test/configCases/code-generation/000077500000000000000000000000001345416772700215005ustar00rootroot00000000000000webpack-4.30.0/test/configCases/code-generation/harmony-pure-default/000077500000000000000000000000001345416772700255505ustar00rootroot00000000000000webpack-4.30.0/test/configCases/code-generation/harmony-pure-default/index.js000066400000000000000000000005131345416772700272140ustar00rootroot00000000000000import { value as v1 } from "./module1"; import { value as v2 } from "./module2"; import { value as v3 } from "./module3"; import { value as v4 } from "./module4"; it("should not execute exports when annotated with pure comment", () => { expect(v1).toBe(42); expect(v2).toBe(42); expect(v3).toBe(42); expect(v4).toBe(42); }); webpack-4.30.0/test/configCases/code-generation/harmony-pure-default/module1.js000066400000000000000000000001511345416772700274510ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export default /*#__PURE__*/inc(); export { value }; webpack-4.30.0/test/configCases/code-generation/harmony-pure-default/module2.js000066400000000000000000000001531345416772700274540ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export default (/*#__PURE__*/inc()); export { value }; webpack-4.30.0/test/configCases/code-generation/harmony-pure-default/module3.js000066400000000000000000000001531345416772700274550ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export default /*#__PURE__*/(inc()); export { value }; webpack-4.30.0/test/configCases/code-generation/harmony-pure-default/module4.js000066400000000000000000000001751345416772700274620ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export // hello default // world /*#__PURE__*/ inc() ; export { value }; webpack-4.30.0/test/configCases/code-generation/harmony-pure-default/webpack.config.js000066400000000000000000000001551345416772700307670ustar00rootroot00000000000000module.exports = { mode: "production", optimization: { minimize: true, concatenateModules: false } }; webpack-4.30.0/test/configCases/code-generation/require-context-id/000077500000000000000000000000001345416772700252305ustar00rootroot00000000000000webpack-4.30.0/test/configCases/code-generation/require-context-id/folder/000077500000000000000000000000001345416772700265035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/code-generation/require-context-id/folder/a.js000066400000000000000000000000261345416772700272570ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/code-generation/require-context-id/folder/b.js000066400000000000000000000000261345416772700272600ustar00rootroot00000000000000module.exports = "b"; webpack-4.30.0/test/configCases/code-generation/require-context-id/index.js000066400000000000000000000002731345416772700266770ustar00rootroot00000000000000it("should escape require.context id correctly", function() { var context = require.context("./folder"); expect(context("./a")).toBe("a"); expect(context.id).toBeTypeOf("string"); }); webpack-4.30.0/test/configCases/code-generation/require-context-id/webpack.config.js000066400000000000000000000001551345416772700304470ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [new webpack.HashedModuleIdsPlugin()] }; webpack-4.30.0/test/configCases/code-generation/use-strict/000077500000000000000000000000001345416772700236025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/code-generation/use-strict/harmony-with-strict.js000066400000000000000000000000421345416772700300700ustar00rootroot00000000000000"use strict"; export default "a"; webpack-4.30.0/test/configCases/code-generation/use-strict/harmony-with-strict2.js000066400000000000000000000001601345416772700301530ustar00rootroot00000000000000"use strict"; import * as a from "./harmony-without-strict2"; export default a; import "./harmony-with-strict3" webpack-4.30.0/test/configCases/code-generation/use-strict/harmony-with-strict3.js000066400000000000000000000000421345416772700301530ustar00rootroot00000000000000"use strict"; export default "a"; webpack-4.30.0/test/configCases/code-generation/use-strict/harmony-without-strict.js000066400000000000000000000000241345416772700306200ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/configCases/code-generation/use-strict/harmony-without-strict2.js000066400000000000000000000000241345416772700307020ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/configCases/code-generation/use-strict/index.js000066400000000000000000000015171345416772700252530ustar00rootroot00000000000000"use strict"; it("should include only one use strict per module", function() { require("./harmony-with-strict"); require("./harmony-without-strict"); require("./harmony-with-strict2"); var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var regExp = /\"use strict\";?\s*(.*)/g var match = regExp.exec(source); var matches = []; while(match) { matches.push(match[1]); match = regExp.exec(source); } matches.sort(); expect(matches).toEqual([ "/* unused harmony default export */ var _unused_webpack_default_export = (\"a\");", "__webpack_require__.r(__webpack_exports__);", "__webpack_require__.r(__webpack_exports__);", "__webpack_require__.r(__webpack_exports__);", "__webpack_require__.r(__webpack_exports__);", "it(\"should include only one use strict per module\", function() {", ]); }); webpack-4.30.0/test/configCases/code-generation/use-strict/webpack.config.js000066400000000000000000000002161345416772700270170ustar00rootroot00000000000000module.exports = { node: { __dirname: false, __filename: false }, optimization: { concatenateModules: false, minimize: false } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/000077500000000000000000000000001345416772700225125ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/correct-order/000077500000000000000000000000001345416772700252645ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/correct-order/a.js000066400000000000000000000000261345416772700260400ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/commons-chunk-plugin/correct-order/index.js000066400000000000000000000002721345416772700267320ustar00rootroot00000000000000var a = require("./a"); it("should run", function() { expect(a).toBe("a"); }); var mainModule = require.main; it("should be main", function() { expect(mainModule).toBe(module); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/correct-order/test.config.js000066400000000000000000000001551345416772700300460ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./main.js" ] } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/correct-order/webpack.config.js000066400000000000000000000003121345416772700304760ustar00rootroot00000000000000module.exports = { entry: { vendor: ["./a"], main: "./index" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { minSize: 1, name: "vendor" } } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/extract-async-from-entry/000077500000000000000000000000001345416772700273775ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/extract-async-from-entry/index.js000066400000000000000000000000541345416772700310430ustar00rootroot00000000000000it("should run successful", function() {}); webpack-4.30.0/test/configCases/commons-chunk-plugin/extract-async-from-entry/test.config.js000066400000000000000000000001341345416772700321560ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./main.js" ]; } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/extract-async-from-entry/webpack.config.js000066400000000000000000000002711345416772700326150ustar00rootroot00000000000000module.exports = { entry: { main: "./index", second: "./index" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { minSize: 1 } } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/000077500000000000000000000000001345416772700244345ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/common.js000066400000000000000000000000331345416772700262560ustar00rootroot00000000000000module.exports = "common"; webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/first.js000066400000000000000000000003161345416772700261210ustar00rootroot00000000000000require("./common"); it("should have the correct main flag for multi first module", function() { var multiModule = __webpack_require__.c[module.parents[0]]; expect(multiModule.hot._main).toBe(true); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/second.js000066400000000000000000000003171345416772700262460ustar00rootroot00000000000000require("./common"); it("should have the correct main flag for multi second module", function() { var multiModule = __webpack_require__.c[module.parents[0]]; expect(multiModule.hot._main).toBe(true); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/shared.js000066400000000000000000000000331345416772700262340ustar00rootroot00000000000000module.exports = "shared"; webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/test.config.js000066400000000000000000000002001345416772700272050ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./first.js", "./second.js" ] } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/vendor.js000066400000000000000000000003531345416772700262700ustar00rootroot00000000000000require("./common"); module.exports = "vendor"; it("should have the correct main flag for multi vendor module", function() { var multiModule = __webpack_require__.c[module.parents[0]]; expect(multiModule.hot._main).toBe(true); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/hot-multi/webpack.config.js000066400000000000000000000006101345416772700276470ustar00rootroot00000000000000var HotModuleReplacementPlugin = require("../../../../lib/HotModuleReplacementPlugin"); module.exports = { entry: { vendor: ["./vendor"], first: ["./shared", "./first"], second: ["./shared", "./second"] }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { minSize: 1, name: "vendor" } }, plugins: [new HotModuleReplacementPlugin()] }; webpack-4.30.0/test/configCases/commons-chunk-plugin/hot/000077500000000000000000000000001345416772700233045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/hot/index.js000066400000000000000000000003461345416772700247540ustar00rootroot00000000000000it("should have the correct main flag", function() { var a = require("./vendor"); expect(a._main).toBe(false); expect(module.hot._main).toBe(true); }); it("should be main", function() { expect(require.main).toBe(module); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/hot/test.config.js000066400000000000000000000001551345416772700260660ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./main.js" ] } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/hot/vendor.js000066400000000000000000000000351345416772700251350ustar00rootroot00000000000000module.exports = module.hot; webpack-4.30.0/test/configCases/commons-chunk-plugin/hot/webpack.config.js000066400000000000000000000005251345416772700265240ustar00rootroot00000000000000var HotModuleReplacementPlugin = require("../../../../lib/HotModuleReplacementPlugin"); module.exports = { entry: { vendor: ["./vendor"], main: "./index" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { minSize: 1, name: "vendor" } }, plugins: [new HotModuleReplacementPlugin()] }; webpack-4.30.0/test/configCases/commons-chunk-plugin/inverted-order/000077500000000000000000000000001345416772700254435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/inverted-order/a.js000066400000000000000000000000261345416772700262170ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/commons-chunk-plugin/inverted-order/index.js000066400000000000000000000002721345416772700271110ustar00rootroot00000000000000var a = require("./a"); it("should run", function() { expect(a).toBe("a"); }); var mainModule = require.main; it("should be main", function() { expect(mainModule).toBe(module); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/inverted-order/test.config.js000066400000000000000000000001551345416772700302250ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./main.js", "./vendor.js" ] } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/inverted-order/webpack.config.js000066400000000000000000000003121345416772700306550ustar00rootroot00000000000000module.exports = { entry: { vendor: ["./a"], main: "./index" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { minSize: 1, name: "vendor" } } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/library/000077500000000000000000000000001345416772700241565ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/library/a.js000066400000000000000000000003171345416772700247350ustar00rootroot00000000000000var path = require("path"); module.exports = { vendor: require("fs").readFileSync(path.join(__dirname, "vendor.js"), "utf-8"), main: require("fs").readFileSync(path.join(__dirname, "main.js"), "utf-8") }; webpack-4.30.0/test/configCases/commons-chunk-plugin/library/index.js000066400000000000000000000005171345416772700256260ustar00rootroot00000000000000require.include("external1"); require.ensure([], function() { require.include("external2"); }) it("should have externals in main file", function() { var a = require("./a"); expect(a.vendor).toMatch("require(\"external0\")"); expect(a.main).toMatch("require(\"external1\")"); expect(a.main).toMatch("require(\"external2\")"); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/library/test.config.js000066400000000000000000000003151345416772700267360ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./main.js" ] }, modules: { "external0": "module 0", "external1": "module 1", "external2": "module 2" } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/library/webpack.config.js000066400000000000000000000006561345416772700274030ustar00rootroot00000000000000module.exports = { entry: { vendor: ["external0", "./a"], main: "./index" }, target: "web", output: { filename: "[name].js", libraryTarget: "umd" }, externals: ["external0", "external1", "external2", "fs", "path"], optimization: { splitChunks: { cacheGroups: { vendor: { test: "vendor", name: "vendor", enforce: true } } } }, node: { __filename: false, __dirname: false } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-entry/000077500000000000000000000000001345416772700246175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/move-entry/a.js000066400000000000000000000000261345416772700253730ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-entry/index.js000066400000000000000000000001471345416772700262660ustar00rootroot00000000000000it("should not be moved", function() { expect(new Error().stack).not.toMatch(/webpackBootstrap/); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/move-entry/test.config.js000066400000000000000000000001561345416772700274020ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./commons.js", "./main.js" ] } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-entry/webpack.config.js000066400000000000000000000004311345416772700300330ustar00rootroot00000000000000module.exports = { entry: { main: "./index?0", second: "./index?1" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { cacheGroups: { commons: { chunks: "initial", minSize: 0, name: "commons" } } } } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/000077500000000000000000000000001345416772700264035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/index.js000066400000000000000000000004751345416772700300560ustar00rootroot00000000000000it("should correctly include indirect children in common chunk", function(done) { Promise.all([ import('./pageA'), import('./pageB').then(m => m.default) ]).then((imports) => { expect(imports[0].default).toBe("reuse"); expect(imports[1].default).toBe("reuse"); done(); }).catch(e => { done(e); }) }); webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/pageA.js000066400000000000000000000001431345416772700277540ustar00rootroot00000000000000var reusableComponent = require("./reusableComponent"); export default reusableComponent.default; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/pageB.js000066400000000000000000000000431345416772700277540ustar00rootroot00000000000000module.exports = import('./pageC') webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/pageC.js000066400000000000000000000001431345416772700277560ustar00rootroot00000000000000var reusableComponent = require("./reusableComponent"); export default reusableComponent.default; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/reusableComponent.js000066400000000000000000000000561345416772700324270ustar00rootroot00000000000000const reuse = "reuse"; export default reuse; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/second.js000066400000000000000000000003121345416772700302100ustar00rootroot00000000000000it("should handle indirect children with multiple parents correctly", function(done) { import('./pageB').then(b => { expect(b.default).toBe("reuse"); done() }).catch(e => { done(); }) }) webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/test.config.js000066400000000000000000000001551345416772700311650ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./main.js", "./misc.js", ]; } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/move-to-grandparent/webpack.config.js000066400000000000000000000002501345416772700316160ustar00rootroot00000000000000module.exports = { entry: { main: "./index", misc: "./second" }, output: { filename: "[name].js" }, optimization: { splitChunks: { minSize: 0 } } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/simple/000077500000000000000000000000001345416772700240035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/commons-chunk-plugin/simple/a.js000066400000000000000000000000261345416772700245570ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/commons-chunk-plugin/simple/index.js000066400000000000000000000002341345416772700254470ustar00rootroot00000000000000it("should run", function() { var a = require("./a"); expect(a).toBe("a"); }); it("should be main", function() { expect(require.main).toBe(module); }); webpack-4.30.0/test/configCases/commons-chunk-plugin/simple/test.config.js000066400000000000000000000001551345416772700265650ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./main.js" ] } }; webpack-4.30.0/test/configCases/commons-chunk-plugin/simple/webpack.config.js000066400000000000000000000003121345416772700272150ustar00rootroot00000000000000module.exports = { entry: { vendor: ["./a"], main: "./index" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { minSize: 1, name: "vendor" } } }; webpack-4.30.0/test/configCases/compiletime/000077500000000000000000000000001345416772700207445ustar00rootroot00000000000000webpack-4.30.0/test/configCases/compiletime/error-not-found/000077500000000000000000000000001345416772700240045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/compiletime/error-not-found/errors.js000066400000000000000000000000441345416772700256540ustar00rootroot00000000000000module.exports = [ /not found/ ]; webpack-4.30.0/test/configCases/compiletime/error-not-found/index.js000066400000000000000000000002501345416772700254460ustar00rootroot00000000000000import { NotHere } from './stub' it('should do nothing', function() { if (typeof NotHere !== 'undefined') { throw new Error('This shouldn\'t be here!'); } }); webpack-4.30.0/test/configCases/compiletime/error-not-found/stub.js000066400000000000000000000000461345416772700253170ustar00rootroot00000000000000const foo = 'bar' export default foo webpack-4.30.0/test/configCases/compiletime/error-not-found/webpack.config.js000066400000000000000000000001011345416772700272120ustar00rootroot00000000000000module.exports = { module: { strictExportPresence: true } }; webpack-4.30.0/test/configCases/compiletime/warn-not-found/000077500000000000000000000000001345416772700236225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/compiletime/warn-not-found/index.js000066400000000000000000000002501345416772700252640ustar00rootroot00000000000000import { NotHere } from './stub' it('should do nothing', function() { if (typeof NotHere !== 'undefined') { throw new Error('This shouldn\'t be here!'); } }); webpack-4.30.0/test/configCases/compiletime/warn-not-found/stub.js000066400000000000000000000000461345416772700251350ustar00rootroot00000000000000const foo = 'bar' export default foo webpack-4.30.0/test/configCases/compiletime/warn-not-found/warnings.js000066400000000000000000000000441345416772700260060ustar00rootroot00000000000000module.exports = [ /not found/ ]; webpack-4.30.0/test/configCases/compiletime/warn-not-found/webpack.config.js000066400000000000000000000000001345416772700270260ustar00rootroot00000000000000webpack-4.30.0/test/configCases/concatenate-modules/000077500000000000000000000000001345416772700223675ustar00rootroot00000000000000webpack-4.30.0/test/configCases/concatenate-modules/split-chunk-entry-module/000077500000000000000000000000001345416772700272525ustar00rootroot00000000000000webpack-4.30.0/test/configCases/concatenate-modules/split-chunk-entry-module/a.js000066400000000000000000000000161345416772700300250ustar00rootroot00000000000000import './b'; webpack-4.30.0/test/configCases/concatenate-modules/split-chunk-entry-module/b.js000066400000000000000000000000001345416772700300170ustar00rootroot00000000000000webpack-4.30.0/test/configCases/concatenate-modules/split-chunk-entry-module/index.js000066400000000000000000000001011345416772700307070ustar00rootroot00000000000000import './a'; it("should compile and evaluate fine", () => {}); webpack-4.30.0/test/configCases/concatenate-modules/split-chunk-entry-module/test.config.js000066400000000000000000000001621345416772700320320ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return ["runtime.js", "common~main.js", "main.js"] } }; webpack-4.30.0/test/configCases/concatenate-modules/split-chunk-entry-module/webpack.config.js000066400000000000000000000004601345416772700324700ustar00rootroot00000000000000module.exports = { entry: { main: "./index" }, target: "web", output: { filename: "[name].js" }, optimization: { concatenateModules: true, runtimeChunk: "single", splitChunks: { minSize: 0, cacheGroups: { common: { chunks: "initial", minChunks: 1 } } } } }; webpack-4.30.0/test/configCases/contenthash/000077500000000000000000000000001345416772700207535ustar00rootroot00000000000000webpack-4.30.0/test/configCases/contenthash/include-chunk-id/000077500000000000000000000000001345416772700240765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/contenthash/include-chunk-id/chunk.js000066400000000000000000000000321345416772700255370ustar00rootroot00000000000000module.exports = "chunk"; webpack-4.30.0/test/configCases/contenthash/include-chunk-id/index.js000066400000000000000000000002071345416772700255420ustar00rootroot00000000000000it("should compile and run the test", function () {}); if(Math.random() < -1) { import(/* webpackChunkName: "chunk" */ "./chunk"); } webpack-4.30.0/test/configCases/contenthash/include-chunk-id/test.config.js000066400000000000000000000014271345416772700266630ustar00rootroot00000000000000var fs = require("fs"); var findFile = function(files, regex) { return files.find(function(file) { if (regex.test(file)) { return true; } }); }; const allFilenameHashes = new Set(); const allChunkHashes = new Set(); module.exports = { findBundle: function(i, options) { var files = fs.readdirSync(options.output.path); const filename = findFile(files, new RegExp(`^bundle${i}`)); const filenameHash = /\.([a-f0-9]+)\.js$/.exec(filename)[1]; allFilenameHashes.add(filenameHash); const chunk = findFile(files, new RegExp(`^chunk${i}`)); const chunkHash = /\.([a-f0-9]+)\.js$/.exec(chunk)[1]; allChunkHashes.add(chunkHash); return "./" + filename; }, afterExecute: () => { expect(allFilenameHashes.size).toBe(2); expect(allChunkHashes.size).toBe(2); } }; webpack-4.30.0/test/configCases/contenthash/include-chunk-id/webpack.config.js000066400000000000000000000007221345416772700273150ustar00rootroot00000000000000module.exports = [ { mode: "production", name: "normal-ids", output: { filename: "bundle0.[contenthash:6].js", chunkFilename: "chunk0.[contenthash:6].js" }, optimization: { chunkIds: "size", moduleIds: "named" } }, { mode: "production", name: "normal-ids", output: { filename: "bundle1.[contenthash:6].js", chunkFilename: "chunk1.[contenthash:6].js" }, optimization: { chunkIds: "named", moduleIds: "named" } } ]; webpack-4.30.0/test/configCases/context-exclusion/000077500000000000000000000000001345416772700221305ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-exclusion/simple/000077500000000000000000000000001345416772700234215ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-exclusion/simple/index.js000066400000000000000000000014441345416772700250710ustar00rootroot00000000000000function requireInContext(someVariable) { return require(`./some-dir/${someVariable}`); } it("should not exclude paths not matching the exclusion pattern", function() { expect(requireInContext("file")).toBe("thats good"); expect(requireInContext("check-here/file")).toBe("thats good"); expect(requireInContext("check-here/check-here/file")).toBe("thats good"); }); it("should exclude paths/files matching the exclusion pattern", function() { expect(() => requireInContext("dont")).toThrowError(/Cannot find module '.\/dont'/); expect(() => requireInContext("dont-check-here/file")).toThrowError(/Cannot find module '.\/dont-check-here\/file'/); expect(() => requireInContext("check-here/dont-check-here/file")).toThrowError(/Cannot find module '.\/check-here\/dont-check-here\/file'/); }); webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/000077500000000000000000000000001345416772700251405ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/check-here/000077500000000000000000000000001345416772700271365ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/check-here/check-here/000077500000000000000000000000001345416772700311345ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/check-here/check-here/file.js000066400000000000000000000000371345416772700324110ustar00rootroot00000000000000module.exports = "thats good"; webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/check-here/dont-check-here/000077500000000000000000000000001345416772700320765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/check-here/dont-check-here/file.js000066400000000000000000000000361345416772700333520ustar00rootroot00000000000000module.exports = "thats bad"; webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/check-here/file.js000066400000000000000000000000371345416772700304130ustar00rootroot00000000000000module.exports = "thats good"; webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/dont-check-here/000077500000000000000000000000001345416772700301005ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/dont-check-here/file.js000066400000000000000000000000361345416772700313540ustar00rootroot00000000000000module.exports = "thats bad"; webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/dont.js000066400000000000000000000000361345416772700264410ustar00rootroot00000000000000module.exports = "thats bad"; webpack-4.30.0/test/configCases/context-exclusion/simple/some-dir/file.js000066400000000000000000000000371345416772700264150ustar00rootroot00000000000000module.exports = "thats good"; webpack-4.30.0/test/configCases/context-exclusion/simple/webpack.config.js000066400000000000000000000001651345416772700266410ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [new webpack.ContextExclusionPlugin(/dont/)] }; webpack-4.30.0/test/configCases/context-replacement/000077500000000000000000000000001345416772700224165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/System.import/000077500000000000000000000000001345416772700252135ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/System.import/index.js000066400000000000000000000002561345416772700266630ustar00rootroot00000000000000it("should replace a async context with a manual map", function() { var a = "a"; return import(a).then(function(a) { expect(a).toEqual(nsObj({ default: "b" })); }); }); webpack-4.30.0/test/configCases/context-replacement/System.import/modules/000077500000000000000000000000001345416772700266635ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/System.import/modules/module-b.js000066400000000000000000000000261345416772700307230ustar00rootroot00000000000000module.exports = "b"; webpack-4.30.0/test/configCases/context-replacement/System.import/webpack.config.js000066400000000000000000000003641345416772700304340ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.ContextReplacementPlugin( /context-replacement/, path.resolve(__dirname, "modules"), { a: "./module-b" } ) ] }; webpack-4.30.0/test/configCases/context-replacement/a/000077500000000000000000000000001345416772700226365ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/a/index.js000066400000000000000000000003741345416772700243070ustar00rootroot00000000000000it("should replace a context with a new resource and reqExp", function(done) { function rqInContext(x, callback) { require([x], function(x) { callback(x); }); } rqInContext("replaced", function(r) { expect(r).toBe("ok"); done(); }); }); webpack-4.30.0/test/configCases/context-replacement/a/new-context/000077500000000000000000000000001345416772700251115ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/a/new-context/node_modules/000077500000000000000000000000001345416772700275665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/a/new-context/node_modules/error.js000066400000000000000000000000421345416772700312510ustar00rootroot00000000000000This should result in an error }])webpack-4.30.0/test/configCases/context-replacement/a/new-context/node_modules/replaced.js000066400000000000000000000000261345416772700317010ustar00rootroot00000000000000module.exports = "ok";webpack-4.30.0/test/configCases/context-replacement/a/webpack.config.js000066400000000000000000000003011345416772700260460ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.ContextReplacementPlugin( /context-replacement.a$/, "new-context", true, /^replaced$/ ) ] }; webpack-4.30.0/test/configCases/context-replacement/b/000077500000000000000000000000001345416772700226375ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/b/error.js000066400000000000000000000000421345416772700243220ustar00rootroot00000000000000This should result in an error }])webpack-4.30.0/test/configCases/context-replacement/b/index.js000066400000000000000000000002451345416772700243050ustar00rootroot00000000000000it("should replace a context with a new regExp", function() { function rqInContext(x) { return require(x); } expect(rqInContext("./only-this")).toBe("ok"); }); webpack-4.30.0/test/configCases/context-replacement/b/only-this.js000066400000000000000000000000261345416772700251210ustar00rootroot00000000000000module.exports = "ok";webpack-4.30.0/test/configCases/context-replacement/b/webpack.config.js000066400000000000000000000002331345416772700260530ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.ContextReplacementPlugin(/context-replacement.b$/, /^\.\/only/) ] }; webpack-4.30.0/test/configCases/context-replacement/c/000077500000000000000000000000001345416772700226405ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/c/index.js000066400000000000000000000005671345416772700243150ustar00rootroot00000000000000it("should replace a context with a manual map", function() { function rqInContext(x) { return require(x); } expect(rqInContext("a")).toBe("a"); expect(rqInContext("b")).toBe("b"); expect(rqInContext("./c")).toBe("b"); expect(rqInContext("d")).toBe("d"); expect(rqInContext("./d")).toBe("d"); (expect(function() { rqInContext("module-b") }).toThrowError()); }); webpack-4.30.0/test/configCases/context-replacement/c/modules/000077500000000000000000000000001345416772700243105ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/c/modules/a.js000066400000000000000000000000261345416772700250640ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/context-replacement/c/modules/module-b.js000066400000000000000000000000261345416772700263500ustar00rootroot00000000000000module.exports = "b"; webpack-4.30.0/test/configCases/context-replacement/c/node_modules/000077500000000000000000000000001345416772700253155ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/c/node_modules/d.js000066400000000000000000000000261345416772700260740ustar00rootroot00000000000000module.exports = "d"; webpack-4.30.0/test/configCases/context-replacement/c/webpack.config.js000066400000000000000000000004721345416772700260610ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.ContextReplacementPlugin( /context-replacement.c$/, path.resolve(__dirname, "modules"), { a: "./a", b: "./module-b", "./c": "./module-b", d: "d", "./d": "d" } ) ] }; webpack-4.30.0/test/configCases/context-replacement/d/000077500000000000000000000000001345416772700226415ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/d/index.js000066400000000000000000000004131345416772700243040ustar00rootroot00000000000000it("should replace a context with resource query and manual map", function() { function rqInContext(x) { return require(x); } expect(rqInContext("a")).toEqual({ resourceQuery: "?cats=meow", query: "?lions=roar", prev: "module.exports = \"a\";\n", }); }); webpack-4.30.0/test/configCases/context-replacement/d/modules/000077500000000000000000000000001345416772700243115ustar00rootroot00000000000000webpack-4.30.0/test/configCases/context-replacement/d/modules/a.js000066400000000000000000000000261345416772700250650ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/context-replacement/d/queryloader.js000066400000000000000000000002761345416772700255400ustar00rootroot00000000000000module.exports = function(content) { return "module.exports = " + JSON.stringify({ resourceQuery: this.resourceQuery, query: this.query, prev: content.replace(/\r\n?/g, "\n") }); }; webpack-4.30.0/test/configCases/context-replacement/d/webpack.config.js000066400000000000000000000005341345416772700260610ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { module: { rules: [ { test: /a\.js$/, use: ["./queryloader?lions=roar"] } ] }, plugins: [ new webpack.ContextReplacementPlugin( /context-replacement.d$/, path.resolve(__dirname, "modules?cats=meow"), { a: "./a" } ) ] }; webpack-4.30.0/test/configCases/crossorigin/000077500000000000000000000000001345416772700207765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/crossorigin/set-crossorigin/000077500000000000000000000000001345416772700241305ustar00rootroot00000000000000webpack-4.30.0/test/configCases/crossorigin/set-crossorigin/empty.js000066400000000000000000000000001345416772700256120ustar00rootroot00000000000000webpack-4.30.0/test/configCases/crossorigin/set-crossorigin/index.js000066400000000000000000000051711345416772700256010ustar00rootroot00000000000000it("should load script without crossorigin attribute (default)", function() { const promise = import("./empty?a" /* webpackChunkName: "crossorigin-default" */); var script = document.head._children.pop(); __non_webpack_require__("./crossorigin-default.web.js"); expect(script.src).toBe("https://test.cases/path/crossorigin-default.web.js"); expect(script.crossOrigin).toBe(undefined); return promise; }); it("should load script without crossorigin attribute (relative)", function() { var originalValue = __webpack_public_path__; __webpack_public_path__ = "../"; const promise = import("./empty?b" /* webpackChunkName: "crossorigin-relative" */); __webpack_public_path__ = originalValue; var script = document.head._children.pop(); __non_webpack_require__("./crossorigin-relative.web.js"); expect(script.src).toBe("https://test.cases/crossorigin-relative.web.js"); expect(script.crossOrigin).toBe(undefined); return promise; }); it("should load script without crossorigin attribute (server relative)", function() { var originalValue = __webpack_public_path__; __webpack_public_path__ = "/server/"; const promise = import("./empty?c" /* webpackChunkName: "crossorigin-server-relative" */); __webpack_public_path__ = originalValue; var script = document.head._children.pop(); __non_webpack_require__("./crossorigin-server-relative.web.js"); expect(script.src).toBe("https://test.cases/server/crossorigin-server-relative.web.js"); expect(script.crossOrigin).toBe(undefined); return promise; }); it("should load script without crossorigin attribute (same origin)", function() { var originalValue = __webpack_public_path__; __webpack_public_path__ = "https://test.cases/"; const promise = import("./empty?d" /* webpackChunkName: "crossorigin-same-origin" */); __webpack_public_path__ = originalValue; var script = document.head._children.pop(); __non_webpack_require__("./crossorigin-same-origin.web.js"); expect(script.src).toBe("https://test.cases/crossorigin-same-origin.web.js"); expect(script.crossOrigin).toBe(undefined); return promise; }); it("should load script with crossorigin attribute anonymous (different origin)", function() { var originalValue = __webpack_public_path__; __webpack_public_path__ = "https://example.com/"; const promise = import("./empty?e" /* webpackChunkName: "crossorigin-different-origin" */); __webpack_public_path__ = originalValue; var script = document.head._children.pop(); __non_webpack_require__("./crossorigin-different-origin.web.js"); expect(script.src).toBe("https://example.com/crossorigin-different-origin.web.js"); expect(script.crossOrigin).toBe("anonymous"); return promise; }); webpack-4.30.0/test/configCases/crossorigin/set-crossorigin/webpack.config.js000066400000000000000000000003021345416772700273410ustar00rootroot00000000000000module.exports = { target: "web", output: { chunkFilename: "[name].web.js", crossOriginLoading: "anonymous" }, performance: { hints: false }, optimization: { minimize: false } }; webpack-4.30.0/test/configCases/custom-hash-function/000077500000000000000000000000001345416772700225135ustar00rootroot00000000000000webpack-4.30.0/test/configCases/custom-hash-function/xxhash/000077500000000000000000000000001345416772700240165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/000077500000000000000000000000001345416772700251205ustar00rootroot00000000000000webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file1.js000066400000000000000000000000341345416772700264530ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file10.js000066400000000000000000000000341345416772700265330ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file11.js000066400000000000000000000000341345416772700265340ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file12.js000066400000000000000000000000341345416772700265350ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file13.js000066400000000000000000000000341345416772700265360ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file14.js000066400000000000000000000000341345416772700265370ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file15.js000066400000000000000000000000341345416772700265400ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file2.js000066400000000000000000000000341345416772700264540ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file3.js000066400000000000000000000000341345416772700264550ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file4.js000066400000000000000000000000341345416772700264560ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file5.js000066400000000000000000000000341345416772700264570ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file6.js000066400000000000000000000000341345416772700264600ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file7.js000066400000000000000000000000341345416772700264610ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file8.js000066400000000000000000000000341345416772700264620ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/files/file9.js000066400000000000000000000000341345416772700264630ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/custom-hash-function/xxhash/index.js000066400000000000000000000003051345416772700254610ustar00rootroot00000000000000it("should have unique ids", function () { var ids = []; for(var i = 1; i <= 15; i++) { var id = require("./files/file" + i + ".js"); expect(ids.indexOf(id)).toBe(-1); ids.push(id); } }); webpack-4.30.0/test/configCases/custom-hash-function/xxhash/webpack.config.js000066400000000000000000000001251345416772700272320ustar00rootroot00000000000000module.exports = [ { output: { hashFunction: require("xxhashjs").h32 } } ]; webpack-4.30.0/test/configCases/deep-scope-analysis/000077500000000000000000000000001345416772700223025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export-scope-hoisting/000077500000000000000000000000001345416772700300475ustar00rootroot00000000000000webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export-scope-hoisting/index.js000066400000000000000000000002671345416772700315210ustar00rootroot00000000000000import { test, unused } from "./module"; it("should run the test", () => { expect(test()).toEqual({ used: "used", unused: undefined }); expect(unused).toEqual(undefined); }); webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export-scope-hoisting/module.js000066400000000000000000000001721345416772700316720ustar00rootroot00000000000000import { used, unused } from "./reference"; export function test() { return { used, unused }; } export { unused } webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export-scope-hoisting/reference.js000066400000000000000000000000711345416772700323410ustar00rootroot00000000000000export var used = "used"; export var unused = "unused"; webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export-scope-hoisting/webpack.config.js000066400000000000000000000014521345416772700332670ustar00rootroot00000000000000const DependencyReference = require("../../../../").dependencies .DependencyReference; module.exports = { optimization: { usedExports: true, concatenateModules: true }, plugins: [ function() { this.hooks.compilation.tap("Test", compilation => { compilation.hooks.dependencyReference.tap( "Test", (ref, dep, module) => { if ( module.identifier().endsWith("module.js") && ref.module && ref.module.identifier().endsWith("reference.js") && Array.isArray(ref.importedNames) && ref.importedNames.includes("unused") ) { return new DependencyReference( ref.module, ref.importedNames.filter(item => item !== "unused"), ref.weak, ref.order ); } return ref; } ); }); } ] }; webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export/000077500000000000000000000000001345416772700251165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export/index.js000066400000000000000000000002671345416772700265700ustar00rootroot00000000000000import { test, unused } from "./module"; it("should run the test", () => { expect(test()).toEqual({ used: "used", unused: undefined }); expect(unused).toEqual(undefined); }); webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export/module.js000066400000000000000000000001721345416772700267410ustar00rootroot00000000000000import { used, unused } from "./reference"; export function test() { return { used, unused }; } export { unused } webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export/reference.js000066400000000000000000000000711345416772700274100ustar00rootroot00000000000000export var used = "used"; export var unused = "unused"; webpack-4.30.0/test/configCases/deep-scope-analysis/remove-export/webpack.config.js000066400000000000000000000014531345416772700303370ustar00rootroot00000000000000const DependencyReference = require("../../../../").dependencies .DependencyReference; module.exports = { optimization: { usedExports: true, concatenateModules: false }, plugins: [ function() { this.hooks.compilation.tap("Test", compilation => { compilation.hooks.dependencyReference.tap( "Test", (ref, dep, module) => { if ( module.identifier().endsWith("module.js") && ref.module && ref.module.identifier().endsWith("reference.js") && Array.isArray(ref.importedNames) && ref.importedNames.includes("unused") ) { return new DependencyReference( ref.module, ref.importedNames.filter(item => item !== "unused"), ref.weak, ref.order ); } return ref; } ); }); } ] }; webpack-4.30.0/test/configCases/defaulter/000077500000000000000000000000001345416772700204105ustar00rootroot00000000000000webpack-4.30.0/test/configCases/defaulter/immutable-config/000077500000000000000000000000001345416772700236325ustar00rootroot00000000000000webpack-4.30.0/test/configCases/defaulter/immutable-config/index.js000066400000000000000000000000701345416772700252740ustar00rootroot00000000000000it("should compile and run the test", function() { }); webpack-4.30.0/test/configCases/defaulter/immutable-config/webpack.config.js000066400000000000000000000001521345416772700270460ustar00rootroot00000000000000module.exports = { resolve: Object.freeze({}) // this fails to compile when the object is not cloned }; webpack-4.30.0/test/configCases/delegated-hash/000077500000000000000000000000001345416772700212745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/000077500000000000000000000000001345416772700225655ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/a.js000066400000000000000000000000001345416772700233310ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/b.js000066400000000000000000000000001345416772700233320ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/bundle.js000066400000000000000000000001021345416772700243650ustar00rootroot00000000000000module.exports = function(req) { return ["a", "b", "c"][req]; }; webpack-4.30.0/test/configCases/delegated-hash/simple/bundle2.js000066400000000000000000000000541345416772700244550ustar00rootroot00000000000000module.exports = ["a", "b", "c", "d", "e"]; webpack-4.30.0/test/configCases/delegated-hash/simple/d.js000066400000000000000000000000001345416772700233340ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/dir/000077500000000000000000000000001345416772700233435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/dir/c.js000066400000000000000000000000001345416772700241110ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/e.js000066400000000000000000000000001345416772700233350ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/index.js000066400000000000000000000003571345416772700242370ustar00rootroot00000000000000it("should delegate the modules", function() { expect(require("./a")).toBe("a"); expect(require("./loader!./b")).toBe("b"); expect(require("./dir/c")).toBe("c"); expect(require("./d")).toBe("d"); expect(require("./e")).toBe("e"); }); webpack-4.30.0/test/configCases/delegated-hash/simple/loader.js000066400000000000000000000000001345416772700243570ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated-hash/simple/webpack.config.js000066400000000000000000000011611345416772700260020ustar00rootroot00000000000000var DelegatedPlugin = require("../../../../lib/DelegatedPlugin"); var HashedModuleIdsPlugin = require("../../../../lib/HashedModuleIdsPlugin"); module.exports = { plugins: [ new HashedModuleIdsPlugin(), new DelegatedPlugin({ source: "./bundle", type: "require", context: __dirname, content: { "./a.js": { id: 0 }, "./loader.js!./b.js": { id: 1 }, "./dir/c.js": { id: 2 } } }), new DelegatedPlugin({ source: "./bundle2", type: "object", context: __dirname, content: { "./d.js": { id: 3 }, "./e.js": { id: 4 } } }) ] }; webpack-4.30.0/test/configCases/delegated/000077500000000000000000000000001345416772700203535ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated/simple/000077500000000000000000000000001345416772700216445ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated/simple/a.js000066400000000000000000000000001345416772700224100ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated/simple/b.js000066400000000000000000000000001345416772700224110ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated/simple/bundle.js000066400000000000000000000001001345416772700234420ustar00rootroot00000000000000module.exports = function(req) { return ["a", "b", "c"][req]; }webpack-4.30.0/test/configCases/delegated/simple/dir/000077500000000000000000000000001345416772700224225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated/simple/dir/c.js000066400000000000000000000000001345416772700231700ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated/simple/index.js000066400000000000000000000002511345416772700233070ustar00rootroot00000000000000it("should delegate the modules", function() { expect(require("./a")).toBe("a"); expect(require("./loader!./b")).toBe("b"); expect(require("./dir/c")).toBe("c"); }); webpack-4.30.0/test/configCases/delegated/simple/loader.js000066400000000000000000000000001345416772700234360ustar00rootroot00000000000000webpack-4.30.0/test/configCases/delegated/simple/webpack.config.js000066400000000000000000000005161345416772700250640ustar00rootroot00000000000000var DelegatedPlugin = require("../../../../lib/DelegatedPlugin"); module.exports = { plugins: [ new DelegatedPlugin({ source: "./bundle", type: "require", context: __dirname, content: { "./a.js": { id: 0 }, "./loader.js!./b.js": { id: 1 }, "./dir/c.js": { id: 2 } } }) ] }; webpack-4.30.0/test/configCases/devtools/000077500000000000000000000000001345416772700202745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/devtools/harmony-eval-source-map/000077500000000000000000000000001345416772700247475ustar00rootroot00000000000000webpack-4.30.0/test/configCases/devtools/harmony-eval-source-map/index.js000066400000000000000000000000601345416772700264100ustar00rootroot00000000000000export {} it("should run fine", function() {}); webpack-4.30.0/test/configCases/devtools/harmony-eval-source-map/webpack.config.js000066400000000000000000000000621345416772700301630ustar00rootroot00000000000000module.exports = { devtool: "eval-source-map" }; webpack-4.30.0/test/configCases/devtools/harmony-eval/000077500000000000000000000000001345416772700226765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/devtools/harmony-eval/index.js000066400000000000000000000000601345416772700243370ustar00rootroot00000000000000export {} it("should run fine", function() {}); webpack-4.30.0/test/configCases/devtools/harmony-eval/webpack.config.js000066400000000000000000000000471345416772700261150ustar00rootroot00000000000000module.exports = { devtool: "eval" }; webpack-4.30.0/test/configCases/dll-plugin-entry/000077500000000000000000000000001345416772700216435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin-entry/0-create-dll/000077500000000000000000000000001345416772700240145ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin-entry/0-create-dll/dep.js000066400000000000000000000001121345416772700251140ustar00rootroot00000000000000export function foo() { console.log("foo"); } export const bar = "bar"; webpack-4.30.0/test/configCases/dll-plugin-entry/0-create-dll/dep2.js000066400000000000000000000000301345416772700251750ustar00rootroot00000000000000module.exports = "foo"; webpack-4.30.0/test/configCases/dll-plugin-entry/0-create-dll/index.js000066400000000000000000000001041345416772700254540ustar00rootroot00000000000000export { bar } from "./dep"; export default 42; require("./dep2"); webpack-4.30.0/test/configCases/dll-plugin-entry/0-create-dll/test.config.js000066400000000000000000000000301345416772700265660ustar00rootroot00000000000000exports.noTests = true; webpack-4.30.0/test/configCases/dll-plugin-entry/0-create-dll/webpack.config.js000066400000000000000000000005611345416772700272340ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { entry: ["."], output: { filename: "dll.js", chunkFilename: "[id].dll.js", libraryTarget: "commonjs2" }, plugins: [ new webpack.DllPlugin({ path: path.resolve( __dirname, "../../../js/config/dll-plugin-entry/manifest0.json" ), entryOnly: true }) ] }; webpack-4.30.0/test/configCases/dll-plugin-entry/1-use-dll/000077500000000000000000000000001345416772700233465ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin-entry/1-use-dll/index.js000066400000000000000000000011371345416772700250150ustar00rootroot00000000000000import Answer, { bar } from "dll/index"; it("should load a module from dll", function() { expect(require("dll/index")).toEqual(nsObj({ bar: "bar", default: 42 })); }); it("should load an harmony module from dll (default export)", function() { expect(Answer).toBe(42); }); it("should load an harmony module from dll (star export)", function() { expect(bar).toBe("bar"); }); it("should give modules the correct ids", function() { expect(Object.keys(__webpack_modules__).filter(m => !m.startsWith("../.."))).toEqual([ "./index.js", "dll-reference ../0-create-dll/dll.js", "dll/index.js" ]); }); webpack-4.30.0/test/configCases/dll-plugin-entry/1-use-dll/webpack.config.js000066400000000000000000000005431345416772700265660ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.DllReferencePlugin({ manifest: require("../../../js/config/dll-plugin-entry/manifest0.json"), // eslint-disable-line node/no-missing-require name: "../0-create-dll/dll.js", scope: "dll", sourceType: "commonjs2" }), new webpack.NamedModulesPlugin() ] }; webpack-4.30.0/test/configCases/dll-plugin-entry/2-error-non-entry/000077500000000000000000000000001345416772700250625ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin-entry/2-error-non-entry/errors.js000066400000000000000000000000621345416772700267320ustar00rootroot00000000000000module.exports = [[/Can't resolve 'dll\/dep2'/]]; webpack-4.30.0/test/configCases/dll-plugin-entry/2-error-non-entry/index.js000066400000000000000000000000251345416772700265240ustar00rootroot00000000000000require("dll/dep2"); webpack-4.30.0/test/configCases/dll-plugin-entry/2-error-non-entry/webpack.config.js000066400000000000000000000005431345416772700303020ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.DllReferencePlugin({ manifest: require("../../../js/config/dll-plugin-entry/manifest0.json"), // eslint-disable-line node/no-missing-require name: "../0-create-dll/dll.js", scope: "dll", sourceType: "commonjs2" }), new webpack.NamedModulesPlugin() ] }; webpack-4.30.0/test/configCases/dll-plugin-format/000077500000000000000000000000001345416772700217725ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin-format/0-create-dll/000077500000000000000000000000001345416772700241435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin-format/0-create-dll/dep.js000066400000000000000000000000301345416772700252420ustar00rootroot00000000000000module.exports = "foo"; webpack-4.30.0/test/configCases/dll-plugin-format/0-create-dll/index.js000066400000000000000000000001151345416772700256050ustar00rootroot00000000000000export { add } from "./utility"; export default "Format"; require("./dep"); webpack-4.30.0/test/configCases/dll-plugin-format/0-create-dll/test.config.js000066400000000000000000000000301345416772700267150ustar00rootroot00000000000000exports.noTests = true; webpack-4.30.0/test/configCases/dll-plugin-format/0-create-dll/utility.js000066400000000000000000000001341345416772700262020ustar00rootroot00000000000000export function add(a, b) { return a + b; } export function diff(a, b) { return a - b; } webpack-4.30.0/test/configCases/dll-plugin-format/0-create-dll/webpack.config.js000066400000000000000000000006251345416772700273640ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { entry: ["."], resolve: { extensions: [".js"] }, output: { filename: "dll.js", chunkFilename: "[id].dll.js", libraryTarget: "commonjs2" }, plugins: [ new webpack.DllPlugin({ path: path.resolve( __dirname, "../../../js/config/dll-plugin-format/manifest0.json" ), format: true }) ] }; webpack-4.30.0/test/configCases/dll-plugin/000077500000000000000000000000001345416772700205045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/000077500000000000000000000000001345416772700226555ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/_d.js000066400000000000000000000000151345416772700235710ustar00rootroot00000000000000import "./d";webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/_e.js000066400000000000000000000000531345416772700235740ustar00rootroot00000000000000import "./e1"; import "./e2"; import "./e";webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/a.js000066400000000000000000000000261345416772700234310ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/b.js000066400000000000000000000000671345416772700234370ustar00rootroot00000000000000module.exports = function() { return import("./c"); } webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/c.js000066400000000000000000000000231345416772700234300ustar00rootroot00000000000000export default "c";webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/d.js000066400000000000000000000000231345416772700234310ustar00rootroot00000000000000export default "d";webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/e.js000066400000000000000000000000551345416772700234370ustar00rootroot00000000000000export * from "./e1"; export * from "./ee2"; webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/e1.js000066400000000000000000000000271345416772700235170ustar00rootroot00000000000000export * from "./ee1"; webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/e2.js000066400000000000000000000000271345416772700235200ustar00rootroot00000000000000export * from "./ee2"; webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/ee1.js000066400000000000000000000000511345416772700236610ustar00rootroot00000000000000export var x1 = 123; export var y1 = 456;webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/ee2.js000066400000000000000000000000511345416772700236620ustar00rootroot00000000000000export var x2 = 123; export var y2 = 456;webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/f.jsx000066400000000000000000000000251345416772700236250ustar00rootroot00000000000000module.exports = 'f';webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/g-loader.js000066400000000000000000000000671345416772700247100ustar00rootroot00000000000000module.exports = function(source) { return source; }; webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/g.abc.js000066400000000000000000000000431345416772700241620ustar00rootroot00000000000000module.exports = typeof module.id; webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/test.config.js000066400000000000000000000000301345416772700254270ustar00rootroot00000000000000exports.noTests = true; webpack-4.30.0/test/configCases/dll-plugin/0-create-dll/webpack.config.js000066400000000000000000000010571345416772700260760ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { entry: ["./a", "./b", "./_d", "./_e", "./f", "./g.abc"], resolve: { extensions: [".js", ".jsx"] }, output: { filename: "dll.js", chunkFilename: "[id].dll.js", libraryTarget: "commonjs2" }, module: { rules: [ { test: /\.abc\.js$/, loader: "./g-loader.js", options: { test: 1 } } ] }, plugins: [ new webpack.DllPlugin({ path: path.resolve( __dirname, "../../../js/config/dll-plugin/manifest0.json" ) }) ] }; webpack-4.30.0/test/configCases/dll-plugin/1-use-dll/000077500000000000000000000000001345416772700222075ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin/1-use-dll/e.js000066400000000000000000000000601345416772700227650ustar00rootroot00000000000000export * from "dll/e1"; export * from "dll/e2"; webpack-4.30.0/test/configCases/dll-plugin/1-use-dll/index.js000066400000000000000000000022571345416772700236620ustar00rootroot00000000000000import d from "dll/d"; import { x1, y2 } from "./e"; import { x2, y1 } from "dll/e"; it("should load a module from dll", function() { expect(require("dll/a")).toBe("a"); }); it("should load a module of non-default type without extension from dll", function() { expect(require("dll/f")).toBe("f"); }); it("should load an async module from dll", function(done) { require("dll/b")().then(function(c) { expect(c).toEqual(nsObj({ default: "c" })); done(); }).catch(done); }); it("should load an harmony module from dll (default export)", function() { expect(d).toBe("d"); }); it("should load an harmony module from dll (star export)", function() { expect(x1).toBe(123); expect(x2).toBe(123); expect(y1).toBe(456); expect(y2).toBe(456); }); it("should load a module with loader applied", function() { expect(require("dll/g.abc.js")).toBe("number"); }); it("should give modules the correct ids", function() { expect(Object.keys(__webpack_modules__).filter(m => !m.startsWith("../.."))).toEqual([ "./index.js", "dll-reference ../0-create-dll/dll.js", "dll/a.js", "dll/b.js", "dll/d.js", "dll/e.js", "dll/e1.js", "dll/e2.js", "dll/f.jsx", "dll/g.abc.js" ]); }); webpack-4.30.0/test/configCases/dll-plugin/1-use-dll/webpack.config.js000066400000000000000000000005751345416772700254340ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.DllReferencePlugin({ manifest: require("../../../js/config/dll-plugin/manifest0.json"), // eslint-disable-line node/no-missing-require name: "../0-create-dll/dll.js", scope: "dll", sourceType: "commonjs2", extensions: [".js", ".jsx"] }), new webpack.NamedModulesPlugin() ] }; webpack-4.30.0/test/configCases/dll-plugin/2-use-dll-without-scope/000077500000000000000000000000001345416772700250205ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin/2-use-dll-without-scope/e.js000066400000000000000000000001101345416772700255720ustar00rootroot00000000000000export * from "../0-create-dll/e1"; export * from "../0-create-dll/e2"; webpack-4.30.0/test/configCases/dll-plugin/2-use-dll-without-scope/index.js000066400000000000000000000025241345416772700264700ustar00rootroot00000000000000import d from "../0-create-dll/d"; import { x1, y2 } from "./e"; import { x2, y1 } from "../0-create-dll/e"; it("should load a module from dll", function() { expect(require("../0-create-dll/a")).toBe("a"); }); it("should load a module of non-default type without extension from dll", function() { expect(require("../0-create-dll/f")).toBe("f"); }); it("should load an async module from dll", function(done) { require("../0-create-dll/b")().then(function(c) { expect(c).toEqual(nsObj({ default: "c" })); done(); }).catch(done); }); it("should load an harmony module from dll (default export)", function() { expect(d).toBe("d"); }); it("should load an harmony module from dll (star export)", function() { expect(x1).toBe(123); expect(x2).toBe(123); expect(y1).toBe(456); expect(y2).toBe(456); }); it("should load a module with loader applied", function() { expect(require("../0-create-dll/g.abc.js")).toBe("number"); }); it("should give modules the correct ids", function() { expect(Object.keys(__webpack_modules__).filter(m => !m.startsWith("../.."))).toEqual([ "../0-create-dll/a.js", "../0-create-dll/b.js", "../0-create-dll/d.js", "../0-create-dll/e.js", "../0-create-dll/e1.js", "../0-create-dll/e2.js", "../0-create-dll/f.jsx", "../0-create-dll/g.abc.js", "./index.js", "dll-reference ../0-create-dll/dll.js" ]); }); webpack-4.30.0/test/configCases/dll-plugin/2-use-dll-without-scope/webpack.config.js000066400000000000000000000012061345416772700302350ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { module: { rules: [ { oneOf: [ { test: /\.abc\.js$/, loader: "../0-create-dll/g-loader.js", options: { test: 1 } } ] } ] }, resolve: { extensions: [".js", ".jsx"] }, plugins: [ new webpack.DllReferencePlugin({ manifest: require("../../../js/config/dll-plugin/manifest0.json"), // eslint-disable-line node/no-missing-require name: "../0-create-dll/dll.js", context: path.resolve(__dirname, "../0-create-dll"), sourceType: "commonjs2" }), new webpack.NamedModulesPlugin() ] }; webpack-4.30.0/test/configCases/dll-plugin/3-use-dll-with-hashid/000077500000000000000000000000001345416772700244205ustar00rootroot00000000000000webpack-4.30.0/test/configCases/dll-plugin/3-use-dll-with-hashid/e.js000066400000000000000000000001101345416772700251720ustar00rootroot00000000000000export * from "../0-create-dll/e1"; export * from "../0-create-dll/e2"; webpack-4.30.0/test/configCases/dll-plugin/3-use-dll-with-hashid/e1.js000066400000000000000000000000601345416772700252570ustar00rootroot00000000000000export * from "dll/e1"; export * from "dll/e2"; webpack-4.30.0/test/configCases/dll-plugin/3-use-dll-with-hashid/index.js000066400000000000000000000014361345416772700260710ustar00rootroot00000000000000import d from "../0-create-dll/d"; import { x1, y2 } from "./e"; import { x2, y1 } from "../0-create-dll/e"; it("should load a module from dll", function() { expect(require("../0-create-dll/a")).toBe("a"); }); it("should load an async module from dll", function(done) { require("../0-create-dll/b")().then(function(c) { expect(c).toEqual(nsObj({ default: "c" })); done(); }).catch(done); }); it("should load an harmony module from dll (default export)", function() { expect(d).toBe("d"); }); it("should load an harmony module from dll (star export)", function() { expect(x1).toBe(123); expect(x2).toBe(123); expect(y1).toBe(456); expect(y2).toBe(456); }); it("should load a module with loader applied", function() { expect(require("../0-create-dll/g.abc.js")).toBe("number"); }); webpack-4.30.0/test/configCases/dll-plugin/3-use-dll-with-hashid/webpack.config.js000066400000000000000000000011331345416772700276340ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { module: { rules: [ { oneOf: [ { test: /\.abc\.js$/, loader: "../0-create-dll/g-loader.js", options: { test: 1 } } ] } ] }, plugins: [ new webpack.DllReferencePlugin({ manifest: require("../../../js/config/dll-plugin/manifest0.json"), // eslint-disable-line node/no-missing-require name: "../0-create-dll/dll.js", context: path.resolve(__dirname, "../0-create-dll"), sourceType: "commonjs2" }), new webpack.HashedModuleIdsPlugin() ] }; webpack-4.30.0/test/configCases/entry/000077500000000000000000000000001345416772700175765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/function-promise/000077500000000000000000000000001345416772700230775ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/function-promise/a.js000066400000000000000000000000551345416772700236550ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-4.30.0/test/configCases/entry/function-promise/b.js000066400000000000000000000000551345416772700236560ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-4.30.0/test/configCases/entry/function-promise/test.config.js000066400000000000000000000001331345416772700256550ustar00rootroot00000000000000module.exports = { findBundle: function() { return [ "./a.js", "./b.js" ] } }; webpack-4.30.0/test/configCases/entry/function-promise/webpack.config.js000066400000000000000000000002071345416772700263140ustar00rootroot00000000000000module.exports = { entry() { return Promise.resolve({ a: "./a", b: ["./b"] }); }, output: { filename: "[name].js" } }; webpack-4.30.0/test/configCases/entry/function/000077500000000000000000000000001345416772700214235ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/function/a.js000066400000000000000000000000551345416772700222010ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-4.30.0/test/configCases/entry/function/b.js000066400000000000000000000000551345416772700222020ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-4.30.0/test/configCases/entry/function/test.config.js000066400000000000000000000001331345416772700242010ustar00rootroot00000000000000module.exports = { findBundle: function() { return [ "./a.js", "./b.js" ] } }; webpack-4.30.0/test/configCases/entry/function/webpack.config.js000066400000000000000000000001661345416772700246440ustar00rootroot00000000000000module.exports = { entry() { return { a: "./a", b: ["./b"] }; }, output: { filename: "[name].js" } }; webpack-4.30.0/test/configCases/entry/issue-1068/000077500000000000000000000000001345416772700213225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/issue-1068/a.js000066400000000000000000000000261345416772700220760ustar00rootroot00000000000000global.order = ["a"]; webpack-4.30.0/test/configCases/entry/issue-1068/b.js000066400000000000000000000000301345416772700220720ustar00rootroot00000000000000global.order.push("b"); webpack-4.30.0/test/configCases/entry/issue-1068/c.js000066400000000000000000000000301345416772700220730ustar00rootroot00000000000000global.order.push("c"); webpack-4.30.0/test/configCases/entry/issue-1068/d.js000066400000000000000000000000301345416772700220740ustar00rootroot00000000000000global.order.push("d"); webpack-4.30.0/test/configCases/entry/issue-1068/e.js000066400000000000000000000000301345416772700220750ustar00rootroot00000000000000global.order.push("e"); webpack-4.30.0/test/configCases/entry/issue-1068/f.js000066400000000000000000000000301345416772700220760ustar00rootroot00000000000000global.order.push("f"); webpack-4.30.0/test/configCases/entry/issue-1068/g.js000066400000000000000000000000301345416772700220770ustar00rootroot00000000000000global.order.push("g"); webpack-4.30.0/test/configCases/entry/issue-1068/h.js000066400000000000000000000000301345416772700221000ustar00rootroot00000000000000global.order.push("h"); webpack-4.30.0/test/configCases/entry/issue-1068/i.js000066400000000000000000000000301345416772700221010ustar00rootroot00000000000000global.order.push("i"); webpack-4.30.0/test/configCases/entry/issue-1068/j.js000066400000000000000000000000301345416772700221020ustar00rootroot00000000000000global.order.push("j"); webpack-4.30.0/test/configCases/entry/issue-1068/k.js000066400000000000000000000000301345416772700221030ustar00rootroot00000000000000global.order.push("k"); webpack-4.30.0/test/configCases/entry/issue-1068/test.js000066400000000000000000000003341345416772700226370ustar00rootroot00000000000000var order = global.order; delete global.order; it("should run the modules in the correct order", function() { expect(order).toEqual([ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" ]); }); webpack-4.30.0/test/configCases/entry/issue-1068/webpack.config.js000066400000000000000000000002211345416772700245330ustar00rootroot00000000000000module.exports = { entry: [ "./a", "./b", "./c", "./d", "./e", "./f", "./g", "./h", "./i", "./j", "./k", "./test" ] }; webpack-4.30.0/test/configCases/entry/issue-8110/000077500000000000000000000000001345416772700213155ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/issue-8110/a.js000066400000000000000000000002211345416772700220660ustar00rootroot00000000000000import run from "./c"; import "./d"; it("should not crash", () => { return run().then(result => { expect(result.default).toBe("ok"); }); }) webpack-4.30.0/test/configCases/entry/issue-8110/b.js000066400000000000000000000000371345416772700220740ustar00rootroot00000000000000import run from "./c"; run(); webpack-4.30.0/test/configCases/entry/issue-8110/c.js000066400000000000000000000000711345416772700220730ustar00rootroot00000000000000export default function run() { return import("./d"); } webpack-4.30.0/test/configCases/entry/issue-8110/d.js000066400000000000000000000000251345416772700220730ustar00rootroot00000000000000export default "ok"; webpack-4.30.0/test/configCases/entry/issue-8110/webpack.config.js000066400000000000000000000001531345416772700245320ustar00rootroot00000000000000module.exports = { entry: { bundle0: "./a", other: "./b" }, output: { filename: "[name].js" } }; webpack-4.30.0/test/configCases/entry/override-entry-point/000077500000000000000000000000001345416772700237035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/override-entry-point/fail.js000066400000000000000000000001511345416772700251510ustar00rootroot00000000000000it("should load correct entry", function() { throw new Error("This entrypoint should not be used"); }); webpack-4.30.0/test/configCases/entry/override-entry-point/ok.js000066400000000000000000000000701345416772700246470ustar00rootroot00000000000000it("should load correct entry", function() { // ok }); webpack-4.30.0/test/configCases/entry/override-entry-point/test.config.js000066400000000000000000000001571345416772700264670ustar00rootroot00000000000000module.exports = { findBundle: function() { return [ "./runtime~main.js", "./main.chunk.js" ] } }; webpack-4.30.0/test/configCases/entry/override-entry-point/webpack.config.js000066400000000000000000000005571345416772700271300ustar00rootroot00000000000000const SingleEntryPlugin = require("../../../../lib/SingleEntryPlugin"); module.exports = { entry: () => ({}), optimization: { runtimeChunk: true }, output: { filename: "[name].js", chunkFilename: "[name].chunk.js" }, target: "web", plugins: [ new SingleEntryPlugin(__dirname, "./fail", "main"), new SingleEntryPlugin(__dirname, "./ok", "main") ] }; webpack-4.30.0/test/configCases/entry/require-entry-point/000077500000000000000000000000001345416772700235405ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/require-entry-point/entry-point.js000066400000000000000000000000001345416772700263540ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/require-entry-point/entry-point2.js000066400000000000000000000000001345416772700264360ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/require-entry-point/require-entry-point.js000066400000000000000000000002221345416772700300340ustar00rootroot00000000000000it("should require entry points fine", function() { require("./require-entry-point"); require("./entry-point"); require("./entry-point2"); }); webpack-4.30.0/test/configCases/entry/require-entry-point/webpack.config.js000066400000000000000000000002341345416772700267550ustar00rootroot00000000000000module.exports = { entry: { bundle0: "./require-entry-point", a: "./entry-point", b: ["./entry-point2"] }, output: { filename: "[name].js" } }; webpack-4.30.0/test/configCases/entry/single-entry-point/000077500000000000000000000000001345416772700233455ustar00rootroot00000000000000webpack-4.30.0/test/configCases/entry/single-entry-point/single-entry-point.js000066400000000000000000000001321345416772700274460ustar00rootroot00000000000000it("should require entry points fine", function() { require("./single-entry-point"); }); webpack-4.30.0/test/configCases/entry/single-entry-point/webpack.config.js000066400000000000000000000000651345416772700265640ustar00rootroot00000000000000module.exports = { entry: "./single-entry-point" }; webpack-4.30.0/test/configCases/errors/000077500000000000000000000000001345416772700177515ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/entry-not-found/000077500000000000000000000000001345416772700230215ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/entry-not-found/errors.js000066400000000000000000000001021345416772700246640ustar00rootroot00000000000000module.exports = [ [/^Entry module not found/, /.\/index\.js/] ];webpack-4.30.0/test/configCases/errors/entry-not-found/webpack.config.js000066400000000000000000000000251345416772700262340ustar00rootroot00000000000000module.exports = {}; webpack-4.30.0/test/configCases/errors/exception-in-chunk-renderer/000077500000000000000000000000001345416772700252655ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/exception-in-chunk-renderer/errors.js000066400000000000000000000000771345416772700271430ustar00rootroot00000000000000module.exports = [ [/Test exception/], [/Test exception/] ]; webpack-4.30.0/test/configCases/errors/exception-in-chunk-renderer/index.js000066400000000000000000000001241345416772700267270ustar00rootroot00000000000000it("should not crash when renderer throws exception", function(done) { done(); }); webpack-4.30.0/test/configCases/errors/exception-in-chunk-renderer/webpack.config.js000066400000000000000000000005241345416772700305040ustar00rootroot00000000000000class ThrowsExceptionInRender { apply(compiler) { compiler.hooks.compilation.tap("ThrowsException", compilation => { compilation.mainTemplate.hooks.requireExtensions.tap( "ThrowsException", () => { throw new Error("Test exception"); } ); }); } } module.exports = { plugins: [new ThrowsExceptionInRender()] }; webpack-4.30.0/test/configCases/errors/import-missing/000077500000000000000000000000001345416772700227325ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/import-missing/a.js000066400000000000000000000000001345416772700234760ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/import-missing/b.js000066400000000000000000000000001345416772700234770ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/import-missing/c.js000066400000000000000000000000001345416772700235000ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/import-missing/d.js000066400000000000000000000000001345416772700235010ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/import-missing/errors.js000066400000000000000000000000541345416772700246030ustar00rootroot00000000000000module.exports = [ [/Module not found/] ]; webpack-4.30.0/test/configCases/errors/import-missing/index.js000066400000000000000000000006321345416772700244000ustar00rootroot00000000000000it("should not crash on missing requires", function() { require.include("./a"); require.include("./b"); require.include("./c"); require.include("./d"); require.include("./e"); require.include("./f"); require.include("./h"); require.include("./i"); require.include("./j"); require.include("./k"); require.include("./l"); require.include("./m"); require.include("./n"); require.include("./o"); }); webpack-4.30.0/test/configCases/errors/import-missing/webpack.config.js000066400000000000000000000000421345416772700261440ustar00rootroot00000000000000module.exports = { bail: true }; webpack-4.30.0/test/configCases/errors/multi-entry-missing-module/000077500000000000000000000000001345416772700251745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/multi-entry-missing-module/index.js000066400000000000000000000010631345416772700266410ustar00rootroot00000000000000it("Should use WebpackMissingModule when module is missing with multiple entry setup", function() { var fs = require("fs"); var path = require("path"); var source = fs.readFileSync(path.join(__dirname, "b.js"), "utf-8"); expect(source).toMatch("!(function webpackMissingModule() { var e = new Error(\"Cannot find module './intentionally-missing-module.js'\"); e.code = 'MODULE_NOT_FOUND'; throw e; }());"); expect(function() { require("./intentionally-missing-module"); }).toThrowError("Cannot find module './intentionally-missing-module'"); }); webpack-4.30.0/test/configCases/errors/multi-entry-missing-module/intentionally-missing-module.js000066400000000000000000000000331345416772700333510ustar00rootroot00000000000000module.exports = "ignored";webpack-4.30.0/test/configCases/errors/multi-entry-missing-module/webpack.config.js000066400000000000000000000004511345416772700304120ustar00rootroot00000000000000const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: { b: ["./intentionally-missing-module.js"], bundle0: ["./index"] }, output: { filename: "[name].js" }, plugins: [new IgnorePlugin(/intentionally-missing-module/)], node: { __dirname: false } }; webpack-4.30.0/test/configCases/errors/self-reexport/000077500000000000000000000000001345416772700225505ustar00rootroot00000000000000webpack-4.30.0/test/configCases/errors/self-reexport/a.js000066400000000000000000000000411345416772700233210ustar00rootroot00000000000000export { something } from "./a"; webpack-4.30.0/test/configCases/errors/self-reexport/aa.js000066400000000000000000000000571345416772700234710ustar00rootroot00000000000000import { something } from "./a"; something(); webpack-4.30.0/test/configCases/errors/self-reexport/b.js000066400000000000000000000001361345416772700233270ustar00rootroot00000000000000 import { something, other } from "./b"; export { something as other, other as something } webpack-4.30.0/test/configCases/errors/self-reexport/bb.js000066400000000000000000000000551345416772700234710ustar00rootroot00000000000000import {something} from "./b"; something(); webpack-4.30.0/test/configCases/errors/self-reexport/c1.js000066400000000000000000000000421345416772700234050ustar00rootroot00000000000000export { something } from "./c2"; webpack-4.30.0/test/configCases/errors/self-reexport/c2.js000066400000000000000000000000421345416772700234060ustar00rootroot00000000000000export { something } from "./c1"; webpack-4.30.0/test/configCases/errors/self-reexport/cc.js000066400000000000000000000000561345416772700234740ustar00rootroot00000000000000import {something} from "./c1"; something(); webpack-4.30.0/test/configCases/errors/self-reexport/errors.js000066400000000000000000000005031345416772700244200ustar00rootroot00000000000000module.exports = [ [/Circular reexports "\.\/a.js"\.something -\(circular\)-> "\.\/a.js"\.something/], [/Circular reexports "\.\/b.js"\.other --> "\.\/b.js"\.something -\(circular\)-> "\.\/b.js"\.other/], [/Circular reexports "\.\/c2.js"\.something --> "\.\/c1.js"\.something -\(circular\)-> "\.\/c2.js"\.something/] ]; webpack-4.30.0/test/configCases/errors/self-reexport/index.js000066400000000000000000000003441345416772700242160ustar00rootroot00000000000000it("should not crash on incorrect exports", function() { if(Math.random() < -1) { import(/* webpackChunkName: "a" */ "./aa"); import(/* webpackChunkName: "b" */ "./bb"); import(/* webpackChunkName: "c" */ "./cc"); } }); webpack-4.30.0/test/configCases/errors/self-reexport/webpack.config.js000066400000000000000000000000521345416772700257630ustar00rootroot00000000000000module.exports = { mode: "production" }; webpack-4.30.0/test/configCases/externals/000077500000000000000000000000001345416772700204425ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/externals-array/000077500000000000000000000000001345416772700235635ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/externals-array/index.js000066400000000000000000000002061345416772700252260ustar00rootroot00000000000000it("should not fail on optional externals", function() { const external = require("external"); expect(external).toBe(EXPECTED); }); webpack-4.30.0/test/configCases/externals/externals-array/webpack.config.js000066400000000000000000000006371345416772700270070ustar00rootroot00000000000000const webpack = require("../../../../"); module.exports = [ { output: { libraryTarget: "commonjs2" }, externals: { external: ["webpack", "version"] }, plugins: [ new webpack.DefinePlugin({ EXPECTED: JSON.stringify(webpack.version) }) ] }, { externals: { external: ["Array", "isArray"] }, plugins: [ new webpack.DefinePlugin({ EXPECTED: "Array.isArray" }) ] } ]; webpack-4.30.0/test/configCases/externals/externals-in-chunk/000077500000000000000000000000001345416772700241615ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/externals-in-chunk/chunk.js000066400000000000000000000001011345416772700256170ustar00rootroot00000000000000exports.a = require("external"); exports.b = import("./chunk2"); webpack-4.30.0/test/configCases/externals/externals-in-chunk/chunk2.js000066400000000000000000000000461345416772700257110ustar00rootroot00000000000000module.exports = require("external2");webpack-4.30.0/test/configCases/externals/externals-in-chunk/index.js000066400000000000000000000010231345416772700256220ustar00rootroot00000000000000it("should move externals in chunks into entry chunk", function(done) { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch("1+" + (1+1)); expect(source).toMatch("3+" + (2+2)); expect(source).toMatch("5+" + (3+3)); import("./chunk").then(function(chunk) { expect(chunk.default.a).toBe(3); chunk.default.b.then(function(chunk2) { expect(chunk2.default).toBe(7); import("external3").then(function(ex) { expect(ex.default).toBe(11); done(); }); }); }); }); webpack-4.30.0/test/configCases/externals/externals-in-chunk/webpack.config.js000066400000000000000000000002261345416772700273770ustar00rootroot00000000000000module.exports = { externals: { external: "1+2", external2: "3+4", external3: "5+6" }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/externals/externals-in-commons-chunk/000077500000000000000000000000001345416772700256325ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/externals-in-commons-chunk/index.js000066400000000000000000000012711345416772700273000ustar00rootroot00000000000000it("should not move externals into the commons chunk", function() { var fs = require("fs"); var source1 = fs.readFileSync(__dirname + "/main.js", "utf-8"); var source2 = fs.readFileSync(__dirname + "/other.js", "utf-8"); var source3 = fs.readFileSync(__dirname + "/common.js", "utf-8"); expect(source1).toMatch("1+" + (1+1)); expect(source1).toMatch("3+" + (2+2)); expect(source2).toMatch("1+" + (1+1)); expect(source2).toMatch("5+" + (3+3)); expect(source3).not.toMatch("1+" + (1+1)); expect(source3).not.toMatch("3+" + (2+2)); expect(source3).not.toMatch("5+" + (3+3)); require("external"); require("external2"); require("./module"); }); webpack-4.30.0/test/configCases/externals/externals-in-commons-chunk/module.js000066400000000000000000000000001345416772700274430ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/externals-in-commons-chunk/other.js000066400000000000000000000001001345416772700273000ustar00rootroot00000000000000require("external"); require("external3"); require("./module"); webpack-4.30.0/test/configCases/externals/externals-in-commons-chunk/test.config.js000066400000000000000000000001551345416772700304140ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./common.js", "./main.js" ] } }; webpack-4.30.0/test/configCases/externals/externals-in-commons-chunk/webpack.config.js000066400000000000000000000006731345416772700310560ustar00rootroot00000000000000module.exports = { entry: { main: "./index", other: "./other" }, externals: { fs: "commonjs fs", external: "1+2", external2: "3+4", external3: "5+6" }, target: "web", output: { filename: "[name].js" }, node: { __dirname: false, __filename: false }, optimization: { minimize: false, splitChunks: { cacheGroups: { common: { chunks: "initial", minSize: 0, name: "common" } } } } }; webpack-4.30.0/test/configCases/externals/externals-system/000077500000000000000000000000001345416772700237715ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/externals-system/index.js000066400000000000000000000007561345416772700254460ustar00rootroot00000000000000/* This test verifies that webpack externals are properly indicated as dependencies to System. * Also that when System provides the external variables to webpack that the variables get plumbed * through correctly and are usable by the webpack bundle. */ it("should get an external from System", function() { const external1 = require("external1"); expect(external1).toBe("the external1 value"); const external2 = require("external2"); expect(external2).toBe("the external2 value"); }); webpack-4.30.0/test/configCases/externals/externals-system/test.config.js000066400000000000000000000004641345416772700265560ustar00rootroot00000000000000const System = require("../../../helpers/fakeSystem"); module.exports = { beforeExecute: () => { System.init({ external1: "the external1 value", external2: "the external2 value" }); }, moduleScope(scope) { scope.System = System; }, afterExecute: () => { System.execute("(anonym)"); } }; webpack-4.30.0/test/configCases/externals/externals-system/webpack.config.js000066400000000000000000000002031345416772700272020ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "system" }, externals: { external1: "external1", external2: "external2" } }; webpack-4.30.0/test/configCases/externals/global/000077500000000000000000000000001345416772700217025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/global/index.js000066400000000000000000000004461345416772700233530ustar00rootroot00000000000000afterEach(done => { delete global.EXTERNAL_TEST_GLOBAL; done(); }); it("should move externals in chunks into entry chunk", function() { global.EXTERNAL_TEST_GLOBAL = 42; // eslint-disable-next-line node/no-missing-require const result = require("external"); expect(result).toBe(42); }); webpack-4.30.0/test/configCases/externals/global/webpack.config.js000066400000000000000000000001211345416772700251120ustar00rootroot00000000000000module.exports = { externals: { external: "global EXTERNAL_TEST_GLOBAL" } }; webpack-4.30.0/test/configCases/externals/harmony/000077500000000000000000000000001345416772700221175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/harmony/index.js000066400000000000000000000001731345416772700235650ustar00rootroot00000000000000import external from "external"; it("should harmony import a dependency", function() { expect(external).toBe("abc"); }); webpack-4.30.0/test/configCases/externals/harmony/webpack.config.js000066400000000000000000000000771345416772700253410ustar00rootroot00000000000000module.exports = { externals: { external: "var 'abc'" } }; webpack-4.30.0/test/configCases/externals/non-umd-externals-umd/000077500000000000000000000000001345416772700246055ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/non-umd-externals-umd/index.js000066400000000000000000000013611345416772700262530ustar00rootroot00000000000000var fs = require("fs"); var path = require("path"); it("should correctly import a UMD external", function() { var external = require("external0"); expect(external).toBe("module 0"); }); it("should contain `require()` statements for the UMD external", function() { var source = fs.readFileSync(path.join(__dirname, "bundle0.js"), "utf-8"); expect(source).toMatch("require(\"external0\")"); }); it("should correctly import a non-UMD external", function() { var external = require("external1"); expect(external).toBe("abc"); }); it("should not contain `require()` statements for the non-UMD external", function() { var source = fs.readFileSync(path.join(__dirname, "bundle0.js"), "utf-8"); expect(source).not.toMatch("require(\"'abc'\")"); }); webpack-4.30.0/test/configCases/externals/non-umd-externals-umd/test.config.js000066400000000000000000000000751345416772700273700ustar00rootroot00000000000000module.exports = { modules: { external0: "module 0" } }; webpack-4.30.0/test/configCases/externals/non-umd-externals-umd/webpack.config.js000066400000000000000000000002651345416772700300260ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd" }, externals: { external0: "external0", external1: "var 'abc'" }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/externals/non-umd-externals-umd2/000077500000000000000000000000001345416772700246675ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/non-umd-externals-umd2/index.js000066400000000000000000000013651345416772700263410ustar00rootroot00000000000000var fs = require("fs"); var path = require("path"); it("should correctly import a UMD2 external", function() { var external = require("external0"); expect(external).toBe("module 0"); }); it("should contain `require()` statements for the UMD2 external", function() { var source = fs.readFileSync(path.join(__dirname, "bundle0.js"), "utf-8"); expect(source).toMatch("require(\"external0\")"); }); it("should correctly import a non-UMD2 external", function() { var external = require("external1"); expect(external).toBe("abc"); }); it("should not contain `require()` statements for the non-UMD2 external", function() { var source = fs.readFileSync(path.join(__dirname, "bundle0.js"), "utf-8"); expect(source).not.toMatch("require(\"'abc'\")"); }); webpack-4.30.0/test/configCases/externals/non-umd-externals-umd2/test.config.js000066400000000000000000000000751345416772700274520ustar00rootroot00000000000000module.exports = { modules: { external0: "module 0" } }; webpack-4.30.0/test/configCases/externals/non-umd-externals-umd2/webpack.config.js000066400000000000000000000002661345416772700301110ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd2" }, externals: { external0: "external0", external1: "var 'abc'" }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/externals/optional-externals-cjs/000077500000000000000000000000001345416772700250475ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/optional-externals-cjs/index.js000066400000000000000000000003511345416772700265130ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); }); webpack-4.30.0/test/configCases/externals/optional-externals-cjs/webpack.config.js000066400000000000000000000001521345416772700302630ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "commonjs2" }, externals: { external: "external" } }; webpack-4.30.0/test/configCases/externals/optional-externals-root/000077500000000000000000000000001345416772700252535ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/optional-externals-root/index.js000066400000000000000000000003511345416772700267170ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); }); webpack-4.30.0/test/configCases/externals/optional-externals-root/webpack.config.js000066400000000000000000000001441345416772700304700ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "var" }, externals: { external: "external" } }; webpack-4.30.0/test/configCases/externals/optional-externals-umd/000077500000000000000000000000001345416772700250555ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/optional-externals-umd/index.js000066400000000000000000000003511345416772700265210ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); }); webpack-4.30.0/test/configCases/externals/optional-externals-umd/webpack.config.js000066400000000000000000000001441345416772700302720ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd" }, externals: { external: "external" } }; webpack-4.30.0/test/configCases/externals/optional-externals-umd2-mixed/000077500000000000000000000000001345416772700262435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/optional-externals-umd2-mixed/index.js000066400000000000000000000004001345416772700277020ustar00rootroot00000000000000it("should not fail on optional externals", function() { require("external2"); try { require("external"); } catch(e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); }); webpack-4.30.0/test/configCases/externals/optional-externals-umd2-mixed/webpack.config.js000066400000000000000000000001701345416772700314570ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd2" }, externals: { external: "external", external2: "fs" } }; webpack-4.30.0/test/configCases/externals/optional-externals-umd2/000077500000000000000000000000001345416772700251375ustar00rootroot00000000000000webpack-4.30.0/test/configCases/externals/optional-externals-umd2/index.js000066400000000000000000000003511345416772700266030ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); }); webpack-4.30.0/test/configCases/externals/optional-externals-umd2/webpack.config.js000066400000000000000000000001451345416772700303550ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd2" }, externals: { external: "external" } }; webpack-4.30.0/test/configCases/filename-template/000077500000000000000000000000001345416772700220265ustar00rootroot00000000000000webpack-4.30.0/test/configCases/filename-template/module-filename-template/000077500000000000000000000000001345416772700267025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/filename-template/module-filename-template/index.js000066400000000000000000000004061345416772700303470ustar00rootroot00000000000000it("should include test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map.sources).toContain("dummy:///./test.js"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/filename-template/module-filename-template/test.js000066400000000000000000000000111345416772700302070ustar00rootroot00000000000000// empty webpack-4.30.0/test/configCases/filename-template/module-filename-template/webpack.config.js000066400000000000000000000004111345416772700321140ustar00rootroot00000000000000module.exports = { mode: "development", output: { devtoolLineToLine: true, devtoolModuleFilenameTemplate: function(info) { return "dummy:///" + info.resourcePath; } }, node: { __dirname: false, __filename: false }, devtool: "cheap-source-map" }; webpack-4.30.0/test/configCases/filename-template/split-chunks-filename/000077500000000000000000000000001345416772700262305ustar00rootroot00000000000000webpack-4.30.0/test/configCases/filename-template/split-chunks-filename/index.js000066400000000000000000000003601345416772700276740ustar00rootroot00000000000000it("should create a vendor file", function() { var fs = require("fs"); var path = require("path"); if(!fs.existsSync(path.join(__dirname, "vendor.js"))) throw new Error("vendor.js file was not created"); }); require.include("test"); webpack-4.30.0/test/configCases/filename-template/split-chunks-filename/node_modules/000077500000000000000000000000001345416772700307055ustar00rootroot00000000000000webpack-4.30.0/test/configCases/filename-template/split-chunks-filename/node_modules/test.js000066400000000000000000000000111345416772700322120ustar00rootroot00000000000000// empty webpack-4.30.0/test/configCases/filename-template/split-chunks-filename/webpack.config.js000066400000000000000000000004271345416772700314510ustar00rootroot00000000000000module.exports = { mode: "development", node: { __dirname: false, __filename: false }, optimization: { splitChunks: { cacheGroups: { vendor: { test: /node_modules/, chunks: "initial", filename: "vendor.js", enforce: true } } } } }; webpack-4.30.0/test/configCases/finish-modules/000077500000000000000000000000001345416772700213635ustar00rootroot00000000000000webpack-4.30.0/test/configCases/finish-modules/simple/000077500000000000000000000000001345416772700226545ustar00rootroot00000000000000webpack-4.30.0/test/configCases/finish-modules/simple/index.js000066400000000000000000000000631345416772700243200ustar00rootroot00000000000000it("should compile", function(done) { done(); }); webpack-4.30.0/test/configCases/finish-modules/simple/webpack.config.js000066400000000000000000000004061345416772700260720ustar00rootroot00000000000000var testPlugin = function() { this.hooks.compilation.tap("TestPlugin", compilation => { compilation.hooks.finishModules.tapAsync("TestPlugin", function( _modules, callback ) { callback(); }); }); }; module.exports = { plugins: [testPlugin] }; webpack-4.30.0/test/configCases/hash-length/000077500000000000000000000000001345416772700206375ustar00rootroot00000000000000webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/000077500000000000000000000000001345416772700241335ustar00rootroot00000000000000webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/000077500000000000000000000000001345416772700252355ustar00rootroot00000000000000webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file1.js000066400000000000000000000000341345416772700265700ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file10.js000066400000000000000000000000341345416772700266500ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file11.js000066400000000000000000000000341345416772700266510ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file12.js000066400000000000000000000000341345416772700266520ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file13.js000066400000000000000000000000341345416772700266530ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file14.js000066400000000000000000000000341345416772700266540ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file15.js000066400000000000000000000000341345416772700266550ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file2.js000066400000000000000000000000341345416772700265710ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file3.js000066400000000000000000000000341345416772700265720ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file4.js000066400000000000000000000000341345416772700265730ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file5.js000066400000000000000000000000341345416772700265740ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file6.js000066400000000000000000000000341345416772700265750ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file7.js000066400000000000000000000000341345416772700265760ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file8.js000066400000000000000000000000341345416772700265770ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/files/file9.js000066400000000000000000000000341345416772700266000ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/index.js000066400000000000000000000003051345416772700255760ustar00rootroot00000000000000it("should have unique ids", function () { var ids = []; for(var i = 1; i <= 15; i++) { var id = require("./files/file" + i + ".js"); expect(ids.indexOf(id)).toBe(-1); ids.push(id); } }); webpack-4.30.0/test/configCases/hash-length/hashed-module-ids/webpack.config.js000066400000000000000000000006041345416772700273510ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = [ { plugins: [ new webpack.HashedModuleIdsPlugin({ hashDigestLength: 2 }) ] }, { plugins: [ new webpack.HashedModuleIdsPlugin({ hashDigest: "hex", hashDigestLength: 2 }) ] }, { plugins: [ new webpack.HashedModuleIdsPlugin({ hashFunction: "sha1", hashDigestLength: 3 }) ] } ]; webpack-4.30.0/test/configCases/hash-length/output-filename/000077500000000000000000000000001345416772700237555ustar00rootroot00000000000000webpack-4.30.0/test/configCases/hash-length/output-filename/chunk.js000066400000000000000000000000321345416772700254160ustar00rootroot00000000000000module.exports = "chunk"; webpack-4.30.0/test/configCases/hash-length/output-filename/index.js000066400000000000000000000002741345416772700254250ustar00rootroot00000000000000it("should compile and run the test " + NAME, function () {}); it("should load additional chunks in " + NAME, function (done) { require(['./chunk'], function () { done(); }); }); webpack-4.30.0/test/configCases/hash-length/output-filename/no-async.js000066400000000000000000000002011345416772700260330ustar00rootroot00000000000000it("should compile and run the test " + NAME, function() {}); if (Math.random() < -1) { require(["./chunk"], function() {}); } webpack-4.30.0/test/configCases/hash-length/output-filename/test.config.js000066400000000000000000000023101345416772700265320ustar00rootroot00000000000000var fs = require("fs"); var findFile = function(files, regex) { return files.find(function(file) { if (regex.test(file)) { return true; } }); }; var verifyFilenameLength = function(filename, expectedNameLength) { expect(filename).toMatch(new RegExp("^.{" + expectedNameLength + "}$")); }; module.exports = { findBundle: function(i, options) { var files = fs.readdirSync(options.output.path); var bundleDetects = [ options.amd.expectedChunkFilenameLength && { regex: new RegExp("^\\d+.bundle" + i, "i"), expectedNameLength: options.amd.expectedChunkFilenameLength }, { regex: new RegExp("^bundle" + i, "i"), expectedNameLength: options.amd.expectedFilenameLength } ].filter(Boolean); var bundleDetect; var filename; for (bundleDetect of bundleDetects) { filename = findFile(files, bundleDetect.regex); if (!filename) { throw new Error( `No file found with correct name (regex: ${ bundleDetect.regex.source }, files: ${files.join(", ")})` ); } verifyFilenameLength(filename, bundleDetect.expectedNameLength); } return "./" + filename; }, afterExecute: () => { delete global.webpackJsonp; delete global.webpackChunk; } }; webpack-4.30.0/test/configCases/hash-length/output-filename/webpack.config.js000066400000000000000000000116011345416772700271720ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = [ { name: "hash with length in publicPath", output: { publicPath: "/[hash:6]/", filename: "bundle0.[hash:6].js", chunkFilename: "[id].bundle0.[hash:6].js" }, amd: { expectedFilenameLength: 17, expectedChunkFilenameLength: 19 } }, { name: "hash in publicPath", output: { publicPath: "/[hash]/", filename: "bundle1.[hash].js", chunkFilename: "[id].bundle1.[hash].js" }, amd: { expectedFilenameLength: 31, expectedChunkFilenameLength: 33 } }, { name: "chunkhash with length", output: { filename: "bundle2.[chunkhash:8].js", chunkFilename: "[id].bundle2.[chunkhash:8].js" }, amd: { expectedFilenameLength: 19, expectedChunkFilenameLength: 21 } }, { name: "chunkhash", output: { filename: "bundle3.[chunkhash].js", chunkFilename: "[id].bundle3.[chunkhash].js" }, amd: { expectedFilenameLength: 31, expectedChunkFilenameLength: 33 } }, { name: "hash with and without length", output: { filename: "bundle4.[hash].js", chunkFilename: "[id].bundle4.[hash:8].js" }, amd: { expectedFilenameLength: 31, expectedChunkFilenameLength: 21 } }, { name: "hash with length", output: { filename: "bundle5.[hash:6].js", chunkFilename: "[id].bundle5.[hash:8].js" }, amd: { expectedFilenameLength: 17, expectedChunkFilenameLength: 21 } }, { name: "chunkhash in chunkFilename ", output: { filename: "bundle6.[hash].js", chunkFilename: "[id].bundle6.[chunkhash:7].js" }, amd: { expectedFilenameLength: 31, expectedChunkFilenameLength: 20 }, plugins: [new webpack.HotModuleReplacementPlugin()] }, { name: "hash with length and chunkhash with length", output: { filename: "bundle7.[hash:7].js", chunkFilename: "[id].bundle7.[chunkhash:7].js" }, target: "node", amd: { expectedFilenameLength: 18, expectedChunkFilenameLength: 20 } }, { name: "hash with length in chunkFilename", output: { filename: "bundle8.[hash].js", chunkFilename: "[id].bundle8.[hash:7].js" }, target: "node", amd: { expectedFilenameLength: 31, expectedChunkFilenameLength: 20 } }, { name: "chunkhash with length in chunkFilename", output: { filename: "bundle9.[hash].js", chunkFilename: "[id].bundle9.[chunkhash:7].js" }, target: "node", amd: { expectedFilenameLength: 31, expectedChunkFilenameLength: 20 } }, { name: "contenthash in node", output: { filename: "bundle10.[contenthash].js", chunkFilename: "[id].bundle10.[contenthash].js" }, target: "node", amd: { expectedFilenameLength: 32, expectedChunkFilenameLength: 34 } }, { name: "contenthash in node with length", output: { filename: "bundle11.[contenthash:7].js", chunkFilename: "[id].bundle11.[contenthash:7].js" }, target: "node", amd: { expectedFilenameLength: 9 + 7 + 3, expectedChunkFilenameLength: 2 + 9 + 7 + 3 } }, { name: "contenthash in async-node", output: { filename: "bundle12.[contenthash].js", chunkFilename: "[id].bundle12.[contenthash].js" }, target: "async-node", amd: { expectedFilenameLength: 32, expectedChunkFilenameLength: 34 } }, { name: "contenthash in async-node with length", output: { filename: "bundle13.[contenthash:7].js", chunkFilename: "[id].bundle13.[contenthash:7].js" }, target: "async-node", amd: { expectedFilenameLength: 9 + 7 + 3, expectedChunkFilenameLength: 2 + 9 + 7 + 3 } }, { name: "contenthash in webpack", entry: "./no-async", output: { filename: "bundle14.[contenthash].js", chunkFilename: "[id].bundle14.[contenthash].js", globalObject: "this" }, target: "web", amd: { expectedFilenameLength: 32, expectedChunkFilenameLength: 34 } }, { name: "contenthash in async-node with length", entry: "./no-async", output: { filename: "bundle15.[contenthash:7].js", chunkFilename: "[id].bundle15.[contenthash:7].js", globalObject: "this" }, target: "web", amd: { expectedFilenameLength: 9 + 7 + 3, expectedChunkFilenameLength: 2 + 9 + 7 + 3 } }, { name: "contenthash in webpack", entry: "./no-async", output: { filename: "bundle16.[contenthash].js", chunkFilename: "[id].bundle16.[contenthash].js", globalObject: "this" }, target: "webworker", amd: { expectedFilenameLength: 32, expectedChunkFilenameLength: 34 } }, { name: "contenthash in async-node with length", entry: "./no-async", output: { filename: "bundle17.[contenthash:7].js", chunkFilename: "[id].bundle17.[contenthash:7].js", globalObject: "this" }, target: "webworker", amd: { expectedFilenameLength: 9 + 7 + 3, expectedChunkFilenameLength: 2 + 9 + 7 + 3 } } ]; module.exports.forEach(function(options) { options.plugins = options.plugins || []; options.plugins.push( new webpack.DefinePlugin({ NAME: JSON.stringify(options.name) }) ); }); webpack-4.30.0/test/configCases/ignore/000077500000000000000000000000001345416772700177205ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkContext/000077500000000000000000000000001345416772700223425ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkContext/folder-a/000077500000000000000000000000001345416772700240335ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkContext/folder-a/ignored-module.js000066400000000000000000000000341345416772700273000ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/checkContext/folder-a/normal-module.js000066400000000000000000000000551345416772700271440ustar00rootroot00000000000000module.exports = require("./normal-module"); webpack-4.30.0/test/configCases/ignore/checkContext/folder-b/000077500000000000000000000000001345416772700240345ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkContext/folder-b/ignored-module.js000066400000000000000000000000341345416772700273010ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/checkContext/folder-b/normal-module.js000066400000000000000000000000561345416772700271460ustar00rootroot00000000000000module.exports = require("./ignored-module"); webpack-4.30.0/test/configCases/ignore/checkContext/folder-b/only-context-match-require.js000066400000000000000000000000431345416772700315760ustar00rootroot00000000000000module.exports = "should be fine"; webpack-4.30.0/test/configCases/ignore/checkContext/folder-b/only-context-match.js000066400000000000000000000000721345416772700301260ustar00rootroot00000000000000module.exports = require("./only-context-match-require"); webpack-4.30.0/test/configCases/ignore/checkContext/test.js000066400000000000000000000010561345416772700236610ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore resources that match resource regex and context", function() { expect(function() { require("./folder-b/normal-module"); }).toThrowError(); }); it("should not ignore resources that match resource but not context", function() { expect(function() { require("./folder-a/normal-module"); }).not.toThrowError(); }); it("should not ignore resources that do not match resource but do match context", function() { expect(function() { require("./folder-b/only-context-match"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/checkContext/webpack.config.js000066400000000000000000000004661345416772700255660ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin({ checkResource(resource) { return /ignored-module/.test(resource); }, checkContext(context) { return /folder-b/.test(context); } }) ] }; webpack-4.30.0/test/configCases/ignore/checkResource-one-argument/000077500000000000000000000000001345416772700251045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkResource-one-argument/ignored-module.js000066400000000000000000000000341345416772700303510ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/checkResource-one-argument/normal-module.js000066400000000000000000000000331345416772700302110ustar00rootroot00000000000000module.exports = "normal"; webpack-4.30.0/test/configCases/ignore/checkResource-one-argument/test.js000066400000000000000000000004571345416772700264270ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore ignored resources", function() { expect(function() { require("./ignored-module"); }).toThrowError(); }); it("should not ignore resources that do not match", function() { expect(function() { require("./normal-module"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/checkResource-one-argument/webpack.config.js000066400000000000000000000003601345416772700303210ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin({ checkResource(resource) { return /ignored-module/.test(resource); } }) ] }; webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/000077500000000000000000000000001345416772700253175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-a/000077500000000000000000000000001345416772700270105ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-a/ignored-module.js000066400000000000000000000000341345416772700322550ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-a/normal-module.js000066400000000000000000000000551345416772700321210ustar00rootroot00000000000000module.exports = require("./normal-module"); webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-b/000077500000000000000000000000001345416772700270115ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-b/ignored-module.js000066400000000000000000000000341345416772700322560ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-b/normal-module.js000066400000000000000000000000561345416772700321230ustar00rootroot00000000000000module.exports = require("./ignored-module"); only-context-match-require.js000066400000000000000000000000431345416772700344740ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-bmodule.exports = "should be fine"; webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/folder-b/only-context-match.js000066400000000000000000000000721345416772700331030ustar00rootroot00000000000000module.exports = require("./only-context-match-require"); webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/test.js000066400000000000000000000010561345416772700266360ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore resources that match resource regex and context", function() { expect(function() { require("./folder-b/normal-module"); }).toThrowError(); }); it("should not ignore resources that match resource but not context", function() { expect(function() { require("./folder-a/normal-module"); }).not.toThrowError(); }); it("should not ignore resources that do not match resource but do match context", function() { expect(function() { require("./folder-b/only-context-match"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/checkResource-two-arguments/webpack.config.js000066400000000000000000000004251345416772700305360ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin({ checkResource(resource, context) { return /ignored-module/.test(resource) && /folder-b/.test(context); } }) ] }; webpack-4.30.0/test/configCases/ignore/compatibilityLayer/000077500000000000000000000000001345416772700235665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-a/000077500000000000000000000000001345416772700252575ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-a/ignored-module.js000066400000000000000000000000341345416772700305240ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-a/normal-module.js000066400000000000000000000000551345416772700303700ustar00rootroot00000000000000module.exports = require("./normal-module"); webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-b/000077500000000000000000000000001345416772700252605ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-b/ignored-module.js000066400000000000000000000000341345416772700305250ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-b/normal-module.js000066400000000000000000000000561345416772700303720ustar00rootroot00000000000000module.exports = require("./ignored-module"); webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-b/only-context-match-require.js000066400000000000000000000000431345416772700330220ustar00rootroot00000000000000module.exports = "should be fine"; webpack-4.30.0/test/configCases/ignore/compatibilityLayer/folder-b/only-context-match.js000066400000000000000000000000721345416772700313520ustar00rootroot00000000000000module.exports = require("./only-context-match-require"); webpack-4.30.0/test/configCases/ignore/compatibilityLayer/test.js000066400000000000000000000016331345416772700251060ustar00rootroot00000000000000/* globals it */ "use strict"; // TODO: remove in webpack 5 it("should ignore context modules that match resource regex and context (compat-layer)", function() { const folderBContext = function(mod) { require("./folder-b/" + mod); }; expect(function() { folderBContext("normal-module"); }).toThrowError(); }); it("should not ignore context modules that dont match the resource (compat-layer)", function() { const folderBContext = function(mod) { require("./folder-b/" + mod); }; expect(function() { folderBContext("only-context-match"); }).not.toThrowError(); }); it("should not ignore context modules that dont match the context (compat-layer)", function() { const folderBContext = function(mod) { require("./folder-a/" + mod); }; expect(function() { folderBContext("normal-module"); }).not.toThrowError(); expect(function() { folderBContext("ignored-module"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/compatibilityLayer/webpack.config.js000066400000000000000000000002641345416772700270060ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [new IgnorePlugin(/ignored-module/, /folder-b/)] }; webpack-4.30.0/test/configCases/ignore/multiple-with-externals/000077500000000000000000000000001345416772700245275ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/multiple-with-externals/ignored-module1.js000066400000000000000000000000341345416772700300550ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/multiple-with-externals/ignored-module2.js000066400000000000000000000000341345416772700300560ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/multiple-with-externals/normal-module.js000066400000000000000000000000331345416772700276340ustar00rootroot00000000000000module.exports = "normal"; webpack-4.30.0/test/configCases/ignore/multiple-with-externals/test.js000066400000000000000000000006641345416772700260520ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore ignored resources 1", function() { expect(function() { require("./ignored-module1"); }).toThrowError(); }); it("should ignore ignored resources 2", function() { expect(function() { require("./ignored-module2"); }).toThrowError(); }); it("should not ignore resources that do not match", function() { expect(function() { require("./normal-module"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/multiple-with-externals/webpack.config.js000066400000000000000000000004631345416772700277500ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", externals: { "./normal-module": "{}" }, plugins: [ new IgnorePlugin({ resourceRegExp: /ignored-module1/ }), new IgnorePlugin({ resourceRegExp: /ignored-module2/ }) ] }; webpack-4.30.0/test/configCases/ignore/only-resource-context/000077500000000000000000000000001345416772700242105ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/only-resource-context/src/000077500000000000000000000000001345416772700247775ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/only-resource-context/src/ignored-module.js000066400000000000000000000000341345416772700302440ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/only-resource-context/src/normal-module.js000066400000000000000000000000331345416772700301040ustar00rootroot00000000000000module.exports = "normal"; webpack-4.30.0/test/configCases/ignore/only-resource-context/test.js000066400000000000000000000007111345416772700255240ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore ignored resources", function() { const folderBContext = function(mod) { require("./src/" + mod); }; expect(function() { folderBContext("ignored-module"); }).toThrowError(); }); it("should not ignore resources that do not match", function() { const folderBContext = function(mod) { require("./src/" + mod); }; expect(function() { folderBContext("normal-module"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/only-resource-context/webpack.config.js000066400000000000000000000003061345416772700274250ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin({ resourceRegExp: /ignored-module/ }) ] }; webpack-4.30.0/test/configCases/ignore/only-resource/000077500000000000000000000000001345416772700225265ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/only-resource/ignored-module.js000066400000000000000000000000341345416772700257730ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/only-resource/normal-module.js000066400000000000000000000000331345416772700256330ustar00rootroot00000000000000module.exports = "normal"; webpack-4.30.0/test/configCases/ignore/only-resource/test.js000066400000000000000000000004571345416772700240510ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore ignored resources", function() { expect(function() { require("./ignored-module"); }).toThrowError(); }); it("should not ignore resources that do not match", function() { expect(function() { require("./normal-module"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/only-resource/webpack.config.js000066400000000000000000000003061345416772700257430ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin({ resourceRegExp: /ignored-module/ }) ] }; webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/000077500000000000000000000000001345416772700266615ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-a/000077500000000000000000000000001345416772700303525ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-a/ignored-module.js000066400000000000000000000000341345416772700336170ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-a/normal-module.js000066400000000000000000000000551345416772700334630ustar00rootroot00000000000000module.exports = require("./normal-module"); webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-b/000077500000000000000000000000001345416772700303535ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-b/ignored-module.js000066400000000000000000000000341345416772700336200ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-b/normal-module.js000066400000000000000000000000561345416772700334650ustar00rootroot00000000000000module.exports = require("./ignored-module"); only-context-match-require.js000066400000000000000000000000431345416772700360360ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-bmodule.exports = "should be fine"; only-context-match.js000066400000000000000000000000721345416772700343660ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/folder-bmodule.exports = require("./only-context-match-require"); webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/test.js000066400000000000000000000015211345416772700301750ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore context modules that match resource regex and context", function() { const folderBContext = function(mod) { require("./folder-b/" + mod); }; expect(function() { folderBContext("normal-module"); }).toThrowError(); }); it("should not ignore context modules that dont match the resource", function() { const folderBContext = function(mod) { require("./folder-b/" + mod); }; expect(function() { folderBContext("only-context-match"); }).not.toThrowError(); }); it("should not ignore context modules that dont match the context", function() { const folderBContext = function(mod) { require("./folder-a/" + mod); }; expect(function() { folderBContext("normal-module"); }).not.toThrowError(); expect(function() { folderBContext("ignored-module"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/resource-and-context-contextmodule/webpack.config.js000066400000000000000000000003441345416772700321000ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin({ resourceRegExp: /ignored-module/, contextRegExp: /folder-b/ }) ] }; webpack-4.30.0/test/configCases/ignore/resource-and-context/000077500000000000000000000000001345416772700237715ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-a/000077500000000000000000000000001345416772700254625ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-a/ignored-module.js000066400000000000000000000000341345416772700307270ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-a/normal-module.js000066400000000000000000000000551345416772700305730ustar00rootroot00000000000000module.exports = require("./normal-module"); webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-b/000077500000000000000000000000001345416772700254635ustar00rootroot00000000000000webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-b/ignored-module.js000066400000000000000000000000341345416772700307300ustar00rootroot00000000000000module.exports = "ignored"; webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-b/normal-module.js000066400000000000000000000000561345416772700305750ustar00rootroot00000000000000module.exports = require("./ignored-module"); webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-b/only-context-match-require.js000066400000000000000000000000431345416772700332250ustar00rootroot00000000000000module.exports = "should be fine"; webpack-4.30.0/test/configCases/ignore/resource-and-context/folder-b/only-context-match.js000066400000000000000000000000721345416772700315550ustar00rootroot00000000000000module.exports = require("./only-context-match-require"); webpack-4.30.0/test/configCases/ignore/resource-and-context/test.js000066400000000000000000000010561345416772700253100ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore resources that match resource regex and context", function() { expect(function() { require("./folder-b/normal-module"); }).toThrowError(); }); it("should not ignore resources that match resource but not context", function() { expect(function() { require("./folder-a/normal-module"); }).not.toThrowError(); }); it("should not ignore resources that do not match resource but do match context", function() { expect(function() { require("./folder-b/only-context-match"); }).not.toThrowError(); }); webpack-4.30.0/test/configCases/ignore/resource-and-context/webpack.config.js000066400000000000000000000003441345416772700272100ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin({ resourceRegExp: /ignored-module/, contextRegExp: /folder-b/ }) ] }; webpack-4.30.0/test/configCases/issues/000077500000000000000000000000001345416772700177505ustar00rootroot00000000000000webpack-4.30.0/test/configCases/issues/issue-3596/000077500000000000000000000000001345416772700215045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/issues/issue-3596/b.js000066400000000000000000000001321345416772700222570ustar00rootroot00000000000000it("should not be executed", function() { throw new Error("should not be executed"); }); webpack-4.30.0/test/configCases/issues/issue-3596/index.js000066400000000000000000000000571345416772700231530ustar00rootroot00000000000000it("should compile correctly", function() {}); webpack-4.30.0/test/configCases/issues/issue-3596/webpack.config.js000066400000000000000000000003711345416772700247230ustar00rootroot00000000000000module.exports = { entry: { bundle0: "./index", b: "./b" }, output: { filename: "[name].js" }, plugins: [ function() { this.hooks.emit.tap("TestPlugin", function(compilation) { delete compilation.assets["b.js"]; }); } ] }; webpack-4.30.0/test/configCases/issues/issue-7470/000077500000000000000000000000001345416772700214775ustar00rootroot00000000000000webpack-4.30.0/test/configCases/issues/issue-7470/index.js000066400000000000000000000001461345416772700231450ustar00rootroot00000000000000it("should set NODE_ENV according to mode", () => { expect(process.env.NODE_ENV).toBe(__MODE__); }); webpack-4.30.0/test/configCases/issues/issue-7470/webpack.config.js000066400000000000000000000006411345416772700247160ustar00rootroot00000000000000"use strict"; const DefinePlugin = require("../../../../lib/DefinePlugin"); module.exports = [ { name: "development", mode: "development", plugins: [new DefinePlugin({ __MODE__: `"development"` })] }, { name: "production", mode: "production", plugins: [new DefinePlugin({ __MODE__: `"production"` })] }, { name: "none", mode: "none", plugins: [new DefinePlugin({ __MODE__: `"none"` })] } ]; webpack-4.30.0/test/configCases/issues/issue-7563/000077500000000000000000000000001345416772700215025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/issues/issue-7563/index.js000066400000000000000000000001531345416772700231460ustar00rootroot00000000000000it("should compile without error", function() { return import(/* webpackChunkName: "one" */ "./one"); }); webpack-4.30.0/test/configCases/issues/issue-7563/one.js000066400000000000000000000000241345416772700226150ustar00rootroot00000000000000module.exports = 1; webpack-4.30.0/test/configCases/issues/issue-7563/test.config.js000066400000000000000000000007211345416772700242630ustar00rootroot00000000000000var fs = require('fs'); module.exports = { noTests: true, findBundle: function(i, options) { var regex = new RegExp("^bundle\." + options.name, "i"); var files = fs.readdirSync(options.output.path); var bundle = files.find(function (file) { return regex.test(file); }); if (!bundle) { throw new Error( `No file found with correct name (regex: ${ regex.source }, files: ${files.join(", ")})` ); } return "./" + bundle; } }; webpack-4.30.0/test/configCases/issues/issue-7563/webpack.config.js000066400000000000000000000024751345416772700247300ustar00rootroot00000000000000"use strict"; // Have to test [hash] and [chunkhash] separately to avoid // "Cannot use [chunkhash] or [contenthash] for chunk in 'bundle1.[hash].[hash:16].[chunkhash].[chunkhash:16].[name].[id].[query].js' (use [hash] instead)" var testAllButHash = "[chunkhash].[chunkhash:16].[name].[id].[query]"; var testHash = "[hash].[hash:16]"; module.exports = [ { name: "webworker-all", target: "webworker", output: { filename: "bundle.webworker-all." + testAllButHash + ".js" } }, { name: "webworker-hash", target: "webworker", output: { filename: "bundle.webworker-hash." + testHash + ".js" } }, { name: "node-all", target: "node", output: { filename: "bundle.node-all." + testAllButHash + ".js" } }, { name: "node", target: "node", output: { filename: "bundle.node-hash." + testHash + ".js" } }, { name: "async-node-all", target: "async-node", output: { filename: "bundle.async-node-all." + testAllButHash + ".js" } }, { name: "async-node-hash", target: "async-node", output: { filename: "bundle.async-node-hash." + testHash + ".js" } }, { name: "web-all", target: "web", output: { filename: "bundle.web-all." + testAllButHash + ".js" } }, { name: "web-hash", target: "web", output: { filename: "bundle.web-hash." + testHash + ".js" } } ]; webpack-4.30.0/test/configCases/library/000077500000000000000000000000001345416772700201015ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/0-create-library/000077500000000000000000000000001345416772700231435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/0-create-library/a.js000066400000000000000000000000241345416772700237150ustar00rootroot00000000000000export var a = "a"; webpack-4.30.0/test/configCases/library/0-create-library/index.js000066400000000000000000000001711345416772700246070ustar00rootroot00000000000000export * from "./a"; export default "default-value"; export var b = "b"; export { default as external } from "external"; webpack-4.30.0/test/configCases/library/0-create-library/non-external.js000066400000000000000000000000371345416772700261130ustar00rootroot00000000000000export default "non-external"; webpack-4.30.0/test/configCases/library/0-create-library/test.config.js000066400000000000000000000000301345416772700257150ustar00rootroot00000000000000exports.noTests = true; webpack-4.30.0/test/configCases/library/0-create-library/webpack.config.js000066400000000000000000000015571345416772700263710ustar00rootroot00000000000000module.exports = [ { output: { filename: "commonjs.js", libraryTarget: "commonjs-module" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "umd.js", libraryTarget: "umd" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "umd-default.js", libraryTarget: "umd", libraryExport: "default" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "this.js", libraryTarget: "this" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "global.js", library: "globalName" }, resolve: { alias: { external: "./non-external" } } }, { output: { filename: "commonjs2-external.js", libraryTarget: "commonjs2" }, externals: ["external"] } ]; webpack-4.30.0/test/configCases/library/1-use-library/000077500000000000000000000000001345416772700224755ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/1-use-library/default-test.js000066400000000000000000000003151345416772700254330ustar00rootroot00000000000000import d from "library"; var data = require("library"); it("should get default export from library (" + NAME + ")", function() { expect(data).toBe("default-value"); expect(d).toBe("default-value"); }); webpack-4.30.0/test/configCases/library/1-use-library/global-test.js000066400000000000000000000003661345416772700252550ustar00rootroot00000000000000var data = require("library"); it("should be able get items from library (" + NAME + ")", function() { expect(data).toHaveProperty("default", "default-value"); expect(data).toHaveProperty("a", "a"); expect(data).toHaveProperty("b", "b"); }); webpack-4.30.0/test/configCases/library/1-use-library/index.js000066400000000000000000000006711345416772700241460ustar00rootroot00000000000000import d from "library"; import { a, b, external } from "library"; it("should be able to import harmony exports from library (" + NAME + ")", function() { expect(d).toBe("default-value"); expect(a).toBe("a"); expect(b).toBe("b"); if(typeof TEST_EXTERNAL !== "undefined" && TEST_EXTERNAL) { expect(external).toEqual(["external"]); expect(external).toBe(require("external")); } else { expect(external).toBe("non-external"); } }); webpack-4.30.0/test/configCases/library/1-use-library/node_modules/000077500000000000000000000000001345416772700251525ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/1-use-library/node_modules/external.js000066400000000000000000000000371345416772700273320ustar00rootroot00000000000000module.exports = ["external"]; webpack-4.30.0/test/configCases/library/1-use-library/webpack.config.js000066400000000000000000000026741345416772700257240ustar00rootroot00000000000000var webpack = require("../../../../"); var path = require("path"); module.exports = [ { resolve: { alias: { library: path.resolve( __dirname, "../../../js/config/library/0-create-library/commonjs.js" ) } }, plugins: [ new webpack.DefinePlugin({ NAME: JSON.stringify("commonjs") }) ] }, { resolve: { alias: { library: path.resolve( __dirname, "../../../js/config/library/0-create-library/umd.js" ) } }, plugins: [ new webpack.DefinePlugin({ NAME: JSON.stringify("umd") }) ] }, { entry: "./global-test.js", resolve: { alias: { library: path.resolve( __dirname, "../../../js/config/library/0-create-library/this.js" ) } }, plugins: [ new webpack.DefinePlugin({ NAME: JSON.stringify("this") }) ] }, { resolve: { alias: { library: path.resolve( __dirname, "../../../js/config/library/0-create-library/commonjs2-external.js" ), external: path.resolve(__dirname, "node_modules/external.js") } }, plugins: [ new webpack.DefinePlugin({ NAME: JSON.stringify("commonjs2 with external"), TEST_EXTERNAL: true }) ] }, { entry: "./default-test.js", resolve: { alias: { library: path.resolve( __dirname, "../../../js/config/library/0-create-library/umd-default.js" ) } }, plugins: [ new webpack.DefinePlugin({ NAME: JSON.stringify("default") }) ] } ]; webpack-4.30.0/test/configCases/library/a/000077500000000000000000000000001345416772700203215ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/a/index.js000066400000000000000000000000421345416772700217620ustar00rootroot00000000000000it("should run", function() { });webpack-4.30.0/test/configCases/library/a/webpack.config.js000066400000000000000000000000741345416772700235400ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "this" } }; webpack-4.30.0/test/configCases/library/array-global/000077500000000000000000000000001345416772700224555ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/array-global/index.js000066400000000000000000000001401345416772700241150ustar00rootroot00000000000000it("should define global object with property", function() { expect(a["b"]).toBeDefined(); }); webpack-4.30.0/test/configCases/library/array-global/webpack.config.js000066400000000000000000000000721345416772700256720ustar00rootroot00000000000000module.exports = { output: { library: ["a", "b"] } }; webpack-4.30.0/test/configCases/library/array-window/000077500000000000000000000000001345416772700225245ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/array-window/index.js000066400000000000000000000001521345416772700241670ustar00rootroot00000000000000it("should define property in 'window' object", function() { expect(window["a"]["b"]).toBeDefined(); }); webpack-4.30.0/test/configCases/library/array-window/webpack.config.js000066400000000000000000000001451345416772700257420ustar00rootroot00000000000000module.exports = { target: "web", output: { library: ["a", "b"], libraryTarget: "window" } }; webpack-4.30.0/test/configCases/library/b/000077500000000000000000000000001345416772700203225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/b/index.js000066400000000000000000000007201345416772700217660ustar00rootroot00000000000000it("should run", function() { }); it("should have exported", function(done) { setTimeout(function() { expect(exported.object).toBe(module.exports.object); expect(exported.second).toBe(module.exports.second); done(); }, 1); }); module.exports = { object: {ok: 1}, second: {ok: 2} }; var exported = {}; process.nextTick(function() { exported.object = global.object; exported.second = global.second; delete global.object; delete global.second; }); webpack-4.30.0/test/configCases/library/b/webpack.config.js000066400000000000000000000000761345416772700235430ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "global" } }; webpack-4.30.0/test/configCases/library/umd-array/000077500000000000000000000000001345416772700220025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/umd-array/index.js000066400000000000000000000000421345416772700234430ustar00rootroot00000000000000it("should run", function() { });webpack-4.30.0/test/configCases/library/umd-array/webpack.config.js000066400000000000000000000002371345416772700252220ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd", library: { root: ["test", "library"], amd: "test-library", commonjs: "test-library" } } }; webpack-4.30.0/test/configCases/library/umd/000077500000000000000000000000001345416772700206665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/library/umd/index.js000066400000000000000000000000421345416772700223270ustar00rootroot00000000000000it("should run", function() { });webpack-4.30.0/test/configCases/library/umd/webpack.config.js000066400000000000000000000002311345416772700241000ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd", library: { root: "testLibrary", amd: "test-library", commonjs: "test-library" } } }; webpack-4.30.0/test/configCases/loaders/000077500000000000000000000000001345416772700200665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/generate-ident/000077500000000000000000000000001345416772700227615ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/generate-ident/a.js000066400000000000000000000000001345416772700235250ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/generate-ident/b.js000066400000000000000000000000001345416772700235260ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/generate-ident/c.js000066400000000000000000000000001345416772700235270ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/generate-ident/d.js000066400000000000000000000000001345416772700235300ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/generate-ident/index.js000066400000000000000000000003551345416772700244310ustar00rootroot00000000000000it("should correctly pass complex query object with remaining request", function() { expect(require("./a")).toBe("ok"); expect(require("./b")).toBe("maybe"); expect(require("./c")).toBe("yes"); expect(require("./d")).toBe("ok"); }); webpack-4.30.0/test/configCases/loaders/generate-ident/loader1.js000066400000000000000000000002151345416772700246440ustar00rootroot00000000000000module.exports.pitch = function(remainingRequest) { return "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");"; }; webpack-4.30.0/test/configCases/loaders/generate-ident/loader2.js000066400000000000000000000001451345416772700246470ustar00rootroot00000000000000module.exports = function(source) { return "module.exports = " + JSON.stringify(this.query.f()); }; webpack-4.30.0/test/configCases/loaders/generate-ident/webpack.config.js000066400000000000000000000014541345416772700262030ustar00rootroot00000000000000module.exports = { module: { rules: [ { test: /a\.js$/, use: [ "./loader1", { loader: "./loader2", options: { f: function() { return "ok"; } } } ] }, { test: /(b|c)\.js$/, use: ["./loader1"] }, { test: /b\.js$/, use: { loader: "./loader2", options: { f: function() { return "maybe"; } } } }, { test: /c\.js$/, use: { loader: "./loader2", options: { f: function() { return "yes"; } } } }, { test: /d\.js$/, use: [ "./loader1", "./loader1", "./loader1", { loader: "./loader2", options: { f: function() { return "ok"; } } } ] } ] } }; webpack-4.30.0/test/configCases/loaders/hot-in-context/000077500000000000000000000000001345416772700227465ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/hot-in-context/index.js000066400000000000000000000001601345416772700244100ustar00rootroot00000000000000it("should have hmr flag in loader context", function() { expect(require("./loader!")).toBe(!!module.hot); }); webpack-4.30.0/test/configCases/loaders/hot-in-context/loader.js000066400000000000000000000001331345416772700245470ustar00rootroot00000000000000module.exports = function() { return `module.exports = ${JSON.stringify(!!this.hot)};`; } webpack-4.30.0/test/configCases/loaders/hot-in-context/webpack.config.js000066400000000000000000000002341345416772700261630ustar00rootroot00000000000000const webpack = require("../../../../"); module.exports = [ { // no hmr }, { // with hmr plugins: [new webpack.HotModuleReplacementPlugin()] } ]; webpack-4.30.0/test/configCases/loaders/issue-3320/000077500000000000000000000000001345416772700216035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/issue-3320/a.js000066400000000000000000000000001345416772700223470ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/issue-3320/b.js000066400000000000000000000000001345416772700223500ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/issue-3320/b2.js000066400000000000000000000000001345416772700224320ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/issue-3320/b3.js000066400000000000000000000000001345416772700224330ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/issue-3320/index.js000066400000000000000000000011761345416772700232550ustar00rootroot00000000000000it("should resolve aliased loader module with query", function() { var foo = require('./a'); expect(foo).toBe("someMessage"); }); it("should favor explicit loader query over aliased query (options in rule)", function() { var foo = require('./b'); expect(foo).toBe("someOtherMessage"); }); it("should favor explicit loader query over aliased query (inline query in rule)", function() { var foo = require('./b2'); expect(foo).toBe("someOtherMessage"); }); it("should favor explicit loader query over aliased query (inline query in rule.use)", function() { var foo = require('./b3'); expect(foo).toBe("someOtherMessage"); }); webpack-4.30.0/test/configCases/loaders/issue-3320/node_modules/000077500000000000000000000000001345416772700242605ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/issue-3320/node_modules/any-loader.js000066400000000000000000000003351345416772700266520ustar00rootroot00000000000000var loaderUtils = require('loader-utils'); module.exports = function(source) { var loaderContext = this; var options = loaderUtils.getOptions(loaderContext); return "module.exports=" + JSON.stringify(options.foo); } webpack-4.30.0/test/configCases/loaders/issue-3320/webpack.config.js000066400000000000000000000010201345416772700250120ustar00rootroot00000000000000module.exports = { resolveLoader: { alias: { "some-loader": "any-loader?foo=someMessage" } }, module: { rules: [ { test: /a\.js$/, use: [ { loader: "some-loader" } ] }, { test: /b\.js$/, use: [ { loader: "some-loader", options: { foo: "someOtherMessage" } } ] }, { test: /b2\.js$/, loader: "some-loader?foo=someOtherMessage" }, { test: /b3\.js$/, use: ["some-loader?foo=someOtherMessage"] } ] } }; webpack-4.30.0/test/configCases/loaders/pre-post-loader/000077500000000000000000000000001345416772700231035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/pre-post-loader/a.js000066400000000000000000000000351345416772700236570ustar00rootroot00000000000000module.exports = "resource"; webpack-4.30.0/test/configCases/loaders/pre-post-loader/index.js000066400000000000000000000004401345416772700245460ustar00rootroot00000000000000it("should apply pre and post loaders correctly", function() { expect(require("./a")).toBe("resource loader2 loader1 loader3"); expect(require("!./a")).toBe("resource loader2 loader3"); expect(require("!!./a")).toBe("resource"); expect(require("-!./a")).toBe("resource loader3"); }); webpack-4.30.0/test/configCases/loaders/pre-post-loader/loader1.js000066400000000000000000000001351345416772700247670ustar00rootroot00000000000000module.exports = function(source) { return source + "module.exports += \" loader1\";\n"; }; webpack-4.30.0/test/configCases/loaders/pre-post-loader/loader2.js000066400000000000000000000001351345416772700247700ustar00rootroot00000000000000module.exports = function(source) { return source + "module.exports += \" loader2\";\n"; }; webpack-4.30.0/test/configCases/loaders/pre-post-loader/loader3.js000066400000000000000000000001351345416772700247710ustar00rootroot00000000000000module.exports = function(source) { return source + "module.exports += \" loader3\";\n"; }; webpack-4.30.0/test/configCases/loaders/pre-post-loader/webpack.config.js000066400000000000000000000003671345416772700263270ustar00rootroot00000000000000module.exports = { module: { rules: [ { test: /a\.js$/, use: "./loader1" }, { test: /a\.js$/, use: "./loader2", enforce: "pre" }, { test: /a\.js$/, use: "./loader3", enforce: "post" } ] } }; webpack-4.30.0/test/configCases/loaders/remaining-request/000077500000000000000000000000001345416772700235255ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/remaining-request/a.js000066400000000000000000000000001345416772700242710ustar00rootroot00000000000000webpack-4.30.0/test/configCases/loaders/remaining-request/index.js000066400000000000000000000001751345416772700251750ustar00rootroot00000000000000it("should correctly pass complex query object with remaining request", function() { expect(require("./a")).toBe("ok"); }); webpack-4.30.0/test/configCases/loaders/remaining-request/loader1.js000066400000000000000000000002151345416772700254100ustar00rootroot00000000000000module.exports.pitch = function(remainingRequest) { return "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");"; }; webpack-4.30.0/test/configCases/loaders/remaining-request/loader2.js000066400000000000000000000001451345416772700254130ustar00rootroot00000000000000module.exports = function(source) { return "module.exports = " + JSON.stringify(this.query.f()); }; webpack-4.30.0/test/configCases/loaders/remaining-request/webpack.config.js000066400000000000000000000004031345416772700267400ustar00rootroot00000000000000module.exports = { module: { rules: [ { test: /a\.js$/, use: [ "./loader1", { loader: "./loader2", ident: "loader2", options: { f: function() { return "ok"; } } } ] } ] } }; webpack-4.30.0/test/configCases/module-name/000077500000000000000000000000001345416772700206405ustar00rootroot00000000000000webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/000077500000000000000000000000001345416772700272735ustar00rootroot00000000000000webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/a.js000066400000000000000000000000411345416772700300440ustar00rootroot00000000000000module.exports = require("./c"); webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/b.js000066400000000000000000000000411345416772700300450ustar00rootroot00000000000000module.exports = require("./c"); webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/c.js000066400000000000000000000000341345416772700300500ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/loader-a.js000066400000000000000000000001271345416772700313150ustar00rootroot00000000000000module.exports = function(src) { return `module.exports = "loader-a" + module.id`; }; webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/loader-b.js000066400000000000000000000001271345416772700313160ustar00rootroot00000000000000module.exports = function(src) { return `module.exports = "loader-b" + module.id`; }; webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/test.js000066400000000000000000000004721345416772700306130ustar00rootroot00000000000000it("should assign different names to the same module with different issuers ", function() { var regex = "\\./c\\.js\\?\\w{4}"; expect(require("./c")).toMatch(new RegExp(regex)); expect(require("./a")).toMatch(new RegExp("loader-a" + regex)); expect(require("./b")).toMatch(new RegExp("loader-b" + regex)); }); webpack-4.30.0/test/configCases/module-name/different-issuers-for-same-module/webpack.config.js000066400000000000000000000004021345416772700325050ustar00rootroot00000000000000module.exports = { mode: "development", entry: ["./a", "./b", "./test"], module: { rules: [ { test: /c\.js/, issuer: /a\.js/, loader: "./loader-a" }, { test: /c\.js/, issuer: /b\.js/, loader: "./loader-b" } ] } }; webpack-4.30.0/test/configCases/no-parse/000077500000000000000000000000001345416772700201615ustar00rootroot00000000000000webpack-4.30.0/test/configCases/no-parse/module.exports/000077500000000000000000000000001345416772700231515ustar00rootroot00000000000000webpack-4.30.0/test/configCases/no-parse/module.exports/index.js000066400000000000000000000002531345416772700246160ustar00rootroot00000000000000it("should correctly export stuff from not parsed modules", function() { expect(require("./not-parsed-a")).toBe("ok"); expect(require("./not-parsed-b")).toBe("ok"); }); webpack-4.30.0/test/configCases/no-parse/module.exports/not-parsed-a.js000066400000000000000000000000271345416772700260000ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/configCases/no-parse/module.exports/not-parsed-b.js000066400000000000000000000001241345416772700257770ustar00rootroot00000000000000Object.defineProperty(module, "exports", { get: function() { return "ok"; } }); webpack-4.30.0/test/configCases/no-parse/module.exports/webpack.config.js000066400000000000000000000000741345416772700263700ustar00rootroot00000000000000module.exports = { module: { noParse: /not-parsed/ } }; webpack-4.30.0/test/configCases/no-parse/no-parse-function/000077500000000000000000000000001345416772700235305ustar00rootroot00000000000000webpack-4.30.0/test/configCases/no-parse/no-parse-function/index.js000066400000000000000000000002531345416772700251750ustar00rootroot00000000000000it("should correctly export stuff from not parsed modules", function() { expect(require("./not-parsed-a")).toBe("ok"); expect(require("./not-parsed-b")).toBe("ok"); }); webpack-4.30.0/test/configCases/no-parse/no-parse-function/not-parsed-a.js000066400000000000000000000000271345416772700263570ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/configCases/no-parse/no-parse-function/not-parsed-b.js000066400000000000000000000001241345416772700263560ustar00rootroot00000000000000Object.defineProperty(module, "exports", { get: function() { return "ok"; } }); webpack-4.30.0/test/configCases/no-parse/no-parse-function/webpack.config.js000066400000000000000000000001551345416772700267470ustar00rootroot00000000000000module.exports = { module: { noParse: function(content) { return /not-parsed/.test(content); } } }; webpack-4.30.0/test/configCases/optimization/000077500000000000000000000000001345416772700211635ustar00rootroot00000000000000webpack-4.30.0/test/configCases/optimization/hashed-module-ids/000077500000000000000000000000001345416772700244575ustar00rootroot00000000000000webpack-4.30.0/test/configCases/optimization/hashed-module-ids/files/000077500000000000000000000000001345416772700255615ustar00rootroot00000000000000webpack-4.30.0/test/configCases/optimization/hashed-module-ids/files/file1.js000066400000000000000000000000341345416772700271140ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/hashed-module-ids/files/file2.js000066400000000000000000000000341345416772700271150ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/hashed-module-ids/files/file3.js000066400000000000000000000000341345416772700271160ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/hashed-module-ids/files/file4.js000066400000000000000000000000341345416772700271170ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/hashed-module-ids/files/file5.js000066400000000000000000000000341345416772700271200ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/hashed-module-ids/index.js000066400000000000000000000003031345416772700261200ustar00rootroot00000000000000it("should have named modules ids", function() { for (var i = 1; i <= 5; i++) { var moduleId = require("./files/file" + i + ".js"); expect(moduleId).toMatch(/^[/=a-zA-Z0-9]{4,5}$/); } }); webpack-4.30.0/test/configCases/optimization/hashed-module-ids/webpack.config.js000066400000000000000000000001021345416772700276660ustar00rootroot00000000000000module.exports = { optimization: { hashedModuleIds: true } }; webpack-4.30.0/test/configCases/optimization/minimizer/000077500000000000000000000000001345416772700231665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/optimization/minimizer/index.js000066400000000000000000000000371345416772700246330ustar00rootroot00000000000000it("should compile", () => {}) webpack-4.30.0/test/configCases/optimization/minimizer/webpack.config.js000066400000000000000000000005121345416772700264020ustar00rootroot00000000000000const Compiler = require("../../../../lib/Compiler"); module.exports = { optimization: { minimize: true, minimizer: [ { apply(compiler) { expect(compiler).toBeInstanceOf(Compiler); } }, function(compiler) { expect(compiler).toBe(this); expect(compiler).toBeInstanceOf(Compiler); } ] } }; webpack-4.30.0/test/configCases/optimization/named-modules/000077500000000000000000000000001345416772700237155ustar00rootroot00000000000000webpack-4.30.0/test/configCases/optimization/named-modules/files/000077500000000000000000000000001345416772700250175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/optimization/named-modules/files/file1.js000066400000000000000000000000341345416772700263520ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/named-modules/files/file2.js000066400000000000000000000000341345416772700263530ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/named-modules/files/file3.js000066400000000000000000000000341345416772700263540ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/named-modules/files/file4.js000066400000000000000000000000341345416772700263550ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/named-modules/files/file5.js000066400000000000000000000000341345416772700263560ustar00rootroot00000000000000module.exports = module.id; webpack-4.30.0/test/configCases/optimization/named-modules/index.js000066400000000000000000000004231345416772700253610ustar00rootroot00000000000000var path = require("path"); it("should have named modules ids", function() { for (var i = 1; i <= 5; i++) { var expectedModuleId = "file" + i + ".js"; var moduleId = require("./files/file" + i + ".js"); expect(path.basename(moduleId)).toBe(expectedModuleId); } }); webpack-4.30.0/test/configCases/optimization/named-modules/webpack.config.js000066400000000000000000000000771345416772700271370ustar00rootroot00000000000000module.exports = { optimization: { namedModules: true } }; webpack-4.30.0/test/configCases/output/000077500000000000000000000000001345416772700177755ustar00rootroot00000000000000webpack-4.30.0/test/configCases/output/function/000077500000000000000000000000001345416772700216225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/output/function/a.js000066400000000000000000000001331345416772700223750ustar00rootroot00000000000000it("should output correctly with a function for output.filename", (done) => { done(); }); webpack-4.30.0/test/configCases/output/function/b.js000066400000000000000000000001331345416772700223760ustar00rootroot00000000000000it("should output correctly with a function for output.filename", (done) => { done(); }); webpack-4.30.0/test/configCases/output/function/test.config.js000066400000000000000000000001341345416772700244010ustar00rootroot00000000000000module.exports = { findBundle: function() { return [ "./a.js", "./b.js" ]; } }; webpack-4.30.0/test/configCases/output/function/webpack.config.js000066400000000000000000000003011345416772700250320ustar00rootroot00000000000000module.exports = { entry() { return { a: "./a", b: "./b" }; }, output: { filename: data => { return data.chunk.name === "a" ? `${data.chunk.name}.js` : "[name].js"; } } }; webpack-4.30.0/test/configCases/output/string/000077500000000000000000000000001345416772700213035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/output/string/a.js000066400000000000000000000001311345416772700220540ustar00rootroot00000000000000it("should output correctly with a string for output.filename", (done) => { done(); }); webpack-4.30.0/test/configCases/output/string/test.config.js000066400000000000000000000001171345416772700240630ustar00rootroot00000000000000module.exports = { findBundle: function() { return [ "./a.js" ]; } }; webpack-4.30.0/test/configCases/output/string/webpack.config.js000066400000000000000000000001471345416772700245230ustar00rootroot00000000000000module.exports = { entry() { return { a: "./a" }; }, output: { filename: "[name].js" } }; webpack-4.30.0/test/configCases/parsing/000077500000000000000000000000001345416772700201005ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/context/000077500000000000000000000000001345416772700215645ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/context/index.js000066400000000000000000000005321345416772700232310ustar00rootroot00000000000000it("should automatically create contexts", function() { var template = "tmpl", templateFull = "./tmpl.js"; expect(require("../../../cases/parsing/context/templates/templateLoader")(templateFull)).toBe("test template"); expect(require("../../../cases/parsing/context/templates/templateLoaderIndirect")(templateFull)).toBe("test template"); }); webpack-4.30.0/test/configCases/parsing/context/warnings.js000066400000000000000000000001361345416772700237520ustar00rootroot00000000000000module.exports = [ [/Module parse failed/, /dump-file\.txt/, /templates sync \^\\\.\\\//] ]; webpack-4.30.0/test/configCases/parsing/context/webpack.config.js000066400000000000000000000002411345416772700247770ustar00rootroot00000000000000module.exports = { module: { unknownContextRegExp: /^\.\//, unknownContextCritical: false, exprContextRegExp: /^\.\//, exprContextCritical: false } }; webpack-4.30.0/test/configCases/parsing/extended-api/000077500000000000000000000000001345416772700224475ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/extended-api/index.js000066400000000000000000000004651345416772700241210ustar00rootroot00000000000000it("should have __webpack_hash__", function() { expect(__webpack_hash__).toBeTypeOf("string"); expect(__webpack_hash__).toMatch(/^[0-9a-f]{20}$/); }); it("should have __webpack_chunkname__", function() { expect(__webpack_chunkname__).toBeTypeOf("string"); expect(__webpack_chunkname__).toBe("other"); }); webpack-4.30.0/test/configCases/parsing/extended-api/webpack.config.js000066400000000000000000000002331345416772700256630ustar00rootroot00000000000000"use strict"; const webpack = require("../../../../"); module.exports = { entry: { other: "./index" }, plugins: [new webpack.ExtendedAPIPlugin()] }; webpack-4.30.0/test/configCases/parsing/harmony-global/000077500000000000000000000000001345416772700230135ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/harmony-global/index.js000066400000000000000000000002231345416772700244550ustar00rootroot00000000000000it("should be able to use global in a harmony module", function() { var x = require("./module1"); expect(x.default === global).toBeTruthy(); }); webpack-4.30.0/test/configCases/parsing/harmony-global/module.js000066400000000000000000000000221345416772700246300ustar00rootroot00000000000000export default 1; webpack-4.30.0/test/configCases/parsing/harmony-global/module1.js000066400000000000000000000001711345416772700247160ustar00rootroot00000000000000var freeGlobal = typeof global === "object" && global && global.Object === Object && global; export default freeGlobal; webpack-4.30.0/test/configCases/parsing/harmony-global/webpack.config.js000066400000000000000000000001101345416772700262210ustar00rootroot00000000000000module.exports = { target: "web", performance: { hints: false } }; webpack-4.30.0/test/configCases/parsing/harmony-this-concat/000077500000000000000000000000001345416772700237675ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/harmony-this-concat/abc.js000066400000000000000000000002651345416772700250550ustar00rootroot00000000000000function returnThis() { if(typeof this === "undefined") return "undefined"; return this; } var a = returnThis; var b = returnThis; export { a, b } export default returnThis; webpack-4.30.0/test/configCases/parsing/harmony-this-concat/index.js000066400000000000000000000013101345416772700254270ustar00rootroot00000000000000"use strict"; import d, {a, b as B} from "./abc"; import * as abc from "./abc"; function x() { throw new Error("should not be executed"); } it("should have this = undefined on imported non-strict functions", function() { x expect(d()).toBe("undefined"); x expect(a()).toBe("undefined"); x expect(B()).toBe("undefined"); x expect(abc.a()).toMatchObject({}); x var thing = abc.a(); expect(Object.keys(thing)).toEqual(["a", "b", "default"]); }); import C2, { C } from "./new"; import * as New from "./new"; it("should be possible to use new correctly", function() { x expect(new C()).toEqual({ok: true}); x expect(new C2()).toEqual({ok: true}); x expect(new New.C()).toEqual({ok: true}); }); webpack-4.30.0/test/configCases/parsing/harmony-this-concat/new.js000066400000000000000000000001411345416772700251120ustar00rootroot00000000000000function C() { this.ok = this.pok; } C.prototype.pok = true; export default C; export { C }; webpack-4.30.0/test/configCases/parsing/harmony-this-concat/webpack.config.js000066400000000000000000000002541345416772700272060ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { module: { strictThisContextOnImports: true }, plugins: [new webpack.optimize.ModuleConcatenationPlugin()] }; webpack-4.30.0/test/configCases/parsing/harmony-this/000077500000000000000000000000001345416772700225225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/harmony-this/abc.js000066400000000000000000000017421345416772700236110ustar00rootroot00000000000000function returnThis() { if (typeof this === "undefined") return "undefined"; return this; } var a = returnThis; var b = returnThis; export { a, b }; export const that = this; export const returnThisArrow = () => this; export const returnThisMember = () => this.a; export class C { constructor() { this.x = "bar"; } foo() { return this.x; } bar(x = this.x) { return x; } } export const extendThisClass = () => { return class extends this.Buffer {}; }; export function D() { this.prop = () => "ok"; } // See https://github.com/webpack/webpack/issues/6379 export const E = { x: "bar", foo(x = this.x) { return x; } }; // See https://github.com/webpack/webpack/issues/6967 export const F = function() { return this; }.call("ok"); export function f1(x = this.x) { return x; } export const f2 = function(x = this.x) { return x; }; export const f3 = (x = this) => x; export function G(x) { this.x = x; this.getX = (y = this.x) => y; } export default returnThis; webpack-4.30.0/test/configCases/parsing/harmony-this/index.js000066400000000000000000000036141345416772700241730ustar00rootroot00000000000000"use strict"; import {extendThisClass, returnThisArrow, returnThisMember, that} from "./abc"; import d, {a, b as B, C as _C, D as _D, E, F, f1, f2, f3, G} from "./abc"; import {bindThis, callThis, applyThis} from "./issue-7213"; import * as abc from "./abc"; it("should have this = undefined on harmony modules", () => { expect((typeof that)).toBe("undefined"); expect((typeof abc.that)).toBe("undefined"); expect((typeof returnThisArrow())).toBe("undefined"); expect((typeof abc.returnThisArrow())).toBe("undefined"); expect(function() { returnThisMember(); }).toThrowError(); expect(function() { abc.returnThisMember(); }).toThrowError(); expect(function() { extendThisClass(); }).toThrowError(); }); it("should not break classes and functions", () => { expect((new _C).foo()).toBe("bar"); expect((new _C).bar()).toBe("bar"); expect((new _D).prop()).toBe("ok"); expect(E.foo()).toBe("bar"); expect(F).toBe("ok"); expect(f1.call({x: "f1"})).toBe("f1"); expect(f2.call({x: "f2"})).toBe("f2"); expect(f3.call("f3")).toBe(undefined); expect(f3()).toBe(undefined); expect((new G("ok")).getX()).toBe("ok"); }); function x() { throw new Error("should not be executed"); } it("should have this = undefined on imported non-strict functions", () => { x expect(d()).toBe("undefined"); x expect(a()).toBe("undefined"); x expect(B()).toBe("undefined"); x expect(abc.a()).toBeTypeOf("object"); x var thing = abc.a(); expect(Object.keys(thing)).toEqual(Object.keys(abc)); }); import C2, { C } from "./new"; import * as New from "./new"; it("should be possible to use new correctly", () => { x expect(new C()).toEqual({ok: true}); x expect(new C2()).toEqual({ok: true}); x expect(new New.C()).toEqual({ok: true}); }); it("should not break Babel arrow function transform", () => { expect(bindThis()).toBe(undefined); expect(callThis).toBe(undefined); expect(applyThis).toBe(undefined); }); webpack-4.30.0/test/configCases/parsing/harmony-this/issue-7213.js000066400000000000000000000006441345416772700246060ustar00rootroot00000000000000// This helper is taken from Babel function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } let _this = this; export let bindThis = function() { _newArrowCheck(this, _this); return this }.bind(this); export let callThis = function() { return this }.call(this) export let applyThis = function() { return this }.apply(this) webpack-4.30.0/test/configCases/parsing/harmony-this/new.js000066400000000000000000000001411345416772700236450ustar00rootroot00000000000000function C() { this.ok = this.pok; } C.prototype.pok = true; export default C; export { C }; webpack-4.30.0/test/configCases/parsing/harmony-this/webpack.config.js000066400000000000000000000001071345416772700257360ustar00rootroot00000000000000module.exports = { module: { strictThisContextOnImports: true } }; webpack-4.30.0/test/configCases/parsing/import-ignore/000077500000000000000000000000001345416772700226735ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/import-ignore/index.js000066400000000000000000000005301345416772700243360ustar00rootroot00000000000000const fs = require("fs"); const path = require("path"); it("should be able to ignore import()", () => { const source = fs.readFileSync(path.join(__dirname, "bundle1.js"), "utf-8"); expect(source).toMatch(`import(/* webpackIgnore: true */ "./other2.js")`); expect(source).not.toMatch(`import(/* webpackIgnore: false */ "./other3.js")`); }); webpack-4.30.0/test/configCases/parsing/import-ignore/other.js000066400000000000000000000001431345416772700243500ustar00rootroot00000000000000import(/* webpackIgnore: true */ "./other2.js"); import(/* webpackIgnore: false */ "./other3.js"); webpack-4.30.0/test/configCases/parsing/import-ignore/other2.js000066400000000000000000000000311345416772700244260ustar00rootroot00000000000000export default "other2"; webpack-4.30.0/test/configCases/parsing/import-ignore/other3.js000066400000000000000000000000311345416772700244270ustar00rootroot00000000000000export default "other3"; webpack-4.30.0/test/configCases/parsing/import-ignore/webpack.config.js000066400000000000000000000002331345416772700261070ustar00rootroot00000000000000module.exports = { entry: { bundle0: "./index.js", bundle1: "./other.js" }, output: { filename: "[name].js" }, node: { __dirname: false } }; webpack-4.30.0/test/configCases/parsing/issue-336/000077500000000000000000000000001345416772700215415ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-336/index.js000066400000000000000000000001671345416772700232120ustar00rootroot00000000000000it("should provide a module to a free var in a var decl", function() { var x = aaa.test; expect(x).toBe("test"); }); webpack-4.30.0/test/configCases/parsing/issue-336/node_modules/000077500000000000000000000000001345416772700242165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-336/node_modules/aaa.js000066400000000000000000000000431345416772700252730ustar00rootroot00000000000000module.exports = { test: "test" };webpack-4.30.0/test/configCases/parsing/issue-336/webpack.config.js000066400000000000000000000002141345416772700247540ustar00rootroot00000000000000var ProvidePlugin = require("../../../../lib/ProvidePlugin"); module.exports = { plugins: [ new ProvidePlugin({ aaa: "aaa" }) ] }; webpack-4.30.0/test/configCases/parsing/issue-4857/000077500000000000000000000000001345416772700216355ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-4857/index.js000066400000000000000000000026631345416772700233110ustar00rootroot00000000000000it("should transpile unreachable branches", () => { let count = 0; // BlockStatement if(true) { count++; } else { import("NOT_REACHABLE"); } if(false) { import("NOT_REACHABLE"); } else { count++; } // ExpressionStatement if(true) count++; else import("NOT_REACHABLE"); if(false) import("NOT_REACHABLE"); else count++; // ConditionalExpression true ? count++ : import("NOT_REACHABLE"); false ? import("NOT_REACHABLE") : count++; expect(count).toBe(6); }); it("should not remove hoisted variable declarations", () => { if(false) { var a, [,,b,] = [], {c, D: d, ["E"]: e = 2} = {}; var [{["_"]: f}, ...g] = []; do { switch(g) { default: var h; break; } loop: for(var i;;) for(var j in {}) for(var k of {}) break; try { var l; } catch(e) { var m; } finally { var n; } { var o; } } while(true); with (o) { var withVar; } } expect(() => { a; b; c; d; e; f; g; h; i; j; k; l; m; n; o; }).not.toThrowError(); expect(() => { withVar; }).toThrowError(); }); it("should not remove hoisted function declarations in loose mode", () => { if(false) { function funcDecl() {} } expect(() => { funcDecl; }).not.toThrowError(); }); it("should remove hoisted function declarations in strict mode", () => { "use strict"; if(false) { function funcDecl() {} } expect(() => { funcDecl; }).toThrowError(); }); webpack-4.30.0/test/configCases/parsing/issue-4857/webpack.config.js000066400000000000000000000000741345416772700250540ustar00rootroot00000000000000module.exports = { optimization: { minimize: false } }; webpack-4.30.0/test/configCases/parsing/issue-5624/000077500000000000000000000000001345416772700216265ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-5624/index.js000066400000000000000000000004041345416772700232710ustar00rootroot00000000000000import * as M from "./module"; it("should allow conditionals as callee", function() { var x = (true ? M.fn : M.fn)(); expect(x).toBe("ok"); }); it("should allow conditionals as object", function() { var x = (true ? M : M).fn(); expect(x).toBe("ok"); }); webpack-4.30.0/test/configCases/parsing/issue-5624/module.js000066400000000000000000000000471345416772700234520ustar00rootroot00000000000000export function fn() { return "ok"; } webpack-4.30.0/test/configCases/parsing/issue-5624/webpack.config.js000066400000000000000000000001071345416772700250420ustar00rootroot00000000000000module.exports = { module: { strictThisContextOnImports: true } }; webpack-4.30.0/test/configCases/parsing/issue-8293/000077500000000000000000000000001345416772700216335ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/amd-define.js000066400000000000000000000006011345416772700241570ustar00rootroot00000000000000define([ `./${CONST_PREFIX0}/${DEFINED_EXPRESSION}/${CONST_SUFFIX0}`, window.baz ? `./${CONST_PREFIX1}/${DEFINED_EXPRESSION}/${CONST_SUFFIX1}` : `./${CONST_PREFIX2}/${DEFINED_EXPRESSION}/${CONST_SUFFIX2}`, typeof require === "function" ? `./${CONST_PREFIX3}/${DEFINED_EXPRESSION}/${CONST_SUFFIX3}` : `./${CONST_PREFIX4}/${DEFINED_EXPRESSION}/${CONST_SUFFIX4}` ], () => {}); webpack-4.30.0/test/configCases/parsing/issue-8293/amd-require.js000066400000000000000000000006021345416772700244020ustar00rootroot00000000000000require([ `./${CONST_PREFIX0}/${DEFINED_EXPRESSION}/${CONST_SUFFIX0}`, window.baz ? `./${CONST_PREFIX1}/${DEFINED_EXPRESSION}/${CONST_SUFFIX1}` : `./${CONST_PREFIX2}/${DEFINED_EXPRESSION}/${CONST_SUFFIX2}`, typeof require === "function" ? `./${CONST_PREFIX3}/${DEFINED_EXPRESSION}/${CONST_SUFFIX3}` : `./${CONST_PREFIX4}/${DEFINED_EXPRESSION}/${CONST_SUFFIX4}` ], () => {}); webpack-4.30.0/test/configCases/parsing/issue-8293/commonjs.js000066400000000000000000000005771345416772700240270ustar00rootroot00000000000000require(`./${CONST_PREFIX0}/${DEFINED_EXPRESSION}/${CONST_SUFFIX0}`); require(window.baz ? `./${CONST_PREFIX1}/${DEFINED_EXPRESSION}/${CONST_SUFFIX1}` : `./${CONST_PREFIX2}/${DEFINED_EXPRESSION}/${CONST_SUFFIX2}`); require(typeof require === "function" ? `./${CONST_PREFIX3}/${DEFINED_EXPRESSION}/${CONST_SUFFIX3}` : `./${CONST_PREFIX4}/${DEFINED_EXPRESSION}/${CONST_SUFFIX4}`); webpack-4.30.0/test/configCases/parsing/issue-8293/import.js000066400000000000000000000005761345416772700235130ustar00rootroot00000000000000import(`./${CONST_PREFIX0}/${DEFINED_EXPRESSION}/${CONST_SUFFIX0}`); import(window.baz ? `./${CONST_PREFIX1}/${DEFINED_EXPRESSION}/${CONST_SUFFIX1}` : `./${CONST_PREFIX2}/${DEFINED_EXPRESSION}/${CONST_SUFFIX2}`); import(typeof require === "function" ? `./${CONST_PREFIX3}/${DEFINED_EXPRESSION}/${CONST_SUFFIX3}` : `./${CONST_PREFIX4}/${DEFINED_EXPRESSION}/${CONST_SUFFIX4}`); webpack-4.30.0/test/configCases/parsing/issue-8293/index.js000066400000000000000000000026421345416772700233040ustar00rootroot00000000000000const fs = require("fs"); const path = require("path"); ["import", "amd-require", "amd-define", "commonjs", "require.resolve"].forEach( method => { it(`should be able to replace ${method} param in DefinePlugin`, function() { const source = fs.readFileSync( path.join(__dirname, `bundle-${method}.js`), "utf-8" ); expect(source).toContain(`\`./\${foobar}/suffix0`); expect(source).toContain(`\`./\${foobar}/suffix3`); expect(source).not.toContain(`\`./\${foobar}/suffix4`); expect(source).not.toContain(`\`./\${DEFINED_EXPRESSION}/\${CONST_SUFFIX4}`); expect(source).not.toContain(`typeof require ===`); }); } ); ["import", "commonjs"].forEach(method => { it(`should be able to replace ${method} param in DefinePlugin for conditional expression`, function() { const source = fs.readFileSync( path.join(__dirname, `bundle-${method}.js`), "utf-8" ); expect(source).toContain(`\`./\${"prefix1"}/\${foobar}/\${"suffix1"}`); expect(source).toContain(`\`./\${"prefix2"}/\${foobar}/\${"suffix2"}`); }); }); ["amd-require", "amd-define", "require.resolve"].forEach(method => { it(`should be able to replace ${method} param in DefinePlugin for conditional expression`, function() { const source = fs.readFileSync( path.join(__dirname, `bundle-${method}.js`), "utf-8" ); expect(source).toContain(`\`./\${foobar}/suffix1`); expect(source).toContain(`\`./\${foobar}/suffix2`); }); }); webpack-4.30.0/test/configCases/parsing/issue-8293/prefix0/000077500000000000000000000000001345416772700232105ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix0/folder/000077500000000000000000000000001345416772700244635ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix0/folder/suffix0.js000066400000000000000000000000431345416772700264020ustar00rootroot00000000000000export const test = 'test code 0'; webpack-4.30.0/test/configCases/parsing/issue-8293/prefix1/000077500000000000000000000000001345416772700232115ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix1/folder/000077500000000000000000000000001345416772700244645ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix1/folder/suffix1.js000066400000000000000000000000431345416772700264040ustar00rootroot00000000000000export const test = 'test code 1'; webpack-4.30.0/test/configCases/parsing/issue-8293/prefix2/000077500000000000000000000000001345416772700232125ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix2/folder/000077500000000000000000000000001345416772700244655ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix2/folder/suffix2.js000066400000000000000000000000431345416772700264060ustar00rootroot00000000000000export const test = 'test code 2'; webpack-4.30.0/test/configCases/parsing/issue-8293/prefix3/000077500000000000000000000000001345416772700232135ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix3/folder/000077500000000000000000000000001345416772700244665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix3/folder/suffix3.js000066400000000000000000000000431345416772700264100ustar00rootroot00000000000000export const test = 'test code 3'; webpack-4.30.0/test/configCases/parsing/issue-8293/prefix4/000077500000000000000000000000001345416772700232145ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix4/folder/000077500000000000000000000000001345416772700244675ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/issue-8293/prefix4/folder/suffix4.js000066400000000000000000000000431345416772700264120ustar00rootroot00000000000000export const test = 'test code 4'; webpack-4.30.0/test/configCases/parsing/issue-8293/require.resolve.js000066400000000000000000000006411345416772700253240ustar00rootroot00000000000000require.resolve(`./${CONST_PREFIX0}/${DEFINED_EXPRESSION}/${CONST_SUFFIX0}`); require.resolve( window.baz ? `./${CONST_PREFIX1}/${DEFINED_EXPRESSION}/${CONST_SUFFIX1}` : `./${CONST_PREFIX2}/${DEFINED_EXPRESSION}/${CONST_SUFFIX2}` ); require.resolve( typeof require === "function" ? `./${CONST_PREFIX3}/${DEFINED_EXPRESSION}/${CONST_SUFFIX3}` : `./${CONST_PREFIX4}/${DEFINED_EXPRESSION}/${CONST_SUFFIX4}` ); webpack-4.30.0/test/configCases/parsing/issue-8293/webpack.config.js000066400000000000000000000016761345416772700250630ustar00rootroot00000000000000const webpack = require("../../../../"); module.exports = { entry: { bundle0: "./index.js", "bundle-import": "./import.js", "bundle-amd-require": "./amd-define.js", "bundle-amd-define": "./amd-require.js", "bundle-commonjs": "./commonjs.js", "bundle-require.resolve": "./require.resolve.js" }, output: { filename: "[name].js" }, module: { exprContextCritical: false }, node: { __dirname: false }, plugins: [ new webpack.DefinePlugin({ CONST_PREFIX0: JSON.stringify("prefix0"), CONST_SUFFIX0: JSON.stringify("suffix0"), CONST_PREFIX1: JSON.stringify("prefix1"), CONST_SUFFIX1: JSON.stringify("suffix1"), CONST_PREFIX2: JSON.stringify("prefix2"), CONST_SUFFIX2: JSON.stringify("suffix2"), CONST_PREFIX3: JSON.stringify("prefix3"), CONST_SUFFIX3: JSON.stringify("suffix3"), CONST_PREFIX4: JSON.stringify("prefix4"), CONST_SUFFIX4: JSON.stringify("suffix4"), DEFINED_EXPRESSION: "foobar" }) ] }; webpack-4.30.0/test/configCases/parsing/node-source-plugin-off/000077500000000000000000000000001345416772700243675ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/node-source-plugin-off/index.js000066400000000000000000000002001345416772700260240ustar00rootroot00000000000000it("should not load node-libs-browser when node option is false", function() { expect((typeof process)).toBe("undefined"); }); webpack-4.30.0/test/configCases/parsing/node-source-plugin-off/webpack.config.js000066400000000000000000000000631345416772700276040ustar00rootroot00000000000000module.exports = { target: "web", node: false }; webpack-4.30.0/test/configCases/parsing/node-source-plugin/000077500000000000000000000000001345416772700236175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/node-source-plugin/index.js000066400000000000000000000001621345416772700252630ustar00rootroot00000000000000it("should add node-libs-browser to target web by default", function() { expect(process.browser).toBe(true); }); webpack-4.30.0/test/configCases/parsing/node-source-plugin/webpack.config.js000066400000000000000000000001021345416772700270260ustar00rootroot00000000000000module.exports = { target: "web", node: { process: true } }; webpack-4.30.0/test/configCases/parsing/relative-filedirname/000077500000000000000000000000001345416772700241705ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/relative-filedirname/dir/000077500000000000000000000000001345416772700247465ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/relative-filedirname/dir/file.js000066400000000000000000000000741345416772700262240ustar00rootroot00000000000000exports.filename = __filename; exports.dirname = __dirname; webpack-4.30.0/test/configCases/parsing/relative-filedirname/index.js000066400000000000000000000003741345416772700256410ustar00rootroot00000000000000it("should define __dirname and __filename", function() { expect(__dirname).toBe(""); expect(__filename).toBe("index.js"); expect(require("./dir/file").dirname).toBe("dir"); expect(require("./dir/file").filename).toMatch(/^dir[\\\/]file.js$/); }); webpack-4.30.0/test/configCases/parsing/relative-filedirname/webpack.config.js000066400000000000000000000001101345416772700273760ustar00rootroot00000000000000module.exports = { node: { __filename: true, __dirname: true } }; webpack-4.30.0/test/configCases/parsing/require.main/000077500000000000000000000000001345416772700224775ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/require.main/index.js000066400000000000000000000001261345416772700241430ustar00rootroot00000000000000it("should define require.main", function() { expect(require.main).toBe(module); }); webpack-4.30.0/test/configCases/parsing/require.main/webpack.config.js000066400000000000000000000000251345416772700257120ustar00rootroot00000000000000module.exports = {}; webpack-4.30.0/test/configCases/parsing/system.import/000077500000000000000000000000001345416772700227355ustar00rootroot00000000000000webpack-4.30.0/test/configCases/parsing/system.import/index.js000066400000000000000000000014021345416772700243770ustar00rootroot00000000000000it("should answer typeof System correctly", () => { if(__SYSTEM__ === false) { expect((typeof System)).toBe("undefined"); } else { expect((typeof System)).toBe("object"); } }); it("should answer typeof System.import correctly", () => { if(__SYSTEM__ === false) { expect(() => { typeof System.import; }).toThrowError(); } else { expect((typeof System.import)).toBe("function"); } }); it("should be able to use System.import()", done => { try { System.import("./module").then(mod => { if(__SYSTEM__ === false) { done(new Error("System.import should not be parsed")); } else { expect(mod).toEqual(nsObj({ default: "ok" })); done(); } }); } catch(e) { if(__SYSTEM__ === false) { done(); } else { done(e); } } }); webpack-4.30.0/test/configCases/parsing/system.import/module.js000066400000000000000000000000251345416772700245550ustar00rootroot00000000000000export default "ok"; webpack-4.30.0/test/configCases/parsing/system.import/warnings.js000066400000000000000000000001141345416772700251170ustar00rootroot00000000000000module.exports = [ [/system_undef/, /System\.import\(\) is deprecated/] ]; webpack-4.30.0/test/configCases/parsing/system.import/webpack.config.js000066400000000000000000000006611345416772700261560ustar00rootroot00000000000000const webpack = require("../../../../"); function createConfig(system) { const systemString = "" + system; return { name: `system_${systemString}`, module: { rules: [ { test: /\.js$/, parser: { system } } ] }, plugins: [ new webpack.DefinePlugin({ __SYSTEM__: systemString }) ] }; } module.exports = [ createConfig(undefined), createConfig(true), createConfig(false) ]; webpack-4.30.0/test/configCases/performance/000077500000000000000000000000001345416772700207365ustar00rootroot00000000000000webpack-4.30.0/test/configCases/performance/many-async-imports/000077500000000000000000000000001345416772700245105ustar00rootroot00000000000000webpack-4.30.0/test/configCases/performance/many-async-imports/index.js000066400000000000000000000002511345416772700261530ustar00rootroot00000000000000import promise from "./start"; it("should compile a module with many async imports in acceptable time", function(done) { promise.then(() => done(), e => done(e)); }); webpack-4.30.0/test/configCases/performance/many-async-imports/leaf.js000066400000000000000000000000231345416772700257500ustar00rootroot00000000000000import("./start"); webpack-4.30.0/test/configCases/performance/many-async-imports/reexport.loader.js000066400000000000000000000003431345416772700301630ustar00rootroot00000000000000module.exports = function() { var str = "export default Promise.all([\n"; for(var i = 0; i < 6; i++) { for(var j = 0; j < 2; j++) { str += `import("./reexport.loader.js!?${i}"),\n`; } } str += "]);"; return str; }; webpack-4.30.0/test/configCases/performance/many-async-imports/start.js000066400000000000000000000000611345416772700262000ustar00rootroot00000000000000export { default } from "./reexport.loader.js!"; webpack-4.30.0/test/configCases/performance/many-async-imports/test.config.js000066400000000000000000000000461345416772700272710ustar00rootroot00000000000000module.exports = { timeout: 10000 }; webpack-4.30.0/test/configCases/performance/many-async-imports/test.filter.js000066400000000000000000000001211345416772700273030ustar00rootroot00000000000000module.exports = function(config) { return !/^v(4|6)/.test(process.version); }; webpack-4.30.0/test/configCases/performance/many-async-imports/webpack.config.js000066400000000000000000000000741345416772700277270ustar00rootroot00000000000000module.exports = { optimization: { minimize: false } }; webpack-4.30.0/test/configCases/performance/many-exports/000077500000000000000000000000001345416772700234045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/performance/many-exports/file.loader.js000066400000000000000000000002071345416772700261250ustar00rootroot00000000000000module.exports = function() { var str = ""; for(var i = 0; i < 1000; i++) { str += `export var a${i} = ${i};\n`; } return str; } webpack-4.30.0/test/configCases/performance/many-exports/index.js000066400000000000000000000002411345416772700250460ustar00rootroot00000000000000import sum from "./reexport.loader.js!"; it("should compile a module with many harmony exports in acceptable time", function() { expect(sum).toBe(499500); }); webpack-4.30.0/test/configCases/performance/many-exports/reexport.loader.js000066400000000000000000000003441345416772700270600ustar00rootroot00000000000000module.exports = function() { var str = "import * as i from \"./file.loader.js!\";\n"; str += "var sum = 0;\n"; for(var i = 0; i < 1000; i++) { str += `sum += i.a${i};\n`; } str += "export default sum;\n"; return str; } webpack-4.30.0/test/configCases/performance/many-exports/test.config.js000066400000000000000000000000461345416772700261650ustar00rootroot00000000000000module.exports = { timeout: 10000 }; webpack-4.30.0/test/configCases/performance/many-exports/test.filter.js000066400000000000000000000001211345416772700261770ustar00rootroot00000000000000module.exports = function(config) { return !/^v(4|6)/.test(process.version); }; webpack-4.30.0/test/configCases/performance/many-exports/webpack.config.js000066400000000000000000000000741345416772700266230ustar00rootroot00000000000000module.exports = { optimization: { minimize: false } }; webpack-4.30.0/test/configCases/plugins/000077500000000000000000000000001345416772700201165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/banner-plugin-hashing/000077500000000000000000000000001345416772700242765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/banner-plugin-hashing/index.js000066400000000000000000000024071345416772700257460ustar00rootroot00000000000000const parseBanner = (banner) => { return banner .slice(4,-3) .split(", ") .map(n => n.split(":")) .reduce((acc, val) => { acc[val[0]] = val[1]; return acc; }, {}); }; var source = require("fs") .readFileSync(__filename, "utf-8") .split("\n") .slice(0,1)[0]; const banner = parseBanner(source) const REGEXP_HASH = /^[A-Za-z0-9]{20}$/ it("should interpolate file hash in chunk banner", () => { expect(REGEXP_HASH.test(banner["hash"])).toBe(true); }); it("should interpolate chunkHash in chunk banner", () => { expect(REGEXP_HASH.test(banner["chunkhash"])).toBe(true); }); it("should interpolate file into chunk banner", () => { expect(banner["file"]).toBe("dist/banner.js"); }); it("should interpolate name in chunk banner", () => { expect(banner["name"]).toBe("dist/banner"); }); it("should interpolate basename in chunk banner", () => { expect(banner["filebase"]).toBe("banner.js"); }); it("should interpolate query in chunk banner", () => { expect(banner["query"]).toBe("?value"); }); it("should parse entry into file in chunk banner", () => { expect(banner["file"]).not.toBe(banner["filebase"]); }); it("should parse entry into name in chunk banner", () => { expect(banner["filebase"]).not.toBe(banner["name"]); }); require.include("./test.js"); webpack-4.30.0/test/configCases/plugins/banner-plugin-hashing/test.config.js000066400000000000000000000001631345416772700270570ustar00rootroot00000000000000var fs = require("fs"); module.exports = { findBundle: function(i, options) { return "./dist/banner.js"; } }; webpack-4.30.0/test/configCases/plugins/banner-plugin-hashing/test.js000066400000000000000000000000451345416772700256120ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-4.30.0/test/configCases/plugins/banner-plugin-hashing/vendors.js000066400000000000000000000000451345416772700263130ustar00rootroot00000000000000var bar = {}; module.exports = bar; webpack-4.30.0/test/configCases/plugins/banner-plugin-hashing/webpack.config.js000066400000000000000000000006371345416772700275220ustar00rootroot00000000000000"use strict"; const webpack = require("../../../../"); module.exports = { node: { __dirname: false, __filename: false }, entry: { "dist/banner": ["./index.js"], vendors: ["./vendors.js"] }, output: { filename: "[name].js?value" }, plugins: [ new webpack.BannerPlugin({ banner: "hash:[hash], chunkhash:[chunkhash], name:[name], filebase:[filebase], query:[query], file:[file]" }) ] }; webpack-4.30.0/test/configCases/plugins/banner-plugin/000077500000000000000000000000001345416772700226575ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/banner-plugin/index.js000066400000000000000000000011231345416772700243210ustar00rootroot00000000000000const fs = require("fs"); const path = require("path"); it("should contain banner in bundle0 chunk", () => { const source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch("A test value"); expect(source).toMatch("banner is a string"); expect(source).toMatch("banner is a function"); expect(source).toMatch("/*!\n * multiline\n * banner\n * bundle0\n */"); }); it("should not contain banner in vendors chunk", () => { const source = fs.readFileSync(path.join(__dirname, "vendors.js"), "utf-8"); expect(source).not.toMatch("A test value"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/plugins/banner-plugin/test.js000066400000000000000000000000451345416772700241730ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-4.30.0/test/configCases/plugins/banner-plugin/vendors.js000066400000000000000000000000451345416772700246740ustar00rootroot00000000000000var bar = {}; module.exports = bar; webpack-4.30.0/test/configCases/plugins/banner-plugin/webpack.config.js000066400000000000000000000010211345416772700260670ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { node: { __dirname: false, __filename: false }, entry: { bundle0: ["./index.js"], vendors: ["./vendors.js"] }, output: { filename: "[name].js" }, plugins: [ new webpack.BannerPlugin("banner is a string"), new webpack.BannerPlugin(() => "banner is a function"), new webpack.BannerPlugin({ banner: "A test value", exclude: ["vendors.js"] }), new webpack.BannerPlugin({ banner: ({ chunk }) => `multiline\nbanner\n${chunk.name}` }) ] }; webpack-4.30.0/test/configCases/plugins/define-plugin/000077500000000000000000000000001345416772700226445ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/define-plugin/dir/000077500000000000000000000000001345416772700234225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/define-plugin/dir/a.js000066400000000000000000000000001345416772700241660ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/define-plugin/index.js000066400000000000000000000106061345416772700243140ustar00rootroot00000000000000/* globals it, should */ it("should define FALSE", function() { expect(FALSE).toBe(false); expect((typeof TRUE)).toBe("boolean"); var x = require(FALSE ? "fail" : "./dir/a"); var y = FALSE ? require("fail") : require("./dir/a"); }); it("should define CODE", function() { expect(CODE).toBe(3); expect((typeof CODE)).toBe("number"); if(CODE !== 3) require("fail"); if(typeof CODE !== "number") require("fail"); }); it("should define FUNCTION", function() { expect((FUNCTION(5))).toBe(6); expect((typeof FUNCTION)).toBe("function"); if(typeof FUNCTION !== "function") require("fail"); }); it("should define UNDEFINED", function() { expect((typeof UNDEFINED)).toBe("undefined"); if(typeof UNDEFINED !== "undefined") require("fail"); }); it("should define REGEXP", function() { expect(REGEXP.toString()).toBe("/abc/i"); expect((typeof REGEXP)).toBe("object"); if(typeof REGEXP !== "object") require("fail"); }); it("should define OBJECT", function() { var o = OBJECT; expect(o.SUB.FUNCTION(10)).toBe(11); }); it("should define OBJECT.SUB.CODE", function() { expect((typeof OBJECT.SUB.CODE)).toBe("number"); expect(OBJECT.SUB.CODE).toBe(3); if(OBJECT.SUB.CODE !== 3) require("fail"); if(typeof OBJECT.SUB.CODE !== "number") require("fail"); (function(sub) { // should not crash expect(sub.CODE).toBe(3); }(OBJECT.SUB)); }); it("should define OBJECT.SUB.STRING", function() { expect((typeof OBJECT.SUB.STRING)).toBe("string"); expect(OBJECT.SUB.STRING).toBe("string"); if(OBJECT.SUB.STRING !== "string") require("fail"); if(typeof OBJECT.SUB.STRING !== "string") require("fail"); (function(sub) { // should not crash expect(sub.STRING).toBe("string"); }(OBJECT.SUB)); }); it("should define process.env.DEFINED_NESTED_KEY", function() { expect((process.env.DEFINED_NESTED_KEY)).toBe(5); expect((typeof process.env.DEFINED_NESTED_KEY)).toBe("number"); if(process.env.DEFINED_NESTED_KEY !== 5) require("fail"); if(typeof process.env.DEFINED_NESTED_KEY !== "number") require("fail"); var x = process.env.DEFINED_NESTED_KEY; expect(x).toBe(5); var indirect = process.env; expect((indirect.DEFINED_NESTED_KEY)).toBe(5); (function(env) { expect((env.DEFINED_NESTED_KEY)).toBe(5); expect((typeof env.DEFINED_NESTED_KEY)).toBe("number"); if(env.DEFINED_NESTED_KEY !== 5) require("fail"); if(typeof env.DEFINED_NESTED_KEY !== "number") require("fail"); var x = env.DEFINED_NESTED_KEY; expect(x).toBe(5); }(process.env)); }); it("should define process.env.DEFINED_NESTED_KEY_STRING", function() { if(process.env.DEFINED_NESTED_KEY_STRING !== "string") require("fail"); }); it("should assign to process.env", function() { process.env.TEST = "test"; expect(process.env.TEST).toBe("test"); }); it("should not have brackets on start", function() { function f() { throw new Error("should not be called"); } f // <- no semicolon here OBJECT; }); it("should not explode on recursive typeof calls", function() { expect(typeof wurst).toEqual("undefined"); // <- is recursively defined in config }); it("should not explode on recursive statements", function() { expect(function() { wurst; // <- is recursively defined in config }).toThrowError("suppe is not defined"); }); it("should evaluate composed expressions (issue 5100)", function() { if(!module.hot && process.env.DEFINED_NESTED_KEY_STRING === "string") { // ok } else { require("fail"); } }); it("should follow renamings in var (issue 5215)", function() { var _process$env = process.env, TEST = _process$env.TEST, DEFINED_NESTED_KEY = _process$env.DEFINED_NESTED_KEY; expect(TEST).toBe("test"); expect(DEFINED_NESTED_KEY).toBe(5); }); it("should check that runtimeValue callback argument is a module", function() { expect(RUNTIMEVALUE_CALLBACK_ARGUMENT_IS_A_MODULE).toEqual(true); }); it("should expand properly", function() { const a = require("./dir/a"); var tmp = ''; expect(require('./dir/' + A_DOT_J + tmp + 's')).toBe(a); expect(require('./dir/' + tmp + A_DOT_J + 's')).toBe(a); expect(require('./dir/' + tmp + A_DOT_J + tmp + 's')).toBe(a); expect(require('./dir/' + tmp + A_DOT_J + (tmp + 's'))).toBe(a); expect(require('./dir/' + tmp + (A_DOT_J + tmp + 's'))).toBe(a); expect(require('./dir/' + tmp + (A_DOT_J + tmp) + 's')).toBe(a); expect(require('./dir/' + (tmp + A_DOT_J + tmp + 's'))).toBe(a); expect(require('./dir/' + (tmp + A_DOT_J + tmp) + 's')).toBe(a); expect(require('./dir/' + (tmp + A_DOT_J) + tmp + 's')).toBe(a); }); webpack-4.30.0/test/configCases/plugins/define-plugin/webpack.config.js000066400000000000000000000016621345416772700260670ustar00rootroot00000000000000var DefinePlugin = require("../../../../lib/DefinePlugin"); const Module = require("../../../../lib/Module"); module.exports = { plugins: [ new DefinePlugin({ TRUE: true, FALSE: false, UNDEFINED: undefined, FUNCTION: /* istanbul ignore next */ function(a) { return a + 1; }, CODE: "(1+2)", REGEXP: /abc/i, OBJECT: { SUB: { UNDEFINED: undefined, FUNCTION: /* istanbul ignore next */ function(a) { return a + 1; }, CODE: "(1+2)", REGEXP: /abc/i, STRING: JSON.stringify("string") } }, "process.env.DEFINED_NESTED_KEY": 5, "process.env.DEFINED_NESTED_KEY_STRING": '"string"', "typeof wurst": "typeof suppe", "typeof suppe": "typeof wurst", wurst: "suppe", suppe: "wurst", RUNTIMEVALUE_CALLBACK_ARGUMENT_IS_A_MODULE: DefinePlugin.runtimeValue( function({ module }) { return module instanceof Module; } ), A_DOT_J: '"a.j"' }) ] }; webpack-4.30.0/test/configCases/plugins/environment-plugin/000077500000000000000000000000001345416772700237565ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/environment-plugin/errors.js000066400000000000000000000014331345416772700256310ustar00rootroot00000000000000const variables = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii']; const modules = [{ name: 'aaa', variables: ['aaa'] }, { name: 'bbbccc', variables: ['bbb', 'ccc'] }, { name: 'ddd', variables: [] }, { name: 'eeefff', variables: ['eee', 'fff'] }, { name: 'ggghhh', variables: ['ggg', 'hhh'] }, { name: 'iii', variables: ['iii'] }]; // build an array of regular expressions of expected errors const regex = []; modules.forEach(module => { variables.forEach(variable => { if (module.variables.indexOf(variable) === -1) { // the module doesn't include the env variable, an error is expected when requiring the variable regex.push([ new RegExp(`(${module.name})`), new RegExp(`Can't resolve '${variable}'`), ]); } }); }); module.exports = regex; webpack-4.30.0/test/configCases/plugins/environment-plugin/index.js000066400000000000000000000016101345416772700254210ustar00rootroot00000000000000it("should import a single process.env var", () => { if(process.env.AAA !== "aaa") require.include("aaa"); }); it("should import multiple process.env vars", () => { if(process.env.BBB !== "bbb") require.include("bbb"); if(process.env.CCC !== "ccc") require.include("ccc"); }); it("should warn when a process.env variable is undefined", () => { if(process.env.DDD !== "ddd") require.include("ddd"); }); it("should import an array of process.env vars", () => { if(process.env.EEE !== "eee") require.include("eee"); if(process.env.FFF !== "fff") require.include("fff"); }); it("should import multiple process.env var with default values", () => { if(process.env.GGG !== "ggg") require.include("ggg"); if(process.env.HHH !== "hhh") require.include("hhh"); }); it("should import process.env var with empty value", () => { if(process.env.III !== "") require.include("iii"); }); webpack-4.30.0/test/configCases/plugins/environment-plugin/warnings.js000066400000000000000000000001131345416772700261370ustar00rootroot00000000000000module.exports = [ [/(ddd)/, /DDD environment variable is undefined./] ]; webpack-4.30.0/test/configCases/plugins/environment-plugin/webpack.config.js000066400000000000000000000023101345416772700271700ustar00rootroot00000000000000"use strict"; const EnvironmentPlugin = require("../../../../lib/EnvironmentPlugin"); process.env.AAA = "aaa"; process.env.BBB = "bbb"; process.env.CCC = "ccc"; process.env.EEE = "eee"; process.env.FFF = "fff"; process.env.GGG = "ggg"; process.env.III = ""; module.exports = [ { name: "aaa", module: { unknownContextRegExp: /$^/, unknownContextCritical: false }, plugins: [new EnvironmentPlugin("AAA")] }, { name: "bbbccc", module: { unknownContextRegExp: /$^/, unknownContextCritical: false }, plugins: [new EnvironmentPlugin("BBB", "CCC")] }, { name: "ddd", module: { unknownContextRegExp: /$^/, unknownContextCritical: false }, plugins: [new EnvironmentPlugin("DDD")] }, { name: "eeefff", module: { unknownContextRegExp: /$^/, unknownContextCritical: false }, plugins: [new EnvironmentPlugin(["EEE", "FFF"])] }, { name: "ggghhh", module: { unknownContextRegExp: /$^/, unknownContextCritical: false }, plugins: [ new EnvironmentPlugin({ GGG: "ggg-default", HHH: "hhh" }) ] }, { name: "iii", module: { unknownContextRegExp: /$^/, unknownContextCritical: false }, plugins: [new EnvironmentPlugin("III")] } ]; webpack-4.30.0/test/configCases/plugins/lib-manifest-plugin/000077500000000000000000000000001345416772700237645ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/lib-manifest-plugin/a.js000066400000000000000000000000261345416772700245400ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/plugins/lib-manifest-plugin/index.js000066400000000000000000000011631345416772700254320ustar00rootroot00000000000000var fs = require("fs"); var path = require("path"); it("should complete", function(done) { require.ensure(["./a"], function(require) { expect(require("./a")).toBe("a"); done(); }); }); it("should write the correct manifest", function() { var manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'bundle0-manifest.json'), "utf-8")); expect(manifest).toHaveProperty("content"); expect(manifest).toHaveProperty("name"); expect(manifest.content).not.toHaveProperty(["./a.js"]); expect(manifest.content).toHaveProperty(["./index.js"]); expect(manifest.content["./index.js"]).toHaveProperty("id", module.id); }); webpack-4.30.0/test/configCases/plugins/lib-manifest-plugin/webpack.config.js000066400000000000000000000005661345416772700272110ustar00rootroot00000000000000var path = require("path"); var LibManifestPlugin = require("../../../../lib/LibManifestPlugin"); module.exports = { entry: { bundle0: ["./"] }, plugins: [ new LibManifestPlugin({ path: path.resolve( __dirname, "../../../js/config/plugins/lib-manifest-plugin/[name]-manifest.json" ), name: "[name]_[hash]" }) ], node: { __dirname: false } }; webpack-4.30.0/test/configCases/plugins/loader-options-plugin/000077500000000000000000000000001345416772700243515ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/loader-options-plugin/index.js000066400000000000000000000004361345416772700260210ustar00rootroot00000000000000it("should set correct options on js files", function() { expect(require("./loader!./index.js")).toEqual({ minimize: true, jsfile: true }); }); it("should set correct options on other files", function() { expect(require("./loader!./txt.txt")).toEqual({ minimize: true }); }); webpack-4.30.0/test/configCases/plugins/loader-options-plugin/loader.js000066400000000000000000000002061345416772700261530ustar00rootroot00000000000000module.exports = function() { return "module.exports = " + JSON.stringify({ minimize: this.minimize, jsfile: this.jsfile }); }; webpack-4.30.0/test/configCases/plugins/loader-options-plugin/txt.txt000066400000000000000000000000001345416772700257170ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/loader-options-plugin/webpack.config.js000066400000000000000000000003241345416772700275660ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true }), new webpack.LoaderOptionsPlugin({ test: /\.js$/, jsfile: true }) ] }; webpack-4.30.0/test/configCases/plugins/min-chunk-size/000077500000000000000000000000001345416772700227575ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/min-chunk-size/a.js000066400000000000000000000000241345416772700235310ustar00rootroot00000000000000export default "a"; webpack-4.30.0/test/configCases/plugins/min-chunk-size/b.js000066400000000000000000000000241345416772700235320ustar00rootroot00000000000000export default "b"; webpack-4.30.0/test/configCases/plugins/min-chunk-size/index.js000066400000000000000000000010311345416772700244170ustar00rootroot00000000000000it("should combine two chunk if too small", done => { // b should not yet available var bf = __webpack_modules__[require.resolveWeak("./b")]; expect((typeof bf)).toBe("undefined"); // load a import("./a").then(a => { expect(a.default).toBe("a"); // check if b is available too var bf = __webpack_modules__[require.resolveWeak("./b")]; expect((typeof bf)).toBe("function"); // load b (just to check if it's ok) import("./b").then(b => { expect(b.default).toBe("b"); done(); }).catch(done); }).catch(done); }); webpack-4.30.0/test/configCases/plugins/min-chunk-size/webpack.config.js000066400000000000000000000002221345416772700261710ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.MinChunkSizePlugin({ minChunkSize: 30 }) ] }; webpack-4.30.0/test/configCases/plugins/profiling-plugin/000077500000000000000000000000001345416772700234035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/profiling-plugin/index.js000066400000000000000000000010741345416772700250520ustar00rootroot00000000000000import "./test.json"; it("should generate a events.json file", () => { var fs = require("fs"), path = require("path"), os = require("os"); expect(fs.existsSync(path.join(__dirname, "events.json"))).toBe(true); }); it("should have proper setup record inside of the json stream", () => { var fs = require("fs"), path = require("path"), os = require("os"); // convert json stream to valid var source = JSON.parse(fs.readFileSync(path.join(__dirname, "events.json"), "utf-8").toString() + "{}]"); expect(source[0].id).toEqual(1); }); webpack-4.30.0/test/configCases/plugins/profiling-plugin/test.filter.js000066400000000000000000000001001345416772700261730ustar00rootroot00000000000000module.exports = function(config) { return !process.env.CI; }; webpack-4.30.0/test/configCases/plugins/profiling-plugin/test.json000066400000000000000000000000341345416772700252520ustar00rootroot00000000000000{ "json": "should work" } webpack-4.30.0/test/configCases/plugins/profiling-plugin/webpack.config.js000066400000000000000000000004551345416772700266250ustar00rootroot00000000000000var rootPath = "../../../../"; var webpack = require(rootPath); var path = require("path"); module.exports = (env, { testPath }) => ({ plugins: [ new webpack.debug.ProfilingPlugin({ outputPath: path.join(testPath, "events.json") }) ], node: { __dirname: false, __filename: false } }); webpack-4.30.0/test/configCases/plugins/progress-plugin/000077500000000000000000000000001345416772700232565ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/progress-plugin/data.js000066400000000000000000000000251345416772700245220ustar00rootroot00000000000000module.exports = []; webpack-4.30.0/test/configCases/plugins/progress-plugin/index.js000066400000000000000000000004331345416772700247230ustar00rootroot00000000000000it("should contain the custom progress messages", function() { var data = require(__dirname + "/data"); expect(data).toContain("optimizing"); expect(data).toContain("optimizing|CustomPlugin"); expect(data).toContain("optimizing|CustomPlugin|custom category|custom message"); }); webpack-4.30.0/test/configCases/plugins/progress-plugin/webpack.config.js000066400000000000000000000011311345416772700264700ustar00rootroot00000000000000var webpack = require("../../../../"); var data = require("./data"); module.exports = { externals: { [__dirname + "/data"]: "commonjs " + __dirname + "/data" }, plugins: [ new webpack.ProgressPlugin((value, ...messages) => { data.push(messages.join("|")); }), { apply: compiler => { compiler.hooks.compilation.tap("CustomPlugin", compilation => { compilation.hooks.optimize.tap( { name: "CustomPlugin", context: true }, context => { context.reportProgress(0, "custom category", "custom message"); } ); }); } } ] }; webpack-4.30.0/test/configCases/plugins/provide-plugin/000077500000000000000000000000001345416772700230625ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/provide-plugin/aaa.js000066400000000000000000000000271345416772700241410ustar00rootroot00000000000000module.exports = "aaa";webpack-4.30.0/test/configCases/plugins/provide-plugin/bbbccc.js000066400000000000000000000000321345416772700246110ustar00rootroot00000000000000module.exports = "bbbccc";webpack-4.30.0/test/configCases/plugins/provide-plugin/ddd.js000066400000000000000000000001001345416772700241420ustar00rootroot00000000000000var ddd = { eee: { "3-f": "fff" } }; module.exports = ddd; webpack-4.30.0/test/configCases/plugins/provide-plugin/env.js000066400000000000000000000000371345416772700242100ustar00rootroot00000000000000module.exports = "development";webpack-4.30.0/test/configCases/plugins/provide-plugin/foo.mjs000066400000000000000000000000701345416772700243550ustar00rootroot00000000000000export default function foo() { return typeof esm; }webpack-4.30.0/test/configCases/plugins/provide-plugin/harmony.js000066400000000000000000000001471345416772700250770ustar00rootroot00000000000000export default "ECMAScript 2015"; export const alias = "ECMAScript Harmony"; export const year = 2015; webpack-4.30.0/test/configCases/plugins/provide-plugin/index.js000066400000000000000000000034111345416772700245260ustar00rootroot00000000000000it("should provide a module for a simple free var", function() { expect(aaa).toBe("aaa"); }); it("should provide a module for a nested var", function() { expect((bbb.ccc)).toBe("bbbccc"); var x = bbb.ccc; expect(x).toBe("bbbccc"); }); it("should provide a module for a nested var within a IIFE's argument", function() { (function(process) { expect((process.env.NODE_ENV)).toBe("development"); var x = process.env.NODE_ENV; expect(x).toBe("development"); }(process)); }); it("should provide a module for thisExpression", () => { expect(this.aaa).toBe("aaa"); }); it("should provide a module for a nested var within a IIFE's this", function() { (function() { expect((this.env.NODE_ENV)).toBe("development"); var x = this.env.NODE_ENV; expect(x).toBe("development"); }.call(process)); }); it("should provide a module for a nested var within a nested IIFE's this", function() { (function() { (function() { expect((this.env.NODE_ENV)).toBe("development"); var x = this.env.NODE_ENV; expect(x).toBe("development"); }.call(this)); }.call(process)); }); it("should not provide a module for a part of a var", function() { expect((typeof bbb)).toBe("undefined"); }); it("should provide a module for a property request", function() { expect((dddeeefff)).toBe("fff"); var x = dddeeefff; expect(x).toBe("fff"); }); it("should provide ES2015 modules", function() { expect((es2015.default)).toBe("ECMAScript 2015"); expect((es2015.alias)).toBe("ECMAScript Harmony"); expect((es2015.year)).toBe(2015); expect((es2015_name)).toBe("ECMAScript 2015"); expect((es2015_alias)).toBe("ECMAScript Harmony"); expect((es2015_year)).toBe(2015); }); it("should not provide for mjs", function(){ var foo = require("./foo.mjs").default; expect(foo()).toBe("undefined"); }); webpack-4.30.0/test/configCases/plugins/provide-plugin/webpack.config.js000066400000000000000000000006551345416772700263060ustar00rootroot00000000000000var ProvidePlugin = require("../../../../lib/ProvidePlugin"); module.exports = { plugins: [ new ProvidePlugin({ aaa: "./aaa", "bbb.ccc": "./bbbccc", dddeeefff: ["./ddd", "eee", "3-f"], "process.env.NODE_ENV": "./env", es2015: "./harmony", es2015_name: ["./harmony", "default"], es2015_alias: ["./harmony", "alias"], es2015_year: ["./harmony", "year"], "this.aaa": "./aaa", esm: "fail" }) ] }; webpack-4.30.0/test/configCases/plugins/source-map-dev-tool-plugin/000077500000000000000000000000001345416772700252145ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/source-map-dev-tool-plugin/index.js000066400000000000000000000010421345416772700266560ustar00rootroot00000000000000it("should contain publicPath prefix in [url] and resolve relatively to fileContext", function() { var fs = require("fs"), path = require("path"); var source = fs.readFileSync(path.join(__dirname, "public/test.js"), "utf-8"); expect(source).toMatch("//# sourceMappingURL=https://10.10.10.10/project/sourcemaps/test.js.map"); }); it("should write sourcemap file relative fo fileContext", function() { var fs = require("fs"), path = require("path"); expect(fs.existsSync(path.join(__dirname, "sourcemaps/test.js.map"))).toBe(true); }); webpack-4.30.0/test/configCases/plugins/source-map-dev-tool-plugin/test.js000066400000000000000000000000721345416772700265300ustar00rootroot00000000000000var testObject = { a: 1 }; module.exports = testObject; webpack-4.30.0/test/configCases/plugins/source-map-dev-tool-plugin/webpack.config.js000066400000000000000000000010271345416772700304320ustar00rootroot00000000000000var webpack = require("../../../../"); var TerserPlugin = require("terser-webpack-plugin"); module.exports = { node: { __dirname: false, __filename: false }, entry: { bundle0: ["./index.js"], "public/test": ["./test.js"] }, output: { filename: "[name].js" }, optimization: { minimizer: [ new TerserPlugin({ sourceMap: true }) ] }, plugins: [ new webpack.SourceMapDevToolPlugin({ filename: "sourcemaps/[file].map", publicPath: "https://10.10.10.10/project/", fileContext: "public" }) ] }; webpack-4.30.0/test/configCases/plugins/terser-plugin/000077500000000000000000000000001345416772700227165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/plugins/terser-plugin/compress.js000066400000000000000000000003011345416772700251010ustar00rootroot00000000000000function f() { var a = 1, b = 2, c = 3; if (a) { b = c; } else { c = b; } console.log(a + b); console.log(b + c); console.log(a + c); console.log(a + b + c); } module.exports = f; webpack-4.30.0/test/configCases/plugins/terser-plugin/extract.js000066400000000000000000000005451345416772700247320ustar00rootroot00000000000000var foo = {}; // ⚠️ move the following comment back to the top // https://github.com/mishoo/UglifyJS2/issues/2500 /** @preserve comment should be extracted extract-test.1 */ // comment should be stripped extract-test.2 /*! * comment should be extracted extract-test.3 */ /** * comment should be stripped extract-test.4 */ module.exports = foo; webpack-4.30.0/test/configCases/plugins/terser-plugin/ie8.js000066400000000000000000000002341345416772700237400ustar00rootroot00000000000000function t(e) { return function(error) { try { e() } catch(e) { error(e) } } } module.exports = t; webpack-4.30.0/test/configCases/plugins/terser-plugin/index.js000066400000000000000000000047051345416772700243710ustar00rootroot00000000000000it("should contain no comments in out chunk", () => { const fs = require("fs"); const source = fs.readFileSync(__filename, "utf-8"); expect(source).not.toMatch(/[^\"]comment should be stripped test\.1[^\"]/); expect(source).not.toMatch(/[^\"]comment should be stripped test\.2[^\"]/); expect(source).not.toMatch(/[^\"]comment should be stripped test\.3[^\"]/); }); it("should contain comments in vendors chunk", function() { const fs = require("fs"); const path = require("path"); const source = fs.readFileSync(path.join(__dirname, "vendors.js"), "utf-8"); expect(source).toMatch("comment should not be stripped vendors.1"); expect(source).toMatch("// comment should not be stripped vendors.2"); expect(source).toMatch(" * comment should not be stripped vendors.3"); }); it("should extract comments to separate file", function() { const fs = require("fs"); const path = require("path"); const source = fs.readFileSync(path.join(__dirname, "extract.js.LICENSE"), "utf-8"); expect(source).toMatch("comment should be extracted extract-test.1"); expect(source).not.toMatch("comment should be stripped extract-test.2"); expect(source).toMatch("comment should be extracted extract-test.3"); expect(source).not.toMatch("comment should be stripped extract-test.4"); }); it("should remove extracted comments and insert a banner", function() { const fs = require("fs"); const path = require("path"); const source = fs.readFileSync(path.join(__dirname, "extract.js"), "utf-8"); expect(source).not.toMatch("comment should be extracted extract-test.1"); expect(source).not.toMatch("comment should be stripped extract-test.2"); expect(source).not.toMatch("comment should be extracted extract-test.3"); expect(source).not.toMatch("comment should be stripped extract-test.4"); expect(source).toMatch("/*! For license information please see extract.js.LICENSE */"); }); it("should pass mangle options", function() { const fs = require("fs"); const path = require("path"); const source = fs.readFileSync(path.join(__dirname, "ie8.js"), "utf-8"); expect(source).toMatch(".exports=function(e){return function(t){try{e()}catch(e){t(e)}}}"); }); it("should pass compress options", function() { const fs = require("fs"); const path = require("path"); const source = fs.readFileSync(path.join(__dirname, "compress.js"), "utf-8"); expect(source).toMatch(".exports=function(){console.log(4),console.log(6),console.log(4),console.log(7)}"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/plugins/terser-plugin/test.js000066400000000000000000000002551345416772700242350ustar00rootroot00000000000000/** @preserve comment should be stripped test.1 */ var foo = {}; // comment should be stripped test.2 /** * comment should be stripped test.3 */ module.exports = foo; webpack-4.30.0/test/configCases/plugins/terser-plugin/vendors.js000066400000000000000000000003021345416772700247270ustar00rootroot00000000000000/** @preserve comment should not be stripped vendors.1 */ var bar = {}; // comment should not be stripped vendors.2 /** * comment should not be stripped vendors.3 */ module.exports = bar; webpack-4.30.0/test/configCases/plugins/terser-plugin/webpack.config.js000066400000000000000000000014051345416772700261340ustar00rootroot00000000000000const TerserPlugin = require("terser-webpack-plugin"); module.exports = { node: { __dirname: false, __filename: false }, entry: { ie8: ["./ie8.js"], bundle0: ["./index.js"], vendors: ["./vendors.js"], extract: ["./extract.js"], compress: ["./compress.js"] }, output: { filename: "[name].js" }, optimization: { minimize: true, minimizer: [ new TerserPlugin({ cache: false, parallel: false, exclude: ["vendors.js", "extract.js"] }), new TerserPlugin({ cache: false, parallel: false, extractComments: true, include: ["extract.js"] }), new TerserPlugin({ cache: false, parallel: false, terserOptions: { compress: { passes: 2 } }, include: ["compress.js"] }) ] } }; webpack-4.30.0/test/configCases/race-conditions/000077500000000000000000000000001345416772700215165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/race-conditions/load-module/000077500000000000000000000000001345416772700237205ustar00rootroot00000000000000webpack-4.30.0/test/configCases/race-conditions/load-module/index.js000066400000000000000000000002201345416772700253570ustar00rootroot00000000000000it("should not deadlock when using loadModule", () => { const result = require("./loader!"); expect(result).toMatch(/console.log\(42\)/); }); webpack-4.30.0/test/configCases/race-conditions/load-module/loader.js000066400000000000000000000006271345416772700255310ustar00rootroot00000000000000module.exports = function() { const callback = this.async(); let finished = false; this.loadModule("./module.js", (err, result) => { if (err) return callback(err); if (finished) return; finished = true; callback(null, `module.exports = ${JSON.stringify(result)};`); }); setTimeout(() => { if (finished) return; finished = true; callback(new Error("loadModule is hanging")); }, 2000); }; webpack-4.30.0/test/configCases/race-conditions/load-module/module.js000066400000000000000000000000211345416772700255340ustar00rootroot00000000000000console.log(42); webpack-4.30.0/test/configCases/race-conditions/load-module/webpack.config.js000066400000000000000000000000461345416772700271360ustar00rootroot00000000000000module.exports = { parallelism: 1 }; webpack-4.30.0/test/configCases/records/000077500000000000000000000000001345416772700200765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-295/000077500000000000000000000000001345416772700215435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-295/file.js000066400000000000000000000000161345416772700230150ustar00rootroot00000000000000// just a filewebpack-4.30.0/test/configCases/records/issue-295/loader.js000066400000000000000000000000671345416772700233520ustar00rootroot00000000000000module.exports = function(source) { return source; }; webpack-4.30.0/test/configCases/records/issue-295/test.js000066400000000000000000000004551345416772700230640ustar00rootroot00000000000000require("./loader!./file"); require("./loader?2!./file"); it("should write relative paths to records", function() { var fs = require("fs"); var path = require("path"); var content = fs.readFileSync(path.join(__dirname, "records.json"), "utf-8"); expect(content).not.toMatch(/webpack|issue/); }); webpack-4.30.0/test/configCases/records/issue-295/webpack.config.js000066400000000000000000000003301345416772700247550ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: "./test", recordsPath: path.resolve( __dirname, "../../../js/config/records/issue-295/records.json" ), target: "node", node: { __dirname: false } }; webpack-4.30.0/test/configCases/records/issue-2991/000077500000000000000000000000001345416772700216305ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-2991/pkgs/000077500000000000000000000000001345416772700225745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-2991/pkgs/somepackage/000077500000000000000000000000001345416772700250535ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-2991/pkgs/somepackage/package.json000066400000000000000000000000421345416772700273350ustar00rootroot00000000000000{ "browser": { "foo": false } } webpack-4.30.0/test/configCases/records/issue-2991/test.js000066400000000000000000000004371345416772700231510ustar00rootroot00000000000000try { require("pkgs/somepackage/foo"); } catch (e) {} it("should write relative paths to records", function() { var fs = require("fs"); var path = require("path"); var content = fs.readFileSync(path.join(__dirname, "records.json"), "utf-8"); expect(content).toMatchSnapshot(); }); webpack-4.30.0/test/configCases/records/issue-2991/webpack.config.js000066400000000000000000000005031345416772700250440ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: "./test", recordsOutputPath: path.resolve( __dirname, "../../../js/config/records/issue-2991/records.json" ), target: "node", node: { __dirname: false }, resolve: { aliasFields: ["browser"], alias: { pkgs: path.resolve(__dirname, "pkgs") } } }; webpack-4.30.0/test/configCases/records/issue-7339/000077500000000000000000000000001345416772700216315ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-7339/dependencies/000077500000000000000000000000001345416772700242575ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-7339/dependencies/bar.js000066400000000000000000000000261345416772700253570ustar00rootroot00000000000000module.exports = "Bar"webpack-4.30.0/test/configCases/records/issue-7339/dependencies/foo.js000066400000000000000000000000261345416772700253760ustar00rootroot00000000000000module.exports = "Foo"webpack-4.30.0/test/configCases/records/issue-7339/test.js000066400000000000000000000004741345416772700231530ustar00rootroot00000000000000function loadDependency(dep) { require("./dependencies/" + dep); } it("should write relative dynamic-require paths to records", function() { var fs = require("fs"); var path = require("path"); var content = fs.readFileSync(path.join(__dirname, "records.json"), "utf-8"); expect(content).toMatchSnapshot(); }); webpack-4.30.0/test/configCases/records/issue-7339/webpack.config.js000066400000000000000000000003371345416772700250520ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: "./test", recordsOutputPath: path.resolve( __dirname, "../../../js/config/records/issue-7339/records.json" ), target: "node", node: { __dirname: false } }; webpack-4.30.0/test/configCases/records/issue-7492/000077500000000000000000000000001345416772700216315ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-7492/async.js000066400000000000000000000000211345416772700232750ustar00rootroot00000000000000import "vendor"; webpack-4.30.0/test/configCases/records/issue-7492/index.js000066400000000000000000000001351345416772700232750ustar00rootroot00000000000000it("should load fine", () => { return import(/* webpackChunkName: "async" */"./async"); }); webpack-4.30.0/test/configCases/records/issue-7492/node_modules/000077500000000000000000000000001345416772700243065ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-7492/node_modules/vendor.js000066400000000000000000000000001345416772700261270ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/issue-7492/records.json000066400000000000000000000002001345416772700241550ustar00rootroot00000000000000{ "chunks": { "byName": { "vendors~async": 123 }, "bySource": { "1 index.js ./async": 123 } } } webpack-4.30.0/test/configCases/records/issue-7492/webpack.config.js000066400000000000000000000003611345416772700250470ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: "./index", recordsInputPath: path.resolve(__dirname, "records.json"), output: { chunkFilename: "[name]-[chunkhash].js" }, optimization: { splitChunks: { minSize: 0 } } }; webpack-4.30.0/test/configCases/records/stable-sort/000077500000000000000000000000001345416772700223355ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/stable-sort/split-2.js000066400000000000000000000000001345416772700241530ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/stable-sort/split.js000066400000000000000000000000001345416772700240140ustar00rootroot00000000000000webpack-4.30.0/test/configCases/records/stable-sort/test.js000066400000000000000000000006241345416772700236540ustar00rootroot00000000000000require.ensure([], function(require) { require('./split.js') }) require.ensure([], function(require) { require('./split-2.js') }, "split") it("sorts the usedIds array to prevent churn", function() { var fs = require("fs"); var path = require("path"); var records = JSON.parse(fs.readFileSync(path.join(__dirname, "records.json"), "utf-8")); expect(records.chunks.usedIds).toEqual([0, 1, 2]); }); webpack-4.30.0/test/configCases/records/stable-sort/webpack.config.js000066400000000000000000000004401345416772700255510ustar00rootroot00000000000000var path = require("path"); module.exports = { mode: "development", entry: "./test", recordsOutputPath: path.resolve( __dirname, "../../../js/config/records/stable-sort/records.json" ), optimization: { namedChunks: false }, target: "node", node: { __dirname: false } }; webpack-4.30.0/test/configCases/rule-set/000077500000000000000000000000001345416772700201755ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/chaining/000077500000000000000000000000001345416772700217555ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/chaining/abc.js000066400000000000000000000000321345416772700230330ustar00rootroot00000000000000module.exports = ["abc"]; webpack-4.30.0/test/configCases/rule-set/chaining/def.js000066400000000000000000000000321345416772700230440ustar00rootroot00000000000000module.exports = ["def"]; webpack-4.30.0/test/configCases/rule-set/chaining/index.js000066400000000000000000000004711345416772700234240ustar00rootroot00000000000000it("should match rule with multiple loaders in 'loader'", function() { var abc = require("./abc"); expect(abc).toEqual([ "abc", "?b", "?a" ]); }); it("should match rule with multiple loaders in 'loaders'", function() { var def = require("./def"); expect(def).toEqual([ "def", "?d", "?c" ]); }); webpack-4.30.0/test/configCases/rule-set/chaining/loader.js000066400000000000000000000003511345416772700235600ustar00rootroot00000000000000module.exports = function(source) { var query = this.query; if(typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; webpack-4.30.0/test/configCases/rule-set/chaining/webpack.config.js000066400000000000000000000003051345416772700251710ustar00rootroot00000000000000module.exports = { module: { rules: [ { resource: /abc\.js$/, loader: "./loader?a!./loader?b" }, { resource: /def\.js$/, loaders: "./loader?c!./loader?d" } ] } }; webpack-4.30.0/test/configCases/rule-set/compiler/000077500000000000000000000000001345416772700220075ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/compiler/a.js000066400000000000000000000000471345416772700225660ustar00rootroot00000000000000module.exports = "loader not matched"; webpack-4.30.0/test/configCases/rule-set/compiler/b.js000066400000000000000000000000471345416772700225670ustar00rootroot00000000000000module.exports = "loader not matched"; webpack-4.30.0/test/configCases/rule-set/compiler/index.js000066400000000000000000000002701345416772700234530ustar00rootroot00000000000000it("should match rule with compiler name", function() { var a = require("./a"); expect(a).toBe("loader matched"); var b = require("./b"); expect(b).toBe("loader not matched"); }); webpack-4.30.0/test/configCases/rule-set/compiler/loader.js000066400000000000000000000001501345416772700236070ustar00rootroot00000000000000module.exports = function(source) { return "module.exports = " + JSON.stringify("loader matched"); }; webpack-4.30.0/test/configCases/rule-set/compiler/webpack.config.js000066400000000000000000000003521345416772700252250ustar00rootroot00000000000000module.exports = { name: "compiler-name", module: { rules: [ { test: /a\.js$/, compiler: "compiler", use: "./loader" }, { test: /b\.js$/, compiler: "other-compiler", use: "./loader" } ] } }; webpack-4.30.0/test/configCases/rule-set/custom/000077500000000000000000000000001345416772700215075ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/custom/a.js000066400000000000000000000000301345416772700222560ustar00rootroot00000000000000module.exports = ["a"]; webpack-4.30.0/test/configCases/rule-set/custom/b.js000066400000000000000000000000301345416772700222570ustar00rootroot00000000000000module.exports = ["b"]; webpack-4.30.0/test/configCases/rule-set/custom/call-a.js000066400000000000000000000000631345416772700231750ustar00rootroot00000000000000module.exports = require("./a" + __resourceQuery); webpack-4.30.0/test/configCases/rule-set/custom/index.js000066400000000000000000000010621345416772700231530ustar00rootroot00000000000000it("should match a custom loader", function() { var a = require("./a"); expect(a).toEqual([ "a", { issuer: "index.js", resource: "a.js", resourceQuery: "" } ]); var b = require("./b?hello"); expect(b).toEqual([ "b", { issuer: "index.js", resource: "b.js", resourceQuery: "?hello" } ]); var ca = require("./call-a?hello"); expect(ca).toEqual([ "a", { issuer: "call-a.js", resource: "a.js", resourceQuery: "?hello" }, { issuer: "index.js", resource: "call-a.js", resourceQuery: "?hello" } ]); }); webpack-4.30.0/test/configCases/rule-set/custom/loader.js000066400000000000000000000003511345416772700233120ustar00rootroot00000000000000module.exports = function(source) { var query = this.query; if(typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; webpack-4.30.0/test/configCases/rule-set/custom/webpack.config.js000066400000000000000000000005241345416772700247260ustar00rootroot00000000000000module.exports = { module: { rules: [ { test: /[ab]\.js$/, use: function(data) { return { loader: "./loader", options: { resource: data.resource.replace(/^.*[\\/]/g, ""), resourceQuery: data.resourceQuery, issuer: data.issuer.replace(/^.*[\\/]/g, "") } }; } } ] } }; webpack-4.30.0/test/configCases/rule-set/query/000077500000000000000000000000001345416772700213425ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/query/a.js000066400000000000000000000000301345416772700221110ustar00rootroot00000000000000module.exports = ["a"]; webpack-4.30.0/test/configCases/rule-set/query/index.js000066400000000000000000000004071345416772700230100ustar00rootroot00000000000000it("should match rule with resource query", function() { var a1 = require("./a"); expect(a1).toEqual([ "a" ]); var a2 = require("./a?loader"); expect(a2).toEqual([ "a", "?query" ]); var a3 = require("./a?other"); expect(a3).toEqual([ "a" ]); }); webpack-4.30.0/test/configCases/rule-set/query/loader.js000066400000000000000000000003511345416772700231450ustar00rootroot00000000000000module.exports = function(source) { var query = this.query; if(typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; webpack-4.30.0/test/configCases/rule-set/query/webpack.config.js000066400000000000000000000001671345416772700245640ustar00rootroot00000000000000module.exports = { module: { rules: [ { resourceQuery: /^\?loader/, use: "./loader?query" } ] } }; webpack-4.30.0/test/configCases/rule-set/resolve-options/000077500000000000000000000000001345416772700233455ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/resolve-options/a.js000066400000000000000000000000451345416772700241220ustar00rootroot00000000000000module.exports = require("./wrong"); webpack-4.30.0/test/configCases/rule-set/resolve-options/b.js000066400000000000000000000000451345416772700241230ustar00rootroot00000000000000module.exports = require("./wrong"); webpack-4.30.0/test/configCases/rule-set/resolve-options/index.js000066400000000000000000000002451345416772700250130ustar00rootroot00000000000000it("should allow to set custom resolving rules", function() { var a = require("./a"); expect(a).toBe("ok"); var b = require("./b"); expect(b).toBe("wrong"); }); webpack-4.30.0/test/configCases/rule-set/resolve-options/ok.js000066400000000000000000000000271345416772700243130ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/configCases/rule-set/resolve-options/webpack.config.js000066400000000000000000000002411345416772700265600ustar00rootroot00000000000000module.exports = { module: { rules: [ { test: require.resolve("./a"), resolve: { alias: { "./wrong": "./ok" } } } ] } }; webpack-4.30.0/test/configCases/rule-set/resolve-options/wrong.js000066400000000000000000000000321345416772700250320ustar00rootroot00000000000000module.exports = "wrong"; webpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/000077500000000000000000000000001345416772700237755ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/a.js000066400000000000000000000000301345416772700245440ustar00rootroot00000000000000module.exports = ["a"]; webpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/ab.js000066400000000000000000000000311345416772700247070ustar00rootroot00000000000000module.exports = ["ab"]; webpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/b.js000066400000000000000000000000441345416772700245520ustar00rootroot00000000000000module.exports = [require("./a")]; webpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/c.js000066400000000000000000000000151345416772700245510ustar00rootroot00000000000000// never usedwebpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/index.js000066400000000000000000000005771345416772700254530ustar00rootroot00000000000000it("should match only one rule in a oneOf block", function() { var ab = require("./ab"); expect(ab).toEqual([ "ab", "?first" ]); }); it("should match with issuer and any option value", function() { var a = require("./a"); var b = require("./b"); expect(a).toEqual([ "a", "?third", ]); expect(b).toEqual([[ "a", "second-3", "?second-2", "?second-1", ]]); }); webpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/loader.js000066400000000000000000000003511345416772700256000ustar00rootroot00000000000000module.exports = function(source) { var query = this.query; if(typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; webpack-4.30.0/test/configCases/rule-set/simple-use-array-fn/webpack.config.js000066400000000000000000000013161345416772700272140ustar00rootroot00000000000000module.exports = { module: { rules: [ { oneOf: [ { test: { and: [/a.\.js$/, /b\.js$/] }, loader: "./loader?first" }, { test: [require.resolve("./a"), require.resolve("./c")], issuer: require.resolve("./b"), use: data => [ "./loader?second-1", { loader: "./loader", options: "second-2" }, { loader: "./loader", options: { get: function() { return "second-3"; } } } ] }, { test: { or: [require.resolve("./a"), require.resolve("./c")] }, loader: "./loader", options: "third" } ] } ] } }; webpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/000077500000000000000000000000001345416772700237755ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/a.js000066400000000000000000000000301345416772700245440ustar00rootroot00000000000000module.exports = ["a"]; webpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/ab.js000066400000000000000000000000311345416772700247070ustar00rootroot00000000000000module.exports = ["ab"]; webpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/b.js000066400000000000000000000000441345416772700245520ustar00rootroot00000000000000module.exports = [require("./a")]; webpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/c.js000066400000000000000000000000151345416772700245510ustar00rootroot00000000000000// never usedwebpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/index.js000066400000000000000000000005771345416772700254530ustar00rootroot00000000000000it("should match only one rule in a oneOf block", function() { var ab = require("./ab"); expect(ab).toEqual([ "ab", "?first" ]); }); it("should match with issuer and any option value", function() { var a = require("./a"); var b = require("./b"); expect(a).toEqual([ "a", "?third", ]); expect(b).toEqual([[ "a", "second-3", "?second-2", "?second-1", ]]); }); webpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/loader.js000066400000000000000000000003511345416772700256000ustar00rootroot00000000000000module.exports = function(source) { var query = this.query; if(typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; webpack-4.30.0/test/configCases/rule-set/simple-use-fn-array/webpack.config.js000066400000000000000000000015051345416772700272140ustar00rootroot00000000000000function createFunctionArrayFromUseArray(useArray) { return useArray.map(function(useItem) { return function(data) { return useItem; }; }); } var useArray = createFunctionArrayFromUseArray([ "./loader?second-1", { loader: "./loader", options: "second-2" }, { loader: "./loader", options: { get: function() { return "second-3"; } } } ]); module.exports = { module: { rules: [ { oneOf: [ { test: { and: [/a.\.js$/, /b\.js$/] }, loader: "./loader?first" }, { test: [require.resolve("./a"), require.resolve("./c")], issuer: require.resolve("./b"), use: useArray }, { test: { or: [require.resolve("./a"), require.resolve("./c")] }, loader: "./loader", options: "third" } ] } ] } }; webpack-4.30.0/test/configCases/rule-set/simple/000077500000000000000000000000001345416772700214665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/rule-set/simple/a.js000066400000000000000000000000301345416772700222350ustar00rootroot00000000000000module.exports = ["a"]; webpack-4.30.0/test/configCases/rule-set/simple/ab.js000066400000000000000000000000311345416772700224000ustar00rootroot00000000000000module.exports = ["ab"]; webpack-4.30.0/test/configCases/rule-set/simple/b.js000066400000000000000000000000441345416772700222430ustar00rootroot00000000000000module.exports = [require("./a")]; webpack-4.30.0/test/configCases/rule-set/simple/c.js000066400000000000000000000000151345416772700222420ustar00rootroot00000000000000// never usedwebpack-4.30.0/test/configCases/rule-set/simple/index.js000066400000000000000000000005771345416772700231440ustar00rootroot00000000000000it("should match only one rule in a oneOf block", function() { var ab = require("./ab"); expect(ab).toEqual([ "ab", "?first" ]); }); it("should match with issuer and any option value", function() { var a = require("./a"); var b = require("./b"); expect(a).toEqual([ "a", "?third", ]); expect(b).toEqual([[ "a", "second-3", "?second-2", "?second-1", ]]); }); webpack-4.30.0/test/configCases/rule-set/simple/loader.js000066400000000000000000000003511345416772700232710ustar00rootroot00000000000000module.exports = function(source) { var query = this.query; if(typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; webpack-4.30.0/test/configCases/rule-set/simple/webpack.config.js000066400000000000000000000013061345416772700247040ustar00rootroot00000000000000module.exports = { module: { rules: [ { oneOf: [ { test: { and: [/a.\.js$/, /b\.js$/] }, loader: "./loader?first" }, { test: [require.resolve("./a"), require.resolve("./c")], issuer: require.resolve("./b"), use: [ "./loader?second-1", { loader: "./loader", options: "second-2" }, { loader: "./loader", options: { get: function() { return "second-3"; } } } ] }, { test: { or: [require.resolve("./a"), require.resolve("./c")] }, loader: "./loader", options: "third" } ] } ] } }; webpack-4.30.0/test/configCases/runtime/000077500000000000000000000000001345416772700201205ustar00rootroot00000000000000webpack-4.30.0/test/configCases/runtime/opt-in-finally/000077500000000000000000000000001345416772700227625ustar00rootroot00000000000000webpack-4.30.0/test/configCases/runtime/opt-in-finally/exception.js000066400000000000000000000000361345416772700253150ustar00rootroot00000000000000throw new Error("Exception"); webpack-4.30.0/test/configCases/runtime/opt-in-finally/index.js000066400000000000000000000003221345416772700244240ustar00rootroot00000000000000it("should throw exception on every try to load a module", function() { expect(function() { require("./exception"); }).toThrowError(); expect(function() { require("./exception"); }).toThrowError(); }); webpack-4.30.0/test/configCases/runtime/opt-in-finally/webpack.config.js000066400000000000000000000001121345416772700261720ustar00rootroot00000000000000module.exports = { output: { strictModuleExceptionHandling: true } }; webpack-4.30.0/test/configCases/scope-hoisting/000077500000000000000000000000001345416772700213705ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/class-naming/000077500000000000000000000000001345416772700237445ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/class-naming/index.js000066400000000000000000000001451345416772700254110ustar00rootroot00000000000000import { Hello as t } from "./module2"; it("should rename classes correctly", () => { new t(); }); webpack-4.30.0/test/configCases/scope-hoisting/class-naming/module.js000066400000000000000000000000261345416772700255650ustar00rootroot00000000000000export class Hello {} webpack-4.30.0/test/configCases/scope-hoisting/class-naming/module2.js000066400000000000000000000001451345416772700256510ustar00rootroot00000000000000import * as MODULE from "./module"; let Hello = class Hello extends MODULE.Hello {} export { Hello } webpack-4.30.0/test/configCases/scope-hoisting/class-naming/webpack.config.js000066400000000000000000000001051345416772700271560ustar00rootroot00000000000000module.exports = { optimization: { concatenateModules: true } }; webpack-4.30.0/test/configCases/scope-hoisting/create-dll-plugin/000077500000000000000000000000001345416772700247005ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/create-dll-plugin/index.js000066400000000000000000000000461345416772700263450ustar00rootroot00000000000000import "./module"; export default 1; webpack-4.30.0/test/configCases/scope-hoisting/create-dll-plugin/module.js000066400000000000000000000000221345416772700265150ustar00rootroot00000000000000export default 2; webpack-4.30.0/test/configCases/scope-hoisting/create-dll-plugin/test.config.js000066400000000000000000000000301345416772700274520ustar00rootroot00000000000000exports.noTests = true; webpack-4.30.0/test/configCases/scope-hoisting/create-dll-plugin/webpack.config.js000066400000000000000000000005101345416772700301120ustar00rootroot00000000000000const path = require("path"); var webpack = require("../../../../"); module.exports = { entry: ["./index.js"], plugins: [ new webpack.DllPlugin({ path: path.resolve( __dirname, "../../../js/config/scope-hoisting/create-dll-plugin/manifest.json" ) }), new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-4.30.0/test/configCases/scope-hoisting/dll-plugin/000077500000000000000000000000001345416772700234375ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/dll-plugin/index.js000066400000000000000000000001741345416772700251060ustar00rootroot00000000000000import value from "dll/module"; it("should not scope hoist delegated modules", function() { expect(value).toBe("ok"); }); webpack-4.30.0/test/configCases/scope-hoisting/dll-plugin/webpack.config.js000066400000000000000000000006011345416772700266520ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.DllReferencePlugin({ name: "function(id) { return {default: 'ok'}; }", scope: "dll", content: { "./module": { id: 1, buildMeta: { exportsType: "namespace", providedExports: ["default"] } } } }), new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-4.30.0/test/configCases/scope-hoisting/esModule/000077500000000000000000000000001345416772700231455ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/esModule/index.js000066400000000000000000000002431345416772700246110ustar00rootroot00000000000000it("should have the __esModule flag", () => { return import("./module").then(mod => { expect(mod.__esModule).toBe(true); expect(mod.default).toBe(84); }) }) webpack-4.30.0/test/configCases/scope-hoisting/esModule/module.js000066400000000000000000000000701345416772700247650ustar00rootroot00000000000000import other from "./other"; export default other * 2; webpack-4.30.0/test/configCases/scope-hoisting/esModule/other.js000066400000000000000000000000231345416772700246170ustar00rootroot00000000000000export default 42; webpack-4.30.0/test/configCases/scope-hoisting/esModule/webpack.config.js000066400000000000000000000001541345416772700263630ustar00rootroot00000000000000module.exports = { mode: "development", devtool: false, optimization: { concatenateModules: true } }; webpack-4.30.0/test/configCases/scope-hoisting/export-global/000077500000000000000000000000001345416772700241475ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/export-global/index.js000066400000000000000000000002671345416772700256210ustar00rootroot00000000000000import { process as p } from "./module"; import { process as p2 } from "./module2"; it("should export globals correctly", () => { expect(p).toBe(42); expect(p2).toBe(process); }); webpack-4.30.0/test/configCases/scope-hoisting/export-global/module.js000066400000000000000000000000501345416772700257650ustar00rootroot00000000000000const process = 42; export { process }; webpack-4.30.0/test/configCases/scope-hoisting/export-global/module2.js000066400000000000000000000000541345416772700260530ustar00rootroot00000000000000const p = process; export { p as process }; webpack-4.30.0/test/configCases/scope-hoisting/export-global/webpack.config.js000066400000000000000000000001051345416772700273610ustar00rootroot00000000000000module.exports = { optimization: { concatenateModules: true } }; webpack-4.30.0/test/configCases/scope-hoisting/harmony-pure-default/000077500000000000000000000000001345416772700254405ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/harmony-pure-default/index.js000066400000000000000000000006251345416772700271100ustar00rootroot00000000000000import x1, { value as v1 } from "./module1"; import x2, { value as v2 } from "./module2"; import { value as v3 } from "./module3"; import x4, { value as v4 } from "./module4"; it("should not execute exports when annotated with pure comment", () => { expect(v1).toBe(42); expect(v2).toBe(42); expect(v3).toBe(42); expect(v4).toBe(42); }); var x = /*#__PURE__*/(function() { return x1 + x2 + x4; }); webpack-4.30.0/test/configCases/scope-hoisting/harmony-pure-default/module1.js000066400000000000000000000001511345416772700273410ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export default /*#__PURE__*/inc(); export { value }; webpack-4.30.0/test/configCases/scope-hoisting/harmony-pure-default/module2.js000066400000000000000000000001531345416772700273440ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export default (/*#__PURE__*/inc()); export { value }; webpack-4.30.0/test/configCases/scope-hoisting/harmony-pure-default/module3.js000066400000000000000000000001531345416772700273450ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export default /*#__PURE__*/(inc()); export { value }; webpack-4.30.0/test/configCases/scope-hoisting/harmony-pure-default/module4.js000066400000000000000000000001751345416772700273520ustar00rootroot00000000000000let value = 42; const inc = () => { value++; }; export // hello default // world /*#__PURE__*/ inc() ; export { value }; webpack-4.30.0/test/configCases/scope-hoisting/harmony-pure-default/webpack.config.js000066400000000000000000000001541345416772700306560ustar00rootroot00000000000000module.exports = { mode: "production", optimization: { minimize: true, concatenateModules: true } }; webpack-4.30.0/test/configCases/scope-hoisting/named-modules/000077500000000000000000000000001345416772700241225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/named-modules/index.js000066400000000000000000000001541345416772700255670ustar00rootroot00000000000000import value from "./module"; it("should generate valid code", function() { expect(value).toBe("ok"); }); webpack-4.30.0/test/configCases/scope-hoisting/named-modules/module.js000066400000000000000000000000721345416772700257440ustar00rootroot00000000000000import module2 from "./module2"; export default module2; webpack-4.30.0/test/configCases/scope-hoisting/named-modules/module2.js000066400000000000000000000000271345416772700260260ustar00rootroot00000000000000module.exports = "ok"; webpack-4.30.0/test/configCases/scope-hoisting/named-modules/webpack.config.js000066400000000000000000000002431345416772700273370ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.NamedModulesPlugin(), new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-4.30.0/test/configCases/scope-hoisting/strictThisContextOnImports/000077500000000000000000000000001345416772700267505ustar00rootroot00000000000000webpack-4.30.0/test/configCases/scope-hoisting/strictThisContextOnImports/index.js000066400000000000000000000006311345416772700304150ustar00rootroot00000000000000import value, { identity } from "./module"; import * as m from "./module"; it("should parse and translate identifiers correctly", function() { expect(identity(value)).toBe(1234); expect(m.identity(value)).toBe(1234); expect(m.identity(identity)).toBe(identity); expect(m.identity(m.identity)).toBe(m.identity); expect(identity(m.identity)).toBe(m.identity); expect(identity(m.default)).toBe(1234); }); webpack-4.30.0/test/configCases/scope-hoisting/strictThisContextOnImports/module.js000066400000000000000000000000771345416772700305770ustar00rootroot00000000000000export function identity(a) { return a; } export default 1234; webpack-4.30.0/test/configCases/scope-hoisting/strictThisContextOnImports/webpack.config.js000066400000000000000000000002541345416772700321670ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { module: { strictThisContextOnImports: true }, plugins: [new webpack.optimize.ModuleConcatenationPlugin()] }; webpack-4.30.0/test/configCases/side-effects/000077500000000000000000000000001345416772700207765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-override/000077500000000000000000000000001345416772700251545ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-override/index.js000066400000000000000000000005421345416772700266220ustar00rootroot00000000000000import { log as plog } from "pmodule/tracker"; import { log as nlog } from "nmodule/tracker"; import p from "pmodule"; import n from "nmodule"; it("should be able to override side effects", function() { expect(p).toBe("def"); expect(n).toBe("def"); expect(plog).toEqual(["a.js", "b.js", "c.js", "index.js"]); expect(nlog).toEqual(["index.js"]); }); webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/000077500000000000000000000000001345416772700276315ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/nmodule/000077500000000000000000000000001345416772700312745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/nmodule/a.js000066400000000000000000000001571345416772700320550ustar00rootroot00000000000000var a = "a"; var b = "b"; var c = "c"; export { a, b, c }; import { track } from "./tracker"; track("a.js"); webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/nmodule/b.js000066400000000000000000000001701345416772700320510ustar00rootroot00000000000000var x = "x"; var y = "y"; export { x, y }; export { z } from "./c"; import { track } from "./tracker"; track("b.js"); webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/nmodule/c.js000066400000000000000000000001171345416772700320530ustar00rootroot00000000000000var z = "z"; export { z }; import { track } from "./tracker"; track("c.js"); webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/nmodule/index.js000066400000000000000000000002021345416772700327330ustar00rootroot00000000000000export * from "./a"; export { x, y, z } from "./b"; import { track } from "./tracker"; track("index.js"); export default "def"; webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/nmodule/package.json000066400000000000000000000000031345416772700335530ustar00rootroot00000000000000{} webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/nmodule/tracker.js000066400000000000000000000002021345416772700332570ustar00rootroot00000000000000export function track(file) { log.push(file); log.sort(); } export var log = []; export function reset() { log.length = 0; } webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/pmodule/000077500000000000000000000000001345416772700312765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/pmodule/a.js000066400000000000000000000001571345416772700320570ustar00rootroot00000000000000var a = "a"; var b = "b"; var c = "c"; export { a, b, c }; import { track } from "./tracker"; track("a.js"); webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/pmodule/b.js000066400000000000000000000001701345416772700320530ustar00rootroot00000000000000var x = "x"; var y = "y"; export { x, y }; export { z } from "./c"; import { track } from "./tracker"; track("b.js"); webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/pmodule/c.js000066400000000000000000000001171345416772700320550ustar00rootroot00000000000000var z = "z"; export { z }; import { track } from "./tracker"; track("c.js"); webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/pmodule/index.js000066400000000000000000000002021345416772700327350ustar00rootroot00000000000000export * from "./a"; export { x, y, z } from "./b"; import { track } from "./tracker"; track("index.js"); export default "def"; webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/pmodule/package.json000066400000000000000000000000351345416772700335620ustar00rootroot00000000000000{ "sideEffects": false } webpack-4.30.0/test/configCases/side-effects/side-effects-override/node_modules/pmodule/tracker.js000066400000000000000000000002021345416772700332610ustar00rootroot00000000000000export function track(file) { log.push(file); log.sort(); } export var log = []; export function reset() { log.length = 0; } webpack-4.30.0/test/configCases/side-effects/side-effects-override/webpack.config.js000066400000000000000000000004361345416772700303750ustar00rootroot00000000000000const path = require("path"); module.exports = { mode: "production", module: { rules: [ { test: path.resolve(__dirname, "node_modules/pmodule"), sideEffects: true }, { test: path.resolve(__dirname, "node_modules/nmodule"), sideEffects: false } ] } }; webpack-4.30.0/test/configCases/side-effects/side-effects-values/000077500000000000000000000000001345416772700246345ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/index.js000066400000000000000000000010601345416772700262760ustar00rootroot00000000000000import { log as booleanValueModuleLog } from "boolean-value-module/tracker"; import booleanValueModule from "boolean-value-module"; import { log as globValueModuleLog } from "glob-value-module/tracker"; import globValueModule from "glob-value-module"; it("should handle a boolean", function() { expect(booleanValueModule).toBe("def"); expect(booleanValueModuleLog).toEqual(["index.js"]); }); it("should handle globs", function() { expect(globValueModule).toBe("def"); expect(globValueModuleLog).toEqual([ "./src/a.js", "a.js", "index.js", ]); }); webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/000077500000000000000000000000001345416772700273115ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/boolean-value-module/000077500000000000000000000000001345416772700333255ustar00rootroot00000000000000a.js000066400000000000000000000001571345416772700340270ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/boolean-value-modulevar a = "a"; var b = "b"; var c = "c"; export { a, b, c }; import { track } from "./tracker"; track("a.js"); b.js000066400000000000000000000001701345416772700340230ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/boolean-value-modulevar x = "x"; var y = "y"; export { x, y }; export { z } from "./c"; import { track } from "./tracker"; track("b.js"); c.js000066400000000000000000000001171345416772700340250ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/boolean-value-modulevar z = "z"; export { z }; import { track } from "./tracker"; track("c.js"); index.js000066400000000000000000000002021345416772700347050ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/boolean-value-moduleexport * from "./a"; export { x, y, z } from "./b"; import { track } from "./tracker"; track("index.js"); export default "def"; package.json000066400000000000000000000000321345416772700355270ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/boolean-value-module{ "sideEffects": false } tracker.js000066400000000000000000000002021345416772700352310ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/boolean-value-moduleexport function track(file) { log.push(file); log.sort(); } export var log = []; export function reset() { log.length = 0; } webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-module/000077500000000000000000000000001345416772700326315ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-module/a.js000066400000000000000000000001171345416772700334060ustar00rootroot00000000000000var z = "z"; export { z }; import { track } from "./tracker"; track("a.js"); webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-module/b.js000066400000000000000000000001701345416772700334060ustar00rootroot00000000000000var x = "x"; var y = "y"; export { x, y }; export { z } from "./a"; import { track } from "./tracker"; track("b.js"); index.js000066400000000000000000000002411345416772700342140ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-moduleimport * as a from "./a"; import * as a2 from "./src/a"; import * as b from "./b"; import { track } from "./tracker"; track("index.js"); export default "def"; package.json000066400000000000000000000000471345416772700350410ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-module{ "sideEffects": [ "./**/a.js" ] } webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-module/src/000077500000000000000000000000001345416772700334205ustar00rootroot00000000000000a.js000066400000000000000000000001261345416772700341160ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-module/srcvar a = "a"; export { a }; import { track } from "../tracker"; track("./src/a.js"); tracker.js000066400000000000000000000002021345416772700345350ustar00rootroot00000000000000webpack-4.30.0/test/configCases/side-effects/side-effects-values/node_modules/glob-value-moduleexport function track(file) { log.push(file); log.sort(); } export var log = []; export function reset() { log.length = 0; } webpack-4.30.0/test/configCases/side-effects/side-effects-values/webpack.config.js000066400000000000000000000001051345416772700300460ustar00rootroot00000000000000module.exports = { mode: "production", module: { rules: [] } }; webpack-4.30.0/test/configCases/simple/000077500000000000000000000000001345416772700177265ustar00rootroot00000000000000webpack-4.30.0/test/configCases/simple/empty-config/000077500000000000000000000000001345416772700223275ustar00rootroot00000000000000webpack-4.30.0/test/configCases/simple/empty-config/index.js000066400000000000000000000000671345416772700237770ustar00rootroot00000000000000it("should compile and run the test", function() { });webpack-4.30.0/test/configCases/simple/empty-config/webpack.config.js000066400000000000000000000000251345416772700255420ustar00rootroot00000000000000module.exports = {}; webpack-4.30.0/test/configCases/simple/multi-compiler-functions-export/000077500000000000000000000000001345416772700262155ustar00rootroot00000000000000webpack-4.30.0/test/configCases/simple/multi-compiler-functions-export/index.js000066400000000000000000000001271345416772700276620ustar00rootroot00000000000000it("should run a multi compiler with functions with export default", function() { }); webpack-4.30.0/test/configCases/simple/multi-compiler-functions-export/webpack.config.js000066400000000000000000000000651345416772700314340ustar00rootroot00000000000000exports.default = [ function() { return {}; } ]; webpack-4.30.0/test/configCases/simple/multi-compiler-functions/000077500000000000000000000000001345416772700246765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/simple/multi-compiler-functions/index.js000066400000000000000000000001031345416772700263350ustar00rootroot00000000000000it("should run a multi compiler with functions", function() { }); webpack-4.30.0/test/configCases/simple/multi-compiler-functions/webpack.config.js000066400000000000000000000000641345416772700301140ustar00rootroot00000000000000module.exports = [ function() { return {}; } ]; webpack-4.30.0/test/configCases/simple/multi-compiler/000077500000000000000000000000001345416772700226705ustar00rootroot00000000000000webpack-4.30.0/test/configCases/simple/multi-compiler/index.js000066400000000000000000000000631345416772700243340ustar00rootroot00000000000000it("should run a multi compiler", function() { });webpack-4.30.0/test/configCases/simple/multi-compiler/webpack.config.js000066400000000000000000000000271345416772700261050ustar00rootroot00000000000000module.exports = [{}]; webpack-4.30.0/test/configCases/source-map/000077500000000000000000000000001345416772700205105ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/array-as-output-library-in-object-output/000077500000000000000000000000001345416772700304355ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/array-as-output-library-in-object-output/index.js000066400000000000000000000001441345416772700321010ustar00rootroot00000000000000it("should compile successfully when output.library.root is an array of strings", function () { }); webpack.config.js000066400000000000000000000002511345416772700335720ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/array-as-output-library-in-object-outputmodule.exports = { devtool: "source-map", output: { library: { root: ["Foo", "[name]"], amd: "[name]", commonjs: "[name]" }, libraryTarget: "umd" } }; webpack-4.30.0/test/configCases/source-map/array-as-output-library/000077500000000000000000000000001345416772700252275ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/array-as-output-library/index.js000066400000000000000000000001351345416772700266730ustar00rootroot00000000000000it("should compile successfully when output.library is an array of strings", function() {}); webpack-4.30.0/test/configCases/source-map/array-as-output-library/webpack.config.js000066400000000000000000000001311345416772700304400ustar00rootroot00000000000000module.exports = { devtool: "source-map", output: { library: ["Foo", "[name]"] } }; webpack-4.30.0/test/configCases/source-map/default-filename-extensions-css/000077500000000000000000000000001345416772700266755ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/default-filename-extensions-css/index.js000066400000000000000000000004041345416772700303400ustar00rootroot00000000000000it("creates source maps for .css output files by default", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var match = /sourceMappingURL\s*=\s*(.*)\*\//.exec(source); expect(match[1]).toBe("bundle0.css.map"); });webpack-4.30.0/test/configCases/source-map/default-filename-extensions-css/test.js000066400000000000000000000000441345416772700302100ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/default-filename-extensions-css/webpack.config.js000066400000000000000000000002411345416772700321100ustar00rootroot00000000000000module.exports = { mode: "development", output: { filename: "bundle0.css" }, node: { __dirname: false, __filename: false }, devtool: "source-map" }; webpack-4.30.0/test/configCases/source-map/default-filename-extensions-js/000077500000000000000000000000001345416772700265215ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/default-filename-extensions-js/index.js000066400000000000000000000003761345416772700301740ustar00rootroot00000000000000it("creates source maps for .js output files by default", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var match = /sourceMappingURL\s*=\s*(.*)/.exec(source); expect(match[1]).toBe("bundle0.js.map"); });webpack-4.30.0/test/configCases/source-map/default-filename-extensions-js/test.js000066400000000000000000000000441345416772700300340ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/default-filename-extensions-js/webpack.config.js000066400000000000000000000002401345416772700317330ustar00rootroot00000000000000module.exports = { mode: "development", output: { filename: "bundle0.js" }, node: { __dirname: false, __filename: false }, devtool: "source-map" }; webpack-4.30.0/test/configCases/source-map/default-filename-extensions-mjs/000077500000000000000000000000001345416772700266765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/default-filename-extensions-mjs/index.js000066400000000000000000000003751345416772700303500ustar00rootroot00000000000000it("creates source maps for .mjs output files by default", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var match = /sourceMappingURL\s*=\s*(.*)/.exec(source); expect(match[1]).toBe("bundle0.mjs.map"); }); webpack-4.30.0/test/configCases/source-map/default-filename-extensions-mjs/test.js000066400000000000000000000000441345416772700302110ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/default-filename-extensions-mjs/webpack.config.js000066400000000000000000000002411345416772700321110ustar00rootroot00000000000000module.exports = { mode: "development", output: { filename: "bundle0.mjs" }, node: { __dirname: false, __filename: false }, devtool: "source-map" }; webpack-4.30.0/test/configCases/source-map/exclude-chunks-source-map/000077500000000000000000000000001345416772700255035ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/exclude-chunks-source-map/index.js000066400000000000000000000010011345416772700271400ustar00rootroot00000000000000it("should include test.js in SourceMap for bundle0 chunk", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map.sources).toContain("webpack:///./test.js"); }); it("should not produce a SourceMap for vendors chunk", function() { var fs = require("fs"), path = require("path"), assert = require("assert"); expect(fs.existsSync(path.join(__dirname, "vendors.js.map"))).toBe(false); }); require.include("./test.js"); webpack-4.30.0/test/configCases/source-map/exclude-chunks-source-map/test.js000066400000000000000000000000451345416772700270170ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-4.30.0/test/configCases/source-map/exclude-chunks-source-map/vendors.js000066400000000000000000000000451345416772700275200ustar00rootroot00000000000000var bar = {}; module.exports = bar; webpack-4.30.0/test/configCases/source-map/exclude-chunks-source-map/webpack.config.js000066400000000000000000000005661345416772700307300ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { mode: "development", devtool: false, node: { __dirname: false, __filename: false }, entry: { bundle0: ["./index.js"], vendors: ["./vendors.js"] }, output: { filename: "[name].js" }, plugins: [ new webpack.SourceMapDevToolPlugin({ filename: "[file].map", exclude: ["vendors.js"] }) ] }; webpack-4.30.0/test/configCases/source-map/exclude-modules-source-map/000077500000000000000000000000001345416772700256605ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/exclude-modules-source-map/index.js000066400000000000000000000005701345416772700273270ustar00rootroot00000000000000it("bundle1 should include eval sourcemapped test1.js and test2.js as is", function() { var fs = require("fs"); var path = require("path"); var bundle1 = fs.readFileSync(path.join(__dirname, "bundle1.js"), "utf-8"); expect(bundle1).toMatch("eval(\"var test1marker"); expect(bundle1).toMatch("var test2marker"); expect(bundle1).not.toMatch("eval(\"var test2marker"); }); webpack-4.30.0/test/configCases/source-map/exclude-modules-source-map/test1.js000066400000000000000000000000651345416772700272570ustar00rootroot00000000000000var test1marker = {}; module.exports = test1marker; webpack-4.30.0/test/configCases/source-map/exclude-modules-source-map/test2.js000066400000000000000000000000651345416772700272600ustar00rootroot00000000000000var test2marker = {}; module.exports = test2marker; webpack-4.30.0/test/configCases/source-map/exclude-modules-source-map/webpack.config.js000066400000000000000000000005721345416772700311020ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { node: { __dirname: false, __filename: false }, entry: { bundle0: ["./index.js"], bundle1: ["./test1.js", "./test2.js"] }, output: { filename: "[name].js" }, plugins: [ new webpack.EvalSourceMapDevToolPlugin({ include: /\.js$/, exclude: /test2\.js/, module: true, columns: false }) ] }; webpack-4.30.0/test/configCases/source-map/line-to-line/000077500000000000000000000000001345416772700230045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/line-to-line/index.js000066400000000000000000000004071345416772700244520ustar00rootroot00000000000000it("should include test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map.sources).toContain("webpack:///./test.js"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/source-map/line-to-line/test.js000066400000000000000000000000441345416772700243170ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/line-to-line/webpack.config.js000066400000000000000000000002471345416772700262250ustar00rootroot00000000000000module.exports = { mode: "development", output: { devtoolLineToLine: true }, node: { __dirname: false, __filename: false }, devtool: "cheap-source-map" }; webpack-4.30.0/test/configCases/source-map/module-names/000077500000000000000000000000001345416772700230765ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/module-names/index.js000066400000000000000000000013741345416772700245500ustar00rootroot00000000000000function getSourceMap(filename) { var fs = require("fs"); var source = fs.readFileSync(__dirname + "/" + filename + ".map", "utf-8"); var map = JSON.parse(source); return map; } it("should include test.js in SourceMap", function() { var map = getSourceMap("bundle0.js"); expect(map.sources).toContain("module"); expect(map.sources).toContain("fallback"); expect(map.sources).toContain("fallback**"); map = getSourceMap("chunk-a.js"); expect(map.sources).toContain("fallback*"); map = getSourceMap("chunk-b.js"); expect(map.sources).toContain("fallback*"); expect(map.sources).toContain("fallback***"); }); require.ensure(["./test.js"], function(require) {}, "chunk-a"); require.ensure(["./test.js", "./test.js?1"], function(require) {}, "chunk-b"); webpack-4.30.0/test/configCases/source-map/module-names/test.js000066400000000000000000000000441345416772700244110ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/module-names/webpack.config.js000066400000000000000000000004041345416772700263120ustar00rootroot00000000000000module.exports = { mode: "development", output: { chunkFilename: "[name].js", devtoolModuleFilenameTemplate: "module", devtoolFallbackModuleFilenameTemplate: "fallback" }, node: { __dirname: false, __filename: false }, devtool: "source-map" }; webpack-4.30.0/test/configCases/source-map/namespace-source-path.library/000077500000000000000000000000001345416772700263375ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/namespace-source-path.library/index.js000066400000000000000000000004461345416772700300100ustar00rootroot00000000000000it("should include webpack://mylibrary/./test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map.sources).toContain("webpack://mylibrary/./test.js"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/source-map/namespace-source-path.library/test.js000066400000000000000000000000441345416772700276520ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/namespace-source-path.library/webpack.config.js000066400000000000000000000002441345416772700315550ustar00rootroot00000000000000module.exports = { mode: "development", output: { library: "mylibrary" }, node: { __dirname: false, __filename: false }, devtool: "cheap-source-map" }; webpack-4.30.0/test/configCases/source-map/namespace-source-path/000077500000000000000000000000001345416772700246745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/namespace-source-path/index.js000066400000000000000000000004521345416772700263420ustar00rootroot00000000000000it("should include webpack://mynamespace/./test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map.sources).toContain("webpack://mynamespace/./test.js"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/source-map/namespace-source-path/test.js000066400000000000000000000000441345416772700262070ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/namespace-source-path/webpack.config.js000066400000000000000000000002571345416772700301160ustar00rootroot00000000000000module.exports = { mode: "development", output: { devtoolNamespace: "mynamespace" }, node: { __dirname: false, __filename: false }, devtool: "cheap-source-map" }; webpack-4.30.0/test/configCases/source-map/nosources/000077500000000000000000000000001345416772700225305ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/nosources/index.js000066400000000000000000000004341345416772700241760ustar00rootroot00000000000000it("should not include sourcesContent if noSources option is used", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map).not.toHaveProperty('sourcesContent'); }); require.include("./test.js"); webpack-4.30.0/test/configCases/source-map/nosources/test.js000066400000000000000000000000451345416772700240440ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-4.30.0/test/configCases/source-map/nosources/webpack.config.js000066400000000000000000000002021345416772700257400ustar00rootroot00000000000000module.exports = { mode: "development", node: { __dirname: false, __filename: false }, devtool: "nosources-source-map" }; webpack-4.30.0/test/configCases/source-map/object-as-output-library/000077500000000000000000000000001345416772700253575ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/object-as-output-library/index.js000066400000000000000000000001401345416772700270170ustar00rootroot00000000000000it("should compile successfully when output.library is an object of type:name", function() {}); webpack-4.30.0/test/configCases/source-map/object-as-output-library/webpack.config.js000066400000000000000000000002401345416772700305710ustar00rootroot00000000000000module.exports = { devtool: "source-map", output: { library: { root: "[name]", amd: "[name]", commonjs: "[name]" }, libraryTarget: "umd" } }; webpack-4.30.0/test/configCases/source-map/relative-source-map-path/000077500000000000000000000000001345416772700253265ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/relative-source-map-path/index.js000066400000000000000000000006621345416772700267770ustar00rootroot00000000000000it("should have a relative url to the source-map", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var match = /sourceMappingURL\s*=\s*(.*)/.exec(source); expect(match[1]).toBe("bundle0.js.map"); }); it("should have a relative url to the source-map with prefix", function(done) { require.ensure([], function(require) { global.expect = expect; require("./test.js"); done(); }); }); webpack-4.30.0/test/configCases/source-map/relative-source-map-path/test.js000066400000000000000000000002461345416772700266450ustar00rootroot00000000000000var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var match = /sourceMappingURL\s*=\s*(.*)/.exec(source); expect(match[1]).toBe("c.js.map"); webpack-4.30.0/test/configCases/source-map/relative-source-map-path/webpack.config.js000066400000000000000000000002511345416772700305420ustar00rootroot00000000000000module.exports = { mode: "development", output: { chunkFilename: "js/chunks/c.js" }, node: { __dirname: false, __filename: false }, devtool: "source-map" }; webpack-4.30.0/test/configCases/source-map/source-map-filename-contenthash/000077500000000000000000000000001345416772700266555ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/source-map-filename-contenthash/index.js000066400000000000000000000004521345416772700303230ustar00rootroot00000000000000it("should contain contenthash as query parameter and path", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var match = /sourceMappingURL\s*=.*-([A-Fa-f0-9]{32})\.map\?([A-Fa-f0-9]{32})-([A-Fa-f0-9]{32})/.exec(source); expect(match.length).toBe(4); }); webpack-4.30.0/test/configCases/source-map/source-map-filename-contenthash/webpack.config.js000066400000000000000000000003231345416772700320710ustar00rootroot00000000000000module.exports = { mode: "development", node: { __dirname: false, __filename: false }, devtool: "source-map", output: { sourceMapFilename: "[file]-[contenthash].map?[contenthash]-[contenthash]" } }; webpack-4.30.0/test/configCases/source-map/source-map-with-profiling-plugin/000077500000000000000000000000001345416772700270175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/source-map-with-profiling-plugin/index.js000066400000000000000000000004171345416772700304660ustar00rootroot00000000000000it("bundle0 should include sourcemapped test.js", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map.sources).toContain("webpack:///./test.js"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/source-map/source-map-with-profiling-plugin/test.filter.js000066400000000000000000000001001345416772700316070ustar00rootroot00000000000000module.exports = function(config) { return !process.env.CI; }; webpack-4.30.0/test/configCases/source-map/source-map-with-profiling-plugin/test.js000066400000000000000000000000451345416772700303330ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-4.30.0/test/configCases/source-map/source-map-with-profiling-plugin/webpack.config.js000066400000000000000000000005751345416772700322440ustar00rootroot00000000000000var webpack = require("../../../../"); var path = require("path"); var os = require("os"); module.exports = { node: { __dirname: false, __filename: false }, entry: { bundle0: ["./index.js"] }, output: { filename: "[name].js" }, plugins: [ new webpack.debug.ProfilingPlugin({ outputPath: path.join(os.tmpdir(), "events.json") }) ], devtool: "source-map" }; webpack-4.30.0/test/configCases/source-map/sources-array-production/000077500000000000000000000000001345416772700254735ustar00rootroot00000000000000webpack-4.30.0/test/configCases/source-map/sources-array-production/index.js000066400000000000000000000004071345416772700271410ustar00rootroot00000000000000it("should include test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); expect(map.sources).toContain("webpack:///./test.js"); }); require.include("./test.js"); webpack-4.30.0/test/configCases/source-map/sources-array-production/test.js000066400000000000000000000000441345416772700270060ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-4.30.0/test/configCases/source-map/sources-array-production/webpack.config.js000066400000000000000000000002101345416772700307020ustar00rootroot00000000000000module.exports = { node: { __dirname: false, __filename: false }, devtool: "source-map", optimization: { minimize: true } }; webpack-4.30.0/test/configCases/split-chunks/000077500000000000000000000000001345416772700210615ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/000077500000000000000000000000001345416772700273455ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/a.js000066400000000000000000000000731345416772700301230ustar00rootroot00000000000000const c = require("./commons"); module.exports = "a" + c; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/b.js000066400000000000000000000000731345416772700301240ustar00rootroot00000000000000const c = require("./commons"); module.exports = "b" + c; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/c.js000066400000000000000000000000731345416772700301250ustar00rootroot00000000000000const c = require("./commons"); module.exports = "c" + c; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/commons.js000066400000000000000000000001131345416772700313510ustar00rootroot00000000000000/* Large module to trigger chunk generation */ module.exports = "commons"; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/index.js000066400000000000000000000005231345416772700310120ustar00rootroot00000000000000it("should run", function() { Promise.all( [ import(/* webpackChunkName: "a" */ "./a"), import(/* webpackChunkName: "b" */ "./b"), import(/* webpackChunkName: "c" */ "./c") ] ); const files = require("fs").readdirSync(__dirname); const hasFile = files.indexOf('a~b~c.bundle.js') !== -1; expect(hasFile).toBe(true); }); webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/test.config.js000066400000000000000000000001231345416772700321220ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return ["main.js"]; } }; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter-default/webpack.config.js000066400000000000000000000004161345416772700325640ustar00rootroot00000000000000module.exports = { entry: { main: "./index" }, node: { __dirname: false, __filename: false }, output: { filename: "[name].js", chunkFilename: "[name].bundle.js", jsonpFunction: "_load_chunk" }, optimization: { splitChunks: { minSize: 1 } } }; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/000077500000000000000000000000001345416772700257235ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/a.js000066400000000000000000000000731345416772700265010ustar00rootroot00000000000000const c = require("./commons"); module.exports = "a" + c; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/b.js000066400000000000000000000000731345416772700265020ustar00rootroot00000000000000const c = require("./commons"); module.exports = "b" + c; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/c.js000066400000000000000000000000731345416772700265030ustar00rootroot00000000000000const c = require("./commons"); module.exports = "c" + c; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/commons.js000066400000000000000000000000351345416772700277320ustar00rootroot00000000000000 module.exports = "commons"; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/index.js000066400000000000000000000005231345416772700273700ustar00rootroot00000000000000it("should run", function() { Promise.all( [ import(/* webpackChunkName: "a" */ "./a"), import(/* webpackChunkName: "b" */ "./b"), import(/* webpackChunkName: "c" */ "./c") ] ); const files = require("fs").readdirSync(__dirname); const hasFile = files.indexOf('a-b-c.bundle.js') !== -1; expect(hasFile).toBe(true); }); webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/test.config.js000066400000000000000000000001231345416772700305000ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return ["main.js"]; } }; webpack-4.30.0/test/configCases/split-chunks/chunk-filename-delimiter/webpack.config.js000066400000000000000000000004561345416772700311460ustar00rootroot00000000000000module.exports = { entry: { main: "./index" }, node: { __dirname: false, __filename: false }, output: { filename: "[name].js", chunkFilename: "[name].bundle.js", jsonpFunction: "_load_chunk" }, optimization: { splitChunks: { automaticNameDelimiter: "-", minSize: 1 } } }; webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/000077500000000000000000000000001345416772700253005ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/a.js000066400000000000000000000000401345416772700260500ustar00rootroot00000000000000import "./x/1"; import "./y/1"; webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/b.js000066400000000000000000000000201345416772700260470ustar00rootroot00000000000000import "./y/2"; webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/c.js000066400000000000000000000000201345416772700260500ustar00rootroot00000000000000import "./y/3"; webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/index.js000066400000000000000000000004561345416772700267520ustar00rootroot00000000000000it("should find all modules", function() { return Promise.all([ import(/* webpackChunkName: "a" */ "./a"), // has 3 modules (1 into x, 1 into y) import(/* webpackChunkName: "b" */ "./b"), // has 2 modules (1 into y) import(/* webpackChunkName: "c" */ "./c"), // has 2 modules (1 into y) ]) }); webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/webpack.config.js000066400000000000000000000006021345416772700305140ustar00rootroot00000000000000const path = require("path"); module.exports = { entry: "./index", optimization: { splitChunks: { cacheGroups: { x: { test: path.resolve(__dirname, "x"), name: "x", priority: 2, enforce: true }, y: { test: path.resolve(__dirname, "y"), priority: 1, name: "y", enforce: true, reuseExistingChunk: true } } } } }; webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/x/000077500000000000000000000000001345416772700255475ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/x/1.js000066400000000000000000000000001345416772700262330ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/y/000077500000000000000000000000001345416772700255505ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/y/1.js000066400000000000000000000000001345416772700262340ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/y/2.js000066400000000000000000000000001345416772700262350ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/incorrect-chunk-reuse/y/3.js000066400000000000000000000000001345416772700262360ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/issue-8908/000077500000000000000000000000001345416772700226175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/issue-8908/a.js000066400000000000000000000000721345416772700233740ustar00rootroot00000000000000require("./vendor/vendor-a"); it("should run", () => {});webpack-4.30.0/test/configCases/split-chunks/issue-8908/b.js000066400000000000000000000000361345416772700233750ustar00rootroot00000000000000require("./vendor/vendor-b"); webpack-4.30.0/test/configCases/split-chunks/issue-8908/index.js000066400000000000000000000001211345416772700242560ustar00rootroot00000000000000it("should run", function() { var a = require("./a"); expect(a).toBe("a"); }); webpack-4.30.0/test/configCases/split-chunks/issue-8908/test.config.js000066400000000000000000000001551345416772700254010ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return ["runtime.js", "vendor-a.js", "a.js"]; } }; webpack-4.30.0/test/configCases/split-chunks/issue-8908/vendor/000077500000000000000000000000001345416772700241145ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/issue-8908/vendor/vendor-a.js000066400000000000000000000000341345416772700261620ustar00rootroot00000000000000module.exports ="vendor-a"; webpack-4.30.0/test/configCases/split-chunks/issue-8908/vendor/vendor-b.js000066400000000000000000000000651345416772700261670ustar00rootroot00000000000000require("./vendor-a"); module.exports = "vendor-b"; webpack-4.30.0/test/configCases/split-chunks/issue-8908/webpack.config.js000066400000000000000000000006231345416772700260360ustar00rootroot00000000000000module.exports = { entry: { a: "./a", b: "./b" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: { chunks: "initial", cacheGroups: { a: { test: /vendor-a/, name: "vendor-a", enforce: true, priority: 1 }, b: { test: /vendor/, name: "vendor-b", enforce: true } } }, runtimeChunk: "single" } }; webpack-4.30.0/test/configCases/split-chunks/no-options/000077500000000000000000000000001345416772700231665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/no-options/a.js000066400000000000000000000000261345416772700237420ustar00rootroot00000000000000module.exports = "a"; webpack-4.30.0/test/configCases/split-chunks/no-options/index.js000066400000000000000000000001211345416772700246250ustar00rootroot00000000000000it("should run", function() { var a = require("./a"); expect(a).toBe("a"); }); webpack-4.30.0/test/configCases/split-chunks/no-options/test.config.js000066400000000000000000000001401345416772700257420ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return ["vendor.js", "main.js"]; } }; webpack-4.30.0/test/configCases/split-chunks/no-options/webpack.config.js000066400000000000000000000004401345416772700264020ustar00rootroot00000000000000const SplitChunksPlugin = require("../../../../lib/optimize/SplitChunksPlugin"); module.exports = { entry: { vendor: ["./a"], main: "./index" }, target: "web", output: { filename: "[name].js" }, optimization: { splitChunks: false }, plugins: [new SplitChunksPlugin()] }; webpack-4.30.0/test/configCases/split-chunks/runtime-chunk-no-async/000077500000000000000000000000001345416772700253775ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/runtime-chunk-no-async/index.js000066400000000000000000000000621345416772700270420ustar00rootroot00000000000000it("should compile and evaluate fine", () => {}); webpack-4.30.0/test/configCases/split-chunks/runtime-chunk-no-async/test.config.js000066400000000000000000000003121345416772700301540ustar00rootroot00000000000000const fs = require("fs"); module.exports = { findBundle: function(i, options) { var files = fs.readdirSync(options.output.path); return ["runtime.js", files.filter(f => /^main/.test(f))[0]]; } }; webpack-4.30.0/test/configCases/split-chunks/runtime-chunk-no-async/webpack.config.js000066400000000000000000000003061345416772700306140ustar00rootroot00000000000000module.exports = { entry: { main: "./index" }, target: "web", output: { filename: "[name].js", chunkFilename: "main.[contenthash:8].js" }, optimization: { runtimeChunk: "single" } }; webpack-4.30.0/test/configCases/split-chunks/runtime-chunk/000077500000000000000000000000001345416772700236525ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/runtime-chunk/a.js000066400000000000000000000004751345416772700244360ustar00rootroot00000000000000it("should be able to load the split chunk on demand", () => { const promise = import(/* webpackChunkName: "shared" */ "./shared"); const script = document.head._children[0]; expect(script.src).toBe("https://test.cases/path/dep~b~shared.js"); __non_webpack_require__("./dep~b~shared.js"); return promise; }); webpack-4.30.0/test/configCases/split-chunks/runtime-chunk/b.js000066400000000000000000000000231345416772700244240ustar00rootroot00000000000000import "./shared"; webpack-4.30.0/test/configCases/split-chunks/runtime-chunk/shared.js000066400000000000000000000000001345416772700254440ustar00rootroot00000000000000webpack-4.30.0/test/configCases/split-chunks/runtime-chunk/test.config.js000066400000000000000000000001361345416772700264330ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return ["runtime.js", "a.js"]; } }; webpack-4.30.0/test/configCases/split-chunks/runtime-chunk/webpack.config.js000066400000000000000000000005241345416772700270710ustar00rootroot00000000000000const path = require("path"); module.exports = { entry: { a: "./a", b: "./b" }, target: "web", output: { filename: "[name].js" }, optimization: { runtimeChunk: "single", splitChunks: { cacheGroups: { dep: { chunks: "all", test: path.resolve(__dirname, "shared.js"), enforce: true } } } } }; webpack-4.30.0/test/configCases/target/000077500000000000000000000000001345416772700177235ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/amd-named/000077500000000000000000000000001345416772700215465ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/amd-named/index.js000066400000000000000000000003211345416772700232070ustar00rootroot00000000000000it("should run", function() { }); it("should name define", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch("define(\"NamedLibrary\","); }); webpack-4.30.0/test/configCases/target/amd-named/webpack.config.js000066400000000000000000000004551345416772700247700ustar00rootroot00000000000000const webpack = require("../../../../"); module.exports = { output: { library: "NamedLibrary", libraryTarget: "amd" }, node: { __dirname: false, __filename: false }, plugins: [ new webpack.BannerPlugin({ raw: true, banner: "function define(name, deps, fn) { fn(); }\n" }) ] }; webpack-4.30.0/test/configCases/target/amd-require/000077500000000000000000000000001345416772700221365ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/amd-require/index.js000066400000000000000000000003351345416772700236040ustar00rootroot00000000000000it("should run", function() { }); it("should name require", function() { var fs = nodeRequire("fs"); var source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch(/require\(\[[^\]]*\], function\(/); }); webpack-4.30.0/test/configCases/target/amd-require/webpack.config.js000066400000000000000000000004731345416772700253600ustar00rootroot00000000000000const webpack = require("../../../../"); module.exports = { output: { libraryTarget: "amd-require" }, node: { __dirname: false, __filename: false }, plugins: [ new webpack.BannerPlugin({ raw: true, banner: "var nodeRequire = require;\nvar require = function(deps, fn) { fn(); }\n" }) ] }; webpack-4.30.0/test/configCases/target/amd-unnamed/000077500000000000000000000000001345416772700221115ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/amd-unnamed/index.js000066400000000000000000000003271345416772700235600ustar00rootroot00000000000000it("should run", function() { }); it("should name define", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch(/define\(\[[^\]]*\], function\(/); }); webpack-4.30.0/test/configCases/target/amd-unnamed/webpack.config.js000066400000000000000000000004141345416772700253260ustar00rootroot00000000000000const webpack = require("../../../../"); module.exports = { output: { libraryTarget: "amd" }, node: { __dirname: false, __filename: false }, plugins: [ new webpack.BannerPlugin({ raw: true, banner: "function define(deps, fn) { fn(); }\n" }) ] }; webpack-4.30.0/test/configCases/target/buffer-default/000077500000000000000000000000001345416772700226165ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/buffer-default/index.js000066400000000000000000000003521345416772700242630ustar00rootroot00000000000000it("should provide a global Buffer shim", function () { expect(Buffer).toBeInstanceOf(Function); }); it("should provide the buffer module", function () { var buffer = require("buffer"); expect((typeof buffer)).toBe("object"); }); webpack-4.30.0/test/configCases/target/buffer-default/webpack.config.js000066400000000000000000000000451345416772700260330ustar00rootroot00000000000000module.exports = { target: "web" }; webpack-4.30.0/test/configCases/target/buffer/000077500000000000000000000000001345416772700211745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/buffer/index.js000066400000000000000000000001461345416772700226420ustar00rootroot00000000000000it("should provide a global Buffer shim", function () { expect(Buffer).toBeInstanceOf(Function); }); webpack-4.30.0/test/configCases/target/buffer/webpack.config.js000066400000000000000000000001221345416772700244050ustar00rootroot00000000000000module.exports = { target: "web", node: { Buffer: true, buffer: false } }; webpack-4.30.0/test/configCases/target/electron-renderer/000077500000000000000000000000001345416772700233425ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/electron-renderer/index.js000066400000000000000000000001531345416772700250060ustar00rootroot00000000000000const foo = require("foo"); it("should use browser main field", () => { expect(foo).toBe("browser"); }); webpack-4.30.0/test/configCases/target/electron-renderer/node_modules/000077500000000000000000000000001345416772700260175ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/electron-renderer/node_modules/foo/000077500000000000000000000000001345416772700266025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/electron-renderer/node_modules/foo/browser.js000066400000000000000000000000341345416772700306200ustar00rootroot00000000000000module.exports = "browser"; webpack-4.30.0/test/configCases/target/electron-renderer/node_modules/foo/main.js000066400000000000000000000000311345416772700300560ustar00rootroot00000000000000module.exports = "main"; webpack-4.30.0/test/configCases/target/electron-renderer/node_modules/foo/package.json000066400000000000000000000001321345416772700310640ustar00rootroot00000000000000{ "name": "foo", "version": "1.0.0", "browser": "./browser.js", "main": "./main.js" } webpack-4.30.0/test/configCases/target/electron-renderer/webpack.config.js000066400000000000000000000001321345416772700265540ustar00rootroot00000000000000module.exports = { target: "electron-renderer", optimization: { minimize: false } }; webpack-4.30.0/test/configCases/target/node-dynamic-import/000077500000000000000000000000001345416772700236025ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/node-dynamic-import/dir/000077500000000000000000000000001345416772700243605ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/node-dynamic-import/dir/one.js000066400000000000000000000000241345416772700254730ustar00rootroot00000000000000module.exports = 1; webpack-4.30.0/test/configCases/target/node-dynamic-import/dir/three.js000066400000000000000000000000241345416772700260210ustar00rootroot00000000000000module.exports = 3; webpack-4.30.0/test/configCases/target/node-dynamic-import/dir/two.js000066400000000000000000000000241345416772700255230ustar00rootroot00000000000000module.exports = 2; webpack-4.30.0/test/configCases/target/node-dynamic-import/dir2/000077500000000000000000000000001345416772700244425ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/node-dynamic-import/dir2/one.js000066400000000000000000000000241345416772700255550ustar00rootroot00000000000000module.exports = 1; webpack-4.30.0/test/configCases/target/node-dynamic-import/dir2/three.js000066400000000000000000000000241345416772700261030ustar00rootroot00000000000000module.exports = 3; webpack-4.30.0/test/configCases/target/node-dynamic-import/dir2/two.js000066400000000000000000000000241345416772700256050ustar00rootroot00000000000000module.exports = 2; webpack-4.30.0/test/configCases/target/node-dynamic-import/index.js000066400000000000000000000033041345416772700252470ustar00rootroot00000000000000function testCase(load, done) { load("two", 2, function() { var sync = true; load("one", 1, function() { expect(sync).toBe(false); load("three", 3, function() { var sync = true; load("two", 2, function() { expect(sync).toBe(true); done(); }); Promise.resolve().then(function() {}).then(function() {}).then(function() { sync = false; }); }); }); Promise.resolve().then(function() { sync = false; }); }); } it("should be able to use expressions in import", function(done) { function load(name, expected, callback) { import("./dir/" + name + '.js') .then((result) => {expect(result).toEqual(nsObj({ default: expected })); callback()}) .catch((err) => {done(err)}); } testCase(load, done); }); it("should be able to use expressions in lazy-once import", function(done) { function load(name, expected, callback) { import(/* webpackMode: "lazy-once" */ "./dir/" + name + '.js') .then((result) => {expect(result).toEqual(nsObj({ default: expected })); callback()}) .catch((err) => {done(err)}); } testCase(load, done); }); it("should be able to use expressions in import", function(done) { function load(name, expected, callback) { import("./dir2/" + name).then((result) => { expect(result).toEqual(nsObj({ default: expected })); callback(); }).catch((err) => { done(err); }); } testCase(load, done); }); it("should convert to function in node", function() { expect((typeof __webpack_require__.e)).toBe("function"); }) it("should be able to use import", function(done) { import("./two").then((two) => { expect(two).toEqual(nsObj({ default: 2 })); done(); }).catch(function(err) { done(err); }); }); webpack-4.30.0/test/configCases/target/node-dynamic-import/test.filter.js000066400000000000000000000002261345416772700264030ustar00rootroot00000000000000var supportsArrowFn = require("../../../helpers/supportsArrowFunctionExpression"); module.exports = function(config) { return supportsArrowFn(); }; webpack-4.30.0/test/configCases/target/node-dynamic-import/two.js000066400000000000000000000000231345416772700247440ustar00rootroot00000000000000module.exports = 2;webpack-4.30.0/test/configCases/target/node-dynamic-import/webpack.config.js000066400000000000000000000001111345416772700270110ustar00rootroot00000000000000module.exports = { target: "node", performance: { hints: false } }; webpack-4.30.0/test/configCases/target/strict-mode-global/000077500000000000000000000000001345416772700234135ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/strict-mode-global/index.js000066400000000000000000000002421345416772700250560ustar00rootroot00000000000000"use strict"; it("should be able to use global in strict mode", function() { expect((typeof global)).toBe("object"); expect((global === null)).toBe(false) }); webpack-4.30.0/test/configCases/target/strict-mode-global/webpack.config.js000066400000000000000000000000451345416772700266300ustar00rootroot00000000000000module.exports = { target: "web" }; webpack-4.30.0/test/configCases/target/system-export/000077500000000000000000000000001345416772700225665ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/system-export/index.js000066400000000000000000000006311345416772700242330ustar00rootroot00000000000000// This test verifies that values exported by a webpack bundle are consumable by systemjs. export const namedThing = { hello: "there" }; export default "the default export"; it("should successfully export values to System", function() { const exports = eval("System").registry["(anonym)"].exports; expect(exports["default"]).toBe("the default export"); expect(exports.namedThing).toBe(namedThing); }); webpack-4.30.0/test/configCases/target/system-export/test.config.js000066400000000000000000000003461345416772700253520ustar00rootroot00000000000000const System = require("../../../helpers/fakeSystem"); module.exports = { beforeExecute: () => { System.init(); }, moduleScope(scope) { scope.System = System; }, afterExecute: () => { System.execute("(anonym)"); } }; webpack-4.30.0/test/configCases/target/system-export/webpack.config.js000066400000000000000000000001631345416772700260040ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "system" }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/target/system-named/000077500000000000000000000000001345416772700223315ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/system-named/index.js000066400000000000000000000003321345416772700237740ustar00rootroot00000000000000/* This test verifies that when output.library is specified that the compiled bundle provides * the library name to System during the System.register */ it("should call System.register with a name", function() {}); webpack-4.30.0/test/configCases/target/system-named/test.config.js000066400000000000000000000003611345416772700251120ustar00rootroot00000000000000const System = require("../../../helpers/fakeSystem"); module.exports = { beforeExecute: () => { System.init(); }, moduleScope(scope) { scope.System = System; }, afterExecute: () => { System.execute("named-system-module"); } }; webpack-4.30.0/test/configCases/target/system-named/webpack.config.js000066400000000000000000000002251345416772700255460ustar00rootroot00000000000000module.exports = { output: { library: "named-system-module", libraryTarget: "system" }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/target/system-unnamed/000077500000000000000000000000001345416772700226745ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/system-unnamed/index.js000066400000000000000000000003211345416772700243350ustar00rootroot00000000000000/* This test verifies that when there is no output.library specified that the call to * System.register does not include a name argument. */ it("should call System.register without a name", function() {}); webpack-4.30.0/test/configCases/target/system-unnamed/test.config.js000066400000000000000000000003461345416772700254600ustar00rootroot00000000000000const System = require("../../../helpers/fakeSystem"); module.exports = { beforeExecute: () => { System.init(); }, moduleScope(scope) { scope.System = System; }, afterExecute: () => { System.execute("(anonym)"); } }; webpack-4.30.0/test/configCases/target/system-unnamed/webpack.config.js000066400000000000000000000001631345416772700261120ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "system" }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/target/umd-auxiliary-comments-object/000077500000000000000000000000001345416772700256045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/umd-auxiliary-comments-object/index.js000066400000000000000000000006301345416772700272500ustar00rootroot00000000000000it("should run", function() { }); it("should have auxiliary comments", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch("//test " + "comment " + "commonjs"); expect(source).toMatch("//test " + "comment " + "commonjs2"); expect(source).toMatch("//test " + "comment " + "amd"); expect(source).toMatch("//test " + "comment " + "root"); }); webpack-4.30.0/test/configCases/target/umd-auxiliary-comments-object/webpack.config.js000066400000000000000000000005051345416772700310220ustar00rootroot00000000000000module.exports = { output: { library: "NamedLibrary", libraryTarget: "umd", umdNamedDefine: true, auxiliaryComment: { commonjs: "test comment commonjs", commonjs2: "test comment commonjs2", amd: "test comment amd", root: "test comment root" } }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/target/umd-auxiliary-comments-string/000077500000000000000000000000001345416772700256445ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/umd-auxiliary-comments-string/index.js000066400000000000000000000003361345416772700273130ustar00rootroot00000000000000it("should run", function() { }); it("should have auxiliary comment string", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch("//test " + "comment"); }); webpack-4.30.0/test/configCases/target/umd-auxiliary-comments-string/webpack.config.js000066400000000000000000000003071345416772700310620ustar00rootroot00000000000000module.exports = { output: { library: "NamedLibrary", libraryTarget: "umd", umdNamedDefine: true, auxiliaryComment: "test comment" }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/target/umd-named-define/000077500000000000000000000000001345416772700230225ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/umd-named-define/index.js000066400000000000000000000003211345416772700244630ustar00rootroot00000000000000it("should run", function() { }); it("should name define", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); expect(source).toMatch("define(\"NamedLibrary\","); }); webpack-4.30.0/test/configCases/target/umd-named-define/webpack.config.js000066400000000000000000000002431345416772700262370ustar00rootroot00000000000000module.exports = { output: { library: "NamedLibrary", libraryTarget: "umd", umdNamedDefine: true }, node: { __dirname: false, __filename: false } }; webpack-4.30.0/test/configCases/target/web/000077500000000000000000000000001345416772700205005ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/web/index.js000066400000000000000000000045661345416772700221600ustar00rootroot00000000000000global.XMLHttpRequest = function() {}; global.XMLHttpRequest.prototype.open = function() {}; it("should provide a global Buffer constructor", function() { expect(Buffer).toBeInstanceOf(Function); }); it("should provide a global process shim", function () { expect(process).toBeInstanceOf(Object); }); it("should provide a global setImmediate shim", function () { expect(setImmediate).toBeInstanceOf(Function); }); it("should provide a global clearImmediate shim", function () { expect(clearImmediate).toBeInstanceOf(Function); }); it("should provide an assert shim", function () { expect(require("assert")).toBeInstanceOf(Function); }); it("should provide a util shim", function () { expect(require("util")).toBeInstanceOf(Object); }); it("should provide a buffer shim", function () { expect(require("buffer")).toBeInstanceOf(Object); }); it("should provide a crypto shim", function () { expect(require("crypto")).toBeInstanceOf(Object); }); it("should provide a domain shim", function () { expect(require("domain")).toBeInstanceOf(Object); }); it("should provide an events shim", function () { expect(require("events")).toBeInstanceOf(Function); }); it("should provide an http shim", function () { expect(require("http")).toBeInstanceOf(Object); }); it("should provide an https shim", function () { expect(require("https")).toBeInstanceOf(Object); }); it("should provide an os shim", function () { expect(require("os")).toBeInstanceOf(Object); }); it("should provide a path shim", function () { expect(require("path")).toBeInstanceOf(Object); }); it("should provide a punycode shim", function () { expect(require("punycode")).toBeInstanceOf(Object); }); it("should provide a stream shim", function () { expect(require("stream")).toBeInstanceOf(Function); }); it("should provide a tty shim", function () { expect(require("tty")).toBeInstanceOf(Object); }); it("should provide a url shim", function () { expect(require("url")).toBeInstanceOf(Object); }); it("should provide a util shim", function () { expect(require("util")).toBeInstanceOf(Object); }); it("should provide a vm shim", function () { expect(require("vm")).toBeInstanceOf(Object); }); it("should provide a zlib shim", function () { expect(require("zlib")).toBeInstanceOf(Object); }); it("should provide a shim for a path in a build-in module", function () { expect(require("process/in.js")).toBe("in process"); }); webpack-4.30.0/test/configCases/target/web/node_modules/000077500000000000000000000000001345416772700231555ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/web/node_modules/process/000077500000000000000000000000001345416772700246335ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/web/node_modules/process/in.js000066400000000000000000000000371345416772700255770ustar00rootroot00000000000000module.exports = "in process"; webpack-4.30.0/test/configCases/target/web/node_modules/process/index.js000066400000000000000000000000511345416772700262740ustar00rootroot00000000000000throw new Error("Should not be loaded"); webpack-4.30.0/test/configCases/target/web/webpack.config.js000066400000000000000000000001571345416772700237210ustar00rootroot00000000000000module.exports = { target: "web", performance: { hints: false }, optimization: { minimize: false } }; webpack-4.30.0/test/configCases/target/webworker/000077500000000000000000000000001345416772700217325ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/webworker/index.js000066400000000000000000000050111345416772700233740ustar00rootroot00000000000000global.XMLHttpRequest = function() {}; global.XMLHttpRequest.prototype.open = function() {}; it("should provide a global Buffer constructor", function() { expect(Buffer).toBeInstanceOf(Function); }); it("should provide a global console shim", function () { expect(console).toBeTypeOf("object"); expect(console.time).toBeTypeOf("function"); }); it("should provide a global process shim", function () { expect(process).toBeInstanceOf(Object); }); it("should provide a global setImmediate shim", function () { expect(setImmediate).toBeInstanceOf(Function); }); it("should provide a global clearImmediate shim", function () { expect(clearImmediate).toBeInstanceOf(Function); }); it("should provide an assert shim", function () { expect(require("assert")).toBeInstanceOf(Function); }); it("should provide a util shim", function () { expect(require("util")).toBeInstanceOf(Object); }); it("should provide a buffer shim", function () { expect(require("buffer")).toBeInstanceOf(Object); }); it("should provide a crypto shim", function () { expect(require("crypto")).toBeInstanceOf(Object); }); it("should provide a domain shim", function () { expect(require("domain")).toBeInstanceOf(Object); }); it("should provide an events shim", function () { expect(require("events")).toBeInstanceOf(Function); }); it("should provide an http shim", function () { expect(require("http")).toBeInstanceOf(Object); }); it("should provide an https shim", function () { expect(require("https")).toBeInstanceOf(Object); }); it("should provide an os shim", function () { expect(require("os")).toBeInstanceOf(Object); }); it("should provide a path shim", function () { expect(require("path")).toBeInstanceOf(Object); }); it("should provide a punycode shim", function () { expect(require("punycode")).toBeInstanceOf(Object); }); it("should provide a stream shim", function () { expect(require("stream")).toBeInstanceOf(Function); }); it("should provide a tty shim", function () { expect(require("tty")).toBeInstanceOf(Object); }); it("should provide a url shim", function () { expect(require("url")).toBeInstanceOf(Object); }); it("should provide a util shim", function () { expect(require("util")).toBeInstanceOf(Object); }); it("should provide a vm shim", function () { expect(require("vm")).toBeInstanceOf(Object); }); it("should provide a zlib shim", function () { expect(require("zlib")).toBeInstanceOf(Object); }); it("should provide a shim for a path in a build-in module", function () { expect(require("process/in.js")).toBe("in process"); }); webpack-4.30.0/test/configCases/target/webworker/node_modules/000077500000000000000000000000001345416772700244075ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/webworker/node_modules/process/000077500000000000000000000000001345416772700260655ustar00rootroot00000000000000webpack-4.30.0/test/configCases/target/webworker/node_modules/process/in.js000066400000000000000000000000371345416772700270310ustar00rootroot00000000000000module.exports = "in process"; webpack-4.30.0/test/configCases/target/webworker/node_modules/process/index.js000066400000000000000000000000511345416772700275260ustar00rootroot00000000000000throw new Error("Should not be loaded"); webpack-4.30.0/test/configCases/target/webworker/webpack.config.js000066400000000000000000000002521345416772700251470ustar00rootroot00000000000000module.exports = { target: "webworker", performance: { hints: false }, node: { __dirname: false, __filename: false }, optimization: { minimize: false } }; webpack-4.30.0/test/configCases/wasm/000077500000000000000000000000001345416772700174045ustar00rootroot00000000000000webpack-4.30.0/test/configCases/wasm/identical/000077500000000000000000000000001345416772700213405ustar00rootroot00000000000000webpack-4.30.0/test/configCases/wasm/identical/index.js000066400000000000000000000006211345416772700230040ustar00rootroot00000000000000it("should allow reference the same wasm multiple times", function() { return import("./module").then(function(module) { const result = module.run(); expect(result).toEqual(84); }); }); it("should allow reference the same wasm multiple times (other chunk)", function() { return import("./module?2").then(function(module) { const result = module.run(); expect(result).toEqual(84); }); }); webpack-4.30.0/test/configCases/wasm/identical/module.js000066400000000000000000000002421345416772700231610ustar00rootroot00000000000000import { getNumber } from "./wasm.wat?1"; import { getNumber as getNumber2 } from "./wasm.wat?2"; export function run() { return getNumber() + getNumber2(); }; webpack-4.30.0/test/configCases/wasm/identical/test.filter.js000066400000000000000000000002221345416772700241350ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function(config) { return supportsWebAssembly(); }; webpack-4.30.0/test/configCases/wasm/identical/wasm.wat000066400000000000000000000004771345416772700230340ustar00rootroot00000000000000(module (type $t0 (func (param i32 i32) (result i32))) (type $t1 (func (result i32))) (func $add (export "add") (type $t0) (param $p0 i32) (param $p1 i32) (result i32) (i32.add (get_local $p0) (get_local $p1))) (func $getNumber (export "getNumber") (type $t1) (result i32) (i32.const 42))) webpack-4.30.0/test/configCases/wasm/identical/webpack.config.js000066400000000000000000000012621345416772700245570ustar00rootroot00000000000000const { CachedSource } = require("webpack-sources"); /** @typedef {import("../../../lib/Compilation")} Compilation */ module.exports = { module: { rules: [ { test: /\.wat$/, loader: "wast-loader", type: "webassembly/experimental" } ] }, plugins: [ function() { this.hooks.compilation.tap( "Test", /** * @param {Compilation} compilation Compilation * @returns {void} */ compilation => { compilation.moduleTemplates.webassembly.hooks.package.tap( "Test", source => { // this is important to make each returned value a new instance return new CachedSource(source); } ); } ); } ] }; webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/000077500000000000000000000000001345416772700246435ustar00rootroot00000000000000webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/async.js000066400000000000000000000000001345416772700263040ustar00rootroot00000000000000webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/errors.js000066400000000000000000000007231345416772700265170ustar00rootroot00000000000000module.exports = [ [ /\.\/wasm.wat/, /WebAssembly module is included in initial chunk/, /\* \.\/index.js --> \.\/module.js --> \.\/wasm.wat/, /\* \.\.\. --> \.\/module.js --> \.\/module2.js --> \.\/wasm.wat/, /\* \.\.\. --> \.\/module2.js --> \.\/module3.js --> \.\/wasm.wat/ ], [ /\.\/wasm2\.wat/, /WebAssembly module is included in initial chunk/, /\* \.\/index.js --> \.\/module.js --> \.\/module2.js --> \.\/module3.js --> \.\/wasm2.wat/ ] ]; webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/index.js000066400000000000000000000000231345416772700263030ustar00rootroot00000000000000import "./module"; webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/module.js000066400000000000000000000001441345416772700264650ustar00rootroot00000000000000import { getNumber } from "./wasm.wat"; import("./async.js"); require("./module2"); getNumber(); webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/module2.js000066400000000000000000000000551345416772700265500ustar00rootroot00000000000000require("./wasm.wat"); require("./module3"); webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/module3.js000066400000000000000000000000571345416772700265530ustar00rootroot00000000000000require("./wasm.wat"); require("./wasm2.wat"); webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/test.filter.js000066400000000000000000000002141345416772700274410ustar00rootroot00000000000000var supportsWebAssembly = require("../../../helpers/supportsWebAssembly"); module.exports = function() { return supportsWebAssembly(); }; webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/wasm.wat000066400000000000000000000001231345416772700263230ustar00rootroot00000000000000(module (func $getNumber (export "getNumber") (result i32) (i32.const 42))) webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/wasm2.wat000066400000000000000000000001231345416772700264050ustar00rootroot00000000000000(module (func $getNumber (export "getNumber") (result i32) (i32.const 42))) webpack-4.30.0/test/configCases/wasm/wasm-in-initial-chunk-error/webpack.config.js000066400000000000000000000002441345416772700300610ustar00rootroot00000000000000module.exports = { entry: "./index", module: { rules: [ { test: /\.wat$/, loader: "wast-loader", type: "webassembly/experimental" } ] } }; webpack-4.30.0/test/configCases/web/000077500000000000000000000000001345416772700172125ustar00rootroot00000000000000webpack-4.30.0/test/configCases/web/node-source/000077500000000000000000000000001345416772700214355ustar00rootroot00000000000000webpack-4.30.0/test/configCases/web/node-source/index.mjs000066400000000000000000000006041345416772700232570ustar00rootroot00000000000000// Block `require`, but keep Webpack from trying to work around it. eval("require = undefined") it("should compile fine", () => { // It's okay if this executes fine or if `global` is not defined. If it // results in a `require()` call, this will throw a `TypeError` instead. try { global } catch (e) { if (!(e instanceof ReferenceError)) throw e } }) webpack-4.30.0/test/configCases/web/node-source/webpack.config.js000066400000000000000000000002061345416772700246510ustar00rootroot00000000000000module.exports = { target: "web", entry: "./index.mjs", performance: { hints: false }, optimization: { minimize: false } }; webpack-4.30.0/test/configCases/web/prefetch-preload/000077500000000000000000000000001345416772700224365ustar00rootroot00000000000000webpack-4.30.0/test/configCases/web/prefetch-preload/chunk1-a.js000066400000000000000000000000001345416772700243710ustar00rootroot00000000000000webpack-4.30.0/test/configCases/web/prefetch-preload/chunk1-b.js000066400000000000000000000000001345416772700243720ustar00rootroot00000000000000webpack-4.30.0/test/configCases/web/prefetch-preload/chunk1-c.js000066400000000000000000000000001345416772700243730ustar00rootroot00000000000000webpack-4.30.0/test/configCases/web/prefetch-preload/chunk1.js000066400000000000000000000004161345416772700241660ustar00rootroot00000000000000export default function() { import(/* webpackPrefetch: true, webpackChunkName: "chunk1-a" */ "./chunk1-a"); import(/* webpackPreload: true, webpackChunkName: "chunk1-b" */ "./chunk1-b"); import(/* webpackPrefetch: 10, webpackChunkName: "chunk1-c" */ "./chunk1-c"); } webpack-4.30.0/test/configCases/web/prefetch-preload/chunk2.js000066400000000000000000000002771345416772700241740ustar00rootroot00000000000000export default function() { import(/* webpackPrefetch: true, webpackChunkName: "chunk1-a" */ "./chunk1-a"); import(/* webpackPreload: true, webpackChunkName: "chunk1-b" */ "./chunk1-b"); } webpack-4.30.0/test/configCases/web/prefetch-preload/index.js000066400000000000000000000056731345416772700241160ustar00rootroot00000000000000 let oldNonce; let oldPublicPath; beforeEach(done => { oldNonce = __webpack_nonce__; oldPublicPath = __webpack_public_path__; done(); }); afterEach(done => { __webpack_nonce__ = oldNonce; __webpack_public_path__ = oldPublicPath; done(); }); it("should prefetch and preload child chunks on chunk load", () => { __webpack_nonce__ = "nonce"; __webpack_public_path__ = "https://example.com/public/path/"; let link, script; expect(document.head._children).toHaveLength(1); // Test prefetch from entry chunk link = document.head._children[0]; expect(link._type).toBe("link"); expect(link.rel).toBe("prefetch"); expect(link.href).toMatch(/chunk1\.js$/); const promise = import(/* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1"); expect(document.head._children).toHaveLength(3); // Test normal script loading script = document.head._children[1]; expect(script._type).toBe("script"); expect(script.src).toMatch(/chunk1\.js$/); expect(script.getAttribute("nonce")).toBe("nonce") expect(script.crossOrigin).toBe("anonymous"); expect(script.onload).toBeTypeOf("function"); // Test preload of chunk1-b link = document.head._children[2]; expect(link._type).toBe("link"); expect(link.rel).toBe("preload"); expect(link.as).toBe("script"); expect(link.href).toMatch(/chunk1-b\.js$/); expect(link.charset).toBe("utf-8"); expect(link.getAttribute("nonce")).toBe("nonce"); expect(link.crossOrigin).toBe("anonymous"); // Run the script __non_webpack_require__("./chunk1.js"); script.onload(); return promise.then(() => { expect(document.head._children).toHaveLength(5); // Test prefetching for chunk1-c and chunk1-a in this order link = document.head._children[3]; expect(link._type).toBe("link"); expect(link.rel).toBe("prefetch"); expect(link.href).toMatch(/chunk1-c\.js$/); expect(link.crossOrigin).toBe("anonymous"); link = document.head._children[4]; expect(link._type).toBe("link"); expect(link.rel).toBe("prefetch"); expect(link.href).toMatch(/chunk1-a\.js$/); expect(link.crossOrigin).toBe("anonymous"); const promise2 = import(/* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1"); // Loading chunk1 again should not trigger prefetch/preload expect(document.head._children).toHaveLength(5); const promise3 = import(/* webpackChunkName: "chunk2" */ "./chunk2"); expect(document.head._children).toHaveLength(6); // Test normal script loading script = document.head._children[5]; expect(script._type).toBe("script"); expect(script.src).toMatch(/chunk2\.js$/); expect(script.getAttribute("nonce")).toBe("nonce") expect(script.crossOrigin).toBe("anonymous"); expect(script.onload).toBeTypeOf("function"); // Run the script __non_webpack_require__("./chunk2.js"); script.onload(); return promise3.then(() => { // Loading chunk2 again should not trigger prefetch/preload as it's already prefetch/preloaded expect(document.head._children).toHaveLength(6); }); }); }) webpack-4.30.0/test/configCases/web/prefetch-preload/webpack.config.js000066400000000000000000000002761345416772700256610ustar00rootroot00000000000000module.exports = { target: "web", output: { chunkFilename: "[name].js", crossOriginLoading: "anonymous" }, performance: { hints: false }, optimization: { minimize: false } }; webpack-4.30.0/test/fixtures/000077500000000000000000000000001345416772700160625ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/a.js000066400000000000000000000000671345416772700166430ustar00rootroot00000000000000module.exports = function a() { return "This is a"; };webpack-4.30.0/test/fixtures/abc.js000066400000000000000000000001231345416772700171410ustar00rootroot00000000000000exports.a = require("./a"); exports.b = require("./b"); exports.c = require("./c");webpack-4.30.0/test/fixtures/abc.txt000066400000000000000000000000031345416772700173410ustar00rootroot00000000000000abcwebpack-4.30.0/test/fixtures/b.js000066400000000000000000000000671345416772700166440ustar00rootroot00000000000000module.exports = function b() { return "This is b"; };webpack-4.30.0/test/fixtures/c.js000066400000000000000000000001101345416772700166320ustar00rootroot00000000000000module.exports = function b() { require("./a"); return "This is c"; };webpack-4.30.0/test/fixtures/chunks.js000066400000000000000000000001001345416772700177020ustar00rootroot00000000000000require.ensure(["./a"], function(require) { require("./b"); });webpack-4.30.0/test/fixtures/complex.js000066400000000000000000000006151345416772700200710ustar00rootroot00000000000000var complex1 = require("./lib/complex1"); require.ensure(["./lib/complex1", "complexm/step2"], function(require) { require("./lib/complex1"); var a = function() {} require.ensure(["complexm/step1"], function(require) { require("./lib/complex1"); var s1 = require("complexm/step1"); var s2 = require("complexm/step2"); console.log(s1); console.log(s2); }); }); console.log(complex1); webpack-4.30.0/test/fixtures/count-loader.js000066400000000000000000000001351345416772700210130ustar00rootroot00000000000000let counter = 0; module.exports = function() { return `module.exports = ${counter++};`; }; webpack-4.30.0/test/fixtures/delay-loader.js000066400000000000000000000001651345416772700207640ustar00rootroot00000000000000module.exports = function(source) { var cb = this.async(); setTimeout(function() { cb(null, source); }, 500); };webpack-4.30.0/test/fixtures/errors/000077500000000000000000000000001345416772700173765ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/errors/async-error-loader.js000066400000000000000000000002271345416772700234450ustar00rootroot00000000000000module.exports = function(source) { const callback = this.async(); const error = new Error("this is a callback error"); callback(error, source); }; webpack-4.30.0/test/fixtures/errors/case-sensitive.js000066400000000000000000000000451345416772700226550ustar00rootroot00000000000000require("./file"); require("./FILE");webpack-4.30.0/test/fixtures/errors/emit-error-loader.js000066400000000000000000000002321345416772700232620ustar00rootroot00000000000000module.exports = function(source) { this.emitWarning(new Error("this is a warning")); this.emitError(new Error("this is an error")); return source; }; webpack-4.30.0/test/fixtures/errors/entry-point-error-loader-required.js000066400000000000000000000000521345416772700264320ustar00rootroot00000000000000require("./emit-error-loader.js!./file"); webpack-4.30.0/test/fixtures/errors/entry-point.js000066400000000000000000000000001345416772700222120ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/errors/file.js000066400000000000000000000000001345416772700206410ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/errors/irregular-error-loader.js000066400000000000000000000003641345416772700243260ustar00rootroot00000000000000module.exports = function(source) { const empty = null; const emptyError = new Error(); this.emitWarning(empty); this.emitWarning(emptyError); this.emitError(empty); this.emitError(emptyError); throw "a string error"; return source; }; webpack-4.30.0/test/fixtures/errors/missingFile.js000066400000000000000000000001441345416772700222040ustar00rootroot00000000000000 // on line 4 require("./missing"); // on line 12 char 10 require("./dir/missing2");webpack-4.30.0/test/fixtures/errors/module.parent.require.js000066400000000000000000000000411345416772700241570ustar00rootroot00000000000000module.parent.require('./file'); webpack-4.30.0/test/fixtures/errors/no-errors-deprecate.js000066400000000000000000000000231345416772700236070ustar00rootroot00000000000000require('./file'); webpack-4.30.0/test/fixtures/errors/no-return-loader.js000066400000000000000000000000371345416772700231310ustar00rootroot00000000000000module.exports = function(){ } webpack-4.30.0/test/fixtures/errors/not-a-json.js000066400000000000000000000000001345416772700217070ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/errors/require.extensions.js000066400000000000000000000000521345416772700236030ustar00rootroot00000000000000require.extensions[".js"] = function() {};webpack-4.30.0/test/fixtures/errors/require.main.require.js000066400000000000000000000000401345416772700240000ustar00rootroot00000000000000require.main.require('./file'); webpack-4.30.0/test/fixtures/errors/throw-error-loader.js000066400000000000000000000001231345416772700234660ustar00rootroot00000000000000module.exports = function(source) { throw new Error("this is a thrown error"); }; webpack-4.30.0/test/fixtures/items/000077500000000000000000000000001345416772700172035ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/items/item (0).js000066400000000000000000000000231345416772700207330ustar00rootroot00000000000000module.exports = 0;webpack-4.30.0/test/fixtures/items/item (1).js000066400000000000000000000000231345416772700207340ustar00rootroot00000000000000module.exports = 1;webpack-4.30.0/test/fixtures/items/item (2).js000066400000000000000000000000231345416772700207350ustar00rootroot00000000000000module.exports = 2;webpack-4.30.0/test/fixtures/items/item (3).js000066400000000000000000000000231345416772700207360ustar00rootroot00000000000000module.exports = 3;webpack-4.30.0/test/fixtures/items/item (4).js000066400000000000000000000000231345416772700207370ustar00rootroot00000000000000module.exports = 4;webpack-4.30.0/test/fixtures/items/item (5).js000066400000000000000000000000231345416772700207400ustar00rootroot00000000000000module.exports = 5;webpack-4.30.0/test/fixtures/items/item (6).js000066400000000000000000000000231345416772700207410ustar00rootroot00000000000000module.exports = 6;webpack-4.30.0/test/fixtures/items/item (7).js000066400000000000000000000000231345416772700207420ustar00rootroot00000000000000module.exports = 7;webpack-4.30.0/test/fixtures/items/item (8).js000066400000000000000000000000231345416772700207430ustar00rootroot00000000000000module.exports = 8;webpack-4.30.0/test/fixtures/items/item (9).js000066400000000000000000000000231345416772700207440ustar00rootroot00000000000000module.exports = 9;webpack-4.30.0/test/fixtures/lib/000077500000000000000000000000001345416772700166305ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/lib/complex1.js000066400000000000000000000000401345416772700207100ustar00rootroot00000000000000module.exports = "lib complex1";webpack-4.30.0/test/fixtures/main1.js000066400000000000000000000002221345416772700174210ustar00rootroot00000000000000var a = require("./a"); if(x) { for(var i = 0; i < 100; i++) { while(true) require("./b"); do { i++; } while(require("m1/a")()); } }webpack-4.30.0/test/fixtures/main2.js000066400000000000000000000002741345416772700174310ustar00rootroot00000000000000var a = require("./a"); with(x) { switch(a) { case 1: require("./b"); default: require.ensure(["m1/a"], function() { var a = require("m1/a"), b = require("m1/b"); }); } }webpack-4.30.0/test/fixtures/main3.js000066400000000000000000000001261345416772700174260ustar00rootroot00000000000000var a = require("./a"); require.ensure([], function(require) { require("./c.js"); });webpack-4.30.0/test/fixtures/main4.js000066400000000000000000000000721345416772700174270ustar00rootroot00000000000000var six = 6; require("bundle!./items/item (" + six + ")");webpack-4.30.0/test/fixtures/node_modules/000077500000000000000000000000001345416772700205375ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/node_modules/complexm/000077500000000000000000000000001345416772700223635ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/node_modules/complexm/step1.js000066400000000000000000000000611345416772700237520ustar00rootroot00000000000000module.exports = require("m1/a") + require("m1");webpack-4.30.0/test/fixtures/node_modules/complexm/step2.js000066400000000000000000000000311345416772700237500ustar00rootroot00000000000000module.exports = "Step2";webpack-4.30.0/test/fixtures/node_modules/complexm/web_modules/000077500000000000000000000000001345416772700246705ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/node_modules/complexm/web_modules/m1/000077500000000000000000000000001345416772700252055ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/node_modules/complexm/web_modules/m1/a.js000066400000000000000000000000441345416772700257610ustar00rootroot00000000000000module.exports = "the correct a.js";webpack-4.30.0/test/fixtures/node_modules/complexm/web_modules/m1/index.js000066400000000000000000000000551345416772700266520ustar00rootroot00000000000000module.exports = " :) " + require("m2/b.js");webpack-4.30.0/test/fixtures/node_modules/m1/000077500000000000000000000000001345416772700210545ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/node_modules/m1/a.js000066400000000000000000000000721345416772700216310ustar00rootroot00000000000000module.exports = function a() { return "This is m1/a"; };webpack-4.30.0/test/fixtures/node_modules/m1/b.js000066400000000000000000000000721345416772700216320ustar00rootroot00000000000000module.exports = function a() { return "This is m1/b"; };webpack-4.30.0/test/fixtures/node_modules/m2-loader/000077500000000000000000000000001345416772700223215ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/node_modules/m2-loader/b.js000066400000000000000000000001141345416772700230740ustar00rootroot00000000000000module.exports = function() { "module.exports = 'This is m2-loader/b';"; } webpack-4.30.0/test/fixtures/node_modules/m2/000077500000000000000000000000001345416772700210555ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/node_modules/m2/b.js000066400000000000000000000000411345416772700216270ustar00rootroot00000000000000module.exports = "This is m2/b"; webpack-4.30.0/test/fixtures/nodetest/000077500000000000000000000000001345416772700177075ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/nodetest/entry.js000066400000000000000000000002521345416772700214050ustar00rootroot00000000000000exports.loadChunk = function(id, cb) { require(["./file" + id], function(result) { cb(result); }); }; exports.nextTick = process.nextTick; exports.fs = require("fs");webpack-4.30.0/test/fixtures/nodetest/file456.js000066400000000000000000000000251345416772700214200ustar00rootroot00000000000000module.exports = 123;webpack-4.30.0/test/fixtures/nodetest/file567.js000066400000000000000000000000221345416772700214200ustar00rootroot00000000000000define({ a: 1 });webpack-4.30.0/test/fixtures/subdir/000077500000000000000000000000001345416772700173525ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/subdir/watched-file.txt000066400000000000000000000000001345416772700224350ustar00rootroot00000000000000webpack-4.30.0/test/fixtures/watched-file.txt000066400000000000000000000000001345416772700211450ustar00rootroot00000000000000webpack-4.30.0/test/formatLocation.unittest.js000066400000000000000000000026411345416772700214110ustar00rootroot00000000000000"use strict"; const formatLocation = require("../lib/formatLocation"); describe("formatLocation", () => { const testCases = [ { name: "undefined", loc: undefined, result: "" }, { name: "null", loc: null, result: "" }, { name: "string", loc: "str", result: "str" }, { name: "number", loc: 12, result: "12" }, { name: "line-column", loc: { start: { line: 1, column: 2 }, end: { line: 3, column: 4 } }, result: "1:2-3:4" }, { name: "line-column (same line)", loc: { start: { line: 1, column: 2 }, end: { line: 1, column: 4 } }, result: "1:2-4" }, { name: "line-column (start only)", loc: { start: { line: 5, column: 6 } }, result: "5:6" }, { name: "start-end string", loc: { start: "start", end: "end" }, result: "start-end" }, { name: "start-end number", loc: { start: 9, end: 7 }, result: "9-7" }, { name: "line", loc: { start: { line: 10 }, end: { index: 20 } }, result: "10:?-+20" }, { name: "line", loc: { start: null, end: /f/ }, result: "" } ]; testCases.forEach(testCase => { it(`should format location correctly for ${testCase.name}`, () => { expect(formatLocation(testCase.loc)).toEqual(testCase.result); }); }); }); webpack-4.30.0/test/helpers/000077500000000000000000000000001345416772700156535ustar00rootroot00000000000000webpack-4.30.0/test/helpers/FakeDocument.js000066400000000000000000000026111345416772700205560ustar00rootroot00000000000000module.exports = class FakeDocument { constructor() { this.head = this.createElement("head"); } createElement(type) { return new FakeElement(type); } getElementsByTagName(name) { if (name === "head") return [this.head]; throw new Error( `FakeDocument.getElementsByTagName(${name}): not implemented` ); } }; class FakeElement { constructor(type) { this._type = type; this._children = []; this._attributes = Object.create(null); this._src = undefined; this._href = undefined; } appendChild(node) { this._children.push(node); } setAttribute(name, value) { this._attributes[name] = value; } getAttribute(name) { return this._attributes[name]; } _toRealUrl(value) { if (/^\//.test(value)) { return `https://test.cases${value}`; } else if (/^\.\.\//.test(value)) { return `https://test.cases${value.substr(2)}`; } else if (/^\.\//.test(value)) { return `https://test.cases/path${value.substr(1)}`; } else if (/^\w+:\/\//.test(value)) { return value; } else if (/^\/\//.test(value)) { return `https:${value}`; } else { return `https://test.cases/path/${value}`; } } set src(value) { if (this._type === "script") { this._src = this._toRealUrl(value); } } get src() { return this._src; } set href(value) { if (this._type === "link") { this._href = this._toRealUrl(value); } } get href() { return this._href; } } webpack-4.30.0/test/helpers/PluginEnvironment.js000066400000000000000000000023361345416772700217000ustar00rootroot00000000000000module.exports = function PluginEnvironment() { const events = []; function addEvent(name, handler) { events.push({ name, handler }); } function getEventName(hookName) { // Convert a hook name to an event name. // e.g. `buildModule` -> `build-module` return hookName.replace(/[A-Z]/g, c => "-" + c.toLowerCase()); } this.getEnvironmentStub = function() { const hooks = new Map(); return { plugin: addEvent, // TODO: Figure out a better way of doing this // In the meanwhile, `hooks` is a `Proxy` which creates fake hooks // on demand. Instead of creating a dummy object with a few `Hook` // method, a custom `Hook` class could be used. hooks: new Proxy({}, { get(target, hookName) { let hook = hooks.get(hookName); if (hook === undefined) { const eventName = getEventName(hookName); hook = { tap(_, handler) { addEvent(eventName, handler); }, tapAsync(_, handler) { addEvent(eventName, handler); }, tapPromise(_, handler) { addEvent(eventName, handler); } }; hooks.set(hookName, hook); } return hook; } }) }; }; this.getEventBindings = function() { return events; }; }; webpack-4.30.0/test/helpers/TemplatePluginEnvironment.js000066400000000000000000000011241345416772700233660ustar00rootroot00000000000000var PluginEnvironment = require('./PluginEnvironment'); module.exports = function TemplatePluginEnvironment() { var events = []; var mainTemplatePluginEnvironment = new PluginEnvironment(); this.getEnvironmentStub = function() { return { mainTemplate: mainTemplatePluginEnvironment.getEnvironmentStub(), templatesPlugin: function(name, handler) { events.push({ name, handler }); } }; }; this.getEventBindings = function() { return events; }; this.getMainTemplateBindings = function() { return mainTemplatePluginEnvironment.getEventBindings(); }; }; webpack-4.30.0/test/helpers/applyPluginWithOptions.js000066400000000000000000000007021345416772700227240ustar00rootroot00000000000000var PluginEnvironment = require('./PluginEnvironment'); module.exports = function applyPluginWithOptions(Plugin) { var plugin = new (Function.prototype.bind.apply(Plugin, arguments)); var pluginEnvironment = new PluginEnvironment(); plugin.apply(pluginEnvironment.getEnvironmentStub()); var env = (this === global) ? {} : this; env.plugin = plugin; env.pluginEnvironment = pluginEnvironment; return pluginEnvironment.getEventBindings(); }; webpack-4.30.0/test/helpers/createLazyTestEnv.js000066400000000000000000000045401345416772700216300ustar00rootroot00000000000000// this function allows to release memory in fn context // after the function has been called. const createOnceFn = fn => { if (!fn) return null; if (fn.length >= 1) { return done => { fn(done); fn = null; }; } return () => { const r = fn(); fn = null; return r; }; }; // this function allows to release memory in fn context // manually, usually after the suite has been run. const createDisposableFn = fn => { if (!fn) return null; let rfn; if (fn.length >= 1) { rfn = done => { fn(done); }; } else { rfn = () => { return fn(); }; } rfn.dispose = () => { fn = null; }; return rfn; }; module.exports = (env, globalTimeout = 2000, nameSuffix = "") => { const suite = env.describe( nameSuffix ? `exported tests ${nameSuffix}` : "exported tests", () => { // this must have a child to be handled correctly env.it("should run the exported tests", () => {}); } ); let numberOfTests = 0; const beforeAndAfterFns = () => { let currentSuite = suite; let afters = []; let befores = []; while (currentSuite) { befores = befores.concat(currentSuite.beforeFns); afters = afters.concat(currentSuite.afterFns); currentSuite = currentSuite.parentSuite; } return { befores: befores.reverse(), afters: afters }; }; return { setDefaultTimeout(time) { globalTimeout = time; }, getNumberOfTests() { return numberOfTests; }, it(title, fn, timeout = globalTimeout) { fn = createOnceFn(fn); numberOfTests++; let spec; if(fn) { spec = env.fit(title, fn, timeout); } else { spec = env.fit(title, () => {}); spec.pend("Skipped"); } suite.addChild(spec); spec.disabled = false; spec.getSpecName = () => { return `${suite.getFullName()} ${spec.description}`; }; spec.beforeAndAfterFns = beforeAndAfterFns; spec.result.fullName = spec.getFullName(); }, beforeEach(fn, timeout = globalTimeout) { fn = createDisposableFn(fn); suite.beforeEach({ fn, timeout: () => timeout }); suite.afterAll({ fn: done => { fn.dispose(); done(); }, timeout: () => 1000 }); }, afterEach(fn, timeout = globalTimeout) { fn = createDisposableFn(fn); suite.afterEach({ fn, timeout: () => timeout }); suite.afterAll({ fn: done => { fn.dispose(); done(); }, timeout: () => 1000 }); } }; }; webpack-4.30.0/test/helpers/currentWatchStep.js000066400000000000000000000000321345416772700215110ustar00rootroot00000000000000exports.step = undefined; webpack-4.30.0/test/helpers/exec-in-directory.js000066400000000000000000000002071345416772700215420ustar00rootroot00000000000000"use strict"; const dir = process.argv[2]; const bin = process.argv[3]; process.argv.splice(1, 2); process.chdir(dir); require(bin); webpack-4.30.0/test/helpers/fakeSystem.js000066400000000000000000000035661345416772700203360ustar00rootroot00000000000000const System = { register: (name, deps, fn) => { if (!System.registry) { throw new Error("System is no initialized"); } if (typeof name !== "string") { fn = deps; deps = name; name = "(anonym)"; } if (!Array.isArray(deps)) { fn = deps; deps = []; } const dynamicExport = result => { if (System.registry[name] !== entry) { throw new Error(`Module ${name} calls dynamicExport too late`); } entry.exports = result; }; if (name in System.registry) { throw new Error(`Module ${name} is already registered`); } const mod = fn(dynamicExport); if (deps.length > 0) { if (!Array.isArray(mod.setters)) { throw new Error( `Module ${name} must have setters, because it has dependencies` ); } if (mod.setters.length !== deps.length) { throw new Error( `Module ${name} has incorrect number of setters for the dependencies` ); } } const entry = { name, deps, fn, mod, executed: false, exports: undefined }; System.registry[name] = entry; }, registry: undefined, init: modules => { System.registry = {}; if (modules) { for (const name of Object.keys(modules)) { System.registry[name] = { executed: true, exports: modules[name] }; } } }, execute: name => { const m = System.registry[name]; if (!m) throw new Error(`Module ${name} not registered`); if (m.executed) throw new Error(`Module ${name} was already executed`); return System.ensureExecuted(name); }, ensureExecuted: name => { const m = System.registry[name]; if (!m) throw new Error(`Module ${name} not registered`); if (!m.executed) { m.executed = true; for (let i = 0; i < m.deps.length; i++) { const dep = m.deps[i]; System.ensureExecuted(dep); m.mod.setters[i](System.registry[dep].exports); } m.mod.execute(); } return m.exports; } }; module.exports = System; webpack-4.30.0/test/helpers/prepareOptions.js000066400000000000000000000012371345416772700212260ustar00rootroot00000000000000"use strict"; const handleExport = options => { const isES6DefaultExported = typeof options === "object" && options !== null && typeof options.default !== "undefined"; options = isES6DefaultExported ? options.default : options; return options; }; const handleFunction = (options, argv) => { if (typeof options === "function") { options = options(argv.env, argv); } return options; }; module.exports = (options, argv) => { argv = argv || {}; options = handleExport(options); if (Array.isArray(options)) { options = options.map(_options => handleFunction(_options, argv)); } else { options = handleFunction(options, argv); } return options; }; webpack-4.30.0/test/helpers/remove.js000066400000000000000000000005161345416772700175100ustar00rootroot00000000000000module.exports.remove = function remove(src) { if (!fs.existsSync(src)) return; const files = fs.readdirSync(src); files.forEach(filename => { const srcFile = path.join(src, filename); const directory = fs.statSync(srcFile).isDirectory(); if (directory) { remove(srcFile); } else { fs.unlinkSync(srcFile); } }); } webpack-4.30.0/test/helpers/supportDefaultAssignment.js000066400000000000000000000004231345416772700232620ustar00rootroot00000000000000module.exports = function supportDefaultAssignment() { try { var E = eval("class E { toString() { return 'default' } }") var f1 = eval("(function f1({a, b = E}) {return new b().toString();})") return f1({a: "test"}) === "default" ; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsArrowFunctionExpression.js000066400000000000000000000003111345416772700247040ustar00rootroot00000000000000module.exports = function supportArrowFunctionExpression() { try { eval("var foo = function(fn) {return fn.toString()}; foo(() => {return 'a'})"); return true; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsBlockScoping.js000066400000000000000000000003121345416772700224020ustar00rootroot00000000000000module.exports = function supportsBlockScoping() { try { var f = eval("(function f() { const x = 1; if (true) { const x = 2; } return x; })"); return f() === 1; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsDefaultArgs.js000066400000000000000000000002521345416772700222310ustar00rootroot00000000000000module.exports = function supportsDefaultArgs() { try { var f = eval("(function f(a = 123) { return a; })"); return f() === 123; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsES6.js000066400000000000000000000001721345416772700204260ustar00rootroot00000000000000module.exports = function supportsES6() { try { eval("class A {}"); return true; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsForOf.js000066400000000000000000000003071345416772700210440ustar00rootroot00000000000000module.exports = function supportDefaultAssignment() { try { var f = eval("(function f() { for(var x of ['ok', 'fail']) return x; })"); return f() === "ok" ; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsIteratorDestructuring.js000066400000000000000000000002741345416772700244100ustar00rootroot00000000000000module.exports = function supportsIteratorDestructuring() { try { var f = eval("(function f([, x, ...y]) { return x; })"); return f([1, 2]) === 2; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsObjectDestructuring.js000066400000000000000000000003011345416772700240140ustar00rootroot00000000000000module.exports = function supportsObjectDestructuring() { try { var f = eval("(function f({x, y}) { return x + y; })"); return f({ x: 1, y: 2 }) === 3; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsOptionalCatchBinding.js000066400000000000000000000002201345416772700240460ustar00rootroot00000000000000module.exports = function supportsOptionalCatchBinding() { try { eval("try {} catch {}"); return true; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsSpread.js000066400000000000000000000003111345416772700212420ustar00rootroot00000000000000module.exports = function supportsSpread() { try { var x = { a: true }, y; // eslint-disable-line no-unused-vars eval("y = { ...x }"); return y !== x && y.a; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsTemplateStrings.js000066400000000000000000000002711345416772700231560ustar00rootroot00000000000000module.exports = function supportsTemplateStrings() { try { var f = eval("(function f() { return String.raw`a\\b`; })"); return f() === "a\\b"; } catch(e) { return false; } }; webpack-4.30.0/test/helpers/supportsWebAssembly.js000066400000000000000000000002121345416772700222410ustar00rootroot00000000000000module.exports = function supportsWebAssembly() { try { return typeof WebAssembly !== "undefined"; } catch(e) { return false; } }; webpack-4.30.0/test/hotCases/000077500000000000000000000000001345416772700157625ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/chunks/000077500000000000000000000000001345416772700172555ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/chunks/accept-system-import/000077500000000000000000000000001345416772700233465ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/chunks/accept-system-import/chunk.js000066400000000000000000000000401345416772700250060ustar00rootroot00000000000000export { value } from "./file"; webpack-4.30.0/test/hotCases/chunks/accept-system-import/chunk2.js000066400000000000000000000000401345416772700250700ustar00rootroot00000000000000export { value } from "./file"; webpack-4.30.0/test/hotCases/chunks/accept-system-import/file.js000066400000000000000000000000601345416772700246170ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-4.30.0/test/hotCases/chunks/accept-system-import/index.js000066400000000000000000000010311345416772700250060ustar00rootroot00000000000000it("should import a changed chunk", (done) => { import("./chunk").then((chunk) => { expect(chunk.value).toBe(1); import("./chunk2").then((chunk2) => { expect(chunk2.value).toBe(1); NEXT(require("../../update")(done)); module.hot.accept(["./chunk", "./chunk2"], () => { import("./chunk").then((chunk) => { expect(chunk.value).toBe(2); import("./chunk2").then((chunk2) => { expect(chunk2.value).toBe(2); done(); }).catch(done); }).catch(done); }); }).catch(done); }).catch(done); }); webpack-4.30.0/test/hotCases/chunks/dynamic-system-import/000077500000000000000000000000001345416772700235335ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/chunks/dynamic-system-import/chunk1.js000066400000000000000000000000751345416772700252640ustar00rootroot00000000000000export { value } from "./file"; module.hot.accept("./file"); webpack-4.30.0/test/hotCases/chunks/dynamic-system-import/chunk2.js000066400000000000000000000000751345416772700252650ustar00rootroot00000000000000export { value } from "./file"; module.hot.accept("./file"); webpack-4.30.0/test/hotCases/chunks/dynamic-system-import/file.js000066400000000000000000000000601345416772700250040ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-4.30.0/test/hotCases/chunks/dynamic-system-import/index.js000066400000000000000000000006131345416772700252000ustar00rootroot00000000000000it("should import a changed chunk (dynamic import)", function(done) { function load(name) { return import("./chunk" + name); } load(1).then((chunk) => { expect(chunk.value).toBe(1); NEXT(require("../../update")(done, true, () => { expect(chunk.value).toBe(2); load(2).then((chunk2) => { expect(chunk2.value).toBe(2); done(); }).catch(done); })); }).catch(done); }); webpack-4.30.0/test/hotCases/chunks/system-import/000077500000000000000000000000001345416772700221115ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/chunks/system-import/chunk.js000066400000000000000000000002721345416772700235600ustar00rootroot00000000000000export { value } from "./file"; export { value as value2 } from "./file2"; export var counter = 0; module.hot.accept("./file"); module.hot.accept("./file2", function() { counter++; }); webpack-4.30.0/test/hotCases/chunks/system-import/chunk2.js000066400000000000000000000002721345416772700236420ustar00rootroot00000000000000export { value } from "./file"; export { value as value2 } from "./file2"; export var counter = 0; module.hot.accept("./file"); module.hot.accept("./file2", function() { counter++; }); webpack-4.30.0/test/hotCases/chunks/system-import/file.js000066400000000000000000000000601345416772700233620ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-4.30.0/test/hotCases/chunks/system-import/file2.js000066400000000000000000000000601345416772700234440ustar00rootroot00000000000000export var value = 3; --- export var value = 4; webpack-4.30.0/test/hotCases/chunks/system-import/index.js000066400000000000000000000010351345416772700235550ustar00rootroot00000000000000it("should import a changed chunk", (done) => { import("./chunk").then((chunk) => { expect(chunk.value).toBe(1); expect(chunk.value2).toBe(3); expect(chunk.counter).toBe(0); NEXT(require("../../update")(done, true, () => { expect(chunk.value).toBe(2); expect(chunk.value2).toBe(4); expect(chunk.counter).toBe(1); import("./chunk2").then(function(chunk2) { expect(chunk2.value).toBe(2); expect(chunk2.value2).toBe(4); expect(chunk2.counter).toBe(0); done(); }).catch(done); })); }).catch(done); }); webpack-4.30.0/test/hotCases/code-generation/000077500000000000000000000000001345416772700210255ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/code-generation/this-in-accept/000077500000000000000000000000001345416772700236355ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/code-generation/this-in-accept/index.js000066400000000000000000000005741345416772700253100ustar00rootroot00000000000000import x from "./module"; it("should have correct this context in accept handler", (done) => { expect(x).toEqual("ok1"); (function() { module.hot.accept("./module", () => { expect(x).toEqual("ok2"); expect(this).toEqual({ ok: true }); done(); }); }).call({ ok: true }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/code-generation/this-in-accept/module.js000066400000000000000000000000601345416772700254540ustar00rootroot00000000000000export default "ok1"; --- export default "ok2"; webpack-4.30.0/test/hotCases/concat/000077500000000000000000000000001345416772700172315ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/concat/reload-compat-flag/000077500000000000000000000000001345416772700226675ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/concat/reload-compat-flag/a.js000066400000000000000000000000221345416772700234370ustar00rootroot00000000000000export default 1; webpack-4.30.0/test/hotCases/concat/reload-compat-flag/index.js000066400000000000000000000005161345416772700243360ustar00rootroot00000000000000var x = require("./module"); it("should allow to hot replace modules in a ConcatenatedModule", (done) => { expect(x).toEqual(nsObj({ default: "ok1" })); module.hot.accept("./module", () => { x = require("./module"); expect(x).toEqual(nsObj({ default: "ok2" })); done(); }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/concat/reload-compat-flag/module.js000066400000000000000000000001161345416772700245100ustar00rootroot00000000000000import "./a"; export default "ok1"; --- import "./a"; export default "ok2"; webpack-4.30.0/test/hotCases/concat/reload-compat-flag/webpack.config.js000066400000000000000000000000711345416772700261030ustar00rootroot00000000000000"use strict"; module.exports = { mode: "production" }; webpack-4.30.0/test/hotCases/concat/reload-external/000077500000000000000000000000001345416772700223175ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/concat/reload-external/a.js000066400000000000000000000001021345416772700230660ustar00rootroot00000000000000export default 1; --- export default 2; --- export default 2; --- webpack-4.30.0/test/hotCases/concat/reload-external/b.js000066400000000000000000000001051345416772700230720ustar00rootroot00000000000000export default 10; --- export default 10; --- export default 20; --- webpack-4.30.0/test/hotCases/concat/reload-external/index.js000066400000000000000000000000231345416772700237570ustar00rootroot00000000000000import "./module"; webpack-4.30.0/test/hotCases/concat/reload-external/module.js000066400000000000000000000006241345416772700241440ustar00rootroot00000000000000import value1 from "./a"; import value2 from "./b"; it("should allow to hot replace modules in a ConcatenatedModule", (done) => { expect(value1).toBe(1); expect(value2).toBe(10); module.hot.accept("./a", () => { expect(value1).toBe(2); NEXT(require("../../update")(done)); }); module.hot.accept("./b", () => { expect(value2).toBe(20); done(); }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/concat/reload-external/webpack.config.js000066400000000000000000000002141345416772700255320ustar00rootroot00000000000000"use strict"; const webpack = require("../../../../"); module.exports = { plugins: [new webpack.optimize.ModuleConcatenationPlugin()] }; webpack-4.30.0/test/hotCases/define/000077500000000000000000000000001345416772700172145ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/define/issue-6962/000077500000000000000000000000001345416772700207505ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/define/issue-6962/a.js000066400000000000000000000000501345416772700215210ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/define/issue-6962/index.js000066400000000000000000000000231345416772700224100ustar00rootroot00000000000000import "./module"; webpack-4.30.0/test/hotCases/define/issue-6962/module.js000066400000000000000000000013471345416772700226000ustar00rootroot00000000000000import value1 from "./a"; it("should have the expected static path defined", function() { expect(DEFINE_PATH).toBe('./a'); }); it("should hot.accept the module located at the static file path without breaking the compiler", function() { module.hot.accept("./a"); expect(value1).toBe(1); }); it("should hot.accept the module located at the defined file path without breaking the compiler, when one argument is passed to hot.accept", function() { module.hot.accept(DEFINE_PATH); }); it("should hot.accept the module located at the defined file path without breaking the compiler, when multiple arguments are passed to hot.accept", function(done) { module.hot.accept(DEFINE_PATH, () => done()); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/define/issue-6962/webpack.config.js000066400000000000000000000002461345416772700241700ustar00rootroot00000000000000"use strict"; const webpack = require("../../../../"); module.exports = { plugins: [ new webpack.DefinePlugin({ DEFINE_PATH: JSON.stringify("./a") }) ] }; webpack-4.30.0/test/hotCases/errors/000077500000000000000000000000001345416772700172765ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/errors/decline/000077500000000000000000000000001345416772700207015ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/errors/decline/a.js000066400000000000000000000001561345416772700214610ustar00rootroot00000000000000import b from "./b"; export default b; if(module.hot) { module.hot.decline("./b"); module.hot.accept(); } webpack-4.30.0/test/hotCases/errors/decline/b.js000066400000000000000000000000361345416772700214570ustar00rootroot00000000000000export { default } from "./c" webpack-4.30.0/test/hotCases/errors/decline/c.js000066400000000000000000000000501345416772700214540ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/errors/decline/index.js000066400000000000000000000006351345416772700223520ustar00rootroot00000000000000import a from "./a"; it("should abort when module is declined by parent", (done) => { expect(a).toBe(1); NEXT(require("../../update")((err) => { try { expect(/Aborted because of declined dependency: \.\/b\.js in \.\/a\.js/.test(err.message)).toBe(true); expect(/Update propagation: \.\/c\.js -> \.\/b\.js -> \.\/a\.js/.test(err.message)).toBe(true); done(); } catch(e) { done(e); } })); }); webpack-4.30.0/test/hotCases/errors/events/000077500000000000000000000000001345416772700206025ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/errors/events/a.js000066400000000000000000000000501345416772700213530ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/errors/events/b.js000066400000000000000000000001031345416772700213530ustar00rootroot00000000000000import c from "./c" if(module.hot) { module.hot.accept("./c"); } webpack-4.30.0/test/hotCases/errors/events/c.js000066400000000000000000000000501345416772700213550ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/errors/events/d.js000066400000000000000000000001001345416772700213520ustar00rootroot00000000000000import e from "./e"; if(module.hot) { module.hot.decline(); } webpack-4.30.0/test/hotCases/errors/events/e.js000066400000000000000000000000501345416772700213570ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/errors/events/f.js000066400000000000000000000001041345416772700213600ustar00rootroot00000000000000import g from "./g"; if(module.hot) { module.hot.decline("./g"); }webpack-4.30.0/test/hotCases/errors/events/g.js000066400000000000000000000000501345416772700213610ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/errors/events/h.js000066400000000000000000000001041345416772700213620ustar00rootroot00000000000000import i from "./i"; if(module.hot) { module.hot.accept("./i"); } webpack-4.30.0/test/hotCases/errors/events/i.js000066400000000000000000000001311345416772700213630ustar00rootroot00000000000000export default 1; --- export default 2; throw new Error("Error while loading module h"); webpack-4.30.0/test/hotCases/errors/events/index.js000066400000000000000000000032161345416772700222510ustar00rootroot00000000000000import a from "./a"; import b from "./b"; import d from "./d"; import f from "./f"; import h from "./h"; import j from "./j"; it("should fire the correct events", (done) => { var events = []; var options = { ignoreUnaccepted: true, ignoreDeclined: true, ignoreErrored: true, onDeclined(data) { events.push(data); }, onUnaccepted(data) { events.push(data); }, onAccepted(data) { events.push(data); }, onErrored(data) { events.push(data); } }; function waitForUpdate(fn) { NEXT(require("../../update")(done, options, () => { try { fn(); } catch(e) { done(e); } })); } waitForUpdate(() => { expect(events).toEqual([ { type: "unaccepted", moduleId: "./index.js", chain: [ "./a.js", "./index.js" ], }, { type: "accepted", moduleId: "./c.js", outdatedDependencies: { "./b.js": [ "./c.js" ] }, outdatedModules: [ "./c.js" ], }, { type: "self-declined", moduleId: "./d.js", chain: [ "./e.js", "./d.js" ], }, { type: "declined", moduleId: "./g.js", parentId: "./f.js", chain: [ "./g.js", "./f.js" ], }, { type: "accepted", moduleId: "./i.js", outdatedDependencies: { "./h.js": [ "./i.js" ] }, outdatedModules: [ "./i.js" ], }, { type: "accepted", moduleId: "./j.js", outdatedDependencies: {}, outdatedModules: [ "./j.js" ], }, { type: "accept-errored", moduleId: "./h.js", dependencyId: "./i.js", error: new Error("Error while loading module h") }, { type: "self-accept-errored", moduleId: "./j.js", error: new Error("Error while loading module j") }, ]); done(); }); }); webpack-4.30.0/test/hotCases/errors/events/j.js000066400000000000000000000001561345416772700213730ustar00rootroot00000000000000export default 1; module.hot.accept(); --- export default 2; throw new Error("Error while loading module j"); webpack-4.30.0/test/hotCases/errors/self-decline/000077500000000000000000000000001345416772700216305ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/errors/self-decline/a.js000066400000000000000000000001231345416772700224020ustar00rootroot00000000000000import b from "./b"; export default b; if(module.hot) { module.hot.decline(); } webpack-4.30.0/test/hotCases/errors/self-decline/b.js000066400000000000000000000000361345416772700224060ustar00rootroot00000000000000export { default } from "./c" webpack-4.30.0/test/hotCases/errors/self-decline/c.js000066400000000000000000000000501345416772700224030ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/errors/self-decline/index.js000066400000000000000000000006111345416772700232730ustar00rootroot00000000000000import a from "./a"; it("should abort when module is declined by itself", (done) => { expect(a).toBe(1); NEXT(require("../../update")((err) => { try { expect(/Aborted because of self decline: \.\/a\.js/.test(err.message)).toBe(true); expect(/Update propagation: \.\/c\.js -> \.\/b\.js -> \.\/a\.js/.test(err.message)).toBe(true); done(); } catch(e) { done(e); } })); }); webpack-4.30.0/test/hotCases/errors/unaccepted-ignored/000077500000000000000000000000001345416772700230365ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/errors/unaccepted-ignored/a.js000066400000000000000000000001241345416772700236110ustar00rootroot00000000000000export default 2; --- export default 3; --- export default 3; --- export default 4; webpack-4.30.0/test/hotCases/errors/unaccepted-ignored/b.js000066400000000000000000000001611345416772700236130ustar00rootroot00000000000000import c from "./c" export default function get() { return c; } if(module.hot) { module.hot.accept("./c"); } webpack-4.30.0/test/hotCases/errors/unaccepted-ignored/c.js000066400000000000000000000001241345416772700236130ustar00rootroot00000000000000export default 1; --- export default 1; --- export default 2; --- export default 3; webpack-4.30.0/test/hotCases/errors/unaccepted-ignored/index.js000066400000000000000000000010161345416772700245010ustar00rootroot00000000000000import a from "./a"; import get from "./b"; var options = { ignoreUnaccepted: true }; it("should ignore unaccepted module updates", (done) => { function waitForUpdate(fn) { NEXT(require("../../update")(done, options, fn)); } expect(a).toBe(2); expect(get()).toBe(1); waitForUpdate(() => { expect(a).toBe(2); expect(get()).toBe(1); waitForUpdate(() => { expect(a).toBe(2); expect(get()).toBe(2); waitForUpdate(() => { expect(a).toBe(2); expect(get()).toBe(3); done(); }); }); }); }); webpack-4.30.0/test/hotCases/errors/unaccepted/000077500000000000000000000000001345416772700214115ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/errors/unaccepted/a.js000066400000000000000000000000211345416772700221600ustar00rootroot00000000000000export default 2;webpack-4.30.0/test/hotCases/errors/unaccepted/b.js000066400000000000000000000000361345416772700221670ustar00rootroot00000000000000export { default } from "./c" webpack-4.30.0/test/hotCases/errors/unaccepted/c.js000066400000000000000000000000501345416772700221640ustar00rootroot00000000000000export default 1; --- export default 2; webpack-4.30.0/test/hotCases/errors/unaccepted/index.js000066400000000000000000000006521345416772700230610ustar00rootroot00000000000000import a from "./a"; import b from "./b"; it("should abort when module is not accepted", (done) => { expect(a).toBe(2); expect(b).toBe(1); NEXT(require("../../update")((err) => { try { expect(/Aborted because \.\/c\.js is not accepted/.test(err.message)).toBe(true); expect(/Update propagation: \.\/c\.js -> \.\/b\.js -> \.\/index\.js/.test(err.message)).toBe(true); done(); } catch(e) { done(e); } })); }); webpack-4.30.0/test/hotCases/fake-update-loader.js000066400000000000000000000003211345416772700217460ustar00rootroot00000000000000module.exports = function(source) { var idx = this.updateIndex; var items = source.split(/---+\r?\n/g); if (items.length > 1) { this.cacheable(false); } return items[idx] || items[items.length - 1]; }; webpack-4.30.0/test/hotCases/harmony/000077500000000000000000000000001345416772700174375ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/harmony/auto-import-default/000077500000000000000000000000001345416772700233415ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/harmony/auto-import-default/file.js000066400000000000000000000000541345416772700246150ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-4.30.0/test/hotCases/harmony/auto-import-default/index.js000066400000000000000000000005151345416772700250070ustar00rootroot00000000000000import value from "./file"; it("should auto-import a ES6 imported default value from non-harmony module on accept", (done) => { expect(value).toBe(1); module.hot.accept("./file", () => { expect(value).toBe(2); outside(); done(); }); NEXT(require("../../update")(done)); }); function outside() { expect(value).toBe(2); } webpack-4.30.0/test/hotCases/harmony/auto-import-multiple/000077500000000000000000000000001345416772700235505ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/harmony/auto-import-multiple/commonjs.js000066400000000000000000000000561345416772700257340ustar00rootroot00000000000000module.exports = 10; --- module.exports = 20; webpack-4.30.0/test/hotCases/harmony/auto-import-multiple/file.js000066400000000000000000000000601345416772700250210ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-4.30.0/test/hotCases/harmony/auto-import-multiple/index.js000066400000000000000000000006711345416772700252210ustar00rootroot00000000000000import { value } from "./file"; import value2 from "./commonjs"; it("should auto-import multiple ES6 imported values on accept", (done) => { expect(value).toBe(1); expect(value2).toBe(10); module.hot.accept(["./file", "./commonjs"], () => { expect(value).toBe(2); expect(value2).toBe(20); outside(); done(); }); NEXT(require("../../update")(done)); }); function outside() { expect(value).toBe(2); expect(value2).toBe(20); } webpack-4.30.0/test/hotCases/harmony/auto-import/000077500000000000000000000000001345416772700217175ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/harmony/auto-import/file.js000066400000000000000000000000601345416772700231700ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-4.30.0/test/hotCases/harmony/auto-import/index.js000066400000000000000000000004731345416772700233700ustar00rootroot00000000000000import { value } from "./file"; it("should auto-import a ES6 imported value on accept", function(done) { expect(value).toBe(1); module.hot.accept("./file", function() { expect(value).toBe(2); outside(); done(); }); NEXT(require("../../update")(done)); }); function outside() { expect(value).toBe(2); } webpack-4.30.0/test/hotCases/json/000077500000000000000000000000001345416772700167335ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/json/error-in-json/000077500000000000000000000000001345416772700214375ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/json/error-in-json/data.json000066400000000000000000000000151345416772700232370ustar00rootroot00000000000000error --- 42 webpack-4.30.0/test/hotCases/json/error-in-json/errors.js000066400000000000000000000000541345416772700233100ustar00rootroot00000000000000module.exports = [[/Module parse failed/]]; webpack-4.30.0/test/hotCases/json/error-in-json/index.js000066400000000000000000000004121345416772700231010ustar00rootroot00000000000000it("should be able to recover from json error", function(done) { expect(() => require("./data.json")).toThrowError(); module.hot.accept("./data.json", function() { expect(require("./data.json")).toBe(42); done(); }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/recover/000077500000000000000000000000001345416772700174275ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/recover/recover-after-error/000077500000000000000000000000001345416772700233225ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/recover/recover-after-error/a.js000066400000000000000000000001311345416772700240730ustar00rootroot00000000000000export default 1; --- export default 2; throw new Error("Failed"); --- export default 3; webpack-4.30.0/test/hotCases/recover/recover-after-error/index.js000066400000000000000000000005561345416772700247750ustar00rootroot00000000000000import a from "./a"; it("should abort when module is not accepted", (done) => { expect(a).toBe(1); NEXT(require("../../update")(done, { ignoreErrored: true }, () => { expect(a).toBe(1); NEXT(require("../../update")(done, { ignoreErrored: true }, () => { expect(a).toBe(3); done(); })); })); }); if(module.hot) { module.hot.accept("./a"); } webpack-4.30.0/test/hotCases/recover/recover-after-loader-error/000077500000000000000000000000001345416772700245665ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/recover/recover-after-loader-error/a.js000066400000000000000000000000711345416772700253420ustar00rootroot00000000000000export default 1; --- Loader error --- export default 3; webpack-4.30.0/test/hotCases/recover/recover-after-loader-error/errors1.js000066400000000000000000000000471345416772700265220ustar00rootroot00000000000000module.exports = [ [/Loader error/] ] webpack-4.30.0/test/hotCases/recover/recover-after-loader-error/index.js000066400000000000000000000006051345416772700262340ustar00rootroot00000000000000import a from "./loader!./a"; it("should abort when module is not accepted", (done) => { expect(a).toBe(1); NEXT(require("../../update")(done, { ignoreErrored: true }, () => { expect(a).toBe(1); NEXT(require("../../update")(done, { ignoreErrored: true }, function() { expect(a).toBe(3); done(); })); })); }); if(module.hot) { module.hot.accept("./loader!./a"); } webpack-4.30.0/test/hotCases/recover/recover-after-loader-error/loader.js000066400000000000000000000001731345416772700263730ustar00rootroot00000000000000module.exports = function(source) { if(source.indexOf("error") >= 0) throw new Error(source.trim()); return source; }; webpack-4.30.0/test/hotCases/recover/recover-after-parsing-error/000077500000000000000000000000001345416772700247635ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/recover/recover-after-parsing-error/a.js000066400000000000000000000001031345416772700255330ustar00rootroot00000000000000export default 1; --- ]}); export default 2; --- export default 3; webpack-4.30.0/test/hotCases/recover/recover-after-parsing-error/errors1.js000066400000000000000000000000551345416772700267160ustar00rootroot00000000000000module.exports = [ [/Module parse failed/] ]webpack-4.30.0/test/hotCases/recover/recover-after-parsing-error/index.js000066400000000000000000000005561345416772700264360ustar00rootroot00000000000000import a from "./a"; it("should abort when module is not accepted", (done) => { expect(a).toBe(1); NEXT(require("../../update")(done, { ignoreErrored: true }, () => { expect(a).toBe(1); NEXT(require("../../update")(done, { ignoreErrored: true }, () => { expect(a).toBe(3); done(); })); })); }); if(module.hot) { module.hot.accept("./a"); } webpack-4.30.0/test/hotCases/runtime/000077500000000000000000000000001345416772700174455ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/accept/000077500000000000000000000000001345416772700207045ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/accept/file.js000066400000000000000000000000541345416772700221600ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-4.30.0/test/hotCases/runtime/accept/index.js000066400000000000000000000005201345416772700223460ustar00rootroot00000000000000var value = require("./file"); it("should accept a dependencies and require a new value", (done) => { expect(value).toBe(1); module.hot.accept("./file", () => { value = require("./file"); expect(value).toBe(2); outside(); done(); }); NEXT(require("../../update")(done)); }); function outside() { expect(value).toBe(2); } webpack-4.30.0/test/hotCases/runtime/bubble-async/000077500000000000000000000000001345416772700220135ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/bubble-async/file.js000066400000000000000000000000541345416772700232670ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-4.30.0/test/hotCases/runtime/bubble-async/index.js000066400000000000000000000006161345416772700234630ustar00rootroot00000000000000import { load } from "./parent-file"; import update from "../../update"; it("should bubble update from a nested dependency", () => { return load().then(value => { expect(value).toBe(1); return new Promise((resolve, reject) => { module.hot.accept("./parent-file", () => { resolve(load().then(value => { expect(value).toBe(2); })); }); NEXT(update(reject)); }); }) }); webpack-4.30.0/test/hotCases/runtime/bubble-async/parent-file.js000066400000000000000000000001201345416772700245500ustar00rootroot00000000000000export function load() { return import("./file").then(file => file.default); } webpack-4.30.0/test/hotCases/runtime/bubble-update/000077500000000000000000000000001345416772700221605ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/bubble-update/file.js000066400000000000000000000000541345416772700234340ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-4.30.0/test/hotCases/runtime/bubble-update/index.js000066400000000000000000000004411345416772700236240ustar00rootroot00000000000000var value = require("./parent-file"); it("should bubble update from a nested dependency", (done) => { expect(value).toBe(1); module.hot.accept("./parent-file", () => { value = require("./parent-file"); expect(value).toBe(2); done(); }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/runtime/bubble-update/parent-file.js000066400000000000000000000000441345416772700247220ustar00rootroot00000000000000module.exports = require("./file"); webpack-4.30.0/test/hotCases/runtime/circular/000077500000000000000000000000001345416772700212515ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/circular/a.js000066400000000000000000000001361345416772700220270ustar00rootroot00000000000000import "./"; import "./b"; export default 1; --- import "./"; import "./b"; export default 2; webpack-4.30.0/test/hotCases/runtime/circular/b.js000066400000000000000000000001201345416772700220210ustar00rootroot00000000000000import "./a"; export default 1; module.hot.accept("./a"); --- export default 2; webpack-4.30.0/test/hotCases/runtime/circular/index.js000066400000000000000000000003261345416772700227170ustar00rootroot00000000000000import a from "./a"; it("should not throw on circular dependencies", (done) => { expect(a).toBe(1); module.hot.accept("./a", () => { expect(a).toBe(2); done(); }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/runtime/dispose-removed-chunk/000077500000000000000000000000001345416772700236605ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/dispose-removed-chunk/a.js000066400000000000000000000000321345416772700244310ustar00rootroot00000000000000export default Date.now();webpack-4.30.0/test/hotCases/runtime/dispose-removed-chunk/b.js000066400000000000000000000000001345416772700244250ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/dispose-removed-chunk/index.js000066400000000000000000000010311345416772700253200ustar00rootroot00000000000000it("should dispose a chunk which is removed from bundle", (done) => { var m1 = require("./module"); m1.default.then((x1) => { NEXT(require("../../update")(done, true, () => { var m2 = require("./module"); m2.default.then((x2) => { NEXT(require("../../update")(done, true, () => { var m3 = require("./module"); m3.default.then((x3) => { expect(x1).not.toEqual(x2); done(); }).catch(done); })); }).catch(done); })); }).catch(done); }); if(module.hot) { module.hot.accept("./module"); } webpack-4.30.0/test/hotCases/runtime/dispose-removed-chunk/module.js000066400000000000000000000001421345416772700255000ustar00rootroot00000000000000export default import("./a"); --- export default import("./b"); --- export default import("./a"); webpack-4.30.0/test/hotCases/runtime/dispose-removed-module/000077500000000000000000000000001345416772700240355ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/dispose-removed-module/a.js000066400000000000000000000002741345416772700246160ustar00rootroot00000000000000var callback; export default function setHandler(cb) { callback = cb; }; if(module.hot) { module.hot.dispose(function() { callback(module.id); }); } --- --- export default module.id;webpack-4.30.0/test/hotCases/runtime/dispose-removed-module/b.js000066400000000000000000000000211345416772700246050ustar00rootroot00000000000000export default 1;webpack-4.30.0/test/hotCases/runtime/dispose-removed-module/index.js000066400000000000000000000007211345416772700255020ustar00rootroot00000000000000var m = require("./module"); it("should dispose a module which is removed from bundle", (done) => { var disposed = []; m.setHandler((id) => { disposed.push(id); }); NEXT(require("../../update")(done, true, () => { require("./module"); NEXT(require("../../update")(done, true, () => { var newModule = require("./module"); expect(disposed).toEqual([newModule.default]); done(); })); })); }); if(module.hot) { module.hot.accept("./module"); } webpack-4.30.0/test/hotCases/runtime/dispose-removed-module/module.js000066400000000000000000000001531345416772700256570ustar00rootroot00000000000000export { default as setHandler } from "./a"; --- import "./b" --- export { default as default } from "./a";webpack-4.30.0/test/hotCases/runtime/self-accept-and-dispose/000077500000000000000000000000001345416772700240375ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/self-accept-and-dispose/file.js000066400000000000000000000002741345416772700253170ustar00rootroot00000000000000var callback; module.hot.accept(); module.hot.dispose(function(data) { data.callback = callback; }); module.exports = function(cb) { callback = cb; } --- module.hot.data.callback(); webpack-4.30.0/test/hotCases/runtime/self-accept-and-dispose/index.js000066400000000000000000000001711345416772700255030ustar00rootroot00000000000000it("should accept itself and pass data", (done) => { require("./file")(done); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/runtime/update-multiple-modules/000077500000000000000000000000001345416772700242265ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/update-multiple-modules/fileA.js000066400000000000000000000000541345416772700256030ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-4.30.0/test/hotCases/runtime/update-multiple-modules/fileB.js000066400000000000000000000000541345416772700256040ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-4.30.0/test/hotCases/runtime/update-multiple-modules/index.js000066400000000000000000000004431345416772700256740ustar00rootroot00000000000000var value = require("./parent-file"); it("should update multiple modules at the same time", (done) => { expect(value).toBe(2); module.hot.accept("./parent-file", () => { value = require("./parent-file"); expect(value).toBe(4); done(); }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/runtime/update-multiple-modules/parent-file.js000066400000000000000000000000721345416772700267710ustar00rootroot00000000000000module.exports = require("./fileA") + require("./fileB"); webpack-4.30.0/test/hotCases/runtime/update-multiple-times/000077500000000000000000000000001345416772700236775ustar00rootroot00000000000000webpack-4.30.0/test/hotCases/runtime/update-multiple-times/file.js000066400000000000000000000001641345416772700251550ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; --- module.exports = 3; --- module.exports = 4; --- module.exports = 5; webpack-4.30.0/test/hotCases/runtime/update-multiple-times/index.js000066400000000000000000000005551345416772700253510ustar00rootroot00000000000000var value = require("./file"); it("should accept a dependencies multiple times", (done) => { expect(value).toBe(1); module.hot.accept("./file", () => { var oldValue = value; value = require("./file"); expect(value).toBe(oldValue + 1); if(value < 4) NEXT(require("../../update")(done)); else done(); }); NEXT(require("../../update")(done)); }); webpack-4.30.0/test/hotCases/update.js000066400000000000000000000003701345416772700176020ustar00rootroot00000000000000module.exports = function(done, options, callback) { return function(err, stats) { if (err) return done(err); module.hot.check(options || true).then(() => { if (callback) callback(stats); }).catch((err) => { done(err); }); } }; webpack-4.30.0/test/hotPlayground/000077500000000000000000000000001345416772700170505ustar00rootroot00000000000000webpack-4.30.0/test/hotPlayground/.gitignore000066400000000000000000000000501345416772700210330ustar00rootroot00000000000000*bundle-update.js bundle.js records.jsonwebpack-4.30.0/test/hotPlayground/addStyle.js000066400000000000000000000010121345416772700211510ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ module.exports = function(cssCode) { var styleElement = document.createElement("style"); styleElement.type = "text/css"; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = cssCode; } else { styleElement.appendChild(document.createTextNode(cssCode)); } var head = document.getElementsByTagName("head")[0]; head.appendChild(styleElement); return function() { head.removeChild(styleElement); }; }webpack-4.30.0/test/hotPlayground/applyStyle2.js000066400000000000000000000002111345416772700216300ustar00rootroot00000000000000// This file can update, because it accept itself. // A dispose handler removes the old