pax_global_header00006660000000000000000000000064131540134210014504gustar00rootroot0000000000000052 comment=92d5c209437f9ef9293571e24cc8dcf10459d578 webpack-3.5.6/000077500000000000000000000000001315401342100131335ustar00rootroot00000000000000webpack-3.5.6/.editorconfig000066400000000000000000000006121315401342100156070ustar00rootroot00000000000000root = true [*] indent_style = tab indent_size = 4 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true max_line_length = 233 [*.json] indent_style = space indent_size = 2 [*.yml] indent_style = space indent_size = 2 [*.yaml] indent_style = space indent_size = 2 [test/cases/parsing/bom/bomfile.{css,js}] charset = utf-8-bom [*.md] trim_trailing_whitespace = false webpack-3.5.6/.eslintrc.js000066400000000000000000000035021315401342100153720ustar00rootroot00000000000000module.exports = { "root": true, "plugins": ["node"], "extends": ["eslint:recommended", "plugin:node/recommended"], "env": { "node": true, "es6": true, }, "parserOptions": { "ecmaVersion": 2017 }, "rules": { "quotes": ["error", "double"], "no-undef": "error", "no-extra-semi": "error", "semi": "error", "no-template-curly-in-string": "error", "no-caller": "error", "yoda": "error", "eqeqeq": "error", "global-require": "off", "brace-style": "error", "eol-last": "error", "indent": ["error", "tab", { "SwitchCase": 1 }], "no-extra-bind": "warn", "no-empty": "off", "no-multiple-empty-lines": "error", "no-multi-spaces": "error", "no-process-exit": "warn", "space-in-parens": "error", "no-trailing-spaces": "error", "no-use-before-define": "off", "no-unused-vars": ["error", { "args": "none" }], "key-spacing": "error", "space-infix-ops": "error", "no-unsafe-negation": "error", "no-loop-func": "warn", "space-before-function-paren": ["error", "never"], "space-before-blocks": "error", "object-curly-spacing": ["error", "always"], "indent": "off", "keyword-spacing": ["error", { "after": false, "overrides": { "const": { "after": true }, "try": { "after": true }, "else": { "after": true }, "throw": { "after": true }, "case": { "after": true }, "return": { "after": true }, "finally": { "after": true }, "do": { "after": true } } }], "no-console": "off", "valid-jsdoc": "error", "node/no-unsupported-features": ["error", { version: 4 }], "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" } }; webpack-3.5.6/.gitattributes000066400000000000000000000001031315401342100160200ustar00rootroot00000000000000* text=auto test/statsCases/* eol=lf examples/* eol=lf bin/* eol=lfwebpack-3.5.6/.github/000077500000000000000000000000001315401342100144735ustar00rootroot00000000000000webpack-3.5.6/.github/ISSUE_TEMPLATE.md000066400000000000000000000021061315401342100171770ustar00rootroot00000000000000 **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-3.5.6/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000015231315401342100202750ustar00rootroot00000000000000 **What kind of change does this PR introduce?** **Did you add tests for your changes?** **If relevant, link to documentation update:** **Summary** **Does this PR introduce a breaking change?** **Other information** webpack-3.5.6/.gitignore000066400000000000000000000002501315401342100151200ustar00rootroot00000000000000/node_modules /test/js /test/browsertest/js /test/fixtures/temp-cache-fixture /benchmark/js /benchmark/fixtures /examples/**/js /coverage .DS_Store *.log .idea .vscode webpack-3.5.6/.jsbeautifyrc000066400000000000000000000013021315401342100156220ustar00rootroot00000000000000{ "js": { "allowed_file_extensions": ["js", "json", "jshintrc", "jsbeautifyrc"], "brace_style": "collapse", "break_chained_methods": false, "e4x": true, "eval_code": false, "end_with_newline": true, "indent_char": "\t", "indent_level": 0, "indent_size": 1, "indent_with_tabs": true, "jslint_happy": false, "jslint_happy_align_switch_case": true, "space_after_anon_function": false, "keep_array_indentation": false, "keep_function_indentation": false, "max_preserve_newlines": 2, "preserve_newlines": true, "space_before_conditional": false, "space_in_paren": false, "unescape_strings": false, "wrap_line_length": 0 } }webpack-3.5.6/.travis.yml000066400000000000000000000020741315401342100152470ustar00rootroot00000000000000sudo: false dist: precise language: node_js branches: only: - master - next cache: directories: - $HOME/.npm - $HOME/.yarn-cache matrix: include: - os: linux node_js: "8" env: NO_WATCH_TESTS=1 JOB_PART=lint - os: linux node_js: "8" env: NO_WATCH_TESTS=1 JOB_PART=test - os: linux node_js: "6" env: NO_WATCH_TESTS=1 JOB_PART=test - os: linux node_js: "4.3" env: NO_WATCH_TESTS=1 JOB_PART=test - os: osx node_js: "8" env: NO_WATCH_TESTS=1 JOB_PART=test allow_failures: - os: osx fast_finish: true before_script: - bash ./ci/travis-install.sh script: npm run travis:$JOB_PART after_success: - cat ./coverage/lcov.info | node_modules/.bin/coveralls --verbose - cat ./coverage/coverage.json | node_modules/codecov.io/bin/codecov.io.js - rm -rf ./coverage notifications: slack: secure: JduSdKWwbnLCwo7Z4E59SGE+Uw832UwnXzQiKEpg1BV45MYDPRiGltly1tRHmPh9OGjvGx3XSkC2tNGOBLtL4UL2SCkf012x0t7jDutKRfcv/njynl8jk8l+UhPmaWiHXDQAgGiiKdL4RfzPLW3HeVHCOWm0LKMzcarTa8tw+rE= webpack-3.5.6/CONTRIBUTING.md000066400000000000000000000040121315401342100153610ustar00rootroot00000000000000# 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 and relevant files are more likely to receive responses. **If you have discovered a bug or have a feature suggestion, feel free to create an issue on Github.** ## 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 ```bash git clone https://github.com/webpack/webpack.git cd webpack npm install -g yarn yarn install yarn link yarn link webpack ``` To run the entire test suite use: ```bash yarn test ``` ## Submitting Changes After getting some feedback, 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. Some things 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. webpack-3.5.6/LICENSE000066400000000000000000000020571315401342100141440ustar00rootroot00000000000000Copyright 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-3.5.6/README.md000066400000000000000000001403751315401342100144240ustar00rootroot00000000000000


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

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.

Install

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

Introduction

> This README reflects Webpack v2.x and v3.x. The Webpack v1.x [documentation can be found here](https://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=top). 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/).

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|Description| |:--:|:----:|:----------| |[common-chunks-webpack-plugin][common]|![common-npm]|Generates chunks of common modules shared between entry points and splits them into separate bundles (e.g vendor.bundle.js && app.bundle.js)| |[extract-text-webpack-plugin][extract]|![extract-npm]|Extracts Text (CSS) from your bundles into a separate file (app.bundle.css)| |[compression-webpack-plugin][compression]|![compression-npm]|Prepare compressed versions of assets to serve them with Content-Encoding| |[i18n-webpack-plugin][i18n]|![i18n-npm]|Adds i18n support to your bundles| |[html-webpack-plugin][html-plugin]|![html-plugin-npm]| Simplifies creation of HTML files (`index.html`) to serve your bundles| [common]: https://github.com/webpack/webpack/blob/master/lib/optimize/CommonsChunkPlugin.js [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 [component]: https://github.com/webpack/component-webpack-plugin [component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg [compression]: https://github.com/webpack/compression-webpack-plugin [compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg [i18n]: https://github.com/webpack/i18n-webpack-plugin [i18n-npm]: https://img.shields.io/npm/v/i18n-webpack-plugin.svg [html-plugin]: https://github.com/ampedandwired/html-webpack-plugin [html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg ### [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|Description| |:--:|:----:|:----------| |[raw-loader][raw]|![raw-npm]|Loads raw content of a file (utf-8)| |[val-loader][val]|![val-npm]|Executes code as module and consider exports as JS code| |[url-loader][url]|![url-npm]|Works like the file loader, but can return a Data Url if the file is smaller than a limit| |[file-loader][file]|![file-npm]|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 [val]: https://github.com/webpack/val-loader [val-npm]: https://img.shields.io/npm/v/val-loader.svg [url]: https://github.com/webpack/url-loader [url-npm]: https://img.shields.io/npm/v/url-loader.svg [file]: https://github.com/webpack/file-loader [file-npm]: https://img.shields.io/npm/v/file-loader.svg #### JSON |Name|Status|Description| |:--:|:----:|:----------| ||![json-npm]|Loads a JSON file (included by default)| ||![json5-npm]|Loads and transpiles a JSON 5 file| ||![cson-npm]|Loads and transpiles a CSON file| [json-npm]: https://img.shields.io/npm/v/json-loader.svg [json5-npm]: https://img.shields.io/npm/v/json5-loader.svg [cson-npm]: https://img.shields.io/npm/v/cson-loader.svg #### Transpiling |Name|Status|Description| |:--:|:----:|:----------| |` ``` # js/common.[chunkhash].js ``` javascript webpackJsonp([2],[ /* 0 */ /*!*******************!*\ !*** ./vendor.js ***! \*******************/ /*! exports provided: default */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); // some vendor lib (should be in common chunk) /* harmony default export */ __webpack_exports__["default"] = (123); /***/ }), /* 1 */, /* 2 */ /*!**********************!*\ !*** multi ./vendor ***! \**********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./vendor */0); /***/ }) ],[2]); ``` # js/main.[chunkhash].js ``` javascript webpackJsonp([3],[ /* 0 */, /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! exports provided: */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__vendor__ = __webpack_require__(/*! ./vendor */ 0); // some module __webpack_require__.e/* import() */(1).then(__webpack_require__.bind(null, /*! ./async1 */ 3)); __webpack_require__.e/* import() */(0).then(__webpack_require__.bind(null, /*! ./async2 */ 4)); /***/ }) ],[1]); ``` # Info ## Uncompressed ``` Hash: 49023fec553882c3285c Version: webpack 3.5.1 Asset Size Chunks Chunk Names 3db3fdaf96bbdadce99a.js 238 bytes 0 [emitted] 7c1138cf80dd374c367e.js 238 bytes 1 [emitted] common.[chunkhash].js 732 bytes 2 [emitted] common main.[chunkhash].js 656 bytes 3 [emitted] main manifest.[chunkhash].js 5.89 kB 4 [emitted] manifest Entrypoint main = manifest.[chunkhash].js common.[chunkhash].js main.[chunkhash].js Entrypoint common = manifest.[chunkhash].js common.[chunkhash].js chunk {0} 3db3fdaf96bbdadce99a.js 29 bytes {3} [rendered] > [1] ./example.js 4:0-18 [4] ./async2.js 29 bytes {0} [built] import() ./async2 [1] ./example.js 4:0-18 chunk {1} 7c1138cf80dd374c367e.js 29 bytes {3} [rendered] > [1] ./example.js 3:0-18 [3] ./async1.js 29 bytes {1} [built] import() ./async1 [1] ./example.js 3:0-18 chunk {2} common.[chunkhash].js (common) 97 bytes {4} [initial] [rendered] > common [2] multi ./vendor [0] ./vendor.js 69 bytes {2} [built] [exports: default] harmony import ./vendor [1] ./example.js 1:0-30 single entry ./vendor [2] multi ./vendor common:100000 [2] multi ./vendor 28 bytes {2} [built] chunk {3} main.[chunkhash].js (main) 90 bytes {2} [initial] [rendered] > main [1] ./example.js [1] ./example.js 90 bytes {3} [built] [no exports] chunk {4} manifest.[chunkhash].js (manifest) 0 bytes [entry] [rendered] ``` ## Minimized (uglify-js, no zip) ``` Hash: 49023fec553882c3285c Version: webpack 3.5.1 Asset Size Chunks Chunk Names 3db3fdaf96bbdadce99a.js 38 bytes 0 [emitted] 7c1138cf80dd374c367e.js 38 bytes 1 [emitted] common.[chunkhash].js 150 bytes 2 [emitted] common main.[chunkhash].js 165 bytes 3 [emitted] main manifest.[chunkhash].js 1.46 kB 4 [emitted] manifest Entrypoint main = manifest.[chunkhash].js common.[chunkhash].js main.[chunkhash].js Entrypoint common = manifest.[chunkhash].js common.[chunkhash].js chunk {0} 3db3fdaf96bbdadce99a.js 29 bytes {3} [rendered] > [1] ./example.js 4:0-18 [4] ./async2.js 29 bytes {0} [built] import() ./async2 [1] ./example.js 4:0-18 chunk {1} 7c1138cf80dd374c367e.js 29 bytes {3} [rendered] > [1] ./example.js 3:0-18 [3] ./async1.js 29 bytes {1} [built] import() ./async1 [1] ./example.js 3:0-18 chunk {2} common.[chunkhash].js (common) 97 bytes {4} [initial] [rendered] > common [2] multi ./vendor [0] ./vendor.js 69 bytes {2} [built] [exports: default] harmony import ./vendor [1] ./example.js 1:0-30 single entry ./vendor [2] multi ./vendor common:100000 [2] multi ./vendor 28 bytes {2} [built] chunk {3} main.[chunkhash].js (main) 90 bytes {2} [initial] [rendered] > main [1] ./example.js [1] ./example.js 90 bytes {3} [built] [no exports] chunk {4} manifest.[chunkhash].js (manifest) 0 bytes [entry] [rendered] ```webpack-3.5.6/examples/chunkhash/async1.js000066400000000000000000000000341315401342100204560ustar00rootroot00000000000000// some async loaded module webpack-3.5.6/examples/chunkhash/async2.js000066400000000000000000000000341315401342100204570ustar00rootroot00000000000000// some async loaded module webpack-3.5.6/examples/chunkhash/build.js000066400000000000000000000000711315401342100203600ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-3.5.6/examples/chunkhash/example.js000066400000000000000000000001261315401342100207150ustar00rootroot00000000000000import vendor from "./vendor"; // some module import("./async1"); import("./async2"); webpack-3.5.6/examples/chunkhash/template.md000066400000000000000000000032071315401342100210640ustar00rootroot00000000000000A 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 by the CommonsChunkPlugin (or if the CommonsChunkPlugin is already used by passing multiple names to the CommonChunkPlugin). 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` * `CommonsChunkPlugin` # example.js ``` javascript {{example.js}} ``` # vendor.js ``` javascript {{vendor.js}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # index.html ``` html ``` # js/common.[chunkhash].js ``` javascript {{js/common.chunkhash.js}} ``` # js/main.[chunkhash].js ``` javascript {{js/main.chunkhash.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/chunkhash/vendor.js000066400000000000000000000001031315401342100205520ustar00rootroot00000000000000// some vendor lib (should be in common chunk) export default 123; webpack-3.5.6/examples/chunkhash/webpack.config.js000066400000000000000000000007351315401342100221500ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { entry: { main: "./example", common: ["./vendor"] // optional }, output: { path: path.join(__dirname, "js"), filename: "[name].chunkhash.js", chunkFilename: "[chunkhash].js" }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: ["common", "manifest"] }) /* without the "common" chunk: new webpack.optimize.CommonsChunkPlugin({ name: "manifest" }) */ ] }; webpack-3.5.6/examples/code-splitted-css-bundle/000077500000000000000000000000001315401342100215465ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitted-css-bundle/README.md000066400000000000000000000110621315401342100230250ustar00rootroot00000000000000 # 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.5.1 Asset Size Chunks Chunk Names ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] 0.output.js 2.43 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 (uglify-js, no zip) ``` Hash: edbe0e91ba86d814d855 Version: webpack 3.5.1 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-3.5.6/examples/code-splitted-css-bundle/build.js000066400000000000000000000000331315401342100231770ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/code-splitted-css-bundle/chunk.js000066400000000000000000000000311315401342100232060ustar00rootroot00000000000000require("./style2.css"); webpack-3.5.6/examples/code-splitted-css-bundle/example.js000066400000000000000000000000561315401342100235400ustar00rootroot00000000000000require("./style.css"); require(["./chunk"]); webpack-3.5.6/examples/code-splitted-css-bundle/image.png000066400000000000000000000001671315401342100233420ustar00rootroot00000000000000PNG  IHDRwSsRGBgAMA a pHYsod IDATWc?5IENDB`webpack-3.5.6/examples/code-splitted-css-bundle/image2.png000066400000000000000000000001671315401342100234240ustar00rootroot00000000000000PNG  IHDRwSsRGBgAMA a pHYsod IDATWc?5IENDB`webpack-3.5.6/examples/code-splitted-css-bundle/style.css000066400000000000000000000000461315401342100234200ustar00rootroot00000000000000body { background: url(image.png); } webpack-3.5.6/examples/code-splitted-css-bundle/style2.css000066400000000000000000000000471315401342100235030ustar00rootroot00000000000000.xyz { background: url(image2.png); } webpack-3.5.6/examples/code-splitted-css-bundle/template.md000066400000000000000000000006131315401342100237030ustar00rootroot00000000000000 # example.js ``` javascript {{example.js}} ``` # style.css ``` css {{style.css}} ``` # chunk.js ``` javascript {{chunk.js}} ``` # style2.css ``` css {{style2.css}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/style.css ``` javascript {{js/style.css}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/code-splitted-css-bundle/webpack.config.js000066400000000000000000000005531315401342100247670ustar00rootroot00000000000000var 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" }) ] }; webpack-3.5.6/examples/code-splitted-require.context-amd/000077500000000000000000000000001315401342100234055ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitted-require.context-amd/README.md000066400000000000000000000260521315401342100246710ustar00rootroot00000000000000# 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); }); ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { function getTemplate(templateName, callback) { __webpack_require__.e/* require */(0).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(/*! ../require.context/templates */ 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); }); /***/ }) /******/ ]); ``` # js/0.output.js ``` javascript webpackJsonp([0],[ /* 0 */, /* 1 */ /*!*********************************************!*\ !*** ../require.context/templates ^\.\/.*$ ***! \*********************************************/ /*! no static exports found */ /*! all exports used */ /***/ (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) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; 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 */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 3 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 4 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]); ``` # Info ## Uncompressed ``` Hash: 1c46bbe47e8b8a0ee8e2 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 1.85 kB 0 [emitted] output.js 6.37 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 463 bytes {1} [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates ^\.\/.*$ 217 bytes {0} [built] amd require context ../require.context/templates [0] ./example.js 2:1-4:3 [2] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [1] ../require.context/templates ^\.\/.*$ ./a.js context element ./a [1] ../require.context/templates ^\.\/.*$ ./a [3] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [1] ../require.context/templates ^\.\/.*$ ./b.js context element ./b [1] ../require.context/templates ^\.\/.*$ ./b [4] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [1] ../require.context/templates ^\.\/.*$ ./c.js context element ./c [1] ../require.context/templates ^\.\/.*$ ./c chunk {1} output.js (main) 261 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 261 bytes {1} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: 1c46bbe47e8b8a0ee8e2 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 544 bytes 0 [emitted] output.js 1.52 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 463 bytes {1} [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates ^\.\/.*$ 217 bytes {0} [built] amd require context ../require.context/templates [0] ./example.js 2:1-4:3 [2] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [1] ../require.context/templates ^\.\/.*$ ./a.js context element ./a [1] ../require.context/templates ^\.\/.*$ ./a [3] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [1] ../require.context/templates ^\.\/.*$ ./b.js context element ./b [1] ../require.context/templates ^\.\/.*$ ./b [4] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [1] ../require.context/templates ^\.\/.*$ ./c.js context element ./c [1] ../require.context/templates ^\.\/.*$ ./c chunk {1} output.js (main) 261 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 261 bytes {1} [built] ``` webpack-3.5.6/examples/code-splitted-require.context-amd/build.js000066400000000000000000000000331315401342100250360ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/code-splitted-require.context-amd/example.js000066400000000000000000000003731315401342100254010ustar00rootroot00000000000000function 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-3.5.6/examples/code-splitted-require.context-amd/template.md000066400000000000000000000004051315401342100255410ustar00rootroot00000000000000# example.js ``` javascript {{example.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/code-splitted-require.context/000077500000000000000000000000001315401342100226465ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitted-require.context/README.md000066400000000000000000000257751315401342100241450ustar00rootroot00000000000000# 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); }); ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { function getTemplate(templateName, callback) { __webpack_require__.e/* require.ensure */(0).then((function(require) { callback(__webpack_require__(/*! ../require.context/templates */ 1)("./"+templateName)()); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); } getTemplate("a", function(a) { console.log(a); }); getTemplate("b", function(b) { console.log(b); }); /***/ }) /******/ ]); ``` # js/0.output.js ``` javascript webpackJsonp([0],[ /* 0 */, /* 1 */ /*!*********************************************!*\ !*** ../require.context/templates ^\.\/.*$ ***! \*********************************************/ /*! no static exports found */ /*! all exports used */ /***/ (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) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; 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 */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 3 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 4 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]); ``` # Info ## Uncompressed ``` Hash: f67ab883501eec17d2fb Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 1.85 kB 0 [emitted] output.js 6.3 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 463 bytes {1} [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates ^\.\/.*$ 217 bytes {0} [built] cjs require context ../require.context/templates [0] ./example.js 3:11-64 [2] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [1] ../require.context/templates ^\.\/.*$ ./a.js context element ./a [1] ../require.context/templates ^\.\/.*$ ./a [3] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [1] ../require.context/templates ^\.\/.*$ ./b.js context element ./b [1] ../require.context/templates ^\.\/.*$ ./b [4] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [1] ../require.context/templates ^\.\/.*$ ./c.js context element ./c [1] ../require.context/templates ^\.\/.*$ ./c chunk {1} output.js (main) 276 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 276 bytes {1} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: f67ab883501eec17d2fb Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 544 bytes 0 [emitted] output.js 1.49 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 463 bytes {1} [rendered] > [0] ./example.js 2:1-4:3 [1] ../require.context/templates ^\.\/.*$ 217 bytes {0} [built] cjs require context ../require.context/templates [0] ./example.js 3:11-64 [2] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [1] ../require.context/templates ^\.\/.*$ ./a.js context element ./a [1] ../require.context/templates ^\.\/.*$ ./a [3] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [1] ../require.context/templates ^\.\/.*$ ./b.js context element ./b [1] ../require.context/templates ^\.\/.*$ ./b [4] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [1] ../require.context/templates ^\.\/.*$ ./c.js context element ./c [1] ../require.context/templates ^\.\/.*$ ./c chunk {1} output.js (main) 276 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 276 bytes {1} [built] ``` webpack-3.5.6/examples/code-splitted-require.context/build.js000066400000000000000000000000331315401342100242770ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/code-splitted-require.context/example.js000066400000000000000000000004121315401342100246340ustar00rootroot00000000000000function 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-3.5.6/examples/code-splitted-require.context/template.md000066400000000000000000000004051315401342100250020ustar00rootroot00000000000000# example.js ``` javascript {{example.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/code-splitting-bundle-loader/000077500000000000000000000000001315401342100224115ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-bundle-loader/README.md000066400000000000000000000220501315401342100236670ustar00rootroot00000000000000This 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"; ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (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 */ /*! all exports used */ /***/ (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 */(0).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); /***/ }) /******/ ]); ``` # js/0.output.js ``` javascript webpackJsonp([0],{ /***/ 2: /*!*****************!*\ !*** ./file.js ***! \*****************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "It works"; /***/ }) }); ``` # Info ## Uncompressed ``` Hash: 0f292e2adbe6929efd48 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 231 bytes 0 [emitted] output.js 6.73 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 28 bytes {1} [rendered] > [1] (webpack)/node_modules/bundle-loader!./file.js 7:0-14:2 [2] ./file.js 28 bytes {0} [built] cjs require !!./file.js [1] (webpack)/node_modules/bundle-loader!./file.js 8:8-30 chunk {1} output.js (main) 378 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {1} [built] [1] (webpack)/node_modules/bundle-loader!./file.js 281 bytes {1} [built] cjs require bundle-loader!./file.js [0] ./example.js 1:0-34 ``` ## Minimized (uglify-js, no zip) ``` Hash: 0f292e2adbe6929efd48 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 58 bytes 0 [emitted] output.js 1.55 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 28 bytes {1} [rendered] > [1] (webpack)/node_modules/bundle-loader!./file.js 7:0-14:2 [2] ./file.js 28 bytes {0} [built] cjs require !!./file.js [1] (webpack)/node_modules/bundle-loader!./file.js 8:8-30 chunk {1} output.js (main) 378 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {1} [built] [1] (webpack)/node_modules/bundle-loader!./file.js 281 bytes {1} [built] cjs require bundle-loader!./file.js [0] ./example.js 1:0-34 ``` webpack-3.5.6/examples/code-splitting-bundle-loader/build.js000066400000000000000000000000331315401342100240420ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/code-splitting-bundle-loader/example.js000066400000000000000000000001361315401342100244020ustar00rootroot00000000000000require("bundle-loader!./file.js")(function(fileJsExports) { console.log(fileJsExports); }); webpack-3.5.6/examples/code-splitting-bundle-loader/file.js000066400000000000000000000000341315401342100236630ustar00rootroot00000000000000module.exports = "It works";webpack-3.5.6/examples/code-splitting-bundle-loader/template.md000066400000000000000000000012061315401342100245450ustar00rootroot00000000000000This 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/code-splitting-harmony/000077500000000000000000000000001315401342100213515ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-harmony/README.md000066400000000000000000000240211315401342100226270ustar00rootroot00000000000000This 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); }); ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! exports provided: */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_a__ = __webpack_require__(/*! a */ 3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_a___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_a__); __webpack_require__.e/* import() */(2).then(__webpack_require__.bind(null, /*! b */ 5)).then(function(b) { console.log("b loaded", b); }) function loadC(name) { return __webpack_require__(/*! c */ 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 ^\.\/.*$ ***! \**************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var map = { "./1": [ 0, 1 ], "./1.js": [ 0, 1 ], "./2": [ 1, 0 ], "./2.js": [ 1, 0 ] }; function webpackAsyncContext(req) { var ids = map[req]; if(!ids) return Promise.reject(new Error("Cannot find module '" + req + "'.")); return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__(ids[0]); }); }; webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 4; module.exports = webpackAsyncContext; /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: f2701c90a6d1597932b5 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 258 bytes 0 [emitted] 1.output.js 249 bytes 1 [emitted] 2.output.js 244 bytes 2 [emitted] output.js 7.55 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 13 bytes {3} [rendered] 1 module chunk {1} 1.output.js 13 bytes {3} [rendered] 1 module chunk {2} 2.output.js 11 bytes {3} [rendered] > [2] ./example.js 3:0-11 1 module chunk {3} output.js (main) 427 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 256 bytes {3} [built] [no exports] [4] ./node_modules/c lazy ^\.\/.*$ 160 bytes {3} [built] import() context lazy c [2] ./example.js 8:8-27 + 1 hidden module ``` ## Minimized (uglify-js, no zip) ``` Hash: f2701c90a6d1597932b5 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 37 bytes 0 [emitted] 1.output.js 36 bytes 1 [emitted] 2.output.js 38 bytes 2 [emitted] output.js 1.9 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 13 bytes {3} [rendered] 1 module chunk {1} 1.output.js 13 bytes {3} [rendered] 1 module chunk {2} 2.output.js 11 bytes {3} [rendered] > [2] ./example.js 3:0-11 1 module chunk {3} output.js (main) 427 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 256 bytes {3} [built] [no exports] [4] ./node_modules/c lazy ^\.\/.*$ 160 bytes {3} [built] import() context lazy c [2] ./example.js 8:8-27 + 1 hidden module ``` webpack-3.5.6/examples/code-splitting-harmony/build.js000066400000000000000000000000331315401342100230020ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/code-splitting-harmony/example.js000066400000000000000000000003631315401342100233440ustar00rootroot00000000000000import 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-3.5.6/examples/code-splitting-harmony/node_modules/000077500000000000000000000000001315401342100240265ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-harmony/node_modules/a.js000066400000000000000000000000131315401342100245760ustar00rootroot00000000000000// module awebpack-3.5.6/examples/code-splitting-harmony/node_modules/b.js000066400000000000000000000000131315401342100245770ustar00rootroot00000000000000// module bwebpack-3.5.6/examples/code-splitting-harmony/node_modules/c/000077500000000000000000000000001315401342100242505ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-harmony/node_modules/c/1.js000066400000000000000000000000151315401342100247420ustar00rootroot00000000000000// module c/1webpack-3.5.6/examples/code-splitting-harmony/node_modules/c/2.js000066400000000000000000000000151315401342100247430ustar00rootroot00000000000000// module c/2webpack-3.5.6/examples/code-splitting-harmony/template.md000066400000000000000000000014001315401342100235010ustar00rootroot00000000000000This 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/code-splitting-native-import-context/000077500000000000000000000000001315401342100241545ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-native-import-context/README.md000066400000000000000000000250761315401342100254450ustar00rootroot00000000000000# 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; ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */, /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { async function getTemplate(templateName) { try { let template = await __webpack_require__(/*! ./templates */ 4)(`./${templateName}`); console.log(template); } catch(err) { console.error("template error"); return new Error(err); } } getTemplate("foo"); getTemplate("bar"); getTemplate("baz"); /***/ }), /* 4 */ /*!*********************************!*\ !*** ./templates lazy ^\.\/.*$ ***! \*********************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var map = { "./bar": [ 0, 2 ], "./bar.js": [ 0, 2 ], "./baz": [ 1, 1 ], "./baz.js": [ 1, 1 ], "./foo": [ 2, 0 ], "./foo.js": [ 2, 0 ] }; function webpackAsyncContext(req) { var ids = map[req]; if(!ids) return Promise.reject(new Error("Cannot find module '" + req + "'.")); return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__(ids[0]); }); }; webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 4; module.exports = webpackAsyncContext; /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: 6f07710827408f86ab81 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 444 bytes 0 [emitted] 1.output.js 450 bytes 1 [emitted] 2.output.js 441 bytes 2 [emitted] output.js 7.08 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 41 bytes {3} [rendered] [2] ./templates/foo.js 41 bytes {0} [optional] [built] [exports: default] context element ./foo.js [4] ./templates lazy ^\.\/.*$ ./foo.js context element ./foo [4] ./templates lazy ^\.\/.*$ ./foo chunk {1} 1.output.js 41 bytes {3} [rendered] [1] ./templates/baz.js 41 bytes {1} [optional] [built] [exports: default] context element ./baz.js [4] ./templates lazy ^\.\/.*$ ./baz.js context element ./baz [4] ./templates lazy ^\.\/.*$ ./baz chunk {2} 2.output.js 41 bytes {3} [rendered] [0] ./templates/bar.js 41 bytes {2} [optional] [built] [exports: default] context element ./bar.js [4] ./templates lazy ^\.\/.*$ ./bar.js context element ./bar [4] ./templates lazy ^\.\/.*$ ./bar chunk {3} output.js (main) 456 bytes [entry] [rendered] > main [3] ./example.js [3] ./example.js 296 bytes {3} [built] [4] ./templates lazy ^\.\/.*$ 160 bytes {3} [optional] [built] import() context lazy ./templates [3] ./example.js 3:23-60 ``` ## Minimized (uglify-js, no zip) ``` Hash: 6f07710827408f86ab81 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 117 bytes 0 [emitted] 1.output.js 116 bytes 1 [emitted] 2.output.js 115 bytes 2 [emitted] output.js 6.76 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 41 bytes {3} [rendered] [2] ./templates/foo.js 41 bytes {0} [optional] [built] [exports: default] context element ./foo.js [4] ./templates lazy ^\.\/.*$ ./foo.js context element ./foo [4] ./templates lazy ^\.\/.*$ ./foo chunk {1} 1.output.js 41 bytes {3} [rendered] [1] ./templates/baz.js 41 bytes {1} [optional] [built] [exports: default] context element ./baz.js [4] ./templates lazy ^\.\/.*$ ./baz.js context element ./baz [4] ./templates lazy ^\.\/.*$ ./baz chunk {2} 2.output.js 41 bytes {3} [rendered] [0] ./templates/bar.js 41 bytes {2} [optional] [built] [exports: default] context element ./bar.js [4] ./templates lazy ^\.\/.*$ ./bar.js context element ./bar [4] ./templates lazy ^\.\/.*$ ./bar chunk {3} output.js (main) 456 bytes [entry] [rendered] > main [3] ./example.js [3] ./example.js 296 bytes {3} [built] [4] ./templates lazy ^\.\/.*$ 160 bytes {3} [optional] [built] import() context lazy ./templates [3] ./example.js 3:23-60 ERROR in output.js from UglifyJs Unexpected token: keyword (function) [output.js:155,6] ``` webpack-3.5.6/examples/code-splitting-native-import-context/build.js000066400000000000000000000000331315401342100256050ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/code-splitting-native-import-context/example.js000066400000000000000000000004311315401342100261430ustar00rootroot00000000000000async 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-3.5.6/examples/code-splitting-native-import-context/template.md000066400000000000000000000007621315401342100263160ustar00rootroot00000000000000# 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/code-splitting-native-import-context/templates/000077500000000000000000000000001315401342100261525ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-native-import-context/templates/bar.js000066400000000000000000000000461315401342100272540ustar00rootroot00000000000000var bar = "bar"; export default bar; webpack-3.5.6/examples/code-splitting-native-import-context/templates/baz.js000066400000000000000000000000461315401342100272640ustar00rootroot00000000000000var baz = "baz"; export default baz; webpack-3.5.6/examples/code-splitting-native-import-context/templates/foo.js000066400000000000000000000000461315401342100272730ustar00rootroot00000000000000var foo = "foo"; export default foo; webpack-3.5.6/examples/code-splitting-specify-chunk-name/000077500000000000000000000000001315401342100233625ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-specify-chunk-name/README.md000066400000000000000000000261221315401342100246440ustar00rootroot00000000000000# 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; ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */, /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__.e/* import() */(0/*! chunk-foo */).then(__webpack_require__.bind(null, /*! ./templates/foo */ 2)).then(function(foo) { console.log('foo:', foo); }) __webpack_require__.e/* require.ensure */(0/*! chunk-foo1 *//* duplicate */).then((function(require) { var foo = __webpack_require__(/*! ./templates/foo */ 2); console.log('foo:', foo); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); var createContextVar = "r"; __webpack_require__(/*! ./templates */ 4)("./ba" + createContextVar).then(function(bar) { console.log('bar:', bar); }) /***/ }), /* 4 */ /*!***********************************!*\ !*** ./templates lazy ^\.\/ba.*$ ***! \***********************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var map = { "./bar": [ 0, 2 ], "./bar.js": [ 0, 2 ], "./baz": [ 1, 1 ], "./baz.js": [ 1, 1 ] }; function webpackAsyncContext(req) { var ids = map[req]; if(!ids) return Promise.reject(new Error("Cannot find module '" + req + "'.")); return __webpack_require__.e(ids[1]).then(function() { return __webpack_require__(ids[0]); }); }; webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = 4; module.exports = webpackAsyncContext; /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: 9d034b3ada38a1291aa9 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 444 bytes 0 [emitted] chunk-foo 1.output.js 450 bytes 1 [emitted] chunk-bar-baz2 2.output.js 441 bytes 2 [emitted] chunk-bar-baz0 output.js 7.3 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (chunk-foo) 41 bytes {3} [rendered] > duplicate chunk-foo [3] ./example.js 1:0-62 > duplicate chunk-foo1 [3] ./example.js 5:0-8:16 [2] ./templates/foo.js 41 bytes {0} [built] [exports: default] import() ./templates/foo [3] ./example.js 1:0-62 cjs require ./templates/foo [3] ./example.js 6:11-37 chunk {1} 1.output.js (chunk-bar-baz2) 41 bytes {3} [rendered] [1] ./templates/baz.js 41 bytes {1} [optional] [built] [exports: default] context element ./baz.js [4] ./templates lazy ^\.\/ba.*$ ./baz.js context element ./baz [4] ./templates lazy ^\.\/ba.*$ ./baz chunk {2} 2.output.js (chunk-bar-baz0) 41 bytes {3} [rendered] [0] ./templates/bar.js 41 bytes {2} [optional] [built] [exports: default] context element ./bar.js [4] ./templates lazy ^\.\/ba.*$ ./bar.js context element ./bar [4] ./templates lazy ^\.\/ba.*$ ./bar chunk {3} output.js (main) 580 bytes [entry] [rendered] > main [3] ./example.js [3] ./example.js 420 bytes {3} [built] [4] ./templates lazy ^\.\/ba.*$ 160 bytes {3} [built] import() context lazy ./templates [3] ./example.js 11:0-84 ``` ## Minimized (uglify-js, no zip) ``` Hash: 9d034b3ada38a1291aa9 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 117 bytes 0 [emitted] chunk-foo 1.output.js 116 bytes 1 [emitted] chunk-bar-baz2 2.output.js 115 bytes 2 [emitted] chunk-bar-baz0 output.js 1.83 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (chunk-foo) 41 bytes {3} [rendered] > duplicate chunk-foo [3] ./example.js 1:0-62 > duplicate chunk-foo1 [3] ./example.js 5:0-8:16 [2] ./templates/foo.js 41 bytes {0} [built] [exports: default] import() ./templates/foo [3] ./example.js 1:0-62 cjs require ./templates/foo [3] ./example.js 6:11-37 chunk {1} 1.output.js (chunk-bar-baz2) 41 bytes {3} [rendered] [1] ./templates/baz.js 41 bytes {1} [optional] [built] [exports: default] context element ./baz.js [4] ./templates lazy ^\.\/ba.*$ ./baz.js context element ./baz [4] ./templates lazy ^\.\/ba.*$ ./baz chunk {2} 2.output.js (chunk-bar-baz0) 41 bytes {3} [rendered] [0] ./templates/bar.js 41 bytes {2} [optional] [built] [exports: default] context element ./bar.js [4] ./templates lazy ^\.\/ba.*$ ./bar.js context element ./bar [4] ./templates lazy ^\.\/ba.*$ ./bar chunk {3} output.js (main) 580 bytes [entry] [rendered] > main [3] ./example.js [3] ./example.js 420 bytes {3} [built] [4] ./templates lazy ^\.\/ba.*$ 160 bytes {3} [built] import() context lazy ./templates [3] ./example.js 11:0-84 ``` webpack-3.5.6/examples/code-splitting-specify-chunk-name/build.js000066400000000000000000000000341315401342100250140ustar00rootroot00000000000000require("../build-common"); webpack-3.5.6/examples/code-splitting-specify-chunk-name/example.js000066400000000000000000000006251315401342100253560ustar00rootroot00000000000000import("./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-3.5.6/examples/code-splitting-specify-chunk-name/template.md000066400000000000000000000007201315401342100255160ustar00rootroot00000000000000# 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/code-splitting-specify-chunk-name/templates/000077500000000000000000000000001315401342100253605ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting-specify-chunk-name/templates/bar.js000066400000000000000000000000461315401342100264620ustar00rootroot00000000000000var bar = "bar"; export default bar; webpack-3.5.6/examples/code-splitting-specify-chunk-name/templates/baz.js000066400000000000000000000000461315401342100264720ustar00rootroot00000000000000var baz = "baz"; export default baz; webpack-3.5.6/examples/code-splitting-specify-chunk-name/templates/foo.js000066400000000000000000000000461315401342100265010ustar00rootroot00000000000000var foo = "foo"; export default foo; webpack-3.5.6/examples/code-splitting/000077500000000000000000000000001315401342100176765ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting/README.md000066400000000000000000000225711315401342100211640ustar00rootroot00000000000000This 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.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"); }); ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!***************************!*\ !*** ./node_modules/b.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module b /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var a = __webpack_require__(/*! a */ 2); var b = __webpack_require__(/*! b */ 0); __webpack_require__.e/* require.ensure */(0).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 */ /*! all exports used */ /***/ (function(module, exports) { // module a /***/ }) /******/ ]); ``` # js/0.output.js ``` javascript webpackJsonp([0],[ /* 0 */, /* 1 */, /* 2 */, /* 3 */ /*!***************************!*\ !*** ./node_modules/c.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module c /***/ }), /* 4 */ /*!***************************!*\ !*** ./node_modules/d.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module d /***/ }) ]); ``` Minimized ``` javascript webpackJsonp([0],[,,,function(n,c){},function(n,c){}]); ``` # Info ## Uncompressed ``` Hash: 6a2e963878a958fd1aca Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 488 bytes 0 [emitted] output.js 6.66 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 22 bytes {1} [rendered] > [1] ./example.js 3:0-6:2 2 modules chunk {1} output.js (main) 166 bytes [entry] [rendered] > main [1] ./example.js [1] ./example.js 144 bytes {1} [built] + 2 hidden modules ``` ## Minimized (uglify-js, no zip) ``` Hash: 6a2e963878a958fd1aca Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 55 bytes 0 [emitted] output.js 1.45 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 22 bytes {1} [rendered] > [1] ./example.js 3:0-6:2 2 modules chunk {1} output.js (main) 166 bytes [entry] [rendered] > main [1] ./example.js [1] ./example.js 144 bytes {1} [built] + 2 hidden modules ``` webpack-3.5.6/examples/code-splitting/build.js000066400000000000000000000000331315401342100213270ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/code-splitting/example.js000066400000000000000000000002131315401342100216630ustar00rootroot00000000000000var a = require("a"); var b = require("b"); require.ensure(["c"], function(require) { require("b").xyz(); var d = require("d"); });webpack-3.5.6/examples/code-splitting/node_modules/000077500000000000000000000000001315401342100223535ustar00rootroot00000000000000webpack-3.5.6/examples/code-splitting/node_modules/a.js000066400000000000000000000000131315401342100231230ustar00rootroot00000000000000// module awebpack-3.5.6/examples/code-splitting/node_modules/b.js000066400000000000000000000000131315401342100231240ustar00rootroot00000000000000// module bwebpack-3.5.6/examples/code-splitting/node_modules/c.js000066400000000000000000000000131315401342100231250ustar00rootroot00000000000000// module cwebpack-3.5.6/examples/code-splitting/node_modules/d.js000066400000000000000000000000131315401342100231260ustar00rootroot00000000000000// module dwebpack-3.5.6/examples/code-splitting/template.md000066400000000000000000000023731315401342100220400ustar00rootroot00000000000000This 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.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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` Minimized ``` javascript {{min:js/0.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/coffee-script/000077500000000000000000000000001315401342100175025ustar00rootroot00000000000000webpack-3.5.6/examples/coffee-script/README.md000066400000000000000000000115261315401342100207660ustar00rootroot00000000000000 # 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 ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!*********************!*\ !*** ./cup2.coffee ***! \*********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { console.log("yeah coffee-script"); module.exports = 42; /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { console.log(__webpack_require__(/*! ./cup1 */ 2)); /***/ }), /* 2 */ /*!*********************!*\ !*** ./cup1.coffee ***! \*********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = { cool: "stuff", answer: 42, external: __webpack_require__(/*! ./cup2.coffee */ 0), again: __webpack_require__(/*! ./cup2 */ 0) }; /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: 22e68923dcce75e38966 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 3.29 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 206 bytes [entry] [rendered] > main [1] ./example.js [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] [2] ./cup1.coffee 118 bytes {0} [built] cjs require ./cup1 [1] ./example.js 1:12-29 ``` ## Minimized (uglify-js, no zip) ``` Hash: 22e68923dcce75e38966 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 640 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 206 bytes [entry] [rendered] > main [1] ./example.js [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] [2] ./cup1.coffee 118 bytes {0} [built] cjs require ./cup1 [1] ./example.js 1:12-29 ```webpack-3.5.6/examples/coffee-script/build.js000066400000000000000000000000331315401342100211330ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/coffee-script/cup1.coffee000066400000000000000000000001471315401342100215250ustar00rootroot00000000000000module.exports = cool: "stuff" answer: 42 external: require "./cup2.coffee" again: require "./cup2"webpack-3.5.6/examples/coffee-script/cup2.coffee000066400000000000000000000000661315401342100215260ustar00rootroot00000000000000console.log "yeah coffee-script" module.exports = 42 webpack-3.5.6/examples/coffee-script/example.js000066400000000000000000000000371315401342100214730ustar00rootroot00000000000000console.log(require("./cup1"));webpack-3.5.6/examples/coffee-script/template.md000066400000000000000000000004701315401342100216400ustar00rootroot00000000000000 # example.js ``` javascript {{example.js}} ``` # cup1.coffee ``` coffee-script {{cup1.coffee}} ``` # cup2.coffee ``` coffee-script {{cup2.coffee}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/coffee-script/webpack.config.js000066400000000000000000000002621315401342100227200ustar00rootroot00000000000000module.exports = { module: { loaders: [ { test: /\.coffee$/, loader: "coffee-loader" } ] }, resolve: { extensions: [".web.coffee", ".web.js", ".coffee", ".js"] } }; webpack-3.5.6/examples/common-chunk-and-vendor-chunk/000077500000000000000000000000001315401342100225105ustar00rootroot00000000000000webpack-3.5.6/examples/common-chunk-and-vendor-chunk/README.md000066400000000000000000000336051315401342100237760ustar00rootroot00000000000000This 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"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { vendor: ["./vendor1", "./vendor2"], pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" // older versions of webpack may require an empty entry point declaration here // common: [] }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ // The order of this array matters names: ["common", "vendor"], minChunks: 2 }) ] }; ``` # js/vendor.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ if(executeModules) { /******/ for(i=0; i < executeModules.length; i++) { /******/ result = __webpack_require__(__webpack_require__.s = executeModules[i]); /******/ } /******/ } /******/ return result; /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 4: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */ /*!*********************************!*\ !*** multi ./vendor1 ./vendor2 ***! \*********************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./vendor1 */3); module.exports = __webpack_require__(/*! ./vendor2 */4); /***/ }), /* 3 */ /*!********************!*\ !*** ./vendor1.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "vendor1"; /***/ }), /* 4 */ /*!********************!*\ !*** ./vendor2.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "vendor2"; /***/ }) /******/ ]); ``` # js/common.js ``` javascript webpackJsonp([0],[ /* 0 */ /*!*********************!*\ !*** ./utility2.js ***! \*********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "utility2"; /***/ }), /* 1 */ /*!*********************!*\ !*** ./utility3.js ***! \*********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "utility3"; /***/ }) ]); ``` # js/pageA.js ``` javascript webpackJsonp([1],{ /***/ 5: /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var utility1 = __webpack_require__(/*! ./utility1 */ 6); var utility2 = __webpack_require__(/*! ./utility2 */ 0); module.exports = "pageA"; /***/ }), /***/ 6: /*!*********************!*\ !*** ./utility1.js ***! \*********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "utility1"; /***/ }) },[5]); ``` # js/pageB.js ``` javascript webpackJsonp([3],{ /***/ 7: /*!******************!*\ !*** ./pageB.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var utility2 = __webpack_require__(/*! ./utility2 */ 0); var utility3 = __webpack_require__(/*! ./utility3 */ 1); module.exports = "pageB"; /***/ }) },[7]); ``` # js/pageC.js ``` javascript webpackJsonp([2],{ /***/ 8: /*!******************!*\ !*** ./pageC.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var utility2 = __webpack_require__(/*! ./utility2 */ 0); var utility3 = __webpack_require__(/*! ./utility3 */ 1); module.exports = "pageC"; /***/ }) },[8]); ``` # Info ## Uncompressed ``` Hash: 3b80b7c17398c31e4705 Version: webpack 3.5.1 Asset Size Chunks Chunk Names common.js 459 bytes 0 [emitted] common pageA.js 595 bytes 1 [emitted] pageA pageC.js 374 bytes 2 [emitted] pageC pageB.js 374 bytes 3 [emitted] pageB vendor.js 6.7 kB 4 [emitted] vendor Entrypoint vendor = vendor.js Entrypoint pageA = vendor.js common.js pageA.js Entrypoint pageB = vendor.js common.js pageB.js Entrypoint pageC = vendor.js common.js pageC.js chunk {0} common.js (common) 56 bytes {4} [initial] [rendered] [0] ./utility2.js 28 bytes {0} [built] cjs require ./utility2 [5] ./pageA.js 2:15-36 cjs require ./utility2 [7] ./pageB.js 1:15-36 cjs require ./utility2 [8] ./pageC.js 1:15-36 [1] ./utility3.js 28 bytes {0} [built] cjs require ./utility3 [7] ./pageB.js 2:15-36 cjs require ./utility3 [8] ./pageC.js 2:15-36 chunk {1} pageA.js (pageA) 133 bytes {0} [initial] [rendered] > pageA [5] ./pageA.js [5] ./pageA.js 105 bytes {1} [built] [6] ./utility1.js 28 bytes {1} [built] cjs require ./utility1 [5] ./pageA.js 1:15-36 chunk {2} pageC.js (pageC) 105 bytes {0} [initial] [rendered] > pageC [8] ./pageC.js [8] ./pageC.js 105 bytes {2} [built] chunk {3} pageB.js (pageB) 105 bytes {0} [initial] [rendered] > pageB [7] ./pageB.js [7] ./pageB.js 105 bytes {3} [built] chunk {4} vendor.js (vendor) 94 bytes [entry] [rendered] > vendor [2] multi ./vendor1 ./vendor2 [2] multi ./vendor1 ./vendor2 40 bytes {4} [built] [3] ./vendor1.js 27 bytes {4} [built] single entry ./vendor1 [2] multi ./vendor1 ./vendor2 vendor:100000 [4] ./vendor2.js 27 bytes {4} [built] single entry ./vendor2 [2] multi ./vendor1 ./vendor2 vendor:100001 ``` ## Minimized (uglify-js, no zip) ``` Hash: 3b80b7c17398c31e4705 Version: webpack 3.5.1 Asset Size Chunks Chunk Names common.js 92 bytes 0 [emitted] common pageA.js 109 bytes 1 [emitted] pageA pageC.js 71 bytes 2 [emitted] pageC pageB.js 71 bytes 3 [emitted] pageB vendor.js 1.48 kB 4 [emitted] vendor Entrypoint vendor = vendor.js Entrypoint pageA = vendor.js common.js pageA.js Entrypoint pageB = vendor.js common.js pageB.js Entrypoint pageC = vendor.js common.js pageC.js chunk {0} common.js (common) 56 bytes {4} [initial] [rendered] [0] ./utility2.js 28 bytes {0} [built] cjs require ./utility2 [5] ./pageA.js 2:15-36 cjs require ./utility2 [7] ./pageB.js 1:15-36 cjs require ./utility2 [8] ./pageC.js 1:15-36 [1] ./utility3.js 28 bytes {0} [built] cjs require ./utility3 [7] ./pageB.js 2:15-36 cjs require ./utility3 [8] ./pageC.js 2:15-36 chunk {1} pageA.js (pageA) 133 bytes {0} [initial] [rendered] > pageA [5] ./pageA.js [5] ./pageA.js 105 bytes {1} [built] [6] ./utility1.js 28 bytes {1} [built] cjs require ./utility1 [5] ./pageA.js 1:15-36 chunk {2} pageC.js (pageC) 105 bytes {0} [initial] [rendered] > pageC [8] ./pageC.js [8] ./pageC.js 105 bytes {2} [built] chunk {3} pageB.js (pageB) 105 bytes {0} [initial] [rendered] > pageB [7] ./pageB.js [7] ./pageB.js 105 bytes {3} [built] chunk {4} vendor.js (vendor) 94 bytes [entry] [rendered] > vendor [2] multi ./vendor1 ./vendor2 [2] multi ./vendor1 ./vendor2 40 bytes {4} [built] [3] ./vendor1.js 27 bytes {4} [built] single entry ./vendor1 [2] multi ./vendor1 ./vendor2 vendor:100000 [4] ./vendor2.js 27 bytes {4} [built] single entry ./vendor2 [2] multi ./vendor1 ./vendor2 vendor:100001 ``` webpack-3.5.6/examples/common-chunk-and-vendor-chunk/build.js000066400000000000000000000000721315401342100241440ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-3.5.6/examples/common-chunk-and-vendor-chunk/pageA.js000066400000000000000000000001461315401342100240640ustar00rootroot00000000000000var utility1 = require('./utility1'); var utility2 = require('./utility2'); module.exports = "pageA";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/pageB.js000066400000000000000000000001461315401342100240650ustar00rootroot00000000000000var utility2 = require('./utility2'); var utility3 = require('./utility3'); module.exports = "pageB";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/pageC.js000066400000000000000000000001461315401342100240660ustar00rootroot00000000000000var utility2 = require('./utility2'); var utility3 = require('./utility3'); module.exports = "pageC";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/template.md000066400000000000000000000027511315401342100246520ustar00rootroot00000000000000This 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}} ``` # js/vendor.js ``` javascript {{js/vendor.js}} ``` # js/common.js ``` javascript {{js/common.js}} ``` # js/pageA.js ``` javascript {{js/pageA.js}} ``` # js/pageB.js ``` javascript {{js/pageB.js}} ``` # js/pageC.js ``` javascript {{js/pageC.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/common-chunk-and-vendor-chunk/utility1.js000066400000000000000000000000341315401342100246270ustar00rootroot00000000000000module.exports = "utility1";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/utility2.js000066400000000000000000000000341315401342100246300ustar00rootroot00000000000000module.exports = "utility2";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/utility3.js000066400000000000000000000000341315401342100246310ustar00rootroot00000000000000module.exports = "utility3";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/vendor1.js000066400000000000000000000000331315401342100244200ustar00rootroot00000000000000module.exports = "vendor1";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/vendor2.js000066400000000000000000000000331315401342100244210ustar00rootroot00000000000000module.exports = "vendor2";webpack-3.5.6/examples/common-chunk-and-vendor-chunk/webpack.config.js000066400000000000000000000010361315401342100257260ustar00rootroot00000000000000var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { vendor: ["./vendor1", "./vendor2"], pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" // older versions of webpack may require an empty entry point declaration here // common: [] }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ // The order of this array matters names: ["common", "vendor"], minChunks: 2 }) ] }; webpack-3.5.6/examples/commonjs/000077500000000000000000000000001315401342100165765ustar00rootroot00000000000000webpack-3.5.6/examples/commonjs/README.md000066400000000000000000000126601315401342100200620ustar00rootroot00000000000000This 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 var inc = require('./increment').increment; var a = 1; inc(a); // 2 ``` # increment.js ``` javascript var 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; }; ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var inc = __webpack_require__(/*! ./increment */ 1).increment; var a = 1; inc(a); // 2 /***/ }), /* 1 */ /*!**********************!*\ !*** ./increment.js ***! \**********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var add = __webpack_require__(/*! ./math */ 2).add; exports.increment = function(val) { return add(val, 1); }; /***/ }), /* 2 */ /*!*****************!*\ !*** ./math.js ***! \*****************/ /*! no static exports found */ /*! all exports used */ /***/ (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 ## Uncompressed ``` Hash: 9407d8cd068b1845b368 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 3.39 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 329 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 69 bytes {0} [built] [1] ./increment.js 98 bytes {0} [built] cjs require ./increment [0] ./example.js 1:10-32 [2] ./math.js 162 bytes {0} [built] cjs require ./math [1] ./increment.js 1:10-27 ``` ## Minimized (uglify-js, no zip) ``` Hash: 9407d8cd068b1845b368 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 672 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 329 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 69 bytes {0} [built] [1] ./increment.js 98 bytes {0} [built] cjs require ./increment [0] ./example.js 1:10-32 [2] ./math.js 162 bytes {0} [built] cjs require ./math [1] ./increment.js 1:10-27 ```webpack-3.5.6/examples/commonjs/build.js000066400000000000000000000000331315401342100202270ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/commonjs/example.js000066400000000000000000000001031315401342100205610ustar00rootroot00000000000000var inc = require('./increment').increment; var a = 1; inc(a); // 2webpack-3.5.6/examples/commonjs/increment.js000066400000000000000000000001371315401342100211210ustar00rootroot00000000000000var add = require('./math').add; exports.increment = function(val) { return add(val, 1); };webpack-3.5.6/examples/commonjs/math.js000066400000000000000000000002341315401342100200640ustar00rootroot00000000000000exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; };webpack-3.5.6/examples/commonjs/template.md000066400000000000000000000014501315401342100207330ustar00rootroot00000000000000This 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/css-bundle/000077500000000000000000000000001315401342100170105ustar00rootroot00000000000000webpack-3.5.6/examples/css-bundle/README.md000066400000000000000000000145561315401342100203020ustar00rootroot00000000000000 # example.js ``` javascript require("./style.css"); ``` # style.css ``` css body { background: url(image.png); } ``` # webpack.config.js ``` javascript var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { module: { loaders: [ { test: /\.css$/, use: ExtractTextPlugin.extract({ use: "css-loader" }) }, { test: /\.png$/, loader: "file-loader" } ] }, plugins: [ new ExtractTextPlugin({ filename: "style.css", allChunks: true }) ] }; ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./style.css */ 1); /***/ }), /* 1 */ /*!*******************!*\ !*** ./style.css ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }) /******/ ]); ``` # js/style.css ``` css body { background: url(js/ce21cbdd9b894e6af794813eb3fdaf60.png); } ``` # Info ## Uncompressed ``` Hash: d3955970c7b0655c299a Version: webpack 3.5.1 Asset Size Chunks Chunk Names ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] output.js 2.9 kB 0 [emitted] main style.css 69 bytes 0 [emitted] main Entrypoint main = output.js style.css chunk {0} output.js, style.css (main) 64 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 23 bytes {0} [built] [1] ./style.css 41 bytes {0} [built] cjs require ./style.css [0] ./example.js 1:0-22 Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!style.css: Asset Size Chunks Chunk Names ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] Entrypoint undefined = extract-text-webpack-plugin-output-filename chunk {0} extract-text-webpack-plugin-output-filename 2.57 kB [entry] [rendered] > [0] (webpack)/node_modules/css-loader!./style.css [0] (webpack)/node_modules/css-loader!./style.css 231 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 (uglify-js, no zip) ``` Hash: 7e35402b768b90e83df1 Version: webpack 3.5.1 Asset Size Chunks Chunk Names ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] output.js 504 bytes 0 [emitted] main style.css 61 bytes 0 [emitted] main Entrypoint main = output.js style.css chunk {0} output.js, style.css (main) 64 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 23 bytes {0} [built] [1] ./style.css 41 bytes {0} [built] cjs require ./style.css [0] ./example.js 1:0-22 Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!style.css: Asset Size Chunks Chunk Names ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] 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-3.5.6/examples/css-bundle/build.js000066400000000000000000000000331315401342100204410ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/css-bundle/example.js000066400000000000000000000000271315401342100210000ustar00rootroot00000000000000require("./style.css");webpack-3.5.6/examples/css-bundle/image.png000066400000000000000000000001671315401342100206040ustar00rootroot00000000000000PNG  IHDRwSsRGBgAMA a pHYsod IDATWc?5IENDB`webpack-3.5.6/examples/css-bundle/style.css000066400000000000000000000000451315401342100206610ustar00rootroot00000000000000body { background: url(image.png); }webpack-3.5.6/examples/css-bundle/template.md000066400000000000000000000005411315401342100211450ustar00rootroot00000000000000 # example.js ``` javascript {{example.js}} ``` # style.css ``` css {{style.css}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/style.css ``` css {{js/style.css}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/css-bundle/webpack.config.js000066400000000000000000000005401315401342100222250ustar00rootroot00000000000000var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { module: { loaders: [ { test: /\.css$/, use: ExtractTextPlugin.extract({ use: "css-loader" }) }, { test: /\.png$/, loader: "file-loader" } ] }, plugins: [ new ExtractTextPlugin({ filename: "style.css", allChunks: true }) ] }; webpack-3.5.6/examples/dll-app-and-vendor/000077500000000000000000000000001315401342100203355ustar00rootroot00000000000000webpack-3.5.6/examples/dll-app-and-vendor/0-vendor/000077500000000000000000000000001315401342100217675ustar00rootroot00000000000000webpack-3.5.6/examples/dll-app-and-vendor/0-vendor/README.md000066400000000000000000000121201315401342100232420ustar00rootroot00000000000000This is the vendor build part. It's built separatly from the app part. The vendors dll is only built when vendors has changed and not while the normal development cycle. The DllPlugin in combination with the `output.library` option exposes the internal require function as global variable in the target enviroment. A manifest is creates which includes mappings from module names to internal ids. ### webpack.config.js ``` javascript var path = require("path"); var webpack = require("../../../"); module.exports = { context: __dirname, entry: ["example-vendor"], output: { filename: "vendor.js", // best use [hash] here too path: path.resolve(__dirname, "js"), library: "vendor_lib_[hash]", }, plugins: [ new webpack.DllPlugin({ name: "vendor_lib_[hash]", path: path.resolve(__dirname, "js/vendor-manifest.json"), }), ], }; ``` # example-vendor ``` javascript export function square(n) { return n * n; } ``` # js/vendor.js ``` javascript var vendor_lib_6b1edee0549eb5092709 = ```
/******/ (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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // 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"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (immutable) */ __webpack_exports__["square"] = square; function square(n) { return n * n; } /***/ }) /******/ ]); ``` # js/vendor-manifest.json ``` javascript {"name":"vendor_lib_6b1edee0549eb5092709","content":{"../node_modules/example-vendor.js":{"id":1,"meta":{"harmonyModule":true},"exports":["square"]}}} ``` # Info ## Uncompressed ``` Hash: 6b1edee0549eb5092709 Version: webpack 3.5.1 Asset Size Chunks Chunk Names vendor.js 3.18 kB 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 60 bytes [entry] [rendered] > main [0] dll main [0] dll main 12 bytes {0} [built] + 1 hidden module ``` ## Minimized (uglify-js, no zip) ``` Hash: 6b1edee0549eb5092709 Version: webpack 3.5.1 Asset Size Chunks Chunk Names vendor.js 652 bytes 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 60 bytes [entry] [rendered] > main [0] dll main [0] dll main 12 bytes {0} [built] + 1 hidden module ``` webpack-3.5.6/examples/dll-app-and-vendor/0-vendor/build.js000066400000000000000000000000751315401342100234260ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../../build-common"); webpack-3.5.6/examples/dll-app-and-vendor/0-vendor/template.md000066400000000000000000000014041315401342100241230ustar00rootroot00000000000000This is the vendor build part. It's built separatly from the app part. The vendors dll is only built when vendors has changed and not while the normal development cycle. The DllPlugin in combination with the `output.library` option exposes the internal require function as global variable in the target enviroment. A manifest is creates which includes mappings from module names to internal ids. ### webpack.config.js ``` javascript {{webpack.config.js}} ``` # example-vendor ``` javascript {{../node_modules/example-vendor.js}} ``` # js/vendor.js ``` javascript {{js/vendor.js}} ``` # js/vendor-manifest.json ``` javascript {{js/vendor-manifest.json}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/dll-app-and-vendor/0-vendor/webpack.config.js000066400000000000000000000006361315401342100252120ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../"); module.exports = { context: __dirname, entry: ["example-vendor"], output: { filename: "vendor.js", // best use [hash] here too path: path.resolve(__dirname, "js"), library: "vendor_lib_[hash]", }, plugins: [ new webpack.DllPlugin({ name: "vendor_lib_[hash]", path: path.resolve(__dirname, "js/vendor-manifest.json"), }), ], }; webpack-3.5.6/examples/dll-app-and-vendor/1-app/000077500000000000000000000000001315401342100212535ustar00rootroot00000000000000webpack-3.5.6/examples/dll-app-and-vendor/1-app/README.md000066400000000000000000000143401315401342100225340ustar00rootroot00000000000000This 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 = { context: __dirname, entry: "./example-app", output: { filename: "app.js", path: path.resolve(__dirname, "js"), }, plugins: [ new webpack.DllReferencePlugin({ context: ".", manifest: require("../0-vendor/js/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 ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!************************!*\ !*** ./example-app.js ***! \************************/ /*! exports provided: */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_example_vendor__ = __webpack_require__(/*! example-vendor */ 1); console.log(Object(__WEBPACK_IMPORTED_MODULE_0_example_vendor__["square"])(7)); console.log(new __WEBPACK_IMPORTED_MODULE_0_example_vendor__["square"](7)); /***/ }), /* 1 */ /*!******************************************************************************************************!*\ !*** delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_6b1edee0549eb5092709 ***! \******************************************************************************************************/ /*! exports provided: square */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(2))(1); /***/ }), /* 2 */ /*!**************************************************!*\ !*** external "vendor_lib_6b1edee0549eb5092709" ***! \**************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = vendor_lib_6b1edee0549eb5092709; /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: 26778169dabaf1f3965d Version: webpack 3.5.1 Asset Size Chunks Chunk Names app.js 3.85 kB 0 [emitted] main Entrypoint main = app.js chunk {0} app.js (main) 182 bytes [entry] [rendered] > main [0] ./example-app.js [0] ./example-app.js 98 bytes {0} [built] [no exports] [1] delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_6b1edee0549eb5092709 42 bytes {0} [built] [exports: square] harmony import example-vendor [0] ./example-app.js 1:0-40 + 1 hidden module ``` ## Minimized (uglify-js, no zip) ``` Hash: 26778169dabaf1f3965d Version: webpack 3.5.1 Asset Size Chunks Chunk Names app.js 710 bytes 0 [emitted] main Entrypoint main = app.js chunk {0} app.js (main) 182 bytes [entry] [rendered] > main [0] ./example-app.js [0] ./example-app.js 98 bytes {0} [built] [no exports] [1] delegated ../node_modules/example-vendor.js from dll-reference vendor_lib_6b1edee0549eb5092709 42 bytes {0} [built] [exports: square] harmony import example-vendor [0] ./example-app.js 1:0-40 + 1 hidden module ``` webpack-3.5.6/examples/dll-app-and-vendor/1-app/build.js000066400000000000000000000000751315401342100227120ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../../build-common"); webpack-3.5.6/examples/dll-app-and-vendor/1-app/example-app.js000066400000000000000000000001361315401342100240220ustar00rootroot00000000000000import { square } from "example-vendor"; console.log(square(7)); console.log(new square(7)); webpack-3.5.6/examples/dll-app-and-vendor/1-app/example.html000066400000000000000000000002501315401342100235710ustar00rootroot00000000000000 webpack-3.5.6/examples/dll-app-and-vendor/1-app/template.md000066400000000000000000000013471315401342100234150ustar00rootroot00000000000000This 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}} ``` # js/app.js ``` javascript {{js/app.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/dll-app-and-vendor/1-app/webpack.config.js000066400000000000000000000005571315401342100245000ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../"); module.exports = { context: __dirname, entry: "./example-app", output: { filename: "app.js", path: path.resolve(__dirname, "js"), }, plugins: [ new webpack.DllReferencePlugin({ context: ".", manifest: require("../0-vendor/js/vendor-manifest.json"), // eslint-disable-line }), ], }; webpack-3.5.6/examples/dll-app-and-vendor/README.md000066400000000000000000000006221315401342100216140ustar00rootroot00000000000000This 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-3.5.6/examples/dll-app-and-vendor/node_modules/000077500000000000000000000000001315401342100230125ustar00rootroot00000000000000webpack-3.5.6/examples/dll-app-and-vendor/node_modules/example-vendor.js000066400000000000000000000000551315401342100262760ustar00rootroot00000000000000export function square(n) { return n * n; } webpack-3.5.6/examples/dll-user/000077500000000000000000000000001315401342100165005ustar00rootroot00000000000000webpack-3.5.6/examples/dll-user/README.md000066400000000000000000000227271315401342100177710ustar00rootroot00000000000000# 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 = { plugins: [ new webpack.DllReferencePlugin({ context: path.join(__dirname, "..", "dll"), manifest: require("../dll/js/alpha-manifest.json") // eslint-disable-line }), new webpack.DllReferencePlugin({ scope: "beta", manifest: require("../dll/js/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")); ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!*********************************************!*\ !*** external "alpha_457b6718a3ff9f8c2d77" ***! \*********************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = alpha_457b6718a3ff9f8c2d77; /***/ }), /* 1 */ /*!********************************************!*\ !*** external "beta_457b6718a3ff9f8c2d77" ***! \********************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = beta_457b6718a3ff9f8c2d77; /***/ }), /* 2 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { console.log(__webpack_require__(/*! ../dll/alpha */ 3)); console.log(__webpack_require__(/*! ../dll/a */ 4)); console.log(__webpack_require__(/*! beta/beta */ 5)); console.log(__webpack_require__(/*! beta/b */ 6)); console.log(__webpack_require__(/*! beta/c */ 7)); console.log(__webpack_require__(/*! module */ 8)); /***/ }), /* 3 */ /*!**************************************************************************!*\ !*** delegated ./alpha.js from dll-reference alpha_457b6718a3ff9f8c2d77 ***! \**************************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(0))(1); /***/ }), /* 4 */ /*!**********************************************************************!*\ !*** delegated ./a.js from dll-reference alpha_457b6718a3ff9f8c2d77 ***! \**********************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(0))(2); /***/ }), /* 5 */ /*!************************************************************************!*\ !*** delegated ./beta.js from dll-reference beta_457b6718a3ff9f8c2d77 ***! \************************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(1))(5); /***/ }), /* 6 */ /*!*********************************************************************!*\ !*** delegated ./b.js from dll-reference beta_457b6718a3ff9f8c2d77 ***! \*********************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(1))(6); /***/ }), /* 7 */ /*!**********************************************************************!*\ !*** delegated ./c.jsx from dll-reference beta_457b6718a3ff9f8c2d77 ***! \**********************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(1))(7); /***/ }), /* 8 */ /*!*****************************************************************************************!*\ !*** delegated ../node_modules/module.js from dll-reference alpha_457b6718a3ff9f8c2d77 ***! \*****************************************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(0))(3); /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: 60ca229a9df08630fded Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 6.06 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 549 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 213 bytes {0} [built] [3] delegated ./alpha.js from dll-reference alpha_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require ../dll/alpha [2] ./example.js 1:12-35 [4] delegated ./a.js from dll-reference alpha_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require ../dll/a [2] ./example.js 2:12-31 [5] delegated ./beta.js from dll-reference beta_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require beta/beta [2] ./example.js 4:12-32 [6] delegated ./b.js from dll-reference beta_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require beta/b [2] ./example.js 5:12-29 [7] delegated ./c.jsx from dll-reference beta_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require beta/c [2] ./example.js 6:12-29 [8] delegated ../node_modules/module.js from dll-reference alpha_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require module [2] ./example.js 8:12-29 + 2 hidden modules ``` ## Minimized (uglify-js, no zip) ``` Hash: 60ca229a9df08630fded Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 904 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 549 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 213 bytes {0} [built] [3] delegated ./alpha.js from dll-reference alpha_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require ../dll/alpha [2] ./example.js 1:12-35 [4] delegated ./a.js from dll-reference alpha_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require ../dll/a [2] ./example.js 2:12-31 [5] delegated ./beta.js from dll-reference beta_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require beta/beta [2] ./example.js 4:12-32 [6] delegated ./b.js from dll-reference beta_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require beta/b [2] ./example.js 5:12-29 [7] delegated ./c.jsx from dll-reference beta_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require beta/c [2] ./example.js 6:12-29 [8] delegated ../node_modules/module.js from dll-reference alpha_457b6718a3ff9f8c2d77 42 bytes {0} [built] cjs require module [2] ./example.js 8:12-29 + 2 hidden modules ``` webpack-3.5.6/examples/dll-user/build.js000066400000000000000000000000331315401342100201310ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/dll-user/example.html000066400000000000000000000003521315401342100210210ustar00rootroot00000000000000 webpack-3.5.6/examples/dll-user/example.js000066400000000000000000000003151315401342100204700ustar00rootroot00000000000000console.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-3.5.6/examples/dll-user/template.md000066400000000000000000000007521315401342100206410ustar00rootroot00000000000000# 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/dll-user/webpack.config.js000066400000000000000000000006551315401342100217240ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { plugins: [ new webpack.DllReferencePlugin({ context: path.join(__dirname, "..", "dll"), manifest: require("../dll/js/alpha-manifest.json") // eslint-disable-line }), new webpack.DllReferencePlugin({ scope: "beta", manifest: require("../dll/js/beta-manifest.json"), // eslint-disable-line extensions: [".js", ".jsx"] }) ] }; webpack-3.5.6/examples/dll/000077500000000000000000000000001315401342100155245ustar00rootroot00000000000000webpack-3.5.6/examples/dll/README.md000066400000000000000000000145111315401342100170050ustar00rootroot00000000000000# 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 = { resolve: { extensions: [".js", ".jsx"] }, entry: { alpha: ["./alpha", "./a", "module"], beta: ["./beta", "./b", "./c"] }, output: { path: path.join(__dirname, "js"), filename: "MyDll.[name].js", library: "[name]_[hash]" }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "js", "[name]-manifest.json"), name: "[name]_[hash]" }) ] }; ``` # js/MyDll.alpha.js ``` javascript var alpha_457b6718a3ff9f8c2d77 = ```
/******/ (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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // 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"; /***/ }) /******/ ]); ``` # js/alpha-manifest.json ``` javascript {"name":"alpha_457b6718a3ff9f8c2d77","content":{"./alpha.js":{"id":1,"meta":{}},"./a.js":{"id":2,"meta":{}},"../node_modules/module.js":{"id":3,"meta":{}}}} ``` # Info ## Uncompressed ``` Hash: 457b6718a3ff9f8c2d77 Version: webpack 3.5.1 Asset Size Chunks Chunk Names MyDll.beta.js 3.31 kB 0 [emitted] beta MyDll.alpha.js 3.34 kB 1 [emitted] alpha Entrypoint alpha = MyDll.alpha.js Entrypoint beta = MyDll.beta.js chunk {0} MyDll.beta.js (beta) 80 bytes [entry] [rendered] > beta [4] dll beta [4] dll beta 12 bytes {0} [built] [5] ./beta.js 24 bytes {0} [built] single entry ./beta [4] dll beta beta:0 [6] ./b.js 21 bytes {0} [built] single entry ./b [4] dll beta beta:1 [7] ./c.jsx 23 bytes {0} [built] single entry ./c [4] dll beta beta:2 chunk {1} MyDll.alpha.js (alpha) 84 bytes [entry] [rendered] > alpha [0] dll alpha [0] dll alpha 12 bytes {1} [built] [1] ./alpha.js 25 bytes {1} [built] single entry ./alpha [0] dll alpha alpha:0 [2] ./a.js 21 bytes {1} [built] single entry ./a [0] dll alpha alpha:1 + 1 hidden module ``` ## Minimized (uglify-js, no zip) ``` Hash: 457b6718a3ff9f8c2d77 Version: webpack 3.5.1 Asset Size Chunks Chunk Names MyDll.beta.js 627 bytes 0 [emitted] beta MyDll.alpha.js 628 bytes 1 [emitted] alpha Entrypoint alpha = MyDll.alpha.js Entrypoint beta = MyDll.beta.js chunk {0} MyDll.beta.js (beta) 80 bytes [entry] [rendered] > beta [4] dll beta [4] dll beta 12 bytes {0} [built] [5] ./beta.js 24 bytes {0} [built] single entry ./beta [4] dll beta beta:0 [6] ./b.js 21 bytes {0} [built] single entry ./b [4] dll beta beta:1 [7] ./c.jsx 23 bytes {0} [built] single entry ./c [4] dll beta beta:2 chunk {1} MyDll.alpha.js (alpha) 84 bytes [entry] [rendered] > alpha [0] dll alpha [0] dll alpha 12 bytes {1} [built] [1] ./alpha.js 25 bytes {1} [built] single entry ./alpha [0] dll alpha alpha:0 [2] ./a.js 21 bytes {1} [built] single entry ./a [0] dll alpha alpha:1 + 1 hidden module ``` webpack-3.5.6/examples/dll/a.js000066400000000000000000000000251315401342100162770ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/examples/dll/alpha.js000066400000000000000000000000311315401342100171410ustar00rootroot00000000000000module.exports = "alpha";webpack-3.5.6/examples/dll/b.js000066400000000000000000000000251315401342100163000ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/examples/dll/beta.js000066400000000000000000000000301315401342100167660ustar00rootroot00000000000000module.exports = "beta";webpack-3.5.6/examples/dll/build.js000066400000000000000000000000711315401342100171570ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-3.5.6/examples/dll/c.jsx000066400000000000000000000000271315401342100164730ustar00rootroot00000000000000module.exports = "jsx";webpack-3.5.6/examples/dll/template.md000066400000000000000000000010221315401342100176540ustar00rootroot00000000000000# 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}} ``` # js/MyDll.alpha.js ``` javascript {{js/MyDll.alpha.js}} ``` # js/alpha-manifest.json ``` javascript {{js/alpha-manifest.json}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/dll/webpack.config.js000066400000000000000000000007101315401342100207400ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { resolve: { extensions: [".js", ".jsx"] }, entry: { alpha: ["./alpha", "./a", "module"], beta: ["./beta", "./b", "./c"] }, output: { path: path.join(__dirname, "js"), filename: "MyDll.[name].js", library: "[name]_[hash]" }, plugins: [ new webpack.DllPlugin({ path: path.join(__dirname, "js", "[name]-manifest.json"), name: "[name]_[hash]" }) ] }; webpack-3.5.6/examples/examples.js000066400000000000000000000011541315401342100171260ustar00rootroot00000000000000"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-3.5.6/examples/explicit-vendor-chunk/000077500000000000000000000000001315401342100211735ustar00rootroot00000000000000webpack-3.5.6/examples/explicit-vendor-chunk/README.md000066400000000000000000000253761315401342100224670ustar00rootroot00000000000000# webpack.config.js ``` javascript var path = require("path"); var webpack = require("../../"); module.exports = [ { name: "vendor", entry: ["./vendor", "./vendor2"], output: { path: path.resolve(__dirname, "js"), filename: "vendor.js", library: "vendor_[hash]" }, plugins: [ new webpack.DllPlugin({ name: "vendor_[hash]", path: path.resolve(__dirname, "js/manifest.json") }) ] }, { name: "app", dependencies: ["vendor"], entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new webpack.DllReferencePlugin({ manifest: path.resolve(__dirname, "js/manifest.json") }) ] } ]; ``` # js/vendor.js ``` javascript var vendor_3e23dee019354f6a37c0 = ```
/******/ (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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // 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"; /***/ }) /******/ ]); ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!**********************************************!*\ !*** external "vendor_3e23dee019354f6a37c0" ***! \**********************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = vendor_3e23dee019354f6a37c0; /***/ }), /* 1 */ /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { console.log(__webpack_require__(/*! ./vendor */ 2)); module.exports = "pageA"; /***/ }), /* 2 */ /*!****************************************************************************!*\ !*** delegated ./vendor.js from dll-reference vendor_3e23dee019354f6a37c0 ***! \****************************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = (__webpack_require__(0))(1); /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: 3e23dee019354f6a37c0873a025592bd40b1b4d6 Version: webpack 3.5.1 Child vendor: Hash: 3e23dee019354f6a37c0 Asset Size Chunks Chunk Names vendor.js 3.11 kB 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 65 bytes [entry] [rendered] > main [0] dll main [0] dll main 12 bytes {0} [built] [1] ./vendor.js 26 bytes {0} [built] single entry ./vendor [0] dll main main:0 [2] ./vendor2.js 27 bytes {0} [built] single entry ./vendor2 [0] dll main main:1 Child app: Hash: 873a025592bd40b1b4d6 Asset Size Chunks Chunk Names pageB.js 3.46 kB 0 [emitted] pageB pageA.js 3.44 kB 1 [emitted] pageA pageC.js 2.63 kB 2 [emitted] pageC Entrypoint pageA = pageA.js Entrypoint pageB = pageB.js Entrypoint pageC = pageC.js chunk {0} pageB.js (pageB) 145 bytes [entry] [rendered] > pageB [3] ./pageB.js [3] ./pageB.js 61 bytes {0} [built] [4] delegated ./vendor2.js from dll-reference vendor_3e23dee019354f6a37c0 42 bytes {0} [built] cjs require ./vendor2 [3] ./pageB.js 1:12-32 + 1 hidden module chunk {1} pageA.js (pageA) 144 bytes [entry] [rendered] > pageA [1] ./pageA.js [1] ./pageA.js 60 bytes {1} [built] [2] delegated ./vendor.js from dll-reference vendor_3e23dee019354f6a37c0 42 bytes {1} [built] cjs require ./vendor [1] ./pageA.js 1:12-31 + 1 hidden module chunk {2} pageC.js (pageC) 25 bytes [entry] [rendered] > pageC [5] ./pageC.js [5] ./pageC.js 25 bytes {2} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: 3e23dee019354f6a37c0873a025592bd40b1b4d6 Version: webpack 3.5.1 Child vendor: Hash: 3e23dee019354f6a37c0 Asset Size Chunks Chunk Names vendor.js 602 bytes 0 [emitted] main Entrypoint main = vendor.js chunk {0} vendor.js (main) 65 bytes [entry] [rendered] > main [0] dll main [0] dll main 12 bytes {0} [built] [1] ./vendor.js 26 bytes {0} [built] single entry ./vendor [0] dll main main:0 [2] ./vendor2.js 27 bytes {0} [built] single entry ./vendor2 [0] dll main main:1 Child app: Hash: 873a025592bd40b1b4d6 Asset Size Chunks Chunk Names pageB.js 609 bytes 0 [emitted] pageB pageA.js 607 bytes 1 [emitted] pageA pageC.js 501 bytes 2 [emitted] pageC Entrypoint pageA = pageA.js Entrypoint pageB = pageB.js Entrypoint pageC = pageC.js chunk {0} pageB.js (pageB) 145 bytes [entry] [rendered] > pageB [3] ./pageB.js [3] ./pageB.js 61 bytes {0} [built] [4] delegated ./vendor2.js from dll-reference vendor_3e23dee019354f6a37c0 42 bytes {0} [built] cjs require ./vendor2 [3] ./pageB.js 1:12-32 + 1 hidden module chunk {1} pageA.js (pageA) 144 bytes [entry] [rendered] > pageA [1] ./pageA.js [1] ./pageA.js 60 bytes {1} [built] [2] delegated ./vendor.js from dll-reference vendor_3e23dee019354f6a37c0 42 bytes {1} [built] cjs require ./vendor [1] ./pageA.js 1:12-31 + 1 hidden module chunk {2} pageC.js (pageC) 25 bytes [entry] [rendered] > pageC [5] ./pageC.js [5] ./pageC.js 25 bytes {2} [built] ``` webpack-3.5.6/examples/explicit-vendor-chunk/build.js000066400000000000000000000000721315401342100226270ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-3.5.6/examples/explicit-vendor-chunk/pageA.html000066400000000000000000000002331315401342100230740ustar00rootroot00000000000000 webpack-3.5.6/examples/explicit-vendor-chunk/pageA.js000066400000000000000000000000731315401342100225460ustar00rootroot00000000000000console.log(require("./vendor")); module.exports = "pageA";webpack-3.5.6/examples/explicit-vendor-chunk/pageB.js000066400000000000000000000000741315401342100225500ustar00rootroot00000000000000console.log(require("./vendor2")); module.exports = "pageB";webpack-3.5.6/examples/explicit-vendor-chunk/pageC.js000066400000000000000000000000311315401342100225420ustar00rootroot00000000000000module.exports = "pageC";webpack-3.5.6/examples/explicit-vendor-chunk/template.md000066400000000000000000000004151315401342100233300ustar00rootroot00000000000000# webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/vendor.js ``` javascript {{js/vendor.js}} ``` # js/pageA.js ``` javascript {{js/pageA.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/explicit-vendor-chunk/vendor.js000066400000000000000000000000321315401342100230210ustar00rootroot00000000000000module.exports = "Vendor";webpack-3.5.6/examples/explicit-vendor-chunk/vendor2.js000066400000000000000000000000331315401342100231040ustar00rootroot00000000000000module.exports = "Vendor2";webpack-3.5.6/examples/explicit-vendor-chunk/webpack.config.js000066400000000000000000000013051315401342100244100ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = [ { name: "vendor", entry: ["./vendor", "./vendor2"], output: { path: path.resolve(__dirname, "js"), filename: "vendor.js", library: "vendor_[hash]" }, plugins: [ new webpack.DllPlugin({ name: "vendor_[hash]", path: path.resolve(__dirname, "js/manifest.json") }) ] }, { name: "app", dependencies: ["vendor"], entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new webpack.DllReferencePlugin({ manifest: path.resolve(__dirname, "js/manifest.json") }) ] } ]; webpack-3.5.6/examples/externals/000077500000000000000000000000001315401342100167565ustar00rootroot00000000000000webpack-3.5.6/examples/externals/README.md000066400000000000000000000147711315401342100202470ustar00rootroot00000000000000This 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 = { output: { libraryTarget: "umd" }, externals: [ "add", { "subtract": { root: "subtract", commonjs2: "./subtract", commonjs: ["./math", "subtract"], amd: "subtract" } } ] }; ``` # js/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]; } })(this, 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (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 */ /*! all exports used */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }), /* 2 */ /*!***************************************************************************************************************!*\ !*** external {"root":"subtract","commonjs2":"./subtract","commonjs":["./math","subtract"],"amd":"subtract"} ***! \***************************************************************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }) /******/ ]); }); ``` # Info ## Uncompressed ``` Hash: b21d422ed5d9ade3ed36 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 4.13 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 197 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 113 bytes {0} [built] + 2 hidden modules ``` ## Minimized (uglify-js, no zip) ``` Hash: b21d422ed5d9ade3ed36 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 978 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 197 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 113 bytes {0} [built] + 2 hidden modules ```webpack-3.5.6/examples/externals/build.js000066400000000000000000000000331315401342100204070ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/externals/example.js000066400000000000000000000001561315401342100207510ustar00rootroot00000000000000var add = require("add"); var subtract = require("subtract"); exports.exampleValue = subtract(add(42, 2), 2);webpack-3.5.6/examples/externals/template.md000066400000000000000000000026721315401342100211220ustar00rootroot00000000000000This 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/externals/webpack.config.js000066400000000000000000000003411315401342100221720ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd" }, externals: [ "add", { "subtract": { root: "subtract", commonjs2: "./subtract", commonjs: ["./math", "subtract"], amd: "subtract" } } ] }; webpack-3.5.6/examples/extra-async-chunk-advanced/000077500000000000000000000000001315401342100220605ustar00rootroot00000000000000webpack-3.5.6/examples/extra-async-chunk-advanced/README.md000066400000000000000000000314141315401342100233420ustar00rootroot00000000000000 # 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 var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { plugins: [ new CommonsChunkPlugin({ name: "main", async: "async1" }), new CommonsChunkPlugin({ name: "main", async: "async2", minChunks: 2 }), new CommonsChunkPlugin({ async: true }), ] }; ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 7: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
``` javascript /******/ ({ /***/ 2: /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { Promise.all/* require */([__webpack_require__.e(4), __webpack_require__.e(0), __webpack_require__.e(1)]).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(3), __webpack_require__.e(0), __webpack_require__.e(1)]).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(2), __webpack_require__.e(1)]).then((function(require) { __webpack_require__(/*! ./a */ 0); Promise.all/* require.ensure */([__webpack_require__.e(6), __webpack_require__.e(0)]).then((function(require) { __webpack_require__(/*! ./f */ 6); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); Promise.all/* require.ensure */([__webpack_require__.e(5), __webpack_require__.e(0)]).then((function(require) { __webpack_require__(/*! ./g */ 7); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }) /******/ }); ``` # Info ## Uncompressed ``` Hash: 37a3748d37b36bc162d0 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 221 bytes 0 [emitted] async2 1.output.js 212 bytes 1 [emitted] async1 2.output.js 215 bytes 2 [emitted] 3.output.js 215 bytes 3 [emitted] 4.output.js 215 bytes 4 [emitted] 5.output.js 215 bytes 5 [emitted] 6.output.js 215 bytes 6 [emitted] output.js 7.22 kB 7 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (async2) 21 bytes {2} {7} [rendered] > async commons duplicate [2] ./example.js 1:0-52 > async commons duplicate [2] ./example.js 3:0-6:2 > async commons duplicate [2] ./example.js 10:1-12:3 > async commons duplicate [2] ./example.js 13:1-15:3 [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 (async1) 21 bytes {7} [rendered] > async commons [2] ./example.js 1:0-52 > async commons [2] ./example.js 3:0-6:2 > async commons [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} 2.output.js 21 bytes {7} [rendered] > [2] ./example.js 8:0-16:2 [5] ./e.js 21 bytes {2} [built] require.ensure item ./e [2] ./example.js 8:0-16:2 chunk {3} 3.output.js 21 bytes {7} [rendered] > [2] ./example.js 3:0-6:2 [4] ./d.js 21 bytes {3} [built] cjs require ./d [2] ./example.js 5:1-15 chunk {4} 4.output.js 21 bytes {7} [rendered] > [2] ./example.js 1:0-52 [3] ./c.js 21 bytes {4} [built] amd require ./c [2] ./example.js 1:0-52 chunk {5} 5.output.js 21 bytes {2} [rendered] > [2] ./example.js 13:1-15:3 [7] ./g.js 21 bytes {5} [built] cjs require ./g [2] ./example.js 14:2-16 chunk {6} 6.output.js 21 bytes {2} [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} output.js (main) 362 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 362 bytes {7} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: 37a3748d37b36bc162d0 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 50 bytes 0 [emitted] async2 1.output.js 49 bytes 1 [emitted] async1 2.output.js 51 bytes 2 [emitted] 3.output.js 51 bytes 3 [emitted] 4.output.js 51 bytes 4 [emitted] 5.output.js 51 bytes 5 [emitted] 6.output.js 51 bytes 6 [emitted] output.js 1.79 kB 7 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (async2) 21 bytes {2} {7} [rendered] > async commons duplicate [2] ./example.js 1:0-52 > async commons duplicate [2] ./example.js 3:0-6:2 > async commons duplicate [2] ./example.js 10:1-12:3 > async commons duplicate [2] ./example.js 13:1-15:3 [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 (async1) 21 bytes {7} [rendered] > async commons [2] ./example.js 1:0-52 > async commons [2] ./example.js 3:0-6:2 > async commons [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} 2.output.js 21 bytes {7} [rendered] > [2] ./example.js 8:0-16:2 [5] ./e.js 21 bytes {2} [built] require.ensure item ./e [2] ./example.js 8:0-16:2 chunk {3} 3.output.js 21 bytes {7} [rendered] > [2] ./example.js 3:0-6:2 [4] ./d.js 21 bytes {3} [built] cjs require ./d [2] ./example.js 5:1-15 chunk {4} 4.output.js 21 bytes {7} [rendered] > [2] ./example.js 1:0-52 [3] ./c.js 21 bytes {4} [built] amd require ./c [2] ./example.js 1:0-52 chunk {5} 5.output.js 21 bytes {2} [rendered] > [2] ./example.js 13:1-15:3 [7] ./g.js 21 bytes {5} [built] cjs require ./g [2] ./example.js 14:2-16 chunk {6} 6.output.js 21 bytes {2} [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} output.js (main) 362 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 362 bytes {7} [built] ``` webpack-3.5.6/examples/extra-async-chunk-advanced/a.js000066400000000000000000000000251315401342100226330ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/examples/extra-async-chunk-advanced/b.js000066400000000000000000000000251315401342100226340ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/examples/extra-async-chunk-advanced/build.js000066400000000000000000000000331315401342100235110ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/extra-async-chunk-advanced/c.js000066400000000000000000000000251315401342100226350ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/examples/extra-async-chunk-advanced/d.js000066400000000000000000000000251315401342100226360ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/examples/extra-async-chunk-advanced/e.js000066400000000000000000000000251315401342100226370ustar00rootroot00000000000000module.exports = "e";webpack-3.5.6/examples/extra-async-chunk-advanced/example.js000066400000000000000000000005321315401342100240510ustar00rootroot00000000000000require(["./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-3.5.6/examples/extra-async-chunk-advanced/f.js000066400000000000000000000000251315401342100226400ustar00rootroot00000000000000module.exports = "f";webpack-3.5.6/examples/extra-async-chunk-advanced/g.js000066400000000000000000000000251315401342100226410ustar00rootroot00000000000000module.exports = "g";webpack-3.5.6/examples/extra-async-chunk-advanced/template.md000066400000000000000000000004151315401342100242150ustar00rootroot00000000000000 # example.js ``` javascript {{example.js}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/extra-async-chunk-advanced/webpack.config.js000066400000000000000000000004741315401342100253030ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { plugins: [ new CommonsChunkPlugin({ name: "main", async: "async1" }), new CommonsChunkPlugin({ name: "main", async: "async2", minChunks: 2 }), new CommonsChunkPlugin({ async: true }), ] }; webpack-3.5.6/examples/extra-async-chunk/000077500000000000000000000000001315401342100203155ustar00rootroot00000000000000webpack-3.5.6/examples/extra-async-chunk/README.md000066400000000000000000000264321315401342100216030ustar00rootroot00000000000000This example shows how to create a async loaded commons chunk. When a chunk has many child chunks which share common modules the `CommonsChunkPlugin` can extract these common modules into a commons chunk which is loaded in parallel to the requested child chunk. 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 `CommonsChunkPlugin` extract these into chunk Z: * 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"], function(a, b, c) {}); // a chunk with a, b, d require.ensure(["./a"], function(require) { require("./b"); require("./d"); }); ``` # webpack.config.js ``` javascript var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { plugins: [ new CommonsChunkPlugin({ // process all children of the main chunk // if omitted it would process all chunks name: "main", // create a additional async chunk for the common modules // which is loaded in parallel to the requested chunks async: true }) ] }; ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
``` javascript /******/ ({ /***/ 2: /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { // a chunks with a, b, c Promise.all/* require */([__webpack_require__.e(0), __webpack_require__.e(2)]).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); // a chunk with a, b, d Promise.all/* require.ensure */([__webpack_require__.e(0), __webpack_require__.e(1)]).then((function(require) { __webpack_require__(/*! ./b */ 1); __webpack_require__(/*! ./d */ 4); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }) /******/ }); ``` # js/0.output.js ``` javascript webpackJsonp([0],[ /* 0 */ /*!**************!*\ !*** ./a.js ***! \**************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "a"; /***/ }), /* 1 */ /*!**************!*\ !*** ./b.js ***! \**************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "b"; /***/ }) ]); ``` # js/1.output.js ``` javascript webpackJsonp([1],{ /***/ 4: /*!**************!*\ !*** ./d.js ***! \**************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "d"; /***/ }) }); ``` # js/2.output.js ``` javascript webpackJsonp([2],{ /***/ 3: /*!**************!*\ !*** ./c.js ***! \**************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "c"; /***/ }) }); ``` # Info ## Uncompressed ``` Hash: ca87dc9e54fc3309c0fd Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 403 bytes 0 [emitted] 1.output.js 215 bytes 1 [emitted] 2.output.js 215 bytes 2 [emitted] output.js 6.56 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 42 bytes {3} [rendered] > async commons [2] ./example.js 2:0-52 > async commons [2] ./example.js 5:0-8:2 [0] ./a.js 21 bytes {0} [built] amd require ./a [2] ./example.js 2:0-52 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-52 cjs require ./b [2] ./example.js 6:1-15 chunk {1} 1.output.js 21 bytes {3} [rendered] > [2] ./example.js 5:0-8:2 [4] ./d.js 21 bytes {1} [built] cjs require ./d [2] ./example.js 7:1-15 chunk {2} 2.output.js 21 bytes {3} [rendered] > [2] ./example.js 2:0-52 [3] ./c.js 21 bytes {2} [built] amd require ./c [2] ./example.js 2:0-52 chunk {3} output.js (main) 194 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 194 bytes {3} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: ca87dc9e54fc3309c0fd Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 78 bytes 0 [emitted] 1.output.js 51 bytes 1 [emitted] 2.output.js 51 bytes 2 [emitted] output.js 1.54 kB 3 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 42 bytes {3} [rendered] > async commons [2] ./example.js 2:0-52 > async commons [2] ./example.js 5:0-8:2 [0] ./a.js 21 bytes {0} [built] amd require ./a [2] ./example.js 2:0-52 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-52 cjs require ./b [2] ./example.js 6:1-15 chunk {1} 1.output.js 21 bytes {3} [rendered] > [2] ./example.js 5:0-8:2 [4] ./d.js 21 bytes {1} [built] cjs require ./d [2] ./example.js 7:1-15 chunk {2} 2.output.js 21 bytes {3} [rendered] > [2] ./example.js 2:0-52 [3] ./c.js 21 bytes {2} [built] amd require ./c [2] ./example.js 2:0-52 chunk {3} output.js (main) 194 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 194 bytes {3} [built] ``` webpack-3.5.6/examples/extra-async-chunk/a.js000066400000000000000000000000251315401342100210700ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/examples/extra-async-chunk/b.js000066400000000000000000000000251315401342100210710ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/examples/extra-async-chunk/build.js000066400000000000000000000000331315401342100217460ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/extra-async-chunk/c.js000066400000000000000000000000251315401342100210720ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/examples/extra-async-chunk/d.js000066400000000000000000000000251315401342100210730ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/examples/extra-async-chunk/example.js000066400000000000000000000002721315401342100223070ustar00rootroot00000000000000// a chunks with a, b, c require(["./a", "./b", "./c"], function(a, b, c) {}); // a chunk with a, b, d require.ensure(["./a"], function(require) { require("./b"); require("./d"); }); webpack-3.5.6/examples/extra-async-chunk/template.md000066400000000000000000000023171315401342100224550ustar00rootroot00000000000000This example shows how to create a async loaded commons chunk. When a chunk has many child chunks which share common modules the `CommonsChunkPlugin` can extract these common modules into a commons chunk which is loaded in parallel to the requested child chunk. 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 `CommonsChunkPlugin` extract these into chunk Z: * 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}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` # js/1.output.js ``` javascript {{js/1.output.js}} ``` # js/2.output.js ``` javascript {{js/2.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/extra-async-chunk/webpack.config.js000066400000000000000000000006021315401342100235310ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { plugins: [ new CommonsChunkPlugin({ // process all children of the main chunk // if omitted it would process all chunks name: "main", // create a additional async chunk for the common modules // which is loaded in parallel to the requested chunks async: true }) ] }; webpack-3.5.6/examples/harmony-interop/000077500000000000000000000000001315401342100201045ustar00rootroot00000000000000webpack-3.5.6/examples/harmony-interop/README.md000066400000000000000000000230551315401342100213700ustar00rootroot00000000000000 # 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 equvivalent 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"; ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!***************!*\ !*** ./fs.js ***! \***************/ /*! no static exports found */ /*! exports used: default, readFile */ /***/ (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 equvivalent to CommonJs modules /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! exports provided: */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__fs__ = __webpack_require__(/*! ./fs */ 0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__fs___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__fs__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__reexport_commonjs__ = __webpack_require__(/*! ./reexport-commonjs */ 2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__example2__ = __webpack_require__(/*! ./example2 */ 3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__example2___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2__example2__); // harmony module // import from CommonJs module __WEBPACK_IMPORTED_MODULE_0__fs___default.a.readFile("file"); Object(__WEBPACK_IMPORTED_MODULE_0__fs__["readFile"])("file"); __WEBPACK_IMPORTED_MODULE_0__fs__["readFile"]("file"); // import from harmony module Object(__WEBPACK_IMPORTED_MODULE_1__reexport_commonjs__["readFile"])("file"); // import a CommonJs module for sideeffects /***/ }), /* 2 */ /*!******************************!*\ !*** ./reexport-commonjs.js ***! \******************************/ /*! no static exports found */ /*! exports used: readFile */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__fs__ = __webpack_require__(/*! ./fs */ 0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__fs___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__fs__); /* harmony namespace reexport (by used) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_0__fs__, "readFile")) __webpack_require__.d(__webpack_exports__, "readFile", function() { return __WEBPACK_IMPORTED_MODULE_0__fs__["readFile"]; }); // 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 */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* 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 ## Uncompressed ``` Hash: 756e5e3b676506d280a4 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 6.13 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 1.2 kB [entry] [rendered] > main [1] ./example.js [0] ./fs.js 265 bytes {0} [built] [only some exports used: default, readFile] harmony import ./fs [1] ./example.js 4:0-22 harmony import ./fs [1] ./example.js 5:0-32 harmony import ./fs [1] ./example.js 6:0-28 harmony import ./fs [2] ./reexport-commonjs.js 2:0-21 [1] ./example.js 389 bytes {0} [built] [no exports] [2] ./reexport-commonjs.js 308 bytes {0} [built] [only some exports used: readFile] harmony import ./reexport-commonjs [1] ./example.js 12:0-60 [3] ./example2.js 159 bytes {0} [built] [no exports used] harmony import ./example2 [1] ./example.js 16:0-20 [4] ./harmony.js 78 bytes {0} [built] [exports: default, named] cjs require ./harmony [3] ./example2.js 4:13-33 ``` ## Minimized (uglify-js, no zip) ``` Hash: 756e5e3b676506d280a4 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 1.03 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 1.2 kB [entry] [rendered] > main [1] ./example.js [0] ./fs.js 265 bytes {0} [built] [only some exports used: default, readFile] harmony import ./fs [1] ./example.js 4:0-22 harmony import ./fs [1] ./example.js 5:0-32 harmony import ./fs [1] ./example.js 6:0-28 harmony import ./fs [2] ./reexport-commonjs.js 2:0-21 [1] ./example.js 389 bytes {0} [built] [no exports] [2] ./reexport-commonjs.js 308 bytes {0} [built] [only some exports used: readFile] harmony import ./reexport-commonjs [1] ./example.js 12:0-60 [3] ./example2.js 159 bytes {0} [built] [no exports used] harmony import ./example2 [1] ./example.js 16:0-20 [4] ./harmony.js 78 bytes {0} [built] [exports: default, named] cjs require ./harmony [3] ./example2.js 4:13-33 ```webpack-3.5.6/examples/harmony-interop/build.js000066400000000000000000000000331315401342100215350ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/harmony-interop/example.js000066400000000000000000000005651315401342100221030ustar00rootroot00000000000000// 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-3.5.6/examples/harmony-interop/example2.js000066400000000000000000000002301315401342100221520ustar00rootroot00000000000000// CommonJs module // require a harmony module var module = require("./harmony"); var defaultExport = module.default; var namedExport = module.named; webpack-3.5.6/examples/harmony-interop/fs.js000066400000000000000000000004021315401342100210460ustar00rootroot00000000000000// 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 equvivalent to CommonJs modules webpack-3.5.6/examples/harmony-interop/harmony.js000066400000000000000000000001131315401342100221120ustar00rootroot00000000000000// just some exports export default "default"; export var named = "named"; webpack-3.5.6/examples/harmony-interop/reexport-commonjs.js000066400000000000000000000004551315401342100241410ustar00rootroot00000000000000// 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-3.5.6/examples/harmony-interop/template.md000066400000000000000000000006341315401342100222440ustar00rootroot00000000000000 # 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/harmony-library/000077500000000000000000000000001315401342100200705ustar00rootroot00000000000000webpack-3.5.6/examples/harmony-library/README.md000066400000000000000000000111341315401342100213470ustar00rootroot00000000000000# webpack.config.js ``` javascript var path = require("path"); module.exports = { entry: "./example", output: { path: path.join(__dirname, "js"), filename: "MyLibrary.umd.js", library: "MyLibrary", libraryTarget: "umd" } }; ``` # js/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(); })(this, 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! exports provided: value, increment, default */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "value", function() { return value; }); /* harmony export (immutable) */ __webpack_exports__["increment"] = increment; var value = 0; function increment() { value++; } /* harmony default export */ __webpack_exports__["default"] = ("MyLibrary"); /***/ }) /******/ ]); }); ``` # Info ## Uncompressed ``` Hash: 0b2bf5443af50d14e1e0 Version: webpack 3.5.1 Asset Size Chunks Chunk Names MyLibrary.umd.js 3.45 kB 0 [emitted] main Entrypoint main = MyLibrary.umd.js chunk {0} MyLibrary.umd.js (main) 97 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {0} [built] [exports: value, increment, default] ``` ## Minimized (uglify-js, no zip) ``` Hash: 0b2bf5443af50d14e1e0 Version: webpack 3.5.1 Asset Size Chunks Chunk Names MyLibrary.umd.js 872 bytes 0 [emitted] main Entrypoint main = MyLibrary.umd.js chunk {0} MyLibrary.umd.js (main) 97 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {0} [built] [exports: value, increment, default] ``` webpack-3.5.6/examples/harmony-library/build.js000066400000000000000000000000711315401342100215230ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-3.5.6/examples/harmony-library/example.js000066400000000000000000000001341315401342100220570ustar00rootroot00000000000000export var value = 0; export function increment() { value++; } export default "MyLibrary"; webpack-3.5.6/examples/harmony-library/template.md000066400000000000000000000003501315401342100222230ustar00rootroot00000000000000# webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/MyLibrary.umd.js ``` javascript {{js/MyLibrary.umd.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/harmony-library/webpack.config.js000066400000000000000000000003101315401342100233000ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: "./example", output: { path: path.join(__dirname, "js"), filename: "MyLibrary.umd.js", library: "MyLibrary", libraryTarget: "umd" } }; webpack-3.5.6/examples/harmony-unused/000077500000000000000000000000001315401342100177275ustar00rootroot00000000000000webpack-3.5.6/examples/harmony-unused/README.md000066400000000000000000000226321315401342100212130ustar00rootroot00000000000000This 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"; ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!*****************!*\ !*** ./math.js ***! \*****************/ /*! exports provided: add, multiply, list */ /*! exports used: add, multiply */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = add; /* harmony export (immutable) */ __webpack_exports__["b"] = multiply; /* unused harmony export 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); } /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! exports provided: */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__math__ = __webpack_require__(/*! ./math */ 0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__library__ = __webpack_require__(/*! ./library */ 2); Object(__WEBPACK_IMPORTED_MODULE_0__math__["a" /* add */])(1, 2); __WEBPACK_IMPORTED_MODULE_1__library__["a" /* reexportedMultiply */](1, 2); /***/ }), /* 2 */ /*!********************!*\ !*** ./library.js ***! \********************/ /*! exports provided: a, b, c, reexportedAdd, reexportedMultiply */ /*! exports used: reexportedMultiply */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__abc__ = __webpack_require__(/*! ./abc */ 3); /* unused harmony reexport a */ /* unused harmony reexport b */ /* unused harmony reexport c */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__math__ = __webpack_require__(/*! ./math */ 0); /* unused harmony reexport reexportedAdd */ /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_1__math__["b"]; }); /***/ }), /* 3 */ /*!****************!*\ !*** ./abc.js ***! \****************/ /*! exports provided: a, b, c */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export a */ /* unused harmony export b */ /* unused harmony export c */ function a() { console.log("a"); } function b() { console.log("b"); } function c() { console.log("c"); } /***/ }) /******/ ]); ``` # js/output.js ``` javascript !function(t){function n(e){if(r[e])return r[e].exports;var u=r[e]={i:e,l:!1,exports:{}};return t[e].call(u.exports,u,u.exports,n),u.l=!0,u.exports}var r={};n.m=t,n.c=r,n.d=function(t,r,e){n.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:e})},n.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(r,"a",r),r},n.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},n.p="js/",n(n.s=1)}([function(t,n,r){"use strict";function e(){for(var t=0,n=0,r=arguments,e=r.length;n main [1] ./example.js [0] ./math.js 366 bytes {0} [built] [exports: add, multiply, list] [only some exports used: add, multiply] harmony import ./math [1] ./example.js 1:0-29 harmony import ./math [2] ./library.js 2:0-78 [1] ./example.js 119 bytes {0} [built] [no exports] [2] ./library.js 112 bytes {0} [built] [exports: a, b, c, reexportedAdd, reexportedMultiply] [only some exports used: reexportedMultiply] harmony import ./library [1] ./example.js 2:0-37 [3] ./abc.js 129 bytes {0} [built] [exports: a, b, c] [no exports used] harmony import ./abc [2] ./library.js 1:0-32 ``` ## Minimized (uglify-js, no zip) ``` Hash: 4cac4181f66e42d03af9 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 895 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 726 bytes [entry] [rendered] > main [1] ./example.js [0] ./math.js 366 bytes {0} [built] [exports: add, multiply, list] [only some exports used: add, multiply] harmony import ./math [1] ./example.js 1:0-29 harmony import ./math [2] ./library.js 2:0-78 [1] ./example.js 119 bytes {0} [built] [no exports] [2] ./library.js 112 bytes {0} [built] [exports: a, b, c, reexportedAdd, reexportedMultiply] [only some exports used: reexportedMultiply] harmony import ./library [1] ./example.js 2:0-37 [3] ./abc.js 129 bytes {0} [built] [exports: a, b, c] [no exports used] harmony import ./abc [2] ./library.js 1:0-32 ``` webpack-3.5.6/examples/harmony-unused/abc.js000066400000000000000000000001761315401342100210160ustar00rootroot00000000000000export function a() { console.log("a"); } export function b() { console.log("b"); } export function c() { console.log("c"); } webpack-3.5.6/examples/harmony-unused/build.js000066400000000000000000000000331315401342100213600ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/harmony-unused/example.js000066400000000000000000000001621315401342100217170ustar00rootroot00000000000000import { add } from './math'; import * as library from "./library"; add(1, 2); library.reexportedMultiply(1, 2); webpack-3.5.6/examples/harmony-unused/library.js000066400000000000000000000001571315401342100217340ustar00rootroot00000000000000export { a, b, c } from "./abc"; export { add as reexportedAdd, multiply as reexportedMultiply } from "./math";webpack-3.5.6/examples/harmony-unused/math.js000066400000000000000000000005331315401342100212170ustar00rootroot00000000000000export 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-3.5.6/examples/harmony-unused/template.md000066400000000000000000000024151315401342100220660ustar00rootroot00000000000000This 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/output.js ``` javascript {{min:js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/harmony/000077500000000000000000000000001315401342100164265ustar00rootroot00000000000000webpack-3.5.6/examples/harmony/README.md000066400000000000000000000230301315401342100177030ustar00rootroot00000000000000 # 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); }; ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! exports provided: */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__increment__ = __webpack_require__(/*! ./increment */ 1); var a = 1; Object(__WEBPACK_IMPORTED_MODULE_0__increment__["a" /* increment */])(a); // 2 // async loading __webpack_require__.e/* import() */(0).then(__webpack_require__.bind(null, /*! ./async-loaded */ 3)).then(function(asyncLoaded) { console.log(asyncLoaded); }); /***/ }), /* 1 */ /*!**********************!*\ !*** ./increment.js ***! \**********************/ /*! exports provided: increment */ /*! exports used: increment */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = increment; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__math__ = __webpack_require__(/*! ./math */ 2); function increment(val) { return Object(__WEBPACK_IMPORTED_MODULE_0__math__["a" /* add */])(val, 1); }; /***/ }), /* 2 */ /*!*****************!*\ !*** ./math.js ***! \*****************/ /*! exports provided: add */ /*! exports used: add */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = add; function add() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; } /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: f5982ea38c08a86ed265 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 484 bytes 0 [emitted] output.js 7.36 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 25 bytes {1} [rendered] > [0] ./example.js 6:0-24 [3] ./async-loaded.js 25 bytes {0} [built] [exports: answer] import() ./async-loaded [0] ./example.js 6:0-24 chunk {1} output.js (main) 419 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 183 bytes {1} [built] [no exports] [1] ./increment.js 94 bytes {1} [built] [exports: increment] [only some exports used: increment] harmony import ./increment [0] ./example.js 1:0-47 [2] ./math.js 142 bytes {1} [built] [exports: add] [only some exports used: add] harmony import ./math [1] ./increment.js 1:0-29 ``` ## Minimized (uglify-js, no zip) ``` Hash: f5982ea38c08a86ed265 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 147 bytes 0 [emitted] output.js 1.69 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 25 bytes {1} [rendered] > [0] ./example.js 6:0-24 [3] ./async-loaded.js 25 bytes {0} [built] [exports: answer] import() ./async-loaded [0] ./example.js 6:0-24 chunk {1} output.js (main) 419 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 183 bytes {1} [built] [no exports] [1] ./increment.js 94 bytes {1} [built] [exports: increment] [only some exports used: increment] harmony import ./increment [0] ./example.js 1:0-47 [2] ./math.js 142 bytes {1} [built] [exports: add] [only some exports used: add] harmony import ./math [1] ./increment.js 1:0-29 ```webpack-3.5.6/examples/harmony/async-loaded.js000066400000000000000000000000301315401342100213200ustar00rootroot00000000000000export var answer = 42; webpack-3.5.6/examples/harmony/build.js000066400000000000000000000000331315401342100200570ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/harmony/example.js000066400000000000000000000002571315401342100204230ustar00rootroot00000000000000import { increment as inc } from './increment'; var a = 1; inc(a); // 2 // async loading import("./async-loaded").then(function(asyncLoaded) { console.log(asyncLoaded); }); webpack-3.5.6/examples/harmony/increment.js000066400000000000000000000001321315401342100207440ustar00rootroot00000000000000import { add } from './math'; export function increment(val) { return add(val, 1); }; webpack-3.5.6/examples/harmony/math.js000066400000000000000000000002071315401342100177140ustar00rootroot00000000000000export function add() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; } webpack-3.5.6/examples/harmony/template.md000066400000000000000000000004011315401342100205560ustar00rootroot00000000000000 # example.js ``` javascript {{example.js}} ``` # increment.js ``` javascript {{increment.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/http2-aggressive-splitting/000077500000000000000000000000001315401342100221625ustar00rootroot00000000000000webpack-3.5.6/examples/http2-aggressive-splitting/README.md000066400000000000000000001041271315401342100234460ustar00rootroot00000000000000This example demonstrates the AggressiveSplittingPlugin for splitting the bundle into multiple smaller chunks to improve caching. This works best with a HTTP2 web server elsewise there is an overhead for the increased number of requests. The AggressiveSplittingPlugin split every chunk until it reaches the specified `maxSize`. In this example it tries to create chunks with <50kB code (after minimizing this reduces to ~10kB). It groups modules together by folder structure. We assume modules in the same folder as similar likely to change and minimize and gzip good together. The AggressiveSplittingPlugin records it's splitting in the webpack records and try to restore splitting from records. This ensures that after changes to the application old splittings (and chunks) are reused. They are probably already in the clients cache. Therefore it's heavily recommended to use records! 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 too many chunks for every change. Chunks can get invalid if a module changes. Modules from invalid chunks go back into the module pool and 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 = { entry: "./example", output: { path: path.join(__dirname, "js"), 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, "js", "records.json") }; ``` # Info ## Uncompressed ``` Hash: 35256bb30300e8777ddd Version: webpack 3.5.1 Asset Size Chunks Chunk Names 04e95786881a7db62441.js 53.1 kB 7 [emitted] af5b936f620d7c2cf46e.js 57.4 kB 0 [emitted] d8035b04d59361a42a17.js 56.6 kB 2 [emitted] 92951e4964e84e709103.js 55.9 kB 3 [emitted] d323f006c00a41b194cb.js 55.9 kB 4 [emitted] 567bf6b0afa4e4baa4fb.js 53.7 kB 5 [emitted] 435514b5a5822c639a06.js 53.7 kB 6 [emitted] fbb0bfdcf201839059f9.js 38.9 kB 1 [emitted] ebe11885009391a25f13.js 37.9 kB 8 [emitted] 1aa11917196d1d3b05c1.js 52.1 kB 9 [emitted] 8556f2285fd844cf9fdd.js 51 kB 10 [emitted] c6598918ddb96aa65fc4.js 50.7 kB 11 [emitted] 17613f7c75a33459b935.js 41.8 kB 12 [emitted] 8cc7b4a18437614b45e4.js 59.6 kB 13 [emitted] 11202a345a2ce63a2fb7.js 31.3 kB 14 [emitted] Entrypoint main = 8cc7b4a18437614b45e4.js 11202a345a2ce63a2fb7.js 17613f7c75a33459b935.js chunk {0} af5b936f620d7c2cf46e.js 49.8 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 23 modules chunk {1} fbb0bfdcf201839059f9.js 32.5 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 17 modules chunk {2} d8035b04d59361a42a17.js 49.7 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 17 modules chunk {3} 92951e4964e84e709103.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 16 modules chunk {4} d323f006c00a41b194cb.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 15 modules chunk {5} 567bf6b0afa4e4baa4fb.js 49.8 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 11 modules chunk {6} 435514b5a5822c639a06.js 50 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 11 modules chunk {7} 04e95786881a7db62441.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 9 modules chunk {8} ebe11885009391a25f13.js 35.8 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 6 modules chunk {9} 1aa11917196d1d3b05c1.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 6 modules chunk {10} 8556f2285fd844cf9fdd.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 4 modules chunk {11} c6598918ddb96aa65fc4.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 4 modules chunk {12} 17613f7c75a33459b935.js 36.4 kB [initial] [rendered] > aggressive-splitted main [14] ./example.js [14] ./example.js 44 bytes {12} [built] + 14 hidden modules chunk {13} 8cc7b4a18437614b45e4.js 49.8 kB [entry] [rendered] [recorded] > aggressive-splitted main [14] ./example.js 13 modules chunk {14} 11202a345a2ce63a2fb7.js 30.2 kB [initial] [rendered] [recorded] > aggressive-splitted main [14] ./example.js 3 modules ``` ## Minimized (uglify-js, no zip) ``` Hash: 35256bb30300e8777ddd Version: webpack 3.5.1 Asset Size Chunks Chunk Names 04e95786881a7db62441.js 10.3 kB 7 [emitted] af5b936f620d7c2cf46e.js 12.3 kB 0 [emitted] d8035b04d59361a42a17.js 11 kB 2 [emitted] 92951e4964e84e709103.js 9.59 kB 3 [emitted] d323f006c00a41b194cb.js 11.9 kB 4 [emitted] 567bf6b0afa4e4baa4fb.js 13.3 kB 5 [emitted] 435514b5a5822c639a06.js 11.5 kB 6 [emitted] fbb0bfdcf201839059f9.js 8 kB 1 [emitted] ebe11885009391a25f13.js 5.76 kB 8 [emitted] 1aa11917196d1d3b05c1.js 8.25 kB 9 [emitted] 8556f2285fd844cf9fdd.js 12.6 kB 10 [emitted] c6598918ddb96aa65fc4.js 10.2 kB 11 [emitted] 17613f7c75a33459b935.js 6.32 kB 12 [emitted] 8cc7b4a18437614b45e4.js 10.1 kB 13 [emitted] 11202a345a2ce63a2fb7.js 6.83 kB 14 [emitted] Entrypoint main = 8cc7b4a18437614b45e4.js 11202a345a2ce63a2fb7.js 17613f7c75a33459b935.js chunk {0} af5b936f620d7c2cf46e.js 49.8 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 23 modules chunk {1} fbb0bfdcf201839059f9.js 32.5 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 17 modules chunk {2} d8035b04d59361a42a17.js 49.7 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 17 modules chunk {3} 92951e4964e84e709103.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 16 modules chunk {4} d323f006c00a41b194cb.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 15 modules chunk {5} 567bf6b0afa4e4baa4fb.js 49.8 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 11 modules chunk {6} 435514b5a5822c639a06.js 50 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 11 modules chunk {7} 04e95786881a7db62441.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 9 modules chunk {8} ebe11885009391a25f13.js 35.8 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 6 modules chunk {9} 1aa11917196d1d3b05c1.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 6 modules chunk {10} 8556f2285fd844cf9fdd.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 4 modules chunk {11} c6598918ddb96aa65fc4.js 49.9 kB {12} {13} {14} [rendered] [recorded] > aggressive-splitted [14] ./example.js 2:0-22 4 modules chunk {12} 17613f7c75a33459b935.js 36.4 kB [initial] [rendered] > aggressive-splitted main [14] ./example.js [14] ./example.js 44 bytes {12} [built] + 14 hidden modules chunk {13} 8cc7b4a18437614b45e4.js 49.8 kB [entry] [rendered] [recorded] > aggressive-splitted main [14] ./example.js 13 modules chunk {14} 11202a345a2ce63a2fb7.js 30.2 kB [initial] [rendered] [recorded] > aggressive-splitted main [14] ./example.js 3 modules ``` ## Records ``` { "modules": { "byIdentifier": { "../../node_modules/fbjs/lib/invariant.js": 0, "../../node_modules/react/lib/ReactElement.js": 1, "../../node_modules/fbjs/lib/warning.js": 2, "../../node_modules/object-assign/index.js": 3, "../../node_modules/react/lib/reactProdInvariant.js": 4, "../../node_modules/fbjs/lib/emptyFunction.js": 5, "../../node_modules/react/lib/ReactCurrentOwner.js": 6, "../../node_modules/fbjs/lib/emptyObject.js": 7, "../../node_modules/react/lib/ReactBaseClasses.js": 8, "../../node_modules/react/lib/ReactNoopUpdateQueue.js": 9, "../../node_modules/react/lib/canDefineProperty.js": 10, "../../node_modules/react/lib/ReactElementSymbol.js": 11, "../../node_modules/react/lib/React.js": 12, "../../node_modules/prop-types/factory.js": 13, "example.js": 14, "../../node_modules/react/react.js": 15, "../../node_modules/react/lib/lowPriorityWarning.js": 16, "../../node_modules/react/lib/ReactChildren.js": 17, "../../node_modules/react/lib/PooledClass.js": 18, "../../node_modules/react/lib/traverseAllChildren.js": 19, "../../node_modules/react/lib/getIteratorFn.js": 20, "../../node_modules/react/lib/KeyEscapeUtils.js": 21, "../../node_modules/react/lib/ReactDOMFactories.js": 22, "../../node_modules/react/lib/ReactPropTypes.js": 23, "../../node_modules/prop-types/factoryWithTypeCheckers.js": 24, "../../node_modules/prop-types/lib/ReactPropTypesSecret.js": 25, "../../node_modules/prop-types/checkPropTypes.js": 26, "../../node_modules/react/lib/ReactVersion.js": 27, "../../node_modules/react/lib/createClass.js": 28, "../../node_modules/create-react-class/factory.js": 29, "../../node_modules/react/lib/onlyChild.js": 30, "../../node_modules/react-dom/index.js": 31, "../../node_modules/react-dom/lib/reactProdInvariant.js": 32, "../../node_modules/react-dom/lib/ReactDOMComponentTree.js": 33, "../../node_modules/fbjs/lib/ExecutionEnvironment.js": 34, "../../node_modules/react-dom/lib/ReactInstrumentation.js": 35, "../../node_modules/react-dom/lib/ReactUpdates.js": 36, "../../node_modules/react-dom/lib/SyntheticEvent.js": 37, "../../node_modules/react-dom/lib/PooledClass.js": 38, "../../node_modules/react-dom/lib/DOMProperty.js": 39, "../../node_modules/react-dom/lib/ReactReconciler.js": 40, "../../node_modules/react-dom/lib/DOMLazyTree.js": 41, "../../node_modules/react-dom/lib/EventPropagators.js": 42, "../../node_modules/react-dom/lib/EventPluginHub.js": 43, "../../node_modules/react-dom/lib/SyntheticUIEvent.js": 44, "../../node_modules/react-dom/lib/ReactInstanceMap.js": 45, "../../node_modules/react-dom/lib/Transaction.js": 46, "../../node_modules/react-dom/lib/SyntheticMouseEvent.js": 47, "../../node_modules/react-dom/lib/setInnerHTML.js": 48, "../../node_modules/react-dom/lib/escapeTextContentForBrowser.js": 49, "../../node_modules/react-dom/lib/ReactBrowserEventEmitter.js": 50, "../../node_modules/react-dom/lib/EventPluginRegistry.js": 51, "../../node_modules/react-dom/lib/EventPluginUtils.js": 52, "../../node_modules/react-dom/lib/ReactErrorUtils.js": 53, "../../node_modules/react-dom/lib/getEventTarget.js": 54, "../../node_modules/react-dom/lib/isEventSupported.js": 55, "../../node_modules/react-dom/lib/getEventModifierState.js": 56, "../../node_modules/react-dom/lib/DOMChildrenOperations.js": 57, "../../node_modules/react-dom/lib/DOMNamespaces.js": 58, "../../node_modules/react-dom/lib/createMicrosoftUnsafeLocalFunction.js": 59, "../../node_modules/react-dom/lib/LinkedValueUtils.js": 60, "../../node_modules/react-dom/lib/ReactComponentEnvironment.js": 61, "../../node_modules/fbjs/lib/shallowEqual.js": 62, "../../node_modules/react-dom/lib/shouldUpdateReactComponent.js": 63, "../../node_modules/react-dom/lib/KeyEscapeUtils.js": 64, "../../node_modules/react-dom/lib/ReactUpdateQueue.js": 65, "../../node_modules/react-dom/lib/validateDOMNesting.js": 66, "../../node_modules/react-dom/lib/getEventCharCode.js": 67, "../../node_modules/react-dom/lib/ReactDOMComponentFlags.js": 68, "../../node_modules/react-dom/lib/accumulateInto.js": 69, "../../node_modules/react-dom/lib/forEachAccumulated.js": 70, "../../node_modules/react-dom/lib/getTextContentAccessor.js": 71, "../../node_modules/react-dom/lib/CallbackQueue.js": 72, "../../node_modules/react-dom/lib/ReactFeatureFlags.js": 73, "../../node_modules/react-dom/lib/inputValueTracking.js": 74, "../../node_modules/react-dom/lib/isTextInputElement.js": 75, "../../node_modules/react-dom/lib/ViewportMetrics.js": 76, "../../node_modules/react-dom/lib/setTextContent.js": 77, "../../node_modules/fbjs/lib/focusNode.js": 78, "../../node_modules/react-dom/lib/CSSProperty.js": 79, "../../node_modules/react-dom/lib/DOMPropertyOperations.js": 80, "../../node_modules/react-dom/lib/ReactDOMSelect.js": 81, "../../node_modules/process/browser.js": 82, "../../node_modules/react-dom/lib/instantiateReactComponent.js": 83, "../../node_modules/react-dom/lib/ReactNodeTypes.js": 84, "../../node_modules/react-dom/lib/ReactEmptyComponent.js": 85, "../../node_modules/react-dom/lib/ReactHostComponent.js": 86, "../../node_modules/react-dom/lib/traverseAllChildren.js": 87, "../../node_modules/react/lib/ReactComponentTreeHook.js": 88, "../../node_modules/fbjs/lib/EventListener.js": 89, "../../node_modules/react-dom/lib/ReactInputSelection.js": 90, "../../node_modules/fbjs/lib/getActiveElement.js": 91, "../../node_modules/react-dom/lib/ReactMount.js": 92, "../../node_modules/react-dom/lib/getHostComponentFromComposite.js": 93, "../../node_modules/react-dom/lib/ReactDOM.js": 94, "../../node_modules/react-dom/lib/ReactDefaultInjection.js": 95, "../../node_modules/react-dom/lib/ARIADOMPropertyConfig.js": 96, "../../node_modules/react-dom/lib/BeforeInputEventPlugin.js": 97, "../../node_modules/react-dom/lib/FallbackCompositionState.js": 98, "../../node_modules/react-dom/lib/SyntheticCompositionEvent.js": 99, "../../node_modules/react-dom/lib/SyntheticInputEvent.js": 100, "../../node_modules/react-dom/lib/ChangeEventPlugin.js": 101, "../../node_modules/react-dom/lib/ReactRef.js": 102, "../../node_modules/react-dom/lib/ReactOwner.js": 103, "../../node_modules/react-dom/lib/DefaultEventPluginOrder.js": 104, "../../node_modules/react-dom/lib/EnterLeaveEventPlugin.js": 105, "../../node_modules/react-dom/lib/HTMLDOMPropertyConfig.js": 106, "../../node_modules/react-dom/lib/ReactComponentBrowserEnvironment.js": 107, "../../node_modules/react-dom/lib/Danger.js": 108, "../../node_modules/fbjs/lib/createNodesFromMarkup.js": 109, "../../node_modules/fbjs/lib/createArrayFromMixed.js": 110, "../../node_modules/fbjs/lib/getMarkupWrap.js": 111, "../../node_modules/react-dom/lib/ReactDOMIDOperations.js": 112, "../../node_modules/react-dom/lib/ReactDOMComponent.js": 113, "../../node_modules/react-dom/lib/AutoFocusUtils.js": 114, "../../node_modules/react-dom/lib/CSSPropertyOperations.js": 115, "../../node_modules/fbjs/lib/camelizeStyleName.js": 116, "../../node_modules/fbjs/lib/camelize.js": 117, "../../node_modules/react-dom/lib/dangerousStyleValue.js": 118, "../../node_modules/fbjs/lib/hyphenateStyleName.js": 119, "../../node_modules/fbjs/lib/hyphenate.js": 120, "../../node_modules/fbjs/lib/memoizeStringOnly.js": 121, "../../node_modules/react-dom/lib/quoteAttributeValueForBrowser.js": 122, "../../node_modules/react-dom/lib/ReactEventEmitterMixin.js": 123, "../../node_modules/react-dom/lib/getVendorPrefixedEventName.js": 124, "../../node_modules/react-dom/lib/ReactDOMInput.js": 125, "../../node_modules/react-dom/lib/ReactPropTypesSecret.js": 126, "../../node_modules/react-dom/lib/ReactDOMOption.js": 127, "../../node_modules/react-dom/lib/ReactDOMTextarea.js": 128, "../../node_modules/react-dom/lib/ReactMultiChild.js": 129, "../../node_modules/react-dom/lib/ReactChildReconciler.js": 130, "../../node_modules/react-dom/lib/ReactCompositeComponent.js": 131, "../../node_modules/react/lib/getNextDebugID.js": 132, "../../node_modules/react-dom/lib/ReactElementSymbol.js": 133, "../../node_modules/react-dom/lib/getIteratorFn.js": 134, "../../node_modules/react-dom/lib/flattenChildren.js": 135, "../../node_modules/react-dom/lib/ReactServerRenderingTransaction.js": 136, "../../node_modules/react-dom/lib/ReactServerUpdateQueue.js": 137, "../../node_modules/react-dom/lib/ReactDOMEmptyComponent.js": 138, "../../node_modules/react-dom/lib/ReactDOMTreeTraversal.js": 139, "../../node_modules/react-dom/lib/ReactDOMTextComponent.js": 140, "../../node_modules/react-dom/lib/ReactDefaultBatchingStrategy.js": 141, "../../node_modules/react-dom/lib/ReactEventListener.js": 142, "../../node_modules/fbjs/lib/getUnboundedScrollPosition.js": 143, "../../node_modules/react-dom/lib/ReactInjection.js": 144, "../../node_modules/react-dom/lib/ReactReconcileTransaction.js": 145, "../../node_modules/react-dom/lib/ReactDOMSelection.js": 146, "../../node_modules/react-dom/lib/getNodeForCharacterOffset.js": 147, "../../node_modules/fbjs/lib/containsNode.js": 148, "../../node_modules/fbjs/lib/isTextNode.js": 149, "../../node_modules/fbjs/lib/isNode.js": 150, "../../node_modules/react-dom/lib/SVGDOMPropertyConfig.js": 151, "../../node_modules/react-dom/lib/SelectEventPlugin.js": 152, "../../node_modules/react-dom/lib/SimpleEventPlugin.js": 153, "../../node_modules/react-dom/lib/SyntheticAnimationEvent.js": 154, "../../node_modules/react-dom/lib/SyntheticClipboardEvent.js": 155, "../../node_modules/react-dom/lib/SyntheticFocusEvent.js": 156, "../../node_modules/react-dom/lib/SyntheticKeyboardEvent.js": 157, "../../node_modules/react-dom/lib/getEventKey.js": 158, "../../node_modules/react-dom/lib/SyntheticDragEvent.js": 159, "../../node_modules/react-dom/lib/SyntheticTouchEvent.js": 160, "../../node_modules/react-dom/lib/SyntheticTransitionEvent.js": 161, "../../node_modules/react-dom/lib/SyntheticWheelEvent.js": 162, "../../node_modules/react-dom/lib/ReactDOMContainerInfo.js": 163, "../../node_modules/react-dom/lib/ReactDOMFeatureFlags.js": 164, "../../node_modules/react-dom/lib/ReactMarkupChecksum.js": 165, "../../node_modules/react-dom/lib/adler32.js": 166, "../../node_modules/react-dom/lib/ReactVersion.js": 167, "../../node_modules/react-dom/lib/findDOMNode.js": 168, "../../node_modules/react-dom/lib/renderSubtreeIntoContainer.js": 169 }, "usedIds": { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "11": 11, "12": 12, "13": 13, "14": 14, "15": 15, "16": 16, "17": 17, "18": 18, "19": 19, "20": 20, "21": 21, "22": 22, "23": 23, "24": 24, "25": 25, "26": 26, "27": 27, "28": 28, "29": 29, "30": 30, "31": 31, "32": 32, "33": 33, "34": 34, "35": 35, "36": 36, "37": 37, "38": 38, "39": 39, "40": 40, "41": 41, "42": 42, "43": 43, "44": 44, "45": 45, "46": 46, "47": 47, "48": 48, "49": 49, "50": 50, "51": 51, "52": 52, "53": 53, "54": 54, "55": 55, "56": 56, "57": 57, "58": 58, "59": 59, "60": 60, "61": 61, "62": 62, "63": 63, "64": 64, "65": 65, "66": 66, "67": 67, "68": 68, "69": 69, "70": 70, "71": 71, "72": 72, "73": 73, "74": 74, "75": 75, "76": 76, "77": 77, "78": 78, "79": 79, "80": 80, "81": 81, "82": 82, "83": 83, "84": 84, "85": 85, "86": 86, "87": 87, "88": 88, "89": 89, "90": 90, "91": 91, "92": 92, "93": 93, "94": 94, "95": 95, "96": 96, "97": 97, "98": 98, "99": 99, "100": 100, "101": 101, "102": 102, "103": 103, "104": 104, "105": 105, "106": 106, "107": 107, "108": 108, "109": 109, "110": 110, "111": 111, "112": 112, "113": 113, "114": 114, "115": 115, "116": 116, "117": 117, "118": 118, "119": 119, "120": 120, "121": 121, "122": 122, "123": 123, "124": 124, "125": 125, "126": 126, "127": 127, "128": 128, "129": 129, "130": 130, "131": 131, "132": 132, "133": 133, "134": 134, "135": 135, "136": 136, "137": 137, "138": 138, "139": 139, "140": 140, "141": 141, "142": 142, "143": 143, "144": 144, "145": 145, "146": 146, "147": 147, "148": 148, "149": 149, "150": 150, "151": 151, "152": 152, "153": 153, "154": 154, "155": 155, "156": 156, "157": 157, "158": 158, "159": 159, "160": 160, "161": 161, "162": 162, "163": 163, "164": 164, "165": 165, "166": 166, "167": 167, "168": 168, "169": 169 } }, "chunks": { "byName": {}, "byBlocks": { "example.js:0/0:0": 0, "example.js:0/0:1": 1, "example.js:0/0:2": 2, "example.js:0/0:3": 3, "example.js:0/0:4": 4, "example.js:0/0:5": 5, "example.js:0/0:6": 6, "example.js:0/0:7": 7, "example.js:0/0:8": 8, "example.js:0/0:9": 9, "example.js:0/0:10": 10, "example.js:0/0:11": 11 }, "usedIds": { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "11": 11, "12": 12, "13": 13, "14": 14 } }, "aggressiveSplits": [ { "modules": [ "../../node_modules/react-dom/index.js", "../../node_modules/fbjs/lib/ExecutionEnvironment.js", "../../node_modules/fbjs/lib/shallowEqual.js", "../../node_modules/fbjs/lib/focusNode.js", "../../node_modules/react-dom/lib/CSSProperty.js", "../../node_modules/process/browser.js", "../../node_modules/fbjs/lib/EventListener.js", "../../node_modules/fbjs/lib/getActiveElement.js", "../../node_modules/react-dom/lib/ARIADOMPropertyConfig.js", "../../node_modules/react-dom/lib/BeforeInputEventPlugin.js", "../../node_modules/fbjs/lib/createNodesFromMarkup.js", "../../node_modules/fbjs/lib/createArrayFromMixed.js", "../../node_modules/fbjs/lib/getMarkupWrap.js", "../../node_modules/react-dom/lib/AutoFocusUtils.js", "../../node_modules/fbjs/lib/camelizeStyleName.js", "../../node_modules/fbjs/lib/camelize.js", "../../node_modules/fbjs/lib/hyphenateStyleName.js", "../../node_modules/fbjs/lib/hyphenate.js", "../../node_modules/fbjs/lib/memoizeStringOnly.js", "../../node_modules/fbjs/lib/getUnboundedScrollPosition.js", "../../node_modules/fbjs/lib/containsNode.js", "../../node_modules/fbjs/lib/isTextNode.js", "../../node_modules/fbjs/lib/isNode.js" ], "hash": "af5b936f620d7c2cf46e0e11bd2b48e3", "id": 0 }, { "modules": [ "../../node_modules/react-dom/lib/reactProdInvariant.js", "../../node_modules/react-dom/lib/setInnerHTML.js", "../../node_modules/react-dom/lib/getEventTarget.js", "../../node_modules/react-dom/lib/isEventSupported.js", "../../node_modules/react-dom/lib/getEventModifierState.js", "../../node_modules/react-dom/lib/getTextContentAccessor.js", "../../node_modules/react-dom/lib/inputValueTracking.js", "../../node_modules/react-dom/lib/isTextInputElement.js", "../../node_modules/react-dom/lib/instantiateReactComponent.js", "../../node_modules/react-dom/lib/getHostComponentFromComposite.js", "../../node_modules/react-dom/lib/quoteAttributeValueForBrowser.js", "../../node_modules/react-dom/lib/getVendorPrefixedEventName.js", "../../node_modules/react-dom/lib/getIteratorFn.js", "../../node_modules/react-dom/lib/flattenChildren.js", "../../node_modules/react-dom/lib/getNodeForCharacterOffset.js", "../../node_modules/react-dom/lib/getEventKey.js", "../../node_modules/react-dom/lib/renderSubtreeIntoContainer.js" ], "hash": "fbb0bfdcf201839059f94a4681a34acf", "id": 1 }, { "modules": [ "../../node_modules/react-dom/lib/ReactInstrumentation.js", "../../node_modules/react-dom/lib/ReactInstanceMap.js", "../../node_modules/react-dom/lib/ReactErrorUtils.js", "../../node_modules/react-dom/lib/ReactFeatureFlags.js", "../../node_modules/react-dom/lib/ReactNodeTypes.js", "../../node_modules/react-dom/lib/ReactHostComponent.js", "../../node_modules/react-dom/lib/ReactInputSelection.js", "../../node_modules/react-dom/lib/ReactDefaultInjection.js", "../../node_modules/react-dom/lib/ReactRef.js", "../../node_modules/react-dom/lib/ReactOwner.js", "../../node_modules/react-dom/lib/ReactDOMTextarea.js", "../../node_modules/react-dom/lib/ReactDOMTextComponent.js", "../../node_modules/react-dom/lib/ReactEventListener.js", "../../node_modules/react-dom/lib/ReactInjection.js", "../../node_modules/react-dom/lib/ReactDOMSelection.js", "../../node_modules/react-dom/lib/SyntheticAnimationEvent.js", "../../node_modules/react-dom/lib/ReactMarkupChecksum.js" ], "hash": "d8035b04d59361a42a17d4fc01467f19", "id": 2 }, { "modules": [ "../../node_modules/react-dom/lib/SyntheticEvent.js", "../../node_modules/react-dom/lib/SyntheticUIEvent.js", "../../node_modules/react-dom/lib/Transaction.js", "../../node_modules/react-dom/lib/SyntheticMouseEvent.js", "../../node_modules/react-dom/lib/escapeTextContentForBrowser.js", "../../node_modules/react-dom/lib/createMicrosoftUnsafeLocalFunction.js", "../../node_modules/react-dom/lib/getEventCharCode.js", "../../node_modules/react-dom/lib/accumulateInto.js", "../../node_modules/react-dom/lib/forEachAccumulated.js", "../../node_modules/react-dom/lib/dangerousStyleValue.js", "../../node_modules/react-dom/lib/SimpleEventPlugin.js", "../../node_modules/react-dom/lib/SyntheticTouchEvent.js", "../../node_modules/react-dom/lib/SyntheticTransitionEvent.js", "../../node_modules/react-dom/lib/SyntheticWheelEvent.js", "../../node_modules/react-dom/lib/adler32.js", "../../node_modules/react-dom/lib/findDOMNode.js" ], "hash": "92951e4964e84e7091031112e8d066b1", "id": 3 }, { "modules": [ "../../node_modules/react-dom/lib/ReactDOMComponentTree.js", "../../node_modules/react-dom/lib/PooledClass.js", "../../node_modules/react-dom/lib/ReactBrowserEventEmitter.js", "../../node_modules/react-dom/lib/LinkedValueUtils.js", "../../node_modules/react-dom/lib/ReactDOMComponentFlags.js", "../../node_modules/react-dom/lib/ReactDOM.js", "../../node_modules/react-dom/lib/ReactDOMIDOperations.js", "../../node_modules/react-dom/lib/ReactDOMOption.js", "../../node_modules/react-dom/lib/ReactChildReconciler.js", "../../node_modules/react-dom/lib/ReactElementSymbol.js", "../../node_modules/react-dom/lib/ReactDOMEmptyComponent.js", "../../node_modules/react-dom/lib/ReactDefaultBatchingStrategy.js", "../../node_modules/react-dom/lib/ReactDOMContainerInfo.js", "../../node_modules/react-dom/lib/ReactDOMFeatureFlags.js", "../../node_modules/react-dom/lib/ReactVersion.js" ], "hash": "d323f006c00a41b194cbeb3dcea2634a", "id": 4 }, { "modules": [ "../../node_modules/react-dom/lib/ReactUpdates.js", "../../node_modules/react-dom/lib/ReactReconciler.js", "../../node_modules/react-dom/lib/ReactUpdateQueue.js", "../../node_modules/react-dom/lib/ViewportMetrics.js", "../../node_modules/react-dom/lib/SyntheticInputEvent.js", "../../node_modules/react-dom/lib/ReactServerUpdateQueue.js", "../../node_modules/react-dom/lib/SVGDOMPropertyConfig.js", "../../node_modules/react-dom/lib/SelectEventPlugin.js", "../../node_modules/react-dom/lib/SyntheticFocusEvent.js", "../../node_modules/react-dom/lib/SyntheticKeyboardEvent.js", "../../node_modules/react-dom/lib/SyntheticDragEvent.js" ], "hash": "567bf6b0afa4e4baa4fba1a99e1a9298", "id": 5 }, { "modules": [ "../../node_modules/react-dom/lib/EventPropagators.js", "../../node_modules/react-dom/lib/EventPluginHub.js", "../../node_modules/react-dom/lib/EventPluginRegistry.js", "../../node_modules/react-dom/lib/EventPluginUtils.js", "../../node_modules/react-dom/lib/ReactComponentEnvironment.js", "../../node_modules/react-dom/lib/KeyEscapeUtils.js", "../../node_modules/react-dom/lib/FallbackCompositionState.js", "../../node_modules/react-dom/lib/DefaultEventPluginOrder.js", "../../node_modules/react-dom/lib/EnterLeaveEventPlugin.js", "../../node_modules/react-dom/lib/HTMLDOMPropertyConfig.js", "../../node_modules/react-dom/lib/Danger.js" ], "hash": "435514b5a5822c639a062f7ecb8fcd04", "id": 6 }, { "modules": [ "../../node_modules/react-dom/lib/DOMProperty.js", "../../node_modules/react-dom/lib/DOMLazyTree.js", "../../node_modules/react-dom/lib/DOMChildrenOperations.js", "../../node_modules/react-dom/lib/DOMNamespaces.js", "../../node_modules/react-dom/lib/CallbackQueue.js", "../../node_modules/react-dom/lib/DOMPropertyOperations.js", "../../node_modules/react-dom/lib/ChangeEventPlugin.js", "../../node_modules/react-dom/lib/ReactComponentBrowserEnvironment.js", "../../node_modules/react-dom/lib/CSSPropertyOperations.js" ], "hash": "04e95786881a7db62441637cbcef06cb", "id": 7 }, { "modules": [ "../../node_modules/react-dom/lib/shouldUpdateReactComponent.js", "../../node_modules/react-dom/lib/validateDOMNesting.js", "../../node_modules/react-dom/lib/setTextContent.js", "../../node_modules/react-dom/lib/traverseAllChildren.js", "../../node_modules/react/lib/ReactComponentTreeHook.js", "../../node_modules/react/lib/getNextDebugID.js" ], "hash": "ebe11885009391a25f13a5d3ebd9a80b", "id": 8 }, { "modules": [ "../../node_modules/react-dom/lib/ReactMount.js", "../../node_modules/react-dom/lib/SyntheticCompositionEvent.js", "../../node_modules/react-dom/lib/ReactMultiChild.js", "../../node_modules/react-dom/lib/ReactServerRenderingTransaction.js", "../../node_modules/react-dom/lib/ReactReconcileTransaction.js", "../../node_modules/react-dom/lib/SyntheticClipboardEvent.js" ], "hash": "1aa11917196d1d3b05c1ff41ee1672ee", "id": 9 }, { "modules": [ "../../node_modules/react-dom/lib/ReactDOMSelect.js", "../../node_modules/react-dom/lib/ReactDOMComponent.js", "../../node_modules/react-dom/lib/ReactPropTypesSecret.js", "../../node_modules/react-dom/lib/ReactDOMTreeTraversal.js" ], "hash": "8556f2285fd844cf9fdd4d78370aba33", "id": 10 }, { "modules": [ "../../node_modules/react-dom/lib/ReactEmptyComponent.js", "../../node_modules/react-dom/lib/ReactEventEmitterMixin.js", "../../node_modules/react-dom/lib/ReactDOMInput.js", "../../node_modules/react-dom/lib/ReactCompositeComponent.js" ], "hash": "c6598918ddb96aa65fc4325d8fd9d499", "id": 11 }, { "modules": [ "../../node_modules/fbjs/lib/invariant.js", "../../node_modules/fbjs/lib/warning.js", "../../node_modules/object-assign/index.js", "../../node_modules/fbjs/lib/emptyFunction.js", "../../node_modules/fbjs/lib/emptyObject.js", "../../node_modules/react/lib/React.js", "../../node_modules/prop-types/factory.js", "../../node_modules/react/react.js", "../../node_modules/react/lib/PooledClass.js", "../../node_modules/react/lib/KeyEscapeUtils.js", "../../node_modules/prop-types/lib/ReactPropTypesSecret.js", "../../node_modules/prop-types/checkPropTypes.js", "../../node_modules/create-react-class/factory.js" ], "hash": "8cc7b4a18437614b45e423a1395b571d", "id": 13 }, { "modules": [ "../../node_modules/react/lib/ReactBaseClasses.js", "../../node_modules/react/lib/ReactChildren.js", "../../node_modules/prop-types/factoryWithTypeCheckers.js" ], "hash": "11202a345a2ce63a2fb79589ee7d9edd", "id": 14 } ] } ``` webpack-3.5.6/examples/http2-aggressive-splitting/build.js000066400000000000000000000001231315401342100236130ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; global.NO_REASONS = true; require("../build-common");webpack-3.5.6/examples/http2-aggressive-splitting/example.js000066400000000000000000000000521315401342100241500ustar00rootroot00000000000000require("react"); require(["react-dom"]); webpack-3.5.6/examples/http2-aggressive-splitting/template.md000066400000000000000000000034521315401342100243230ustar00rootroot00000000000000This example demonstrates the AggressiveSplittingPlugin for splitting the bundle into multiple smaller chunks to improve caching. This works best with a HTTP2 web server elsewise there is an overhead for the increased number of requests. The AggressiveSplittingPlugin split every chunk until it reaches the specified `maxSize`. In this example it tries to create chunks with <50kB code (after minimizing this reduces to ~10kB). It groups modules together by folder structure. We assume modules in the same folder as similar likely to change and minimize and gzip good together. The AggressiveSplittingPlugin records it's splitting in the webpack records and try to restore splitting from records. This ensures that after changes to the application old splittings (and chunks) are reused. They are probably already in the clients cache. Therefore it's heavily recommended to use records! 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 too many chunks for every change. Chunks can get invalid if a module changes. Modules from invalid chunks go back into the module pool and 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 ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` ## Records ``` {{js/records.json}} ``` webpack-3.5.6/examples/http2-aggressive-splitting/webpack.config.js000066400000000000000000000007421315401342100254030ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = { entry: "./example", output: { path: path.join(__dirname, "js"), 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, "js", "records.json") }; webpack-3.5.6/examples/hybrid-routing/000077500000000000000000000000001315401342100177175ustar00rootroot00000000000000webpack-3.5.6/examples/hybrid-routing/README.md000066400000000000000000000433631315401342100212070ustar00rootroot00000000000000# webpack.config.js ``` javascript var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { // The entry points for the pages pageA: "./aEntry", pageB: "./bEntry", // This file contains common modules but also the router entry "commons": "./router" }, output: { path: path.join(__dirname, "js"), publicPath: "js/", filename: "[name].bundle.js", chunkFilename: "[id].chunk.js" }, plugins: [ // Extract common modules from the entries to the commons.js file // This is optional, but good for performance. new CommonsChunkPlugin({ name: "commons", filename: "commons.js" }) // The pages cannot run without the commons.js file now. ] }; ``` # 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. // The bundle-loader is used to create a chunk from the page // -> Pages are only loaded on demand // This line may throw a exception on runtime if the page wasn't found. var pageBundle = require("bundle-loader!./" + name + "Page"); // Wait until the chunk is loaded pageBundle(function(page) { render(page); }); } ``` # pageA.html ``` html ``` # js/commons.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ if(executeModules) { /******/ for(i=0; i < executeModules.length; i++) { /******/ result = __webpack_require__(__webpack_require__.s = executeModules[i]); /******/ } /******/ } /******/ return result; /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 4: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".chunk.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 5); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!*******************!*\ !*** ./render.js ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function(page) { console.log(page()); }; /***/ }), /* 1 */, /* 2 */, /* 3 */, /* 4 */, /* 5 */ /*!*******************!*\ !*** ./router.js ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (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. // The bundle-loader is used to create a chunk from the page // -> Pages are only loaded on demand // This line may throw a exception on runtime if the page wasn't found. var pageBundle = __webpack_require__(/*! bundle-loader!. */ 6)("./" + name + "Page"); // Wait until the chunk is loaded pageBundle(function(page) { render(page); }); } /***/ }), /* 6 */ /*!***********************************************************!*\ !*** . (webpack)/node_modules/bundle-loader ^\.\/.*Page$ ***! \***********************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var map = { "./aPage": 7, "./bPage": 8 }; function webpackContext(req) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 6; /***/ }), /* 7 */ /*!*******************************************************!*\ !*** (webpack)/node_modules/bundle-loader!./aPage.js ***! \*******************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (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__(/*! !./aPage.js */ 1); 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); /***/ }), /* 8 */ /*!*******************************************************!*\ !*** (webpack)/node_modules/bundle-loader!./bPage.js ***! \*******************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (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 */(0).then((function(require) { data = __webpack_require__(/*! !./bPage.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); /***/ }) /******/ ]); ``` # js/pageA.bundle.js ``` javascript webpackJsonp([3,1],[ /* 0 */, /* 1 */ /*!******************!*\ !*** ./aPage.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This is page A."; }; /***/ }), /* 2 */, /* 3 */ /*!*******************!*\ !*** ./aEntry.js ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { // Just show the page "a" var render = __webpack_require__(/*! ./render */ 0); render(__webpack_require__(/*! ./aPage */ 1)); /***/ }) ],[3]); ``` # js/1.chunk.js ``` javascript webpackJsonp([1],[ /* 0 */, /* 1 */ /*!******************!*\ !*** ./aPage.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This is page A."; }; /***/ }) ]); ``` # Info ## Uncompressed ``` Hash: 4b00bdf84d7923f55b44 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.chunk.js 267 bytes 0 [emitted] 1.chunk.js 273 bytes 1 [emitted] pageB.bundle.js 630 bytes 2, 0 [emitted] pageB pageA.bundle.js 621 bytes 3, 1 [emitted] pageA commons.js 9.59 kB 4 [emitted] commons Entrypoint pageA = commons.js pageA.bundle.js Entrypoint pageB = commons.js pageB.bundle.js Entrypoint commons = commons.js chunk {0} 0.chunk.js 61 bytes {4} [rendered] > [8] (webpack)/node_modules/bundle-loader!./bPage.js 7:0-14:2 [2] ./bPage.js 61 bytes {0} {2} [built] cjs require ./bPage [4] ./bEntry.js 3:7-25 cjs require !!./bPage.js [8] (webpack)/node_modules/bundle-loader!./bPage.js 8:8-31 chunk {1} 1.chunk.js 61 bytes {4} [rendered] > [7] (webpack)/node_modules/bundle-loader!./aPage.js 7:0-14:2 [1] ./aPage.js 61 bytes {1} {3} [built] cjs require ./aPage [3] ./aEntry.js 3:7-25 cjs require !!./aPage.js [7] (webpack)/node_modules/bundle-loader!./aPage.js 8:8-31 chunk {2} pageB.bundle.js (pageB) 150 bytes {4} [initial] [rendered] > pageB [4] ./bEntry.js [2] ./bPage.js 61 bytes {0} {2} [built] cjs require ./bPage [4] ./bEntry.js 3:7-25 cjs require !!./bPage.js [8] (webpack)/node_modules/bundle-loader!./bPage.js 8:8-31 [4] ./bEntry.js 89 bytes {2} [built] chunk {3} pageA.bundle.js (pageA) 150 bytes {4} [initial] [rendered] > pageA [3] ./aEntry.js [1] ./aPage.js 61 bytes {1} {3} [built] cjs require ./aPage [3] ./aEntry.js 3:7-25 cjs require !!./aPage.js [7] (webpack)/node_modules/bundle-loader!./aPage.js 8:8-31 [3] ./aEntry.js 89 bytes {3} [built] chunk {4} commons.js (commons) 1.71 kB [entry] [rendered] > commons [5] ./router.js [0] ./render.js 60 bytes {4} [built] cjs require ./render [3] ./aEntry.js 2:13-32 cjs require ./render [4] ./bEntry.js 2:13-32 cjs require ./render [5] ./router.js 1:13-32 [5] ./router.js 903 bytes {4} [built] [6] . (webpack)/node_modules/bundle-loader ^\.\/.*Page$ 184 bytes {4} [built] cjs require context bundle-loader!. [5] ./router.js 18:18-61 [7] (webpack)/node_modules/bundle-loader!./aPage.js 282 bytes {4} [optional] [built] context element ./aPage [6] . (webpack)/node_modules/bundle-loader ^\.\/.*Page$ ./aPage [8] (webpack)/node_modules/bundle-loader!./bPage.js 282 bytes {4} [optional] [built] context element ./bPage [6] . (webpack)/node_modules/bundle-loader ^\.\/.*Page$ ./bPage ``` ## Minimized (uglify-js, no zip) ``` Hash: 4b00bdf84d7923f55b44 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.chunk.js 83 bytes 0 [emitted] 1.chunk.js 82 bytes 1 [emitted] pageB.bundle.js 118 bytes 2, 0 [emitted] pageB pageA.bundle.js 117 bytes 3, 1 [emitted] pageA commons.js 2.13 kB 4 [emitted] commons Entrypoint pageA = commons.js pageA.bundle.js Entrypoint pageB = commons.js pageB.bundle.js Entrypoint commons = commons.js chunk {0} 0.chunk.js 61 bytes {4} [rendered] > [8] (webpack)/node_modules/bundle-loader!./bPage.js 7:0-14:2 [2] ./bPage.js 61 bytes {0} {2} [built] cjs require ./bPage [4] ./bEntry.js 3:7-25 cjs require !!./bPage.js [8] (webpack)/node_modules/bundle-loader!./bPage.js 8:8-31 chunk {1} 1.chunk.js 61 bytes {4} [rendered] > [7] (webpack)/node_modules/bundle-loader!./aPage.js 7:0-14:2 [1] ./aPage.js 61 bytes {1} {3} [built] cjs require ./aPage [3] ./aEntry.js 3:7-25 cjs require !!./aPage.js [7] (webpack)/node_modules/bundle-loader!./aPage.js 8:8-31 chunk {2} pageB.bundle.js (pageB) 150 bytes {4} [initial] [rendered] > pageB [4] ./bEntry.js [2] ./bPage.js 61 bytes {0} {2} [built] cjs require ./bPage [4] ./bEntry.js 3:7-25 cjs require !!./bPage.js [8] (webpack)/node_modules/bundle-loader!./bPage.js 8:8-31 [4] ./bEntry.js 89 bytes {2} [built] chunk {3} pageA.bundle.js (pageA) 150 bytes {4} [initial] [rendered] > pageA [3] ./aEntry.js [1] ./aPage.js 61 bytes {1} {3} [built] cjs require ./aPage [3] ./aEntry.js 3:7-25 cjs require !!./aPage.js [7] (webpack)/node_modules/bundle-loader!./aPage.js 8:8-31 [3] ./aEntry.js 89 bytes {3} [built] chunk {4} commons.js (commons) 1.71 kB [entry] [rendered] > commons [5] ./router.js [0] ./render.js 60 bytes {4} [built] cjs require ./render [3] ./aEntry.js 2:13-32 cjs require ./render [4] ./bEntry.js 2:13-32 cjs require ./render [5] ./router.js 1:13-32 [5] ./router.js 903 bytes {4} [built] [6] . (webpack)/node_modules/bundle-loader ^\.\/.*Page$ 184 bytes {4} [built] cjs require context bundle-loader!. [5] ./router.js 18:18-61 [7] (webpack)/node_modules/bundle-loader!./aPage.js 282 bytes {4} [optional] [built] context element ./aPage [6] . (webpack)/node_modules/bundle-loader ^\.\/.*Page$ ./aPage [8] (webpack)/node_modules/bundle-loader!./bPage.js 282 bytes {4} [optional] [built] context element ./bPage [6] . (webpack)/node_modules/bundle-loader ^\.\/.*Page$ ./bPage ``` webpack-3.5.6/examples/hybrid-routing/aEntry.js000066400000000000000000000001271315401342100215170ustar00rootroot00000000000000// Just show the page "a" var render = require("./render"); render(require("./aPage"));webpack-3.5.6/examples/hybrid-routing/aPage.js000066400000000000000000000000731315401342100212720ustar00rootroot00000000000000module.exports = function() { return "This is page A."; };webpack-3.5.6/examples/hybrid-routing/bEntry.js000066400000000000000000000001271315401342100215200ustar00rootroot00000000000000// Just show the page "b" var render = require("./render"); render(require("./bPage"));webpack-3.5.6/examples/hybrid-routing/bPage.js000066400000000000000000000000731315401342100212730ustar00rootroot00000000000000module.exports = function() { return "This is page B."; };webpack-3.5.6/examples/hybrid-routing/build.js000066400000000000000000000000721315401342100213530ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-3.5.6/examples/hybrid-routing/pageA.html000066400000000000000000000002431315401342100216210ustar00rootroot00000000000000 webpack-3.5.6/examples/hybrid-routing/pageB.html000066400000000000000000000002431315401342100216220ustar00rootroot00000000000000 webpack-3.5.6/examples/hybrid-routing/render.js000066400000000000000000000000721315401342100215330ustar00rootroot00000000000000module.exports = function(page) { console.log(page()); };webpack-3.5.6/examples/hybrid-routing/router.js000066400000000000000000000015571315401342100216050ustar00rootroot00000000000000var 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. // The bundle-loader is used to create a chunk from the page // -> Pages are only loaded on demand // This line may throw a exception on runtime if the page wasn't found. var pageBundle = require("bundle-loader!./" + name + "Page"); // Wait until the chunk is loaded pageBundle(function(page) { render(page); }); } webpack-3.5.6/examples/hybrid-routing/template.md000066400000000000000000000011601315401342100220520ustar00rootroot00000000000000# 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}} ``` # js/commons.js ``` javascript {{js/commons.js}} ``` # js/pageA.bundle.js ``` javascript {{js/pageA.bundle.js}} ``` # js/1.chunk.js ``` javascript {{js/1.chunk.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/hybrid-routing/webpack.config.js000066400000000000000000000013111315401342100231310ustar00rootroot00000000000000var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { // The entry points for the pages pageA: "./aEntry", pageB: "./bEntry", // This file contains common modules but also the router entry "commons": "./router" }, output: { path: path.join(__dirname, "js"), publicPath: "js/", filename: "[name].bundle.js", chunkFilename: "[id].chunk.js" }, plugins: [ // Extract common modules from the entries to the commons.js file // This is optional, but good for performance. new CommonsChunkPlugin({ name: "commons", filename: "commons.js" }) // The pages cannot run without the commons.js file now. ] }; webpack-3.5.6/examples/i18n/000077500000000000000000000000001315401342100155305ustar00rootroot00000000000000webpack-3.5.6/examples/i18n/README.md000066400000000000000000000201761315401342100170150ustar00rootroot00000000000000This 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, entry: "./example", output: { path: path.join(__dirname, "js"), filename: language + ".output.js" }, plugins: [ new I18nPlugin( languages[language] ) ] }; }); ``` # de.json ``` javascript { "Hello World": "Hallo Welt" } ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { console.log("Hallo Welt"); console.log("Missing Text"); /***/ }) /******/ ]); ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { console.log("Hello World"); console.log("Missing Text"); /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: b61d16621736c97f557e52b4d8e68140f1345ef8 Version: webpack 3.5.1 Child en: Hash: b61d16621736c97f557e Asset Size Chunks Chunk Names en.output.js 2.69 kB 0 [emitted] main Entrypoint main = en.output.js chunk {0} en.output.js (main) 65 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 65 bytes {0} [built] Child de: Hash: 52b4d8e68140f1345ef8 Asset Size Chunks Chunk Names de.output.js 2.69 kB 0 [emitted] main Entrypoint main = de.output.js chunk {0} de.output.js (main) 65 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 65 bytes {0} [built] [1 warning] WARNING in ./example.js Missing localization: Missing Text ``` ## Minimized (uglify-js, no zip) ``` Hash: b61d16621736c97f557e52b4d8e68140f1345ef8 Version: webpack 3.5.1 Child en: Hash: b61d16621736c97f557e Asset Size Chunks Chunk Names en.output.js 538 bytes 0 [emitted] main Entrypoint main = en.output.js chunk {0} en.output.js (main) 65 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 65 bytes {0} [built] Child de: Hash: 52b4d8e68140f1345ef8 Asset Size Chunks Chunk Names de.output.js 537 bytes 0 [emitted] main Entrypoint main = de.output.js chunk {0} de.output.js (main) 65 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 65 bytes {0} [built] [1 warning] WARNING in ./example.js Missing localization: Missing Text ```webpack-3.5.6/examples/i18n/build.js000066400000000000000000000000711315401342100171630ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-3.5.6/examples/i18n/de.json000066400000000000000000000000401315401342100170050ustar00rootroot00000000000000{ "Hello World": "Hallo Welt" }webpack-3.5.6/examples/i18n/example.js000066400000000000000000000001001315401342100175100ustar00rootroot00000000000000console.log(__("Hello World")); console.log(__("Missing Text"));webpack-3.5.6/examples/i18n/template.md000066400000000000000000000014201315401342100176620ustar00rootroot00000000000000This 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}} ``` # js/de.output.js ``` javascript {{js/de.output.js}} ``` # js/en.output.js ``` javascript {{js/en.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/i18n/webpack.config.js000066400000000000000000000006421315401342100207500ustar00rootroot00000000000000var 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, entry: "./example", output: { path: path.join(__dirname, "js"), filename: language + ".output.js" }, plugins: [ new I18nPlugin( languages[language] ) ] }; }); webpack-3.5.6/examples/loader/000077500000000000000000000000001315401342100162175ustar00rootroot00000000000000webpack-3.5.6/examples/loader/README.md000066400000000000000000000202611315401342100174770ustar00rootroot00000000000000# 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; } ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!****************************************************!*\ !*** (webpack)/node_modules/css-loader!./test.css ***! \****************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! ../../node_modules/css-loader/lib/css-base.js */ 3)(undefined); // imports // module exports.push([module.i, ".some-class {\r\n\tcolor: hotpink;\r\n}\r\n", ""]); // exports /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { // use our loader console.dir(__webpack_require__(/*! ./loader!./file */ 2)); // use buildin css loader console.dir(__webpack_require__(/*! ./test.css */ 0)); // default by extension console.dir(__webpack_require__(/*! css-loader!./test.css */ 0)); // manual /***/ }), /* 2 */ /*!*****************************!*\ !*** ./loader.js!./file.js ***! \*****************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { exports.answer = 42; exports.foo = "bar"; /***/ }), /* 3 */ /*!*********************************************************!*\ !*** (webpack)/node_modules/css-loader/lib/css-base.js ***! \*********************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { /* 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(typeof id === "number") 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(typeof item[0] !== "number" || !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 ## Uncompressed ``` Hash: c15a21a2e67111e1cd94 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 6.24 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 2.72 kB [entry] [rendered] > main [1] ./example.js [0] (webpack)/node_modules/css-loader!./test.css 209 bytes {0} [built] cjs require !css-loader!./test.css [1] ./example.js 6:12-45 cjs require ./test.css [1] ./example.js 5:12-33 [1] ./example.js 210 bytes {0} [built] [2] ./loader.js!./file.js 41 bytes {0} [built] cjs require ./loader!./file [1] ./example.js 2:12-38 + 1 hidden module ``` ## Minimized (uglify-js, no zip) ``` Hash: 1848e785d8b4fe1c67d0 Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 1.48 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 2.7 kB [entry] [rendered] > main [1] ./example.js [0] (webpack)/node_modules/css-loader!./test.css 192 bytes {0} [built] cjs require !css-loader!./test.css [1] ./example.js 6:12-45 cjs require ./test.css [1] ./example.js 5:12-33 [1] ./example.js 210 bytes {0} [built] [2] ./loader.js!./file.js 41 bytes {0} [built] cjs require ./loader!./file [1] ./example.js 2:12-38 + 1 hidden module ``` webpack-3.5.6/examples/loader/build.js000066400000000000000000000000331315401342100176500ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/loader/example.js000066400000000000000000000003141315401342100202060ustar00rootroot00000000000000// 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-3.5.6/examples/loader/file.js000066400000000000000000000000241315401342100174700ustar00rootroot00000000000000exports.foo = "bar";webpack-3.5.6/examples/loader/loader.js000066400000000000000000000001221315401342100200160ustar00rootroot00000000000000module.exports = function(content) { return "exports.answer = 42;\n" + content; }webpack-3.5.6/examples/loader/template.md000066400000000000000000000007471315401342100203640ustar00rootroot00000000000000# example.js ``` javascript {{example.js}} ``` # file.js ``` javascript {{file.js}} ``` # loader.js ``` javascript {{loader.js}} ``` # test.css ``` css {{test.css}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Console output Prints in node.js (`enhanced-require example.js`) and in browser: ``` { answer: 42, foo: 'bar' } { foobar: 1234 } { foobar: 1234 } ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/loader/test.css000066400000000000000000000000411315401342100177030ustar00rootroot00000000000000.some-class { color: hotpink; } webpack-3.5.6/examples/loader/webpack.config.js000066400000000000000000000001411315401342100214310ustar00rootroot00000000000000module.exports = { module: { loaders: [ { test: /\.css$/, loader: "css-loader" } ] } }; webpack-3.5.6/examples/mixed/000077500000000000000000000000001315401342100160575ustar00rootroot00000000000000webpack-3.5.6/examples/mixed/README.md000066400000000000000000000406631315401342100173470ustar00rootroot00000000000000This 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"); } ); ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!*********************!*\ !*** ./commonjs.js ***! \*********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { // CommonJs Module Format module.exports = 123; // but you can use amd style requires new Promise(function(resolve) { resolve(); }).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 */ /*! all exports used */ /***/ (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 */ /*! all exports used */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__commonjs__ = __webpack_require__(/*! ./commonjs */ 0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__commonjs___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__commonjs__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__amd__ = __webpack_require__(/*! ./amd */ 1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__amd___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__amd__); // ES6 Modules /* harmony default export */ __webpack_exports__["default"] = (456); /***/ }), /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (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/* require */(0).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [ __webpack_require__(/*! ./commonjs */ 0), __webpack_require__(/*! ./amd */ 1), __webpack_require__(/*! ../require.context/templates */ 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); /***/ }) /******/ ]); ``` # js/0.output.js ``` javascript webpackJsonp([0],[ /* 0 */, /* 1 */, /* 2 */, /* 3 */, /* 4 */ /*!*************************************************!*\ !*** ../require.context/templates ^\.\/.*\.js$ ***! \*************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var map = { "./a.js": 5, "./b.js": 6, "./c.js": 7 }; function webpackContext(req) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; 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 */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 6 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 7 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]); ``` # Info ## Uncompressed ``` Hash: ec4ce5e31af3a13d93fa Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 1.86 kB 0 [emitted] output.js 9.08 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 439 bytes {1} [rendered] > [3] ./example.js 7:0-14:1 [4] ../require.context/templates ^\.\/.*\.js$ 193 bytes {0} [built] amd require context ../require.context/templates [3] ./example.js 7:0-14:1 [5] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [4] ../require.context/templates ^\.\/.*\.js$ ./a.js [6] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [4] ../require.context/templates ^\.\/.*\.js$ ./b.js [7] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [4] ../require.context/templates ^\.\/.*\.js$ ./c.js chunk {1} output.js (main) 1.05 kB [entry] [rendered] > main [3] ./example.js [0] ./commonjs.js 233 bytes {1} [built] amd require ./commonjs [1] ./amd.js 2:0-12:1 cjs require ./commonjs [1] ./amd.js 7:18-39 harmony import ./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 309 bytes {1} [built] amd require ./amd [0] ./commonjs.js 5:0-11:1 cjs require ./amd [0] ./commonjs.js 8:13-29 harmony import ./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 101 bytes {1} [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 410 bytes {1} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: ec4ce5e31af3a13d93fa Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 523 bytes 0 [emitted] output.js 1.89 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 439 bytes {1} [rendered] > [3] ./example.js 7:0-14:1 [4] ../require.context/templates ^\.\/.*\.js$ 193 bytes {0} [built] amd require context ../require.context/templates [3] ./example.js 7:0-14:1 [5] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [4] ../require.context/templates ^\.\/.*\.js$ ./a.js [6] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [4] ../require.context/templates ^\.\/.*\.js$ ./b.js [7] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [4] ../require.context/templates ^\.\/.*\.js$ ./c.js chunk {1} output.js (main) 1.05 kB [entry] [rendered] > main [3] ./example.js [0] ./commonjs.js 233 bytes {1} [built] amd require ./commonjs [1] ./amd.js 2:0-12:1 cjs require ./commonjs [1] ./amd.js 7:18-39 harmony import ./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 309 bytes {1} [built] amd require ./amd [0] ./commonjs.js 5:0-11:1 cjs require ./amd [0] ./commonjs.js 8:13-29 harmony import ./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 101 bytes {1} [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 410 bytes {1} [built] ``` webpack-3.5.6/examples/mixed/amd.js000066400000000000000000000004521315401342100171570ustar00rootroot00000000000000// 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-3.5.6/examples/mixed/build.js000066400000000000000000000000331315401342100175100ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/mixed/commonjs.js000066400000000000000000000003371315401342100202450ustar00rootroot00000000000000// 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-3.5.6/examples/mixed/example.js000066400000000000000000000006141315401342100200510ustar00rootroot00000000000000// 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-3.5.6/examples/mixed/harmony.js000066400000000000000000000001401315401342100200650ustar00rootroot00000000000000// ES6 Modules import commonjs from "./commonjs"; import amd from "./amd"; export default 456; webpack-3.5.6/examples/mixed/template.md000066400000000000000000000013021315401342100202100ustar00rootroot00000000000000This 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/move-to-parent/000077500000000000000000000000001315401342100176265ustar00rootroot00000000000000webpack-3.5.6/examples/move-to-parent/README.md000066400000000000000000000244221315401342100211110ustar00rootroot00000000000000This example shows example of using the CommonsChunkPlugin for moving modules from child-chunks to the parent chunk. The `CommonsChunkPlugin` is used with `selectedChunks = false` argument to check for common modules in the child-chunks. Without the plugin the pages would have this chunks: * page * chunk: a * chunk: a, b * chunk: a, b, c * chunk: a, b, c, d Using the `CommonsChunkPlugin` without `minChunks` argument only moves modules which are shared by all children (here only module `a`): * pageA: a * chunk: b * chunk: b, c * chunk: b, c, d With `minChunks = 3`: * pageB: a, b * chunk: c * chunk: c, d It's also possible to provide a function instead of a number for `minChunks`. The function is called for each module to decide if the module should be moved or not (see pageC and pageD): * pageC: a, c, d * chunk: b # page.js ``` javascript require(["./a"]); require(["./a", "./b"]); require(["./a", "./b", "./c"]); require(["./a", "./b", "./c", "./d"]); ``` # webpack.config.js ``` javascript var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); var outputOptions = { path: path.join(__dirname, "js"), filename: "[name].bundle.js", chunkFilename: "[id].chunk.js" }; module.exports = [{ name: "page", entry: { page: "./page" }, output: outputOptions }, { name: "pageA", entry: { pageA: "./page" }, output: outputOptions, plugins: [ //check for common modules in children of pageA and move them to the parent new CommonsChunkPlugin({ name: "pageA", children: true }), ] }, { name: "pageB", entry: { pageB: "./page" }, output: outputOptions, plugins: [ // the same for pageB but move them if at least 3 children share the module new CommonsChunkPlugin({ name: "pageB", children: true, minChunks: 3 }), ] }, { name: "pageC", entry: { pageC: "./page" }, output: outputOptions, plugins: [ // the same for pageC and pageD but with a custom logic for moving new CommonsChunkPlugin({ name: "pageC", children: true, minChunks: function(module, count) { // move only module "b" return !/b\.js/.test(module.identifier()); } }) ] }]; ``` # Info ## Uncompressed ``` Hash: 32754229c1b49aaf5dd3020f354a206f830a17560d92a3529fe0380101f3e2c85f80fcddae09adcf Version: webpack 3.5.1 Child page: Hash: 32754229c1b49aaf5dd3 Asset Size Chunks Chunk Names 0.chunk.js 800 bytes 0, 1, 2, 3 [emitted] 1.chunk.js 598 bytes 1, 2, 3 [emitted] 2.chunk.js 405 bytes 2, 3 [emitted] 3.chunk.js 212 bytes 3 [emitted] page.bundle.js 6.62 kB 4 [emitted] page Entrypoint page = page.bundle.js chunk {0} 0.chunk.js 84 bytes {4} [rendered] > [3] ./page.js 4:0-37 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] [4] ./d.js 21 bytes {0} [built] chunk {1} 1.chunk.js 63 bytes {4} [rendered] > [3] ./page.js 3:0-30 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] chunk {2} 2.chunk.js 42 bytes {4} [rendered] > [3] ./page.js 2:0-23 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] [1] ./b.js 21 bytes {0} {1} {2} [built] chunk {3} 3.chunk.js 21 bytes {4} [rendered] > [3] ./page.js 1:0-16 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] chunk {4} page.bundle.js (page) 118 bytes [entry] [rendered] > page [3] ./page.js [3] ./page.js 118 bytes {4} [built] Child pageA: Hash: 020f354a206f830a1756 Asset Size Chunks Chunk Names 0.chunk.js 616 bytes 0, 1, 2 [emitted] 1.chunk.js 414 bytes 1, 2 [emitted] 2.chunk.js 221 bytes 2 [emitted] pageA.bundle.js 6.83 kB 3 [emitted] pageA Entrypoint pageA = pageA.bundle.js chunk {0} 0.chunk.js 63 bytes {3} [rendered] > [3] ./page.js 4:0-37 [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] [4] ./d.js 21 bytes {0} [built] chunk {1} 1.chunk.js 42 bytes {3} [rendered] > [3] ./page.js 3:0-30 [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] chunk {2} 2.chunk.js 21 bytes {3} [rendered] > [3] ./page.js 2:0-23 [1] ./b.js 21 bytes {0} {1} {2} [built] chunk {3} pageA.bundle.js (pageA) 139 bytes [entry] [rendered] > pageA [3] ./page.js [0] ./a.js 21 bytes {3} [built] [3] ./page.js 118 bytes {3} [built] Child pageB: Hash: 0d92a3529fe0380101f3 Asset Size Chunks Chunk Names 0.chunk.js 432 bytes 0, 1 [emitted] 1.chunk.js 215 bytes 1 [emitted] pageB.bundle.js 7.02 kB 2 [emitted] pageB Entrypoint pageB = pageB.bundle.js chunk {0} 0.chunk.js 42 bytes {2} [rendered] > [3] ./page.js 4:0-37 [2] ./c.js 21 bytes {0} {1} [built] [4] ./d.js 21 bytes {0} [built] chunk {1} 1.chunk.js 21 bytes {2} [rendered] > [3] ./page.js 3:0-30 [2] ./c.js 21 bytes {0} {1} [built] chunk {2} pageB.bundle.js (pageB) 160 bytes [entry] [rendered] > pageB [3] ./page.js [0] ./a.js 21 bytes {2} [built] [1] ./b.js 21 bytes {2} [built] [3] ./page.js 118 bytes {2} [built] Child pageC: Hash: e2c85f80fcddae09adcf Asset Size Chunks Chunk Names 0.chunk.js 221 bytes 0 [emitted] pageC.bundle.js 7.23 kB 1 [emitted] pageC Entrypoint pageC = pageC.bundle.js chunk {0} 0.chunk.js 21 bytes {1} [rendered] > duplicate [3] ./page.js 2:0-23 > duplicate [3] ./page.js 3:0-30 > duplicate [3] ./page.js 4:0-37 [1] ./b.js 21 bytes {0} [built] chunk {1} pageC.bundle.js (pageC) 181 bytes [entry] [rendered] > pageC [3] ./page.js [0] ./a.js 21 bytes {1} [built] [2] ./c.js 21 bytes {1} [built] [3] ./page.js 118 bytes {1} [built] [4] ./d.js 21 bytes {1} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: 32754229c1b49aaf5dd3020f354a206f830a17560d92a3529fe0380101f3e2c85f80fcddae09adcf Version: webpack 3.5.1 Child page: Hash: 32754229c1b49aaf5dd3 Asset Size Chunks Chunk Names 0.chunk.js 143 bytes 0, 1, 2, 3 [emitted] 1.chunk.js 111 bytes 1, 2, 3 [emitted] 2.chunk.js 80 bytes 2, 3 [emitted] 3.chunk.js 49 bytes 3 [emitted] page.bundle.js 1.54 kB 4 [emitted] page Entrypoint page = page.bundle.js chunk {0} 0.chunk.js 84 bytes {4} [rendered] > [3] ./page.js 4:0-37 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] [4] ./d.js 21 bytes {0} [built] chunk {1} 1.chunk.js 63 bytes {4} [rendered] > [3] ./page.js 3:0-30 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] chunk {2} 2.chunk.js 42 bytes {4} [rendered] > [3] ./page.js 2:0-23 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] [1] ./b.js 21 bytes {0} {1} {2} [built] chunk {3} 3.chunk.js 21 bytes {4} [rendered] > [3] ./page.js 1:0-16 [0] ./a.js 21 bytes {0} {1} {2} {3} [built] chunk {4} page.bundle.js (page) 118 bytes [entry] [rendered] > page [3] ./page.js [3] ./page.js 118 bytes {4} [built] Child pageA: Hash: 020f354a206f830a1756 Asset Size Chunks Chunk Names 0.chunk.js 113 bytes 0, 1, 2 [emitted] 1.chunk.js 81 bytes 1, 2 [emitted] 2.chunk.js 50 bytes 2 [emitted] pageA.bundle.js 1.59 kB 3 [emitted] pageA Entrypoint pageA = pageA.bundle.js chunk {0} 0.chunk.js 63 bytes {3} [rendered] > [3] ./page.js 4:0-37 [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] [4] ./d.js 21 bytes {0} [built] chunk {1} 1.chunk.js 42 bytes {3} [rendered] > [3] ./page.js 3:0-30 [1] ./b.js 21 bytes {0} {1} {2} [built] [2] ./c.js 21 bytes {0} {1} [built] chunk {2} 2.chunk.js 21 bytes {3} [rendered] > [3] ./page.js 2:0-23 [1] ./b.js 21 bytes {0} {1} {2} [built] chunk {3} pageA.bundle.js (pageA) 139 bytes [entry] [rendered] > pageA [3] ./page.js [0] ./a.js 21 bytes {3} [built] [3] ./page.js 118 bytes {3} [built] Child pageB: Hash: 0d92a3529fe0380101f3 Asset Size Chunks Chunk Names 0.chunk.js 83 bytes 0, 1 [emitted] 1.chunk.js 51 bytes 1 [emitted] pageB.bundle.js 1.64 kB 2 [emitted] pageB Entrypoint pageB = pageB.bundle.js chunk {0} 0.chunk.js 42 bytes {2} [rendered] > [3] ./page.js 4:0-37 [2] ./c.js 21 bytes {0} {1} [built] [4] ./d.js 21 bytes {0} [built] chunk {1} 1.chunk.js 21 bytes {2} [rendered] > [3] ./page.js 3:0-30 [2] ./c.js 21 bytes {0} {1} [built] chunk {2} pageB.bundle.js (pageB) 160 bytes [entry] [rendered] > pageB [3] ./page.js [0] ./a.js 21 bytes {2} [built] [1] ./b.js 21 bytes {2} [built] [3] ./page.js 118 bytes {2} [built] Child pageC: Hash: e2c85f80fcddae09adcf Asset Size Chunks Chunk Names 0.chunk.js 50 bytes 0 [emitted] pageC.bundle.js 1.65 kB 1 [emitted] pageC Entrypoint pageC = pageC.bundle.js chunk {0} 0.chunk.js 21 bytes {1} [rendered] > duplicate [3] ./page.js 2:0-23 > duplicate [3] ./page.js 3:0-30 > duplicate [3] ./page.js 4:0-37 [1] ./b.js 21 bytes {0} [built] chunk {1} pageC.bundle.js (pageC) 181 bytes [entry] [rendered] > pageC [3] ./page.js [0] ./a.js 21 bytes {1} [built] [2] ./c.js 21 bytes {1} [built] [3] ./page.js 118 bytes {1} [built] [4] ./d.js 21 bytes {1} [built] ``` webpack-3.5.6/examples/move-to-parent/a.js000066400000000000000000000000251315401342100204010ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/examples/move-to-parent/b.js000066400000000000000000000000251315401342100204020ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/examples/move-to-parent/build.js000066400000000000000000000001241315401342100212600ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; global.NO_REASONS = true; require("../build-common"); webpack-3.5.6/examples/move-to-parent/c.js000066400000000000000000000000251315401342100204030ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/examples/move-to-parent/d.js000066400000000000000000000000251315401342100204040ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/examples/move-to-parent/page.js000066400000000000000000000001621315401342100210770ustar00rootroot00000000000000require(["./a"]); require(["./a", "./b"]); require(["./a", "./b", "./c"]); require(["./a", "./b", "./c", "./d"]); webpack-3.5.6/examples/move-to-parent/template.md000066400000000000000000000020471315401342100217660ustar00rootroot00000000000000This example shows example of using the CommonsChunkPlugin for moving modules from child-chunks to the parent chunk. The `CommonsChunkPlugin` is used with `selectedChunks = false` argument to check for common modules in the child-chunks. Without the plugin the pages would have this chunks: * page * chunk: a * chunk: a, b * chunk: a, b, c * chunk: a, b, c, d Using the `CommonsChunkPlugin` without `minChunks` argument only moves modules which are shared by all children (here only module `a`): * pageA: a * chunk: b * chunk: b, c * chunk: b, c, d With `minChunks = 3`: * pageB: a, b * chunk: c * chunk: c, d It's also possible to provide a function instead of a number for `minChunks`. The function is called for each module to decide if the module should be moved or not (see pageC and pageD): * pageC: a, c, d * chunk: b # page.js ``` javascript {{page.js}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/move-to-parent/webpack.config.js000066400000000000000000000022141315401342100230430ustar00rootroot00000000000000var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); var outputOptions = { path: path.join(__dirname, "js"), filename: "[name].bundle.js", chunkFilename: "[id].chunk.js" }; module.exports = [{ name: "page", entry: { page: "./page" }, output: outputOptions }, { name: "pageA", entry: { pageA: "./page" }, output: outputOptions, plugins: [ //check for common modules in children of pageA and move them to the parent new CommonsChunkPlugin({ name: "pageA", children: true }), ] }, { name: "pageB", entry: { pageB: "./page" }, output: outputOptions, plugins: [ // the same for pageB but move them if at least 3 children share the module new CommonsChunkPlugin({ name: "pageB", children: true, minChunks: 3 }), ] }, { name: "pageC", entry: { pageC: "./page" }, output: outputOptions, plugins: [ // the same for pageC and pageD but with a custom logic for moving new CommonsChunkPlugin({ name: "pageC", children: true, minChunks: function(module, count) { // move only module "b" return !/b\.js/.test(module.identifier()); } }) ] }]; webpack-3.5.6/examples/multi-compiler/000077500000000000000000000000001315401342100177135ustar00rootroot00000000000000webpack-3.5.6/examples/multi-compiler/README.md000066400000000000000000000201661315401342100211770ustar00rootroot00000000000000 # 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", entry: "./example", output: { path: path.join(__dirname, "js"), filename: "mobile.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("mobile") }) ] }, { name: "desktop", entry: "./example", output: { path: path.join(__dirname, "js"), filename: "desktop.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("desktop") }) ] } ]; ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { if(false) { require("./mobile-stuff"); } console.log("Running " + "desktop" + " build"); /***/ }) /******/ ]); ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (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 */ /*! all exports used */ /***/ (function(module, exports) { // mobile only stuff /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: a201abd2de73265dd538cceba4bc5163d755f291 Version: webpack 3.5.1 Child mobile: Hash: a201abd2de73265dd538 Asset Size Chunks Chunk Names mobile.js 2.96 kB 0 [emitted] main Entrypoint main = mobile.js chunk {0} mobile.js (main) 117 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {0} [built] [1] ./mobile-stuff.js 20 bytes {0} [built] cjs require ./mobile-stuff [0] ./example.js 2:1-26 Child desktop: Hash: cceba4bc5163d755f291 Asset Size Chunks Chunk Names desktop.js 2.72 kB 0 [emitted] main Entrypoint main = desktop.js chunk {0} desktop.js (main) 97 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {0} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: a201abd2de73265dd538cceba4bc5163d755f291 Version: webpack 3.5.1 Child mobile: Hash: a201abd2de73265dd538 Asset Size Chunks Chunk Names mobile.js 540 bytes 0 [emitted] main Entrypoint main = mobile.js chunk {0} mobile.js (main) 117 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {0} [built] [1] ./mobile-stuff.js 20 bytes {0} [built] cjs require ./mobile-stuff [0] ./example.js 2:1-26 Child desktop: Hash: cceba4bc5163d755f291 Asset Size Chunks Chunk Names desktop.js 520 bytes 0 [emitted] main Entrypoint main = desktop.js chunk {0} desktop.js (main) 97 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 97 bytes {0} [built] ```webpack-3.5.6/examples/multi-compiler/build.js000066400000000000000000000000711315401342100213460ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-3.5.6/examples/multi-compiler/example.js000066400000000000000000000001361315401342100217040ustar00rootroot00000000000000if(ENV === "mobile") { require("./mobile-stuff"); } console.log("Running " + ENV + " build");webpack-3.5.6/examples/multi-compiler/mobile-stuff.js000066400000000000000000000000241315401342100226410ustar00rootroot00000000000000// mobile only stuffwebpack-3.5.6/examples/multi-compiler/template.md000066400000000000000000000005021315401342100220450ustar00rootroot00000000000000 # example.js ``` javascript {{example.js}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/desktop.js ``` javascript {{js/desktop.js}} ``` # js/mobile.js ``` javascript {{js/mobile.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ```webpack-3.5.6/examples/multi-compiler/webpack.config.js000066400000000000000000000007771315401342100231440ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); module.exports = [ { name: "mobile", entry: "./example", output: { path: path.join(__dirname, "js"), filename: "mobile.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("mobile") }) ] }, { name: "desktop", entry: "./example", output: { path: path.join(__dirname, "js"), filename: "desktop.js" }, plugins: [ new webpack.DefinePlugin({ ENV: JSON.stringify("desktop") }) ] } ]; webpack-3.5.6/examples/multi-part-library/000077500000000000000000000000001315401342100205115ustar00rootroot00000000000000webpack-3.5.6/examples/multi-part-library/README.md000066400000000000000000000220271315401342100217730ustar00rootroot00000000000000This 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 = { entry: { alpha: "./alpha", beta: "./beta" }, output: { path: path.join(__dirname, "js"), filename: "MyLibrary.[name].js", library: ["MyLibrary", "[name]"], libraryTarget: "umd" } }; ``` # js/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(); })(this, 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` js /******/ ([ /* 0 */ /*!******************!*\ !*** ./alpha.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "alpha"; /***/ }) /******/ ]); }); ``` # js/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(); })(this, 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */, /* 1 */ /*!*****************!*\ !*** ./beta.js ***! \*****************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "beta"; /***/ }) /******/ ]); }); ``` # Info ## Uncompressed ``` Hash: e5033b72cf0ec9da1ad7 Version: webpack 3.5.1 Asset Size Chunks Chunk Names MyLibrary.beta.js 3.06 kB 0 [emitted] beta MyLibrary.alpha.js 3.05 kB 1 [emitted] alpha Entrypoint alpha = MyLibrary.alpha.js Entrypoint beta = MyLibrary.beta.js chunk {0} MyLibrary.beta.js (beta) 24 bytes [entry] [rendered] > beta [1] ./beta.js [1] ./beta.js 24 bytes {0} [built] chunk {1} MyLibrary.alpha.js (alpha) 25 bytes [entry] [rendered] > alpha [0] ./alpha.js [0] ./alpha.js 25 bytes {1} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: e5033b72cf0ec9da1ad7 Version: webpack 3.5.1 Asset Size Chunks Chunk Names MyLibrary.beta.js 759 bytes 0 [emitted] beta MyLibrary.alpha.js 761 bytes 1 [emitted] alpha Entrypoint alpha = MyLibrary.alpha.js Entrypoint beta = MyLibrary.beta.js chunk {0} MyLibrary.beta.js (beta) 24 bytes [entry] [rendered] > beta [1] ./beta.js [1] ./beta.js 24 bytes {0} [built] chunk {1} MyLibrary.alpha.js (alpha) 25 bytes [entry] [rendered] > alpha [0] ./alpha.js [0] ./alpha.js 25 bytes {1} [built] ``` webpack-3.5.6/examples/multi-part-library/alpha.js000066400000000000000000000000311315401342100221260ustar00rootroot00000000000000module.exports = "alpha";webpack-3.5.6/examples/multi-part-library/beta.js000066400000000000000000000000301315401342100217530ustar00rootroot00000000000000module.exports = "beta";webpack-3.5.6/examples/multi-part-library/build.js000066400000000000000000000000711315401342100221440ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-3.5.6/examples/multi-part-library/template.md000066400000000000000000000032721315401342100226520ustar00rootroot00000000000000This 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}} ``` # js/MyLibrary.alpha.js ``` javascript {{js/MyLibrary.alpha.js}} ``` # js/MyLibrary.beta.js ``` javascript {{js/MyLibrary.beta.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/multi-part-library/webpack.config.js000066400000000000000000000003651315401342100237330ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: { alpha: "./alpha", beta: "./beta" }, output: { path: path.join(__dirname, "js"), filename: "MyLibrary.[name].js", library: ["MyLibrary", "[name]"], libraryTarget: "umd" } }; webpack-3.5.6/examples/multiple-commons-chunks/000077500000000000000000000000001315401342100215465ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-commons-chunks/README.md000066400000000000000000000416701315401342100230350ustar00rootroot00000000000000# pageA.js ``` javascript require("./modules/a-b-c"); require("./modules/a-b"); require("./modules/a-c"); ``` # adminPageA.js ``` javascript require("./modules/a-b-c"); require("./modules/admin"); ``` # webpack.config.js ``` javascript var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC", adminPageA: "./adminPageA", adminPageB: "./adminPageB", adminPageC: "./adminPageC", }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ name: "admin-commons", chunks: ["adminPageA", "adminPageB"] }), new CommonsChunkPlugin({ name: "commons", chunks: ["pageA", "pageB", "admin-commons"], minChunks: 2 }), new CommonsChunkPlugin({ name: "c-commons", chunks: ["pageC", "adminPageC"] }), ] }; ``` # pageA.html ``` html ``` # adminPageA.html ``` html ``` # js/commons.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ if(executeModules) { /******/ for(i=0; i < executeModules.length; i++) { /******/ result = __webpack_require__(__webpack_require__.s = executeModules[i]); /******/ } /******/ } /******/ return result; /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 7: 0, /******/ 8: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!**************************!*\ !*** ./modules/a-b-c.js ***! \**************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { /***/ }), /* 1 */, /* 2 */, /* 3 */, /* 4 */ /*!************************!*\ !*** ./modules/a-b.js ***! \************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { /***/ }) /******/ ]); ``` # js/pageA.js ``` javascript webpackJsonp([2],{ /***/ 2: /*!************************!*\ !*** ./modules/a-c.js ***! \************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { /***/ }), /***/ 5: /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./modules/a-b-c */ 0); __webpack_require__(/*! ./modules/a-b */ 4); __webpack_require__(/*! ./modules/a-c */ 2); /***/ }) },[5]); ``` # js/admin-commons.js ``` javascript webpackJsonp([4],[ /* 0 */, /* 1 */ /*!**************************!*\ !*** ./modules/admin.js ***! \**************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { /***/ }) ]); ``` # js/adminPageA.js ``` javascript webpackJsonp([6],{ /***/ 8: /*!***********************!*\ !*** ./adminPageA.js ***! \***********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./modules/a-b-c */ 0); __webpack_require__(/*! ./modules/admin */ 1); /***/ }) },[8]); ``` # Info ## Uncompressed ``` Hash: 3ef8f91b150be0e10937 Version: webpack 3.5.1 Asset Size Chunks Chunk Names pageC.js 813 bytes 0 [emitted] pageC pageB.js 573 bytes 1 [emitted] pageB pageA.js 573 bytes 2 [emitted] pageA adminPageC.js 552 bytes 3, 4 [emitted] adminPageC admin-commons.js 236 bytes 4 [emitted] admin-commons adminPageB.js 340 bytes 5 [emitted] adminPageB adminPageA.js 340 bytes 6 [emitted] adminPageA commons.js 6.24 kB 7, 8 [emitted] commons c-commons.js 5.99 kB 8 [emitted] c-commons Entrypoint pageA = commons.js pageA.js Entrypoint pageB = commons.js pageB.js Entrypoint pageC = c-commons.js pageC.js Entrypoint adminPageA = commons.js admin-commons.js adminPageA.js Entrypoint adminPageB = commons.js admin-commons.js adminPageB.js Entrypoint adminPageC = c-commons.js adminPageC.js chunk {0} pageC.js (pageC) 83 bytes {8} [initial] [rendered] > pageC [7] ./pageC.js [2] ./modules/a-c.js 0 bytes {0} {2} [built] cjs require ./modules/a-c [5] ./pageA.js 3:0-24 cjs require ./modules/a-c [7] ./pageC.js 3:0-24 [3] ./modules/b-c.js 0 bytes {0} {1} [built] cjs require ./modules/b-c [6] ./pageB.js 3:0-24 cjs require ./modules/b-c [7] ./pageC.js 2:0-24 [7] ./pageC.js 83 bytes {0} [built] chunk {1} pageB.js (pageB) 83 bytes {7} [initial] [rendered] > pageB [6] ./pageB.js [3] ./modules/b-c.js 0 bytes {0} {1} [built] cjs require ./modules/b-c [6] ./pageB.js 3:0-24 cjs require ./modules/b-c [7] ./pageC.js 2:0-24 [6] ./pageB.js 83 bytes {1} [built] chunk {2} pageA.js (pageA) 83 bytes {7} [initial] [rendered] > pageA [5] ./pageA.js [2] ./modules/a-c.js 0 bytes {0} {2} [built] cjs require ./modules/a-c [5] ./pageA.js 3:0-24 cjs require ./modules/a-c [7] ./pageC.js 3:0-24 [5] ./pageA.js 83 bytes {2} [built] chunk {3} adminPageC.js (adminPageC) 56 bytes {8} [initial] [rendered] > adminPageC [10] ./adminPageC.js [1] ./modules/admin.js 0 bytes {3} {4} [built] cjs require ./modules/admin [8] ./adminPageA.js 2:0-26 cjs require ./modules/admin [9] ./adminPageB.js 2:0-26 cjs require ./modules/admin [10] ./adminPageC.js 2:0-26 [10] ./adminPageC.js 56 bytes {3} [built] chunk {4} admin-commons.js (admin-commons) 0 bytes {7} [initial] [rendered] [1] ./modules/admin.js 0 bytes {3} {4} [built] cjs require ./modules/admin [8] ./adminPageA.js 2:0-26 cjs require ./modules/admin [9] ./adminPageB.js 2:0-26 cjs require ./modules/admin [10] ./adminPageC.js 2:0-26 chunk {5} adminPageB.js (adminPageB) 56 bytes {4} [initial] [rendered] > adminPageB [9] ./adminPageB.js [9] ./adminPageB.js 56 bytes {5} [built] chunk {6} adminPageA.js (adminPageA) 56 bytes {4} [initial] [rendered] > adminPageA [8] ./adminPageA.js [8] ./adminPageA.js 56 bytes {6} [built] chunk {7} commons.js (commons) 0 bytes [entry] [rendered] [0] ./modules/a-b-c.js 0 bytes {7} {8} [built] cjs require ./modules/a-b-c [5] ./pageA.js 1:0-26 cjs require ./modules/a-b-c [6] ./pageB.js 1:0-26 cjs require ./modules/a-b-c [7] ./pageC.js 1:0-26 cjs require ./modules/a-b-c [8] ./adminPageA.js 1:0-26 cjs require ./modules/a-b-c [9] ./adminPageB.js 1:0-26 cjs require ./modules/a-b-c [10] ./adminPageC.js 1:0-26 [4] ./modules/a-b.js 0 bytes {7} [built] cjs require ./modules/a-b [5] ./pageA.js 2:0-24 cjs require ./modules/a-b [6] ./pageB.js 2:0-24 chunk {8} c-commons.js (c-commons) 0 bytes [entry] [rendered] [0] ./modules/a-b-c.js 0 bytes {7} {8} [built] cjs require ./modules/a-b-c [5] ./pageA.js 1:0-26 cjs require ./modules/a-b-c [6] ./pageB.js 1:0-26 cjs require ./modules/a-b-c [7] ./pageC.js 1:0-26 cjs require ./modules/a-b-c [8] ./adminPageA.js 1:0-26 cjs require ./modules/a-b-c [9] ./adminPageB.js 1:0-26 cjs require ./modules/a-b-c [10] ./adminPageC.js 1:0-26 ``` ## Minimized (uglify-js, no zip) ``` Hash: 3ef8f91b150be0e10937 Version: webpack 3.5.1 Asset Size Chunks Chunk Names pageC.js 93 bytes 0 [emitted] pageC pageB.js 76 bytes 1 [emitted] pageB pageA.js 76 bytes 2 [emitted] pageA adminPageC.js 75 bytes 3, 4 [emitted] adminPageC admin-commons.js 37 bytes 4 [emitted] admin-commons adminPageB.js 53 bytes 5 [emitted] adminPageB adminPageA.js 53 bytes 6 [emitted] adminPageA commons.js 1.4 kB 7, 8 [emitted] commons c-commons.js 1.38 kB 8 [emitted] c-commons Entrypoint pageA = commons.js pageA.js Entrypoint pageB = commons.js pageB.js Entrypoint pageC = c-commons.js pageC.js Entrypoint adminPageA = commons.js admin-commons.js adminPageA.js Entrypoint adminPageB = commons.js admin-commons.js adminPageB.js Entrypoint adminPageC = c-commons.js adminPageC.js chunk {0} pageC.js (pageC) 83 bytes {8} [initial] [rendered] > pageC [7] ./pageC.js [2] ./modules/a-c.js 0 bytes {0} {2} [built] cjs require ./modules/a-c [5] ./pageA.js 3:0-24 cjs require ./modules/a-c [7] ./pageC.js 3:0-24 [3] ./modules/b-c.js 0 bytes {0} {1} [built] cjs require ./modules/b-c [6] ./pageB.js 3:0-24 cjs require ./modules/b-c [7] ./pageC.js 2:0-24 [7] ./pageC.js 83 bytes {0} [built] chunk {1} pageB.js (pageB) 83 bytes {7} [initial] [rendered] > pageB [6] ./pageB.js [3] ./modules/b-c.js 0 bytes {0} {1} [built] cjs require ./modules/b-c [6] ./pageB.js 3:0-24 cjs require ./modules/b-c [7] ./pageC.js 2:0-24 [6] ./pageB.js 83 bytes {1} [built] chunk {2} pageA.js (pageA) 83 bytes {7} [initial] [rendered] > pageA [5] ./pageA.js [2] ./modules/a-c.js 0 bytes {0} {2} [built] cjs require ./modules/a-c [5] ./pageA.js 3:0-24 cjs require ./modules/a-c [7] ./pageC.js 3:0-24 [5] ./pageA.js 83 bytes {2} [built] chunk {3} adminPageC.js (adminPageC) 56 bytes {8} [initial] [rendered] > adminPageC [10] ./adminPageC.js [1] ./modules/admin.js 0 bytes {3} {4} [built] cjs require ./modules/admin [8] ./adminPageA.js 2:0-26 cjs require ./modules/admin [9] ./adminPageB.js 2:0-26 cjs require ./modules/admin [10] ./adminPageC.js 2:0-26 [10] ./adminPageC.js 56 bytes {3} [built] chunk {4} admin-commons.js (admin-commons) 0 bytes {7} [initial] [rendered] [1] ./modules/admin.js 0 bytes {3} {4} [built] cjs require ./modules/admin [8] ./adminPageA.js 2:0-26 cjs require ./modules/admin [9] ./adminPageB.js 2:0-26 cjs require ./modules/admin [10] ./adminPageC.js 2:0-26 chunk {5} adminPageB.js (adminPageB) 56 bytes {4} [initial] [rendered] > adminPageB [9] ./adminPageB.js [9] ./adminPageB.js 56 bytes {5} [built] chunk {6} adminPageA.js (adminPageA) 56 bytes {4} [initial] [rendered] > adminPageA [8] ./adminPageA.js [8] ./adminPageA.js 56 bytes {6} [built] chunk {7} commons.js (commons) 0 bytes [entry] [rendered] [0] ./modules/a-b-c.js 0 bytes {7} {8} [built] cjs require ./modules/a-b-c [5] ./pageA.js 1:0-26 cjs require ./modules/a-b-c [6] ./pageB.js 1:0-26 cjs require ./modules/a-b-c [7] ./pageC.js 1:0-26 cjs require ./modules/a-b-c [8] ./adminPageA.js 1:0-26 cjs require ./modules/a-b-c [9] ./adminPageB.js 1:0-26 cjs require ./modules/a-b-c [10] ./adminPageC.js 1:0-26 [4] ./modules/a-b.js 0 bytes {7} [built] cjs require ./modules/a-b [5] ./pageA.js 2:0-24 cjs require ./modules/a-b [6] ./pageB.js 2:0-24 chunk {8} c-commons.js (c-commons) 0 bytes [entry] [rendered] [0] ./modules/a-b-c.js 0 bytes {7} {8} [built] cjs require ./modules/a-b-c [5] ./pageA.js 1:0-26 cjs require ./modules/a-b-c [6] ./pageB.js 1:0-26 cjs require ./modules/a-b-c [7] ./pageC.js 1:0-26 cjs require ./modules/a-b-c [8] ./adminPageA.js 1:0-26 cjs require ./modules/a-b-c [9] ./adminPageB.js 1:0-26 cjs require ./modules/a-b-c [10] ./adminPageC.js 1:0-26 ``` webpack-3.5.6/examples/multiple-commons-chunks/adminPageA.html000066400000000000000000000003371315401342100244250ustar00rootroot00000000000000 webpack-3.5.6/examples/multiple-commons-chunks/adminPageA.js000066400000000000000000000000671315401342100240750ustar00rootroot00000000000000require("./modules/a-b-c"); require("./modules/admin");webpack-3.5.6/examples/multiple-commons-chunks/adminPageB.js000066400000000000000000000000671315401342100240760ustar00rootroot00000000000000require("./modules/a-b-c"); require("./modules/admin");webpack-3.5.6/examples/multiple-commons-chunks/adminPageC.js000066400000000000000000000000671315401342100240770ustar00rootroot00000000000000require("./modules/a-b-c"); require("./modules/admin");webpack-3.5.6/examples/multiple-commons-chunks/build.js000066400000000000000000000000721315401342100232020ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-3.5.6/examples/multiple-commons-chunks/common.js000066400000000000000000000000321315401342100233670ustar00rootroot00000000000000module.exports = "Common";webpack-3.5.6/examples/multiple-commons-chunks/modules/000077500000000000000000000000001315401342100232165ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-commons-chunks/modules/a-b-c.js000066400000000000000000000000001315401342100244210ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-commons-chunks/modules/a-b.js000066400000000000000000000000001315401342100242010ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-commons-chunks/modules/a-c.js000066400000000000000000000000001315401342100242020ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-commons-chunks/modules/admin.js000066400000000000000000000000001315401342100246320ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-commons-chunks/modules/b-c.js000066400000000000000000000000001315401342100242030ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-commons-chunks/pageA.html000066400000000000000000000002341315401342100234500ustar00rootroot00000000000000 webpack-3.5.6/examples/multiple-commons-chunks/pageA.js000066400000000000000000000001201315401342100231120ustar00rootroot00000000000000require("./modules/a-b-c"); require("./modules/a-b"); require("./modules/a-c"); webpack-3.5.6/examples/multiple-commons-chunks/pageB.js000066400000000000000000000001201315401342100231130ustar00rootroot00000000000000require("./modules/a-b-c"); require("./modules/a-b"); require("./modules/b-c"); webpack-3.5.6/examples/multiple-commons-chunks/pageC.js000066400000000000000000000001201315401342100231140ustar00rootroot00000000000000require("./modules/a-b-c"); require("./modules/b-c"); require("./modules/a-c"); webpack-3.5.6/examples/multiple-commons-chunks/template.md000066400000000000000000000011231315401342100237000ustar00rootroot00000000000000# pageA.js ``` javascript {{pageA.js}} ``` # adminPageA.js ``` javascript {{adminPageA.js}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # pageA.html ``` html {{pageA.html}} ``` # adminPageA.html ``` html {{adminPageA.html}} ``` # js/commons.js ``` javascript {{js/commons.js}} ``` # js/pageA.js ``` javascript {{js/pageA.js}} ``` # js/admin-commons.js ``` javascript {{js/admin-commons.js}} ``` # js/adminPageA.js ``` javascript {{js/adminPageA.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/multiple-commons-chunks/webpack.config.js000066400000000000000000000012551315401342100247670ustar00rootroot00000000000000var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { pageA: "./pageA", pageB: "./pageB", pageC: "./pageC", adminPageA: "./adminPageA", adminPageB: "./adminPageB", adminPageC: "./adminPageC", }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ name: "admin-commons", chunks: ["adminPageA", "adminPageB"] }), new CommonsChunkPlugin({ name: "commons", chunks: ["pageA", "pageB", "admin-commons"], minChunks: 2 }), new CommonsChunkPlugin({ name: "c-commons", chunks: ["pageC", "adminPageC"] }), ] }; webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/000077500000000000000000000000001315401342100260715ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/README.md000066400000000000000000000275411315401342100273610ustar00rootroot00000000000000 # a.js ``` javascript require("./style.css"); require("./styleA.css"); ``` # b.js ``` javascript require("./style.css"); require("./styleB.css"); ``` # c.js ``` javascript require("./styleC.css"); ``` # style.css ``` css body { background: url(image.png); } ``` # styleA.css ``` css .a { background: url(imageA.png); } ``` # styleB.css ``` css .b { background: url(imageB.png); } ``` # styleC.css ``` css @import "style.css"; .c { background: url(imageC.png); } ``` # webpack.config.js ``` javascript var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { entry: { A: "./a", B: "./b", C: "./c", }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, module: { loaders: [ { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.png$/, loader: "file-loader" } ] }, plugins: [ new CommonsChunkPlugin({ name: "commons", filename: "commons.js", chunks: ["A", "B"] }), new ExtractTextPlugin({ filename: "[name].css" }), ] }; ``` # js/A.js ``` javascript webpackJsonp([1],[ /* 0 */, /* 1 */ /*!**************!*\ !*** ./a.js ***! \**************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./style.css */ 0); __webpack_require__(/*! ./styleA.css */ 2); /***/ }), /* 2 */ /*!********************!*\ !*** ./styleA.css ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }) ],[1]); ``` # js/commons.css ``` css body { background: url(js/ce21cbdd9b894e6af794813eb3fdaf60.png); } ``` # js/A.css ``` css .a { background: url(js/d090b6fba0f6d326d282a19146ff54a7.png); } ``` # js/B.css ``` css .b { background: url(js/16155c689e517682064c99893cb832cc.png); } ``` # js/B.css (Minimized) ``` css .b{background:url(js/16155c689e517682064c99893cb832cc.png)} ``` # js/C.css ``` css body { background: url(js/ce21cbdd9b894e6af794813eb3fdaf60.png); } .c { background: url(js/c2a2f62d69330b7d787782f5010f9d13.png); } ``` # js/C.css (Minimized) ``` css body{background:url(js/ce21cbdd9b894e6af794813eb3fdaf60.png)}.c{background:url(js/c2a2f62d69330b7d787782f5010f9d13.png)} ``` # Info ## Uncompressed ``` Hash: b6d05f310264e74bb969 Version: webpack 3.5.1 Asset Size Chunks Chunk Names C.js 2.89 kB 2 [emitted] C d090b6fba0f6d326d282a19146ff54a7.png 120 bytes [emitted] ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] c2a2f62d69330b7d787782f5010f9d13.png 120 bytes [emitted] B.js 561 bytes 0 [emitted] B A.js 543 bytes 1 [emitted] A 16155c689e517682064c99893cb832cc.png 120 bytes [emitted] commons.js 6.01 kB 3 [emitted] commons A.css 69 bytes 1 [emitted] A B.css 69 bytes 0 [emitted] B C.css 140 bytes 2 [emitted] C commons.css 71 bytes 3 [emitted] commons Entrypoint A = commons.js commons.css A.js A.css Entrypoint B = commons.js commons.css B.js B.css Entrypoint C = C.js C.css chunk {0} B.js, B.css (B) 92 bytes {3} [initial] [rendered] > B [3] ./b.js [3] ./b.js 51 bytes {0} [built] [4] ./styleB.css 41 bytes {0} [built] cjs require ./styleB.css [3] ./b.js 2:0-23 chunk {1} A.js, A.css (A) 92 bytes {3} [initial] [rendered] > A [1] ./a.js [1] ./a.js 51 bytes {1} [built] [2] ./styleA.css 41 bytes {1} [built] cjs require ./styleA.css [1] ./a.js 2:0-23 chunk {2} C.js, C.css (C) 67 bytes [entry] [rendered] > C [5] ./c.js [5] ./c.js 26 bytes {2} [built] [6] ./styleC.css 41 bytes {2} [built] cjs require ./styleC.css [5] ./c.js 1:0-23 chunk {3} commons.js, commons.css (commons) 41 bytes [entry] [rendered] [0] ./style.css 41 bytes {3} [built] cjs require ./style.css [1] ./a.js 1:0-22 cjs require ./style.css [3] ./b.js 1:0-22 Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!styleA.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!./styleA.css [0] (webpack)/node_modules/css-loader!./styleA.css 234 bytes {0} [built] [2] ./imageA.png 82 bytes {0} [built] cjs require ./imageA.png [0] (webpack)/node_modules/css-loader!./styleA.css 6:56-79 + 1 hidden module Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!styleB.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!./styleB.css [0] (webpack)/node_modules/css-loader!./styleB.css 234 bytes {0} [built] [2] ./imageB.png 82 bytes {0} [built] cjs require ./imageB.png [0] (webpack)/node_modules/css-loader!./styleB.css 6:56-79 + 1 hidden module 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 Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!styleC.css: 2 assets Entrypoint undefined = extract-text-webpack-plugin-output-filename chunk {0} extract-text-webpack-plugin-output-filename 2.97 kB [entry] [rendered] > [1] (webpack)/node_modules/css-loader!./styleC.css [1] (webpack)/node_modules/css-loader!./styleC.css 313 bytes {0} [built] [2] (webpack)/node_modules/css-loader!./style.css 235 bytes {0} [built] cjs require -!../../node_modules/css-loader/index.js!./style.css [1] (webpack)/node_modules/css-loader!./styleC.css 3:10-73 [3] ./image.png 82 bytes {0} [built] cjs require ./image.png [2] (webpack)/node_modules/css-loader!./style.css 6:58-80 [4] ./imageC.png 82 bytes {0} [built] cjs require ./imageC.png [1] (webpack)/node_modules/css-loader!./styleC.css 6:56-79 + 1 hidden module ``` ## Minimized (uglify-js, no zip) ``` Hash: 71684330ef0116733460 Version: webpack 3.5.1 Asset Size Chunks Chunk Names C.js 508 bytes 2 [emitted] C d090b6fba0f6d326d282a19146ff54a7.png 120 bytes [emitted] ce21cbdd9b894e6af794813eb3fdaf60.png 119 bytes [emitted] c2a2f62d69330b7d787782f5010f9d13.png 120 bytes [emitted] B.js 70 bytes 0 [emitted] B A.js 68 bytes 1 [emitted] A 16155c689e517682064c99893cb832cc.png 120 bytes [emitted] commons.js 1.38 kB 3 [emitted] commons A.css 59 bytes 1 [emitted] A B.css 59 bytes 0 [emitted] B C.css 120 bytes 2 [emitted] C commons.css 61 bytes 3 [emitted] commons Entrypoint A = commons.js commons.css A.js A.css Entrypoint B = commons.js commons.css B.js B.css Entrypoint C = C.js C.css chunk {0} B.js, B.css (B) 92 bytes {3} [initial] [rendered] > B [3] ./b.js [3] ./b.js 51 bytes {0} [built] [4] ./styleB.css 41 bytes {0} [built] cjs require ./styleB.css [3] ./b.js 2:0-23 chunk {1} A.js, A.css (A) 92 bytes {3} [initial] [rendered] > A [1] ./a.js [1] ./a.js 51 bytes {1} [built] [2] ./styleA.css 41 bytes {1} [built] cjs require ./styleA.css [1] ./a.js 2:0-23 chunk {2} C.js, C.css (C) 67 bytes [entry] [rendered] > C [5] ./c.js [5] ./c.js 26 bytes {2} [built] [6] ./styleC.css 41 bytes {2} [built] cjs require ./styleC.css [5] ./c.js 1:0-23 chunk {3} commons.js, commons.css (commons) 41 bytes [entry] [rendered] [0] ./style.css 41 bytes {3} [built] cjs require ./style.css [1] ./a.js 1:0-22 cjs require ./style.css [3] ./b.js 1:0-22 Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!styleA.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!./styleA.css [0] (webpack)/node_modules/css-loader!./styleA.css 217 bytes {0} [built] [2] ./imageA.png 82 bytes {0} [built] cjs require ./imageA.png [0] (webpack)/node_modules/css-loader!./styleA.css 6:48-71 + 1 hidden module Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!styleB.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!./styleB.css [0] (webpack)/node_modules/css-loader!./styleB.css 217 bytes {0} [built] [2] ./imageB.png 82 bytes {0} [built] cjs require ./imageB.png [0] (webpack)/node_modules/css-loader!./styleB.css 6:48-71 + 1 hidden module 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 Child extract-text-webpack-plugin ../../node_modules/extract-text-webpack-plugin/dist ../../node_modules/css-loader/index.js!styleC.css: 2 assets Entrypoint undefined = extract-text-webpack-plugin-output-filename chunk {0} extract-text-webpack-plugin-output-filename 2.94 kB [entry] [rendered] > [1] (webpack)/node_modules/css-loader!./styleC.css [1] (webpack)/node_modules/css-loader!./styleC.css 296 bytes {0} [built] [2] (webpack)/node_modules/css-loader!./style.css 218 bytes {0} [built] cjs require -!../../node_modules/css-loader/index.js!./style.css [1] (webpack)/node_modules/css-loader!./styleC.css 3:10-73 [3] ./image.png 82 bytes {0} [built] cjs require ./image.png [2] (webpack)/node_modules/css-loader!./style.css 6:50-72 [4] ./imageC.png 82 bytes {0} [built] cjs require ./imageC.png [1] (webpack)/node_modules/css-loader!./styleC.css 6:48-71 + 1 hidden module ``` webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/a.js000066400000000000000000000000611315401342100266440ustar00rootroot00000000000000require("./style.css"); require("./styleA.css"); webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/b.js000066400000000000000000000000611315401342100266450ustar00rootroot00000000000000require("./style.css"); require("./styleB.css"); webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/build.js000066400000000000000000000000711315401342100275240ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common");webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/c.js000066400000000000000000000000311315401342100266430ustar00rootroot00000000000000require("./styleC.css"); webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/image.png000066400000000000000000000001671315401342100276650ustar00rootroot00000000000000PNG  IHDRwSsRGBgAMA a pHYsod IDATWc?5IENDB`webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/imageA.png000066400000000000000000000001701315401342100277600ustar00rootroot00000000000000PNG  IHDRĉsRGBgAMA a pHYs(J IDATWcx+T-=IENDB`webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/imageB.png000066400000000000000000000001701315401342100277610ustar00rootroot00000000000000PNG  IHDRĉsRGBgAMA a pHYs(J IDATWc?"IENDB`webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/imageC.png000066400000000000000000000001701315401342100277620ustar00rootroot00000000000000PNG  IHDRĉsRGBgAMA a pHYs(J IDATWc? OIENDB`webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/style.css000066400000000000000000000000461315401342100277430ustar00rootroot00000000000000body { background: url(image.png); } webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/styleA.css000066400000000000000000000000451315401342100300430ustar00rootroot00000000000000.a { background: url(imageA.png); } webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/styleB.css000066400000000000000000000000451315401342100300440ustar00rootroot00000000000000.b { background: url(imageB.png); } webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/styleC.css000066400000000000000000000000721315401342100300450ustar00rootroot00000000000000@import "style.css"; .c { background: url(imageC.png); } webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/template.md000066400000000000000000000013661315401342100302340ustar00rootroot00000000000000 # a.js ``` javascript {{a.js}} ``` # b.js ``` javascript {{b.js}} ``` # c.js ``` javascript {{c.js}} ``` # style.css ``` css {{style.css}} ``` # styleA.css ``` css {{styleA.css}} ``` # styleB.css ``` css {{styleB.css}} ``` # styleC.css ``` css {{styleC.css}} ``` # webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/A.js ``` javascript {{js/A.js}} ``` # js/commons.css ``` css {{js/commons.css}} ``` # js/A.css ``` css {{js/A.css}} ``` # js/B.css ``` css {{js/B.css}} ``` # js/B.css (Minimized) ``` css {{min:js/B.css}} ``` # js/C.css ``` css {{js/C.css}} ``` # js/C.css (Minimized) ``` css {{min:js/C.css}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/multiple-entry-points-commons-chunk-css-bundle/webpack.config.js000066400000000000000000000012671315401342100313150ustar00rootroot00000000000000var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { entry: { A: "./a", B: "./b", C: "./c", }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, module: { loaders: [ { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.png$/, loader: "file-loader" } ] }, plugins: [ new CommonsChunkPlugin({ name: "commons", filename: "commons.js", chunks: ["A", "B"] }), new ExtractTextPlugin({ filename: "[name].css" }), ] }; webpack-3.5.6/examples/multiple-entry-points/000077500000000000000000000000001315401342100212555ustar00rootroot00000000000000webpack-3.5.6/examples/multiple-entry-points/README.md000066400000000000000000000305361315401342100225430ustar00rootroot00000000000000This 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 and the required changes (`[name]`) in the `output` option. You can also see how to use the CommonsChunkPlugin. You can see the output files: * `commons.js` contains: * the module system * chunk loading logic * module `common.js` which is used in both pages * `pageA.bundle.js` contains: (`pageB.bundle.js` is similar) * 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 var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { pageA: "./pageA", pageB: "./pageB" }, output: { path: path.join(__dirname, "js"), filename: "[name].bundle.js", chunkFilename: "[id].chunk.js" }, plugins: [ new CommonsChunkPlugin({ filename: "commons.js", name: "commons" }) ] }; ``` # pageA.html ``` html ``` # js/commons.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ if(executeModules) { /******/ for(i=0; i < executeModules.length; i++) { /******/ result = __webpack_require__(__webpack_require__.s = executeModules[i]); /******/ } /******/ } /******/ return result; /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 3: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".chunk.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!*******************!*\ !*** ./common.js ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "Common"; /***/ }) /******/ ]); ``` # js/pageA.bundle.js ``` javascript webpackJsonp([2],{ /***/ 2: /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var common = __webpack_require__(/*! ./common */ 0); __webpack_require__.e/* require */(0).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); /***/ }) },[2]); ``` # js/pageB.bundle.js ``` javascript webpackJsonp([1],{ /***/ 3: /*!******************!*\ !*** ./pageB.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var common = __webpack_require__(/*! ./common */ 0); __webpack_require__.e/* require.ensure */(0/* duplicate */).then((function(require) { var shared = __webpack_require__(/*! ./shared */ 1); shared("This is page B"); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); /***/ }) },[3]); ``` # js/0.chunk.js ``` javascript webpackJsonp([0],[ /* 0 */, /* 1 */ /*!*******************!*\ !*** ./shared.js ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var common = __webpack_require__(/*! ./common */ 0); module.exports = function(msg) { console.log(msg); }; /***/ }) ]); ``` # Info ## Uncompressed ``` Hash: 4f8af9066e2b5dda0f23 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.chunk.js 346 bytes 0 [emitted] pageB.bundle.js 521 bytes 1 [emitted] pageB pageA.bundle.js 547 bytes 2 [emitted] pageA commons.js 6 kB 3 [emitted] commons Entrypoint pageA = commons.js pageA.bundle.js Entrypoint pageB = commons.js pageB.bundle.js chunk {0} 0.chunk.js 91 bytes {1} {2} [rendered] > duplicate [2] ./pageA.js 2:0-4:2 > duplicate [3] ./pageB.js 2:0-5:2 [1] ./shared.js 91 bytes {0} [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 {1} pageB.bundle.js (pageB) 152 bytes {3} [initial] [rendered] > pageB [3] ./pageB.js [3] ./pageB.js 152 bytes {1} [built] chunk {2} pageA.bundle.js (pageA) 108 bytes {3} [initial] [rendered] > pageA [2] ./pageA.js [2] ./pageA.js 108 bytes {2} [built] chunk {3} commons.js (commons) 26 bytes [entry] [rendered] [0] ./common.js 26 bytes {3} [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 ``` ## Minimized (uglify-js, no zip) ``` Hash: 4f8af9066e2b5dda0f23 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.chunk.js 81 bytes 0 [emitted] pageB.bundle.js 122 bytes 1 [emitted] pageB pageA.bundle.js 147 bytes 2 [emitted] pageA commons.js 1.4 kB 3 [emitted] commons Entrypoint pageA = commons.js pageA.bundle.js Entrypoint pageB = commons.js pageB.bundle.js chunk {0} 0.chunk.js 91 bytes {1} {2} [rendered] > duplicate [2] ./pageA.js 2:0-4:2 > duplicate [3] ./pageB.js 2:0-5:2 [1] ./shared.js 91 bytes {0} [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 {1} pageB.bundle.js (pageB) 152 bytes {3} [initial] [rendered] > pageB [3] ./pageB.js [3] ./pageB.js 152 bytes {1} [built] chunk {2} pageA.bundle.js (pageA) 108 bytes {3} [initial] [rendered] > pageA [2] ./pageA.js [2] ./pageA.js 108 bytes {2} [built] chunk {3} commons.js (commons) 26 bytes [entry] [rendered] [0] ./common.js 26 bytes {3} [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 ``` webpack-3.5.6/examples/multiple-entry-points/build.js000066400000000000000000000000721315401342100227110ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-3.5.6/examples/multiple-entry-points/common.js000066400000000000000000000000321315401342100230760ustar00rootroot00000000000000module.exports = "Common";webpack-3.5.6/examples/multiple-entry-points/pageA.html000066400000000000000000000002431315401342100231570ustar00rootroot00000000000000 webpack-3.5.6/examples/multiple-entry-points/pageA.js000066400000000000000000000001511315401342100226250ustar00rootroot00000000000000var common = require("./common"); require(["./shared"], function(shared) { shared("This is page A"); });webpack-3.5.6/examples/multiple-entry-points/pageAB.html000066400000000000000000000003401315401342100232570ustar00rootroot00000000000000 webpack-3.5.6/examples/multiple-entry-points/pageB.js000066400000000000000000000002241315401342100226270ustar00rootroot00000000000000var common = require("./common"); require.ensure(["./shared"], function(require) { var shared = require("./shared"); shared("This is page B"); });webpack-3.5.6/examples/multiple-entry-points/shared.js000066400000000000000000000001301315401342100230530ustar00rootroot00000000000000var common = require("./common"); module.exports = function(msg) { console.log(msg); };webpack-3.5.6/examples/multiple-entry-points/template.md000066400000000000000000000035371315401342100234220ustar00rootroot00000000000000This 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 and the required changes (`[name]`) in the `output` option. You can also see how to use the CommonsChunkPlugin. You can see the output files: * `commons.js` contains: * the module system * chunk loading logic * module `common.js` which is used in both pages * `pageA.bundle.js` contains: (`pageB.bundle.js` is similar) * 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}} ``` # js/commons.js ``` javascript {{js/commons.js}} ``` # js/pageA.bundle.js ``` javascript {{js/pageA.bundle.js}} ``` # js/pageB.bundle.js ``` javascript {{js/pageB.bundle.js}} ``` # js/0.chunk.js ``` javascript {{js/0.chunk.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/multiple-entry-points/webpack.config.js000066400000000000000000000006031315401342100244720ustar00rootroot00000000000000var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { pageA: "./pageA", pageB: "./pageB" }, output: { path: path.join(__dirname, "js"), filename: "[name].bundle.js", chunkFilename: "[id].chunk.js" }, plugins: [ new CommonsChunkPlugin({ filename: "commons.js", name: "commons" }) ] }; webpack-3.5.6/examples/named-chunks/000077500000000000000000000000001315401342100173265ustar00rootroot00000000000000webpack-3.5.6/examples/named-chunks/README.md000066400000000000000000000243261315401342100206140ustar00rootroot00000000000000# 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"); }); ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 2: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */, /* 1 */, /* 2 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var a = __webpack_require__(/*! a */ 3); __webpack_require__.e/* require.ensure */(0/*! my own chunk */).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 */(0/*! my own chunk */).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 */(0/*! my own chunk */).then((function(require) { // the same again }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); __webpack_require__.e/* require.ensure */(1).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 */ /*! all exports used */ /***/ (function(module, exports) { // module a /***/ }) /******/ ]); ``` # js/0.output.js ``` javascript webpackJsonp([0,1],[ /* 0 */ /*!***************************!*\ !*** ./node_modules/b.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module b /***/ }), /* 1 */ /*!***************************!*\ !*** ./node_modules/d.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module d /***/ }), /* 2 */, /* 3 */, /* 4 */ /*!***************************!*\ !*** ./node_modules/c.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module c /***/ }) ]); ``` # js/1.output.js ``` javascript webpackJsonp([1],[ /* 0 */ /*!***************************!*\ !*** ./node_modules/b.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module b /***/ }), /* 1 */ /*!***************************!*\ !*** ./node_modules/d.js ***! \***************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { // module d /***/ }) ]); ``` # Info ## Uncompressed ``` Hash: 1e92144469a06ecc61e5 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 701 bytes 0, 1 [emitted] my own chunk 1.output.js 461 bytes 1 [emitted] output.js 7.04 kB 2 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (my own chunk) 33 bytes {2} [rendered] > my own chunk [2] ./example.js 3:0-6:18 > my own chunk [2] ./example.js 8:0-11:18 > my own chunk [2] ./example.js 13:0-15:18 3 modules chunk {1} 1.output.js 22 bytes {2} [rendered] > [2] ./example.js 17:0-20:2 2 modules chunk {2} output.js (main) 452 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 441 bytes {2} [built] + 1 hidden module ``` ## Minimized (uglify-js, no zip) ``` Hash: 1e92144469a06ecc61e5 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 72 bytes 0, 1 [emitted] my own chunk 1.output.js 52 bytes 1 [emitted] output.js 1.58 kB 2 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js (my own chunk) 33 bytes {2} [rendered] > my own chunk [2] ./example.js 3:0-6:18 > my own chunk [2] ./example.js 8:0-11:18 > my own chunk [2] ./example.js 13:0-15:18 3 modules chunk {1} 1.output.js 22 bytes {2} [rendered] > [2] ./example.js 17:0-20:2 2 modules chunk {2} output.js (main) 452 bytes [entry] [rendered] > main [2] ./example.js [2] ./example.js 441 bytes {2} [built] + 1 hidden module ``` webpack-3.5.6/examples/named-chunks/build.js000066400000000000000000000000331315401342100207570ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/named-chunks/example.js000066400000000000000000000006451315401342100213240ustar00rootroot00000000000000var 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-3.5.6/examples/named-chunks/node_modules/000077500000000000000000000000001315401342100220035ustar00rootroot00000000000000webpack-3.5.6/examples/named-chunks/node_modules/a.js000066400000000000000000000000131315401342100225530ustar00rootroot00000000000000// module awebpack-3.5.6/examples/named-chunks/node_modules/b.js000066400000000000000000000000131315401342100225540ustar00rootroot00000000000000// module bwebpack-3.5.6/examples/named-chunks/node_modules/c.js000066400000000000000000000000131315401342100225550ustar00rootroot00000000000000// module cwebpack-3.5.6/examples/named-chunks/node_modules/d.js000066400000000000000000000000131315401342100225560ustar00rootroot00000000000000// module dwebpack-3.5.6/examples/named-chunks/template.md000066400000000000000000000004771315401342100214730ustar00rootroot00000000000000# example.js ``` javascript {{example.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` # js/1.output.js ``` javascript {{js/1.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/node_modules/000077500000000000000000000000001315401342100174265ustar00rootroot00000000000000webpack-3.5.6/examples/node_modules/module.js000066400000000000000000000000321315401342100212440ustar00rootroot00000000000000module.exports = "module";webpack-3.5.6/examples/require.context/000077500000000000000000000000001315401342100201105ustar00rootroot00000000000000webpack-3.5.6/examples/require.context/README.md000066400000000000000000000155421315401342100213760ustar00rootroot00000000000000# 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"; } ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!************************!*\ !*** ./templates/a.js ***! \************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 1 */ /*!************************!*\ !*** ./templates/b.js ***! \************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 2 */ /*!************************!*\ !*** ./templates/c.js ***! \************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }), /* 3 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { function getTemplate(templateName) { return __webpack_require__(/*! ./templates */ 4)("./"+templateName); } console.log(getTemplate("a")); console.log(getTemplate("b")); /***/ }), /* 4 */ /*!****************************!*\ !*** ./templates ^\.\/.*$ ***! \****************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var map = { "./a": 0, "./a.js": 0, "./b": 1, "./b.js": 1, "./c": 2, "./c.js": 2 }; function webpackContext(req) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 4; /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: acf02a400c4d02cc105a Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 4.42 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 613 bytes [entry] [rendered] > main [3] ./example.js [0] ./templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [4] ./templates ^\.\/.*$ ./a.js context element ./a [4] ./templates ^\.\/.*$ ./a [1] ./templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [4] ./templates ^\.\/.*$ ./b.js context element ./b [4] ./templates ^\.\/.*$ ./b [2] ./templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [4] ./templates ^\.\/.*$ ./c.js context element ./c [4] ./templates ^\.\/.*$ ./c [3] ./example.js 150 bytes {0} [built] [4] ./templates ^\.\/.*$ 217 bytes {0} [built] cjs require context ./templates [3] ./example.js 2:8-44 ``` ## Minimized (uglify-js, no zip) ``` Hash: acf02a400c4d02cc105a Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 1.08 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 613 bytes [entry] [rendered] > main [3] ./example.js [0] ./templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [4] ./templates ^\.\/.*$ ./a.js context element ./a [4] ./templates ^\.\/.*$ ./a [1] ./templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [4] ./templates ^\.\/.*$ ./b.js context element ./b [4] ./templates ^\.\/.*$ ./b [2] ./templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [4] ./templates ^\.\/.*$ ./c.js context element ./c [4] ./templates ^\.\/.*$ ./c [3] ./example.js 150 bytes {0} [built] [4] ./templates ^\.\/.*$ 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-3.5.6/examples/require.context/build.js000066400000000000000000000000331315401342100215410ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/require.context/example.js000066400000000000000000000002221315401342100220750ustar00rootroot00000000000000function getTemplate(templateName) { return require("./templates/"+templateName); } console.log(getTemplate("a")); console.log(getTemplate("b"));webpack-3.5.6/examples/require.context/template.md000066400000000000000000000007361315401342100222530ustar00rootroot00000000000000# 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"; } ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` # Code Splitting See [this example combined with code splitting](../code-splitted-require.context) webpack-3.5.6/examples/require.context/templates/000077500000000000000000000000001315401342100221065ustar00rootroot00000000000000webpack-3.5.6/examples/require.context/templates/a.js000066400000000000000000000001201315401342100226550ustar00rootroot00000000000000module.exports = function() { return "This text was generated by template A"; }webpack-3.5.6/examples/require.context/templates/b.js000066400000000000000000000001201315401342100226560ustar00rootroot00000000000000module.exports = function() { return "This text was generated by template B"; }webpack-3.5.6/examples/require.context/templates/c.js000066400000000000000000000001201315401342100226570ustar00rootroot00000000000000module.exports = function() { return "This text was generated by template C"; }webpack-3.5.6/examples/require.resolve/000077500000000000000000000000001315401342100201035ustar00rootroot00000000000000webpack-3.5.6/examples/require.resolve/README.md000066400000000000000000000112561315401342100213670ustar00rootroot00000000000000# 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"); // vertify it if(a == a2) throw new Error("Cache clear failed :("); ``` # a.js ``` javascript module.exports = Math.random(); ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 1); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!**************!*\ !*** ./a.js ***! \**************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = Math.random(); /***/ }), /* 1 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var a = __webpack_require__(/*! ./a */ 0); // get module id var aId = /*require.resolve*/(/*! ./a.js */ 0); // clear module in require.cache delete __webpack_require__.c[aId]; // require module again, it should be reexecuted var a2 = __webpack_require__(/*! ./a */ 0); // vertify it if(a == a2) throw new Error("Cache clear failed :("); /***/ }) /******/ ]); ``` # Info ## Uncompressed ``` Hash: 4ed342adc60583d992ab Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 3.18 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 326 bytes [entry] [rendered] > main [1] ./example.js [0] ./a.js 31 bytes {0} [built] require.resolve ./a.js [1] ./example.js 4:10-35 cjs require ./a [1] ./example.js 1:8-22 cjs require ./a [1] ./example.js 10:9-23 [1] ./example.js 295 bytes {0} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: 4ed342adc60583d992ab Version: webpack 3.5.1 Asset Size Chunks Chunk Names output.js 599 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 326 bytes [entry] [rendered] > main [1] ./example.js [0] ./a.js 31 bytes {0} [built] require.resolve ./a.js [1] ./example.js 4:10-35 cjs require ./a [1] ./example.js 1:8-22 cjs require ./a [1] ./example.js 10:9-23 [1] ./example.js 295 bytes {0} [built] ``` webpack-3.5.6/examples/require.resolve/a.js000066400000000000000000000000371315401342100206610ustar00rootroot00000000000000module.exports = Math.random();webpack-3.5.6/examples/require.resolve/build.js000066400000000000000000000000331315401342100215340ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/require.resolve/example.js000066400000000000000000000004331315401342100220740ustar00rootroot00000000000000var 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"); // vertify it if(a == a2) throw new Error("Cache clear failed :(");webpack-3.5.6/examples/require.resolve/template.md000066400000000000000000000003621315401342100222410ustar00rootroot00000000000000# example.js ``` javascript {{example.js}} ``` # a.js ``` javascript {{a.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/scope-hoisting/000077500000000000000000000000001315401342100177045ustar00rootroot00000000000000webpack-3.5.6/examples/scope-hoisting/README.md000066400000000000000000000326611315401342100211730ustar00rootroot00000000000000This 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 concatentation 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 var webpack = require("../../"); module.exports = { plugins: [ new webpack.optimize.ModuleConcatenationPlugin() ] }; ``` # js/output.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".output.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // 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"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); // 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 */__webpack_require__.d(__webpack_exports__, "b", function() { return y; }); // shared module var x = "x"; /***/ }), /* 1 */ /*!********************************!*\ !*** ./example.js + 2 modules ***! \********************************/ /*! exports provided: */ /*! all exports used */ /*! ModuleConcatenation bailout: Module is an entry point */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); // 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() */(0).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); }); /***/ }) /******/ ]); ``` # js/0.output.js ``` javascript webpackJsonp([0],[ /* 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: Module is referenced from these modules with unsupported syntax: ./example.js (referenced with import()) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); var d_namespaceObject = {}; __webpack_require__.d(d_namespaceObject, "a", function() { return a; }); // EXTERNAL MODULE: ./node_modules/cjs.js var cjs = __webpack_require__(2); var cjs_default = /*#__PURE__*/__webpack_require__.n(cjs); // 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 */__webpack_require__.d(__webpack_exports__, "c", function() { return c; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "x", function() { return shared["a" /* x */]; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "y", function() { return shared["b" /* y */]; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "d", function() { return d_namespaceObject; }); /***/ }) ]); ``` Minimized ``` javascript webpackJsonp([0],[,,function(n,r){r.c="e"},function(n,r,t){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var e={};t.d(e,"a",function(){return d});var u=t(2),c=t(0),o=String.fromCharCode(u.c.charCodeAt(0)-2),d="d";t.d(r,"c",function(){return o}),t.d(r,"x",function(){return c.a}),t.d(r,"y",function(){return c.b}),t.d(r,"d",function(){return e})}]); ``` # Info ## Uncompressed ``` Hash: 6596ce0a50ccbbaa89c6 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 1.9 kB 0 [emitted] output.js 7.39 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 286 bytes {1} [rendered] > [] 4:0-16 [3] ./lazy.js + 2 modules 242 bytes {0} [built] [exports: d, c, x, y] import() ./lazy [] ./example.js 4:0-16 + 1 hidden module chunk {1} output.js (main) 390 bytes [entry] [rendered] > main [] [0] ./node_modules/shared.js + 1 modules 105 bytes {1} [built] [exports: x, y] [only some exports used: x, y] harmony import shared [1] ./example.js + 2 modules 3:0-23 harmony import shared [3] ./lazy.js + 2 modules 6:0-30 [1] ./example.js + 2 modules 285 bytes {1} [built] [no exports] ``` ## Minimized (uglify-js, no zip) ``` Hash: 6596ce0a50ccbbaa89c6 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.output.js 364 bytes 0 [emitted] output.js 1.66 kB 1 [emitted] main Entrypoint main = output.js chunk {0} 0.output.js 286 bytes {1} [rendered] > [] 4:0-16 [3] ./lazy.js + 2 modules 242 bytes {0} [built] [exports: d, c, x, y] import() ./lazy [] ./example.js 4:0-16 + 1 hidden module chunk {1} output.js (main) 390 bytes [entry] [rendered] > main [] [0] ./node_modules/shared.js + 1 modules 105 bytes {1} [built] [exports: x, y] [only some exports used: x, y] harmony import shared [1] ./example.js + 2 modules 3:0-23 harmony import shared [3] ./lazy.js + 2 modules 6:0-30 [1] ./example.js + 2 modules 285 bytes {1} [built] [no exports] ``` webpack-3.5.6/examples/scope-hoisting/build.js000066400000000000000000000000331315401342100213350ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/scope-hoisting/example.js000066400000000000000000000002411315401342100216720ustar00rootroot00000000000000import { 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-3.5.6/examples/scope-hoisting/graph.png000066400000000000000000000401021315401342100215100ustar00rootroot00000000000000PNG  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-3.5.6/examples/scope-hoisting/graph.svg000066400000000000000000000151721315401342100215340ustar00rootroot00000000000000exampleabsharedshared2lazycdcjswebpack-3.5.6/examples/scope-hoisting/graph2.png000066400000000000000000000472201315401342100216020ustar00rootroot00000000000000PNG  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-3.5.6/examples/scope-hoisting/graph2.svg000066400000000000000000000167521315401342100216230ustar00rootroot00000000000000Chunk AChunk Bexampleabsharedshared2lazycdcjswebpack-3.5.6/examples/scope-hoisting/graph3.png000066400000000000000000000605011315401342100216000ustar00rootroot00000000000000PNG  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-3.5.6/examples/scope-hoisting/graph3.svg000066400000000000000000000210171315401342100216120ustar00rootroot00000000000000Chunk AScope 1Scope 2Chunk BScope 3exampleabsharedshared2cjslazycdwebpack-3.5.6/examples/scope-hoisting/lazy.js000066400000000000000000000000711315401342100212170ustar00rootroot00000000000000export * from "c"; import * as d from "d"; export { d }; webpack-3.5.6/examples/scope-hoisting/node_modules/000077500000000000000000000000001315401342100223615ustar00rootroot00000000000000webpack-3.5.6/examples/scope-hoisting/node_modules/a.js000066400000000000000000000000701315401342100231340ustar00rootroot00000000000000// module a export var a = "a"; export * from "shared"; webpack-3.5.6/examples/scope-hoisting/node_modules/b.js000066400000000000000000000000621315401342100231360ustar00rootroot00000000000000// module b export function a() { return "b"; }; webpack-3.5.6/examples/scope-hoisting/node_modules/c.js000066400000000000000000000002041315401342100231350ustar00rootroot00000000000000// module c import { c as e } from "cjs"; export var c = String.fromCharCode(e.charCodeAt(0) - 2); export { x, y } from "shared"; webpack-3.5.6/examples/scope-hoisting/node_modules/cjs.js000066400000000000000000000000521315401342100234730ustar00rootroot00000000000000// module cjs (commonjs) exports.c = "e"; webpack-3.5.6/examples/scope-hoisting/node_modules/d.js000066400000000000000000000000401315401342100231340ustar00rootroot00000000000000// module d export var a = "d"; webpack-3.5.6/examples/scope-hoisting/node_modules/shared.js000066400000000000000000000000761315401342100241700ustar00rootroot00000000000000// shared module export var x = "x"; export * from "shared2"; webpack-3.5.6/examples/scope-hoisting/node_modules/shared2.js000066400000000000000000000000461315401342100242470ustar00rootroot00000000000000// shared2 module export var y = "y"; webpack-3.5.6/examples/scope-hoisting/template.md000066400000000000000000000034571315401342100220520ustar00rootroot00000000000000This 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 concatentation 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}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/0.output.js ``` javascript {{js/0.output.js}} ``` Minimized ``` javascript {{min:js/0.output.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/scope-hoisting/webpack.config.js000066400000000000000000000001721315401342100231220ustar00rootroot00000000000000var webpack = require("../../"); module.exports = { plugins: [ new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-3.5.6/examples/source-map/000077500000000000000000000000001315401342100170245ustar00rootroot00000000000000webpack-3.5.6/examples/source-map/README.md000066400000000000000000000515521315401342100203130ustar00rootroot00000000000000This 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"); var webpack = require("../../"); 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 => ({ entry: { bundle: "coffee-loader!./example.coffee", }, output: { path: path.join(__dirname, "js"), filename: `./[name]-${devtool}.js`, }, devtool, plugins: [ new webpack.optimize.CommonsChunkPlugin(["manifest"]), ], })); ``` # Generated source-maps ## source-map.js and source-map.js.map ``` javascript webpackJsonp([0],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { var math, race, slice = [].slice; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : []; return print(winner, runners); }; /***/ }) ],[0]); //# sourceMappingURL=bundle-source-map.js.map ``` ``` javascript {"version":3,"sources":["webpack:///./example.coffee"],"names":[],"mappings":";;;;;;;;;AAGA;EAAA;;AAAA,OACE;EAAA,MAAQ,IAAI,CAAC,IAAb;EACA,QAAQ,MADR;EAEA,MAAQ,SAAC,CAAD;WAAO,IAAI,OAAO,CAAP;EAAX,CAFR;;;AAKF,OAAO;AACL;EADM,uBAAQ;SACd,MAAM,MAAN,EAAc,OAAd;AADK","file":"./bundle-source-map.js","sourcesContent":["# Taken from http://coffeescript.org/\r\n\r\n# Objects:\r\nmath =\r\n root: Math.sqrt\r\n square: square\r\n cube: (x) -> x * square x\r\n\r\n# Splats:\r\nrace = (winner, runners...) ->\r\n print winner, runners\r\n\n\n\n// WEBPACK FOOTER //\n// ./example.coffee"],"sourceRoot":""} ``` ## hidden-source-map.js and hidden-source-map.js.map ``` javascript webpackJsonp([0],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { var math, race, slice = [].slice; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : []; return print(winner, runners); }; /***/ }) ],[0]); ``` ``` javascript {"version":3,"sources":["webpack:///./example.coffee"],"names":[],"mappings":";;;;;;;;;AAGA;EAAA;;AAAA,OACE;EAAA,MAAQ,IAAI,CAAC,IAAb;EACA,QAAQ,MADR;EAEA,MAAQ,SAAC,CAAD;WAAO,IAAI,OAAO,CAAP;EAAX,CAFR;;;AAKF,OAAO;AACL;EADM,uBAAQ;SACd,MAAM,MAAN,EAAc,OAAd;AADK","file":"./bundle-hidden-source-map.js","sourcesContent":["# Taken from http://coffeescript.org/\r\n\r\n# Objects:\r\nmath =\r\n root: Math.sqrt\r\n square: square\r\n cube: (x) -> x * square x\r\n\r\n# Splats:\r\nrace = (winner, runners...) ->\r\n print winner, runners\r\n\n\n\n// WEBPACK FOOTER //\n// ./example.coffee"],"sourceRoot":""} ``` ## inline-source-map.js ``` javascript webpackJsonp([0],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { var math, race, slice = [].slice; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : []; return print(winner, runners); }; /***/ }) ],[0]); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9leGFtcGxlLmNvZmZlZSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFHQTtFQUFBOztBQUFBLE9BQ0U7RUFBQSxNQUFRLElBQUksQ0FBQyxJQUFiO0VBQ0EsUUFBUSxNQURSO0VBRUEsTUFBUSxTQUFDLENBQUQ7V0FBTyxJQUFJLE9BQU8sQ0FBUDtFQUFYLENBRlI7OztBQUtGLE9BQU87QUFDTDtFQURNLHVCQUFRO1NBQ2QsTUFBTSxNQUFOLEVBQWMsT0FBZDtBQURLIiwiZmlsZSI6Ii4vYnVuZGxlLWlubGluZS1zb3VyY2UtbWFwLmpzIiwic291cmNlc0NvbnRlbnQiOlsiIyBUYWtlbiBmcm9tIGh0dHA6Ly9jb2ZmZWVzY3JpcHQub3JnL1xyXG5cclxuIyBPYmplY3RzOlxyXG5tYXRoID1cclxuICByb290OiAgIE1hdGguc3FydFxyXG4gIHNxdWFyZTogc3F1YXJlXHJcbiAgY3ViZTogICAoeCkgLT4geCAqIHNxdWFyZSB4XHJcblxyXG4jIFNwbGF0czpcclxucmFjZSA9ICh3aW5uZXIsIHJ1bm5lcnMuLi4pIC0+XHJcbiAgcHJpbnQgd2lubmVyLCBydW5uZXJzXHJcblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyAuL2V4YW1wbGUuY29mZmVlIl0sInNvdXJjZVJvb3QiOiIifQ== ``` ## nosources-source-map.js.map ``` javascript {"version":3,"sources":["webpack:///./example.coffee"],"names":[],"mappings":";;;;;;;;;AAGA;EAAA;;AAAA,OACE;EAAA,MAAQ,IAAI,CAAC,IAAb;EACA,QAAQ,MADR;EAEA,MAAQ,SAAC,CAAD;WAAO,IAAI,OAAO,CAAP;EAAX,CAFR;;;AAKF,OAAO;AACL;EADM,uBAAQ;SACd,MAAM,MAAN,EAAc,OAAd;AADK","file":"./bundle-nosources-source-map.js","sourceRoot":""} ``` ## eval-source-map.js ``` javascript webpackJsonp([0],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { eval("var math, race,\n slice = [].slice;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\nrace = function() {\n var runners, winner;\n winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];\n return print(winner, runners);\n};\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9leGFtcGxlLmNvZmZlZT85MWU1Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUdBO0VBQUE7O0FBQUEsT0FDRTtFQUFBLE1BQVEsSUFBSSxDQUFDLElBQWI7RUFDQSxRQUFRLE1BRFI7RUFFQSxNQUFRLFNBQUMsQ0FBRDtXQUFPLElBQUksT0FBTyxDQUFQO0VBQVgsQ0FGUjs7O0FBS0YsT0FBTztBQUNMO0VBRE0sdUJBQVE7U0FDZCxNQUFNLE1BQU4sRUFBYyxPQUFkO0FBREsiLCJmaWxlIjoiMC5qcyIsInNvdXJjZXNDb250ZW50IjpbIiMgVGFrZW4gZnJvbSBodHRwOi8vY29mZmVlc2NyaXB0Lm9yZy9cclxuXHJcbiMgT2JqZWN0czpcclxubWF0aCA9XHJcbiAgcm9vdDogICBNYXRoLnNxcnRcclxuICBzcXVhcmU6IHNxdWFyZVxyXG4gIGN1YmU6ICAgKHgpIC0+IHggKiBzcXVhcmUgeFxyXG5cclxuIyBTcGxhdHM6XHJcbnJhY2UgPSAod2lubmVyLCBydW5uZXJzLi4uKSAtPlxyXG4gIHByaW50IHdpbm5lciwgcnVubmVyc1xyXG5cblxuXG4vLyBXRUJQQUNLIEZPT1RFUiAvL1xuLy8gLi9leGFtcGxlLmNvZmZlZSJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///0\n"); /***/ }) ],[0]); ``` ## eval.js ``` javascript webpackJsonp([0],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { eval("var math, race,\n slice = [].slice;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\nrace = function() {\n var runners, winner;\n winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];\n return print(winner, runners);\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/node_modules/coffee-loader!./example.coffee\n// module id = 0\n// module chunks = 0\n\n//# sourceURL=webpack:///./example.coffee?(webpack)/node_modules/coffee-loader"); /***/ }) ],[0]); ``` ## cheap-eval-source-map.js ``` javascript webpackJsonp([0],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { eval("var math, race,\n slice = [].slice;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\nrace = function() {\n var runners, winner;\n winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];\n return print(winner, runners);\n};\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL2V4YW1wbGUuY29mZmVlPzA5MjciXSwic291cmNlc0NvbnRlbnQiOlsidmFyIG1hdGgsIHJhY2UsXG4gIHNsaWNlID0gW10uc2xpY2U7XG5cbm1hdGggPSB7XG4gIHJvb3Q6IE1hdGguc3FydCxcbiAgc3F1YXJlOiBzcXVhcmUsXG4gIGN1YmU6IGZ1bmN0aW9uKHgpIHtcbiAgICByZXR1cm4geCAqIHNxdWFyZSh4KTtcbiAgfVxufTtcblxucmFjZSA9IGZ1bmN0aW9uKCkge1xuICB2YXIgcnVubmVycywgd2lubmVyO1xuICB3aW5uZXIgPSBhcmd1bWVudHNbMF0sIHJ1bm5lcnMgPSAyIDw9IGFyZ3VtZW50cy5sZW5ndGggPyBzbGljZS5jYWxsKGFyZ3VtZW50cywgMSkgOiBbXTtcbiAgcmV0dXJuIHByaW50KHdpbm5lciwgcnVubmVycyk7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gKHdlYnBhY2spL25vZGVfbW9kdWxlcy9jb2ZmZWUtbG9hZGVyIS4vZXhhbXBsZS5jb2ZmZWVcbi8vIG1vZHVsZSBpZCA9IDBcbi8vIG1vZHVsZSBjaHVua3MgPSAwIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///0\n"); /***/ }) ],[0]); ``` ## cheap-module-eval-source-map.js ``` javascript webpackJsonp([0],[ /* 0 */ /*!*************************************************************!*\ !*** (webpack)/node_modules/coffee-loader!./example.coffee ***! \*************************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { eval("var math, race,\n slice = [].slice;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\nrace = function() {\n var runners, winner;\n winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];\n return print(winner, runners);\n};\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL2V4YW1wbGUuY29mZmVlPzkxZTUiXSwic291cmNlc0NvbnRlbnQiOlsiIyBUYWtlbiBmcm9tIGh0dHA6Ly9jb2ZmZWVzY3JpcHQub3JnL1xyXG5cclxuIyBPYmplY3RzOlxyXG5tYXRoID1cclxuICByb290OiAgIE1hdGguc3FydFxyXG4gIHNxdWFyZTogc3F1YXJlXHJcbiAgY3ViZTogICAoeCkgLT4geCAqIHNxdWFyZSB4XHJcblxyXG4jIFNwbGF0czpcclxucmFjZSA9ICh3aW5uZXIsIHJ1bm5lcnMuLi4pIC0+XHJcbiAgcHJpbnQgd2lubmVyLCBydW5uZXJzXHJcblxuXG5cbi8vIFdFQlBBQ0sgRk9PVEVSIC8vXG4vLyAuL2V4YW1wbGUuY29mZmVlIl0sIm1hcHBpbmdzIjoiQUFHQTtBQUFBO0FBQ0E7QUFEQTtBQUNBO0FBQ0E7QUFDQTtBQUFBO0FBQUE7OztBQUdBO0FBQ0E7QUFEQTtBQUNBO0FBREE7Iiwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///0\n"); /***/ }) ],[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/\r\n\r\n# Objects:\r\nmath =\r\n root: Math.sqrt\r\n square: square\r\n cube: (x) -> x * square x\r\n\r\n# Splats:\r\nrace = (winner, runners...) ->\r\n print winner, runners\r\n\n\n\n// WEBPACK FOOTER //\n// ./example.coffee"],"mappings":";;;;;;;;;AAGA;AAAA;AACA;AADA;AACA;AACA;AACA;AAAA;AAAA;;;AAGA;AACA;AADA;AACA;AADA;;;;A","sourceRoot":""} ``` ## cheap-source-map.js.map ``` javascript {"version":3,"file":"./bundle-cheap-source-map.js","sources":["webpack:///./example.coffee"],"sourcesContent":["var math, race,\n slice = [].slice;\n\nmath = {\n root: Math.sqrt,\n square: square,\n cube: function(x) {\n return x * square(x);\n }\n};\n\nrace = function() {\n var runners, winner;\n winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];\n return print(winner, runners);\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/node_modules/coffee-loader!./example.coffee\n// module id = 0\n// module chunks = 0"],"mappings":";;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;A","sourceRoot":""} ``` # webpack output ``` Hash: 6ee996e84863368c38e521284f8d1d322741045b5f9e187528736f9dd586ad053259eb9ee4cf69b5354b67e68d715d903c31515124d263f93c8aa7159d388dea6bd43ac605cdd4e103e888cf20eaf6f75dc2d2924e3fdc22d6889086c1479edc2c87f028 Version: webpack 3.5.1 Child Hash: 6ee996e84863368c38e5 Asset Size Chunks Chunk Names ./bundle-cheap-eval-source-map.js 1.69 kB 0 [emitted] bundle ./manifest-cheap-eval-source-map.js 5.8 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-cheap-eval-source-map.js ./bundle-cheap-eval-source-map.js chunk {0} ./bundle-cheap-eval-source-map.js (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-cheap-eval-source-map.js (manifest) 0 bytes [entry] [rendered] Child Hash: 21284f8d1d322741045b Asset Size Chunks Chunk Names ./bundle-cheap-module-eval-source-map.js 1.42 kB 0 [emitted] bundle ./manifest-cheap-module-eval-source-map.js 5.81 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-cheap-module-eval-source-map.js ./bundle-cheap-module-eval-source-map.js chunk {0} ./bundle-cheap-module-eval-source-map.js (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-cheap-module-eval-source-map.js (manifest) 0 bytes [entry] [rendered] Child Hash: 5f9e187528736f9dd586 Asset Size Chunks Chunk Names ./bundle-cheap-module-source-map.js 703 bytes 0 [emitted] bundle ./manifest-cheap-module-source-map.js 5.87 kB 1 [emitted] manifest ./bundle-cheap-module-source-map.js.map 507 bytes 0 [emitted] bundle ./manifest-cheap-module-source-map.js.map 5.9 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-cheap-module-source-map.js ./manifest-cheap-module-source-map.js.map ./bundle-cheap-module-source-map.js ./bundle-cheap-module-source-map.js.map chunk {0} ./bundle-cheap-module-source-map.js, ./bundle-cheap-module-source-map.js.map (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-cheap-module-source-map.js, ./manifest-cheap-module-source-map.js.map (manifest) 0 bytes [entry] [rendered] Child Hash: ad053259eb9ee4cf69b5 Asset Size Chunks Chunk Names ./bundle-cheap-source-map.js 696 bytes 0 [emitted] bundle ./manifest-cheap-source-map.js 5.85 kB 1 [emitted] manifest ./bundle-cheap-source-map.js.map 703 bytes 0 [emitted] bundle ./manifest-cheap-source-map.js.map 5.88 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-cheap-source-map.js ./manifest-cheap-source-map.js.map ./bundle-cheap-source-map.js ./bundle-cheap-source-map.js.map chunk {0} ./bundle-cheap-source-map.js, ./bundle-cheap-source-map.js.map (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-cheap-source-map.js, ./manifest-cheap-source-map.js.map (manifest) 0 bytes [entry] [rendered] Child Hash: 354b67e68d715d903c31 Asset Size Chunks Chunk Names ./bundle-eval.js 890 bytes 0 [emitted] bundle ./manifest-eval.js 5.79 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-eval.js ./bundle-eval.js chunk {0} ./bundle-eval.js (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-eval.js (manifest) 0 bytes [entry] [rendered] Child Hash: 515124d263f93c8aa715 Asset Size Chunks Chunk Names ./bundle-eval-source-map.js 1.56 kB 0 [emitted] bundle ./manifest-eval-source-map.js 5.8 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-eval-source-map.js ./bundle-eval-source-map.js chunk {0} ./bundle-eval-source-map.js (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-eval-source-map.js (manifest) 0 bytes [entry] [rendered] Child Hash: 9d388dea6bd43ac605cd Asset Size Chunks Chunk Names ./bundle-hidden-source-map.js 644 bytes 0 [emitted] bundle ./manifest-hidden-source-map.js 5.8 kB 1 [emitted] manifest ./bundle-hidden-source-map.js.map 604 bytes 0 [emitted] bundle ./manifest-hidden-source-map.js.map 5.93 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-hidden-source-map.js ./manifest-hidden-source-map.js.map ./bundle-hidden-source-map.js ./bundle-hidden-source-map.js.map chunk {0} ./bundle-hidden-source-map.js, ./bundle-hidden-source-map.js.map (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-hidden-source-map.js, ./manifest-hidden-source-map.js.map (manifest) 0 bytes [entry] [rendered] Child Hash: d4e103e888cf20eaf6f7 Asset Size Chunks Chunk Names ./bundle-inline-source-map.js 1.52 kB 0 [emitted] bundle ./manifest-inline-source-map.js 13.8 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-inline-source-map.js ./bundle-inline-source-map.js chunk {0} ./bundle-inline-source-map.js (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-inline-source-map.js (manifest) 0 bytes [entry] [rendered] Child Hash: 5dc2d2924e3fdc22d688 Asset Size Chunks Chunk Names ./bundle-nosources-source-map.js 700 bytes 0 [emitted] bundle ./manifest-nosources-source-map.js 5.86 kB 1 [emitted] manifest ./bundle-nosources-source-map.js.map 315 bytes 0 [emitted] bundle ./manifest-nosources-source-map.js.map 935 bytes 1 [emitted] manifest Entrypoint bundle = ./manifest-nosources-source-map.js ./manifest-nosources-source-map.js.map ./bundle-nosources-source-map.js ./bundle-nosources-source-map.js.map chunk {0} ./bundle-nosources-source-map.js, ./bundle-nosources-source-map.js.map (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-nosources-source-map.js, ./manifest-nosources-source-map.js.map (manifest) 0 bytes [entry] [rendered] Child Hash: 9086c1479edc2c87f028 Asset Size Chunks Chunk Names ./bundle-source-map.js 690 bytes 0 [emitted] bundle ./manifest-source-map.js 5.84 kB 1 [emitted] manifest ./bundle-source-map.js.map 597 bytes 0 [emitted] bundle ./manifest-source-map.js.map 5.92 kB 1 [emitted] manifest Entrypoint bundle = ./manifest-source-map.js ./manifest-source-map.js.map ./bundle-source-map.js ./bundle-source-map.js.map chunk {0} ./bundle-source-map.js, ./bundle-source-map.js.map (bundle) 308 bytes {1} [initial] [rendered] > bundle [0] (webpack)/node_modules/coffee-loader!./example.coffee [0] (webpack)/node_modules/coffee-loader!./example.coffee 308 bytes {0} [built] chunk {1} ./manifest-source-map.js, ./manifest-source-map.js.map (manifest) 0 bytes [entry] [rendered] ``` webpack-3.5.6/examples/source-map/build.js000066400000000000000000000000721315401342100204600ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-3.5.6/examples/source-map/example.coffee000066400000000000000000000002761315401342100216350ustar00rootroot00000000000000# 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-3.5.6/examples/source-map/template.md000066400000000000000000000023031315401342100211570ustar00rootroot00000000000000This 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 {{js/bundle-source-map.js}} ``` ``` javascript {{js/bundle-source-map.js.map}} ``` ## hidden-source-map.js and hidden-source-map.js.map ``` javascript {{js/bundle-hidden-source-map.js}} ``` ``` javascript {{js/bundle-hidden-source-map.js.map}} ``` ## inline-source-map.js ``` javascript {{js/bundle-inline-source-map.js}} ``` ## nosources-source-map.js.map ``` javascript {{js/bundle-nosources-source-map.js.map}} ``` ## eval-source-map.js ``` javascript {{js/bundle-eval-source-map.js}} ``` ## eval.js ``` javascript {{js/bundle-eval.js}} ``` ## cheap-eval-source-map.js ``` javascript {{js/bundle-cheap-eval-source-map.js}} ``` ## cheap-module-eval-source-map.js ``` javascript {{js/bundle-cheap-module-eval-source-map.js}} ``` ## cheap-module-source-map.js.map ``` javascript {{js/bundle-cheap-module-source-map.js.map}} ``` ## cheap-source-map.js.map ``` javascript {{js/bundle-cheap-source-map.js.map}} ``` # webpack output ``` {{stdout}} ``` webpack-3.5.6/examples/source-map/webpack.config.js000066400000000000000000000010551315401342100222430ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../"); 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 => ({ entry: { bundle: "coffee-loader!./example.coffee", }, output: { path: path.join(__dirname, "js"), filename: `./[name]-${devtool}.js`, }, devtool, plugins: [ new webpack.optimize.CommonsChunkPlugin(["manifest"]), ], })); webpack-3.5.6/examples/template-common.js000066400000000000000000000041601315401342100204110ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ 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; exports.replaceBase = function replaceBase(template) { let cwd = process.cwd(); let webpack = path.join(__dirname, ".."); let webpackParent = path.join(__dirname, "..", ".."); cwd = lessStrict(cwd.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); cwd = new RegExp(cwd, "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(cwd, ".") .replace(webpack, "(webpack)") .replace(webpackParent, "(webpack)/~") .replace(timeRegexp, "") .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.replaceResults = function replaceResults(template, baseDir, stdout, prefix) { const regexp = new RegExp("\\{\\{" + (prefix ? prefix+":" : "") + "([^:\\}]+)\\}\\}", "g") return template.replace(regexp, function(match) { match = match.substr(2 + (prefix ? prefix.length+1 : 0), match.length - 4 - (prefix ? prefix.length+1 : 0)); if(match === "stdout") return stdout; return fs.readFileSync(path.join(baseDir, match), "utf-8").replace(/[\r\n]*$/, ""); }); } webpack-3.5.6/examples/two-explicit-vendor-chunks/000077500000000000000000000000001315401342100221655ustar00rootroot00000000000000webpack-3.5.6/examples/two-explicit-vendor-chunks/README.md000066400000000000000000000262071315401342100234530ustar00rootroot00000000000000# webpack.config.js ``` javascript var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { vendor1: ["./vendor1"], vendor2: ["./vendor2"], pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ names: ["vendor2", "vendor1"], minChunks: Infinity }) ] }; ``` # js/vendor1.js
/******/ (function(modules) { /* webpackBootstrap */ }) ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ 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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ if(executeModules) { /******/ for(i=0; i < executeModules.length; i++) { /******/ result = __webpack_require__(__webpack_require__.s = executeModules[i]); /******/ } /******/ } /******/ return result; /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 4: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + chunkId + ".js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // on error function for async loading /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./vendor1.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = "Vendor1"; /***/ }), /* 1 */, /* 2 */ /*!***********************!*\ !*** multi ./vendor1 ***! \***********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./vendor1 */0); /***/ }) /******/ ]); ``` # js/vendor2.js ``` javascript webpackJsonp([0],[ /* 0 */, /* 1 */ /*!********************!*\ !*** ./vendor2.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = "Vendor2"; __webpack_require__(/*! ./vendor1 */ 0); /***/ }), /* 2 */, /* 3 */ /*!***********************!*\ !*** multi ./vendor2 ***! \***********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./vendor2 */1); /***/ }) ],[3]); ``` # js/pageA.js ``` javascript webpackJsonp([3],{ /***/ 4: /*!******************!*\ !*** ./pageA.js ***! \******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = "pageA"; __webpack_require__(/*! ./vendor1 */ 0); __webpack_require__(/*! ./vendor2 */ 1); /***/ }) },[4]); ``` # Info ## Uncompressed ``` Hash: 87020004ae57cbfa3361 Version: webpack 3.5.1 Asset Size Chunks Chunk Names vendor2.js 598 bytes 0 [emitted] vendor2 pageC.js 235 bytes 1 [emitted] pageC pageB.js 235 bytes 2 [emitted] pageB pageA.js 342 bytes 3 [emitted] pageA vendor1.js 6.41 kB 4 [emitted] vendor1 Entrypoint vendor1 = vendor1.js Entrypoint vendor2 = vendor1.js vendor2.js Entrypoint pageA = vendor1.js vendor2.js pageA.js Entrypoint pageB = vendor1.js vendor2.js pageB.js Entrypoint pageC = vendor1.js vendor2.js pageC.js chunk {0} vendor2.js (vendor2) 80 bytes {4} [initial] [rendered] > vendor2 [3] multi ./vendor2 [1] ./vendor2.js 52 bytes {0} [built] single entry ./vendor2 [3] multi ./vendor2 vendor2:100000 cjs require ./vendor2 [4] ./pageA.js 3:0-20 [3] multi ./vendor2 28 bytes {0} [built] chunk {1} pageC.js (pageC) 25 bytes {0} [initial] [rendered] > pageC [6] ./pageC.js [6] ./pageC.js 25 bytes {1} [built] chunk {2} pageB.js (pageB) 25 bytes {0} [initial] [rendered] > pageB [5] ./pageB.js [5] ./pageB.js 25 bytes {2} [built] chunk {3} pageA.js (pageA) 73 bytes {0} [initial] [rendered] > pageA [4] ./pageA.js [4] ./pageA.js 73 bytes {3} [built] chunk {4} vendor1.js (vendor1) 55 bytes [entry] [rendered] > vendor1 [2] multi ./vendor1 [0] ./vendor1.js 27 bytes {4} [built] cjs require ./vendor1 [1] ./vendor2.js 2:0-20 single entry ./vendor1 [2] multi ./vendor1 vendor1:100000 cjs require ./vendor1 [4] ./pageA.js 2:0-20 [2] multi ./vendor1 28 bytes {4} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: 87020004ae57cbfa3361 Version: webpack 3.5.1 Asset Size Chunks Chunk Names vendor2.js 100 bytes 0 [emitted] vendor2 pageC.js 59 bytes 1 [emitted] pageC pageB.js 59 bytes 2 [emitted] pageB pageA.js 71 bytes 3 [emitted] pageA vendor1.js 1.44 kB 4 [emitted] vendor1 Entrypoint vendor1 = vendor1.js Entrypoint vendor2 = vendor1.js vendor2.js Entrypoint pageA = vendor1.js vendor2.js pageA.js Entrypoint pageB = vendor1.js vendor2.js pageB.js Entrypoint pageC = vendor1.js vendor2.js pageC.js chunk {0} vendor2.js (vendor2) 80 bytes {4} [initial] [rendered] > vendor2 [3] multi ./vendor2 [1] ./vendor2.js 52 bytes {0} [built] single entry ./vendor2 [3] multi ./vendor2 vendor2:100000 cjs require ./vendor2 [4] ./pageA.js 3:0-20 [3] multi ./vendor2 28 bytes {0} [built] chunk {1} pageC.js (pageC) 25 bytes {0} [initial] [rendered] > pageC [6] ./pageC.js [6] ./pageC.js 25 bytes {1} [built] chunk {2} pageB.js (pageB) 25 bytes {0} [initial] [rendered] > pageB [5] ./pageB.js [5] ./pageB.js 25 bytes {2} [built] chunk {3} pageA.js (pageA) 73 bytes {0} [initial] [rendered] > pageA [4] ./pageA.js [4] ./pageA.js 73 bytes {3} [built] chunk {4} vendor1.js (vendor1) 55 bytes [entry] [rendered] > vendor1 [2] multi ./vendor1 [0] ./vendor1.js 27 bytes {4} [built] cjs require ./vendor1 [1] ./vendor2.js 2:0-20 single entry ./vendor1 [2] multi ./vendor1 vendor1:100000 cjs require ./vendor1 [4] ./pageA.js 2:0-20 [2] multi ./vendor1 28 bytes {4} [built] ``` webpack-3.5.6/examples/two-explicit-vendor-chunks/build.js000066400000000000000000000000721315401342100236210ustar00rootroot00000000000000global.NO_TARGET_ARGS = true; require("../build-common"); webpack-3.5.6/examples/two-explicit-vendor-chunks/pageA.html000066400000000000000000000003241315401342100240670ustar00rootroot00000000000000 webpack-3.5.6/examples/two-explicit-vendor-chunks/pageA.js000066400000000000000000000001061315401342100235350ustar00rootroot00000000000000module.exports = "pageA"; require("./vendor1"); require("./vendor2"); webpack-3.5.6/examples/two-explicit-vendor-chunks/pageB.js000066400000000000000000000000311315401342100235330ustar00rootroot00000000000000module.exports = "pageB";webpack-3.5.6/examples/two-explicit-vendor-chunks/pageC.js000066400000000000000000000000311315401342100235340ustar00rootroot00000000000000module.exports = "pageC";webpack-3.5.6/examples/two-explicit-vendor-chunks/template.md000066400000000000000000000005061315401342100243230ustar00rootroot00000000000000# webpack.config.js ``` javascript {{webpack.config.js}} ``` # js/vendor1.js ``` javascript {{js/vendor1.js}} ``` # js/vendor2.js ``` javascript {{js/vendor2.js}} ``` # js/pageA.js ``` javascript {{js/pageA.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/two-explicit-vendor-chunks/vendor1.js000066400000000000000000000000331315401342100240750ustar00rootroot00000000000000module.exports = "Vendor1";webpack-3.5.6/examples/two-explicit-vendor-chunks/vendor2.js000066400000000000000000000000621315401342100241000ustar00rootroot00000000000000module.exports = "Vendor2"; require("./vendor1"); webpack-3.5.6/examples/two-explicit-vendor-chunks/webpack.config.js000066400000000000000000000006551315401342100254110ustar00rootroot00000000000000var path = require("path"); var CommonsChunkPlugin = require("../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { vendor1: ["./vendor1"], vendor2: ["./vendor2"], pageA: "./pageA", pageB: "./pageB", pageC: "./pageC" }, output: { path: path.join(__dirname, "js"), filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ names: ["vendor2", "vendor1"], minChunks: Infinity }) ] }; webpack-3.5.6/examples/web-worker/000077500000000000000000000000001315401342100170355ustar00rootroot00000000000000webpack-3.5.6/examples/web-worker/README.md000066400000000000000000000324661315401342100203270ustar00rootroot00000000000000 # example.js ``` javascript var Worker = require("worker-loader!./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()); }); } ``` # js/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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ ```
``` javascript /******/ ([ /* 0 */ /*!********************!*\ !*** ./example.js ***! \********************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { var Worker = __webpack_require__(/*! worker-loader!./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!./worker.js ***! \********************************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { module.exports = function() { return new Worker(__webpack_require__.p + "hash.worker.js"); }; /***/ }) /******/ ]); ``` # js/[hash].worker.js ``` javascript /******/ (function(modules) { // webpackBootstrap /******/ this["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 = { /******/ 1: 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) { /******/ return new Promise(function(resolve) { /******/ // "1" is the signal for "already loaded" /******/ if(!installedChunks[chunkId]) { /******/ importScripts("" + chunkId + ".hash.worker.js"); /******/ } /******/ resolve(); /******/ }); /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = "js/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /*!*******************!*\ !*** ./worker.js ***! \*******************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports, __webpack_require__) { onmessage = function(event) { var template = event.data; __webpack_require__.e/* require */(0).then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(/*! ../require.context/templates */ 1)("./" + event.data)]; (function(tmpl) { postMessage(tmpl()); }.apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));}).catch(__webpack_require__.oe); } /***/ }) /******/ ]); ``` # js/0.[hash].worker.js ``` javascript webpackChunk([0],[ /* 0 */, /* 1 */ /*!*********************************************!*\ !*** ../require.context/templates ^\.\/.*$ ***! \*********************************************/ /*! no static exports found */ /*! all exports used */ /***/ (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) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; 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 */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template A"; } /***/ }), /* 3 */ /*!*****************************************!*\ !*** ../require.context/templates/b.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template B"; } /***/ }), /* 4 */ /*!*****************************************!*\ !*** ../require.context/templates/c.js ***! \*****************************************/ /*! no static exports found */ /*! all exports used */ /***/ (function(module, exports) { module.exports = function() { return "This text was generated by template C"; } /***/ }) ]); ``` # Info ## Uncompressed ``` Hash: de5e6c34dad6f90c6640 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.hash.worker.js 1.85 kB [emitted] hash.worker.js 3.91 kB [emitted] output.js 3.27 kB 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 311 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 215 bytes {0} [built] [1] (webpack)/node_modules/worker-loader!./worker.js 96 bytes {0} [not cacheable] [built] cjs require worker-loader!./worker [0] ./example.js 1:13-46 Child worker: Asset Size Chunks Chunk Names 0.hash.worker.js 1.85 kB 0 [emitted] hash.worker.js 3.91 kB 1 [emitted] main Entrypoint main = hash.worker.js chunk {0} 0.hash.worker.js 463 bytes {1} [rendered] > [0] ./worker.js 3:1-5:3 [1] ../require.context/templates ^\.\/.*$ 217 bytes {0} [built] amd require context ../require.context/templates [0] ./worker.js 3:1-5:3 [2] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [1] ../require.context/templates ^\.\/.*$ ./a.js context element ./a [1] ../require.context/templates ^\.\/.*$ ./a [3] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [1] ../require.context/templates ^\.\/.*$ ./b.js context element ./b [1] ../require.context/templates ^\.\/.*$ ./b [4] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [1] ../require.context/templates ^\.\/.*$ ./c.js context element ./c [1] ../require.context/templates ^\.\/.*$ ./c chunk {1} hash.worker.js (main) 168 bytes [entry] [rendered] > main [0] ./worker.js [0] ./worker.js 168 bytes {1} [built] ``` ## Minimized (uglify-js, no zip) ``` Hash: de5e6c34dad6f90c6640 Version: webpack 3.5.1 Asset Size Chunks Chunk Names 0.hash.worker.js 544 bytes [emitted] hash.worker.js 811 bytes [emitted] output.js 632 bytes 0 [emitted] main Entrypoint main = output.js chunk {0} output.js (main) 311 bytes [entry] [rendered] > main [0] ./example.js [0] ./example.js 215 bytes {0} [built] [1] (webpack)/node_modules/worker-loader!./worker.js 96 bytes {0} [not cacheable] [built] cjs require worker-loader!./worker [0] ./example.js 1:13-46 Child worker: Asset Size Chunks Chunk Names 0.hash.worker.js 544 bytes 0 [emitted] hash.worker.js 811 bytes 1 [emitted] main Entrypoint main = hash.worker.js chunk {0} 0.hash.worker.js 463 bytes {1} [rendered] > [0] ./worker.js 3:1-5:3 [1] ../require.context/templates ^\.\/.*$ 217 bytes {0} [built] amd require context ../require.context/templates [0] ./worker.js 3:1-5:3 [2] ../require.context/templates/a.js 82 bytes {0} [optional] [built] context element ./a.js [1] ../require.context/templates ^\.\/.*$ ./a.js context element ./a [1] ../require.context/templates ^\.\/.*$ ./a [3] ../require.context/templates/b.js 82 bytes {0} [optional] [built] context element ./b.js [1] ../require.context/templates ^\.\/.*$ ./b.js context element ./b [1] ../require.context/templates ^\.\/.*$ ./b [4] ../require.context/templates/c.js 82 bytes {0} [optional] [built] context element ./c.js [1] ../require.context/templates ^\.\/.*$ ./c.js context element ./c [1] ../require.context/templates ^\.\/.*$ ./c chunk {1} hash.worker.js (main) 168 bytes [entry] [rendered] > main [0] ./worker.js [0] ./worker.js 168 bytes {1} [built] ``` webpack-3.5.6/examples/web-worker/build.js000066400000000000000000000000331315401342100204660ustar00rootroot00000000000000require("../build-common");webpack-3.5.6/examples/web-worker/example.js000066400000000000000000000003211315401342100210220ustar00rootroot00000000000000var Worker = require("worker-loader!./worker"); var worker = new Worker; worker.postMessage("b"); worker.onmessage = function(event) { var templateB = event.data; // "This text was generated by template B" } webpack-3.5.6/examples/web-worker/template.md000066400000000000000000000006021315401342100211700ustar00rootroot00000000000000 # example.js ``` javascript {{example.js}} ``` # worker.js ``` javascript {{worker.js}} ``` # js/output.js ``` javascript {{js/output.js}} ``` # js/[hash].worker.js ``` javascript {{js/hash.worker.js}} ``` # js/0.[hash].worker.js ``` javascript {{js/0.hash.worker.js}} ``` # Info ## Uncompressed ``` {{stdout}} ``` ## Minimized (uglify-js, no zip) ``` {{min:stdout}} ``` webpack-3.5.6/examples/web-worker/webpack.config.js000066400000000000000000000003711315401342100222540ustar00rootroot00000000000000var webpack = require("../../"); module.exports = { plugins: [ new webpack.LoaderOptionsPlugin({ options: { worker: { output: { filename: "hash.worker.js", chunkFilename: "[id].hash.worker.js" } } } }) ] }; webpack-3.5.6/examples/web-worker/worker.js000066400000000000000000000002421315401342100207020ustar00rootroot00000000000000onmessage = function(event) { var template = event.data; require(["../require.context/templates/" + event.data], function(tmpl) { postMessage(tmpl()); }); } webpack-3.5.6/hot/000077500000000000000000000000001315401342100137255ustar00rootroot00000000000000webpack-3.5.6/hot/.eslintrc000066400000000000000000000001211315401342100155430ustar00rootroot00000000000000{ "env": { "node": true }, "rules": { "node/exports-style": ["off"] } } webpack-3.5.6/hot/dev-server.js000066400000000000000000000030321315401342100163430ustar00rootroot00000000000000/* 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-3.5.6/hot/emitter.js000066400000000000000000000001131315401342100157270ustar00rootroot00000000000000var EventEmitter = require("events"); module.exports = new EventEmitter(); webpack-3.5.6/hot/log-apply-result.js000066400000000000000000000023731315401342100175100ustar00rootroot00000000000000/* 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-3.5.6/hot/log.js000066400000000000000000000017501315401342100150470ustar00rootroot00000000000000var 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); } } }; var group = console.group || dummy; var groupCollapsed = console.groupCollapsed || dummy; var groupEnd = console.groupEnd || dummy; module.exports.group = logGroup(group); module.exports.groupCollapsed = logGroup(groupCollapsed); module.exports.groupEnd = logGroup(groupEnd); module.exports.setLogLevel = function(level) { logLevel = level; }; webpack-3.5.6/hot/only-dev-server.js000066400000000000000000000043741315401342100173340ustar00rootroot00000000000000/* 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-3.5.6/hot/poll.js000066400000000000000000000021411315401342100152270ustar00rootroot00000000000000/* 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-3.5.6/hot/signal.js000066400000000000000000000030151315401342100155370ustar00rootroot00000000000000/* 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); }); }).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-3.5.6/lib/000077500000000000000000000000001315401342100137015ustar00rootroot00000000000000webpack-3.5.6/lib/APIPlugin.js000066400000000000000000000034651315401342100160370ustar00rootroot00000000000000/* 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"); const REPLACEMENTS = { __webpack_require__: "__webpack_require__", // eslint-disable-line camelcase __webpack_public_path__: "__webpack_require__.p", // eslint-disable-line camelcase __webpack_modules__: "__webpack_require__.m", // eslint-disable-line camelcase __webpack_chunk_load__: "__webpack_require__.e", // eslint-disable-line camelcase __non_webpack_require__: "require", // eslint-disable-line camelcase __webpack_nonce__: "__webpack_require__.nc", // eslint-disable-line camelcase "require.onError": "__webpack_require__.oe" // eslint-disable-line camelcase }; const REPLACEMENT_TYPES = { __webpack_public_path__: "string", // eslint-disable-line camelcase __webpack_require__: "function", // eslint-disable-line camelcase __webpack_modules__: "object", // eslint-disable-line camelcase __webpack_chunk_load__: "function", // eslint-disable-line camelcase __webpack_nonce__: "string" // eslint-disable-line camelcase }; class APIPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", parser => { Object.keys(REPLACEMENTS).forEach(key => { parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key])); parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key])); }); }); }); } } module.exports = APIPlugin; webpack-3.5.6/lib/AmdMainTemplatePlugin.js000066400000000000000000000030661315401342100204250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; const Template = require("./Template"); class AmdMainTemplatePlugin { constructor(name) { this.name = name; } apply(compilation) { const mainTemplate = compilation.mainTemplate; compilation.templatesPlugin("render-with-entry", (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) => Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`) ).join(", "); if(this.name) { const name = mainTemplate.applyPluginsWaterfall("asset-path", 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, "});"); } }); mainTemplate.plugin("global-hash-paths", (paths) => { if(this.name) paths.push(this.name); return paths; }); mainTemplate.plugin("hash", (hash) => { hash.update("exports amd"); hash.update(this.name); }); } } module.exports = AmdMainTemplatePlugin; webpack-3.5.6/lib/AsyncDependenciesBlock.js000066400000000000000000000020021315401342100205700ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependenciesBlock = require("./DependenciesBlock"); module.exports = class AsyncDependenciesBlock extends DependenciesBlock { constructor(name, module, loc) { super(); this.chunkName = name; this.chunks = null; this.module = module; this.loc = loc; } get chunk() { throw new Error("`chunk` was been renamed to `chunks` and is now an array"); } set chunk(chunk) { throw new Error("`chunk` was been renamed to `chunks` and is now an array"); } updateHash(hash) { hash.update(this.chunkName || ""); hash.update(this.chunks && this.chunks.map((chunk) => { return chunk.id !== null ? chunk.id : ""; }).join(",") || ""); super.updateHash(hash); } disconnect() { this.chunks = null; super.disconnect(); } unseal() { this.chunks = null; super.unseal(); } sortItems() { super.sortItems(); if(this.chunks) { this.chunks.sort((a, b) => a.compareTo(b)); } } }; webpack-3.5.6/lib/AutomaticPrefetchPlugin.js000066400000000000000000000021331315401342100210240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("async"); const PrefetchDependency = require("./dependencies/PrefetchDependency"); const NormalModule = require("./NormalModule"); class AutomaticPrefetchPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory); }); let lastModules = null; compiler.plugin("after-compile", (compilation, callback) => { lastModules = compilation.modules .filter(m => m instanceof NormalModule) .map(m => ({ context: m.context, request: m.request })); callback(); }); compiler.plugin("make", (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-3.5.6/lib/BannerPlugin.js000066400000000000000000000036151315401342100166300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); const wrapComment = (str) => { if(!str.includes("\n")) return `/*! ${str} */`; return `/*!\n * ${str.split("\n").join("\n * ")}\n */`; }; class BannerPlugin { constructor(options) { if(arguments.length > 1) throw new Error("BannerPlugin only takes one argument (pass an options object)"); if(typeof options === "string") options = { banner: options }; this.options = options || {}; this.banner = this.options.raw ? options.banner : wrapComment(options.banner); } apply(compiler) { const options = this.options; const banner = this.banner; compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunk-assets", (chunks, callback) => { chunks.forEach((chunk) => { if(options.entryOnly && !chunk.isInitial()) return; chunk.files .filter(ModuleFilenameHelpers.matchObject.bind(undefined, options)) .forEach((file) => { 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); } if(filename.indexOf("/") < 0) { basename = filename; } else { basename = filename.substr(filename.lastIndexOf("/") + 1); } const comment = compilation.getPath(banner, { hash, chunk, filename, basename, query, }); return compilation.assets[file] = new ConcatSource(comment, "\n", compilation.assets[file]); }); }); callback(); }); }); } } module.exports = BannerPlugin; webpack-3.5.6/lib/BasicEvaluatedExpression.js000066400000000000000000000071621315401342100212010ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class BasicEvaluatedExpression { constructor() { this.range = null; } isNull() { return !!this.null; } isString() { return Object.prototype.hasOwnProperty.call(this, "string"); } isNumber() { return Object.prototype.hasOwnProperty.call(this, "number"); } isBoolean() { return Object.prototype.hasOwnProperty.call(this, "bool"); } isRegExp() { return Object.prototype.hasOwnProperty.call(this, "regExp"); } isConditional() { return Object.prototype.hasOwnProperty.call(this, "options"); } isArray() { return Object.prototype.hasOwnProperty.call(this, "items"); } isConstArray() { return Object.prototype.hasOwnProperty.call(this, "array"); } isIdentifier() { return Object.prototype.hasOwnProperty.call(this, "identifier"); } isWrapped() { return Object.prototype.hasOwnProperty.call(this, "prefix") || Object.prototype.hasOwnProperty.call(this, "postfix"); } isTemplateString() { return Object.prototype.hasOwnProperty.call(this, "quasis"); } isTruthy() { return this.truthy; } isFalsy() { return this.falsy; } asBool() { if(this.truthy) return true; else if(this.falsy) return false; else if(this.isBoolean()) return this.bool; else if(this.isNull()) return false; else if(this.isString()) return !!this.string; else if(this.isNumber()) return !!this.number; else if(this.isRegExp()) return true; else if(this.isArray()) return true; else if(this.isConstArray()) return true; else if(this.isWrapped()) return this.prefix && this.prefix.asBool() || this.postfix && this.postfix.asBool() ? true : undefined; else if(this.isTemplateString()) { if(this.quasis.length === 1) return this.quasis[0].asBool(); for(let i = 0; i < this.quasis.length; i++) { if(this.quasis[i].asBool()) return true; } // can't tell if string will be empty without executing } return undefined; } setString(str) { if(str === null) delete this.string; else this.string = str; return this; } setNull() { this.null = true; return this; } setNumber(num) { if(num === null) delete this.number; else this.number = num; return this; } setBoolean(bool) { if(bool === null) delete this.bool; else this.bool = bool; return this; } setRegExp(regExp) { if(regExp === null) delete this.regExp; else this.regExp = regExp; return this; } setIdentifier(identifier) { if(identifier === null) delete this.identifier; else this.identifier = identifier; return this; } setWrapped(prefix, postfix) { this.prefix = prefix; this.postfix = postfix; return this; } unsetWrapped() { delete this.prefix; delete this.postfix; return this; } setOptions(options) { if(options === null) delete this.options; else this.options = options; return this; } setItems(items) { if(items === null) delete this.items; else this.items = items; return this; } setArray(array) { if(array === null) delete this.array; else this.array = array; return this; } setTemplateString(quasis) { if(quasis === null) delete this.quasis; else this.quasis = quasis; return this; } setTruthy() { this.falsy = false; this.truthy = true; return this; } setFalsy() { this.falsy = true; this.truthy = false; return this; } addOptions(options) { if(!this.options) this.options = []; options.forEach(item => { this.options.push(item); }, this); return this; } setRange(range) { this.range = range; return this; } } module.exports = BasicEvaluatedExpression; webpack-3.5.6/lib/CachePlugin.js000066400000000000000000000043721315401342100164270ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("async"); class CachePlugin { constructor(cache) { this.cache = cache || {}; this.FS_ACCURENCY = 2000; } apply(compiler) { if(Array.isArray(compiler.compilers)) { compiler.compilers.forEach((c, idx) => { c.apply(new CachePlugin(this.cache[idx] = this.cache[idx] || {})); }); } else { compiler.plugin("compilation", compilation => { if(!compilation.notCacheable) { compilation.cache = this.cache; } else if(this.watching) { compilation.warnings.push( new Error(`CachePlugin - Cache cannot be used because of: ${compilation.notCacheable}`) ); } }); compiler.plugin("watch-run", (compiler, callback) => { this.watching = true; callback(); }); compiler.plugin("run", (compiler, callback) => { if(!compiler._lastCompilationFileDependencies) return callback(); const fs = compiler.inputFileSystem; const fileTs = compiler.fileTimestamps = {}; 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[file] = +stat.mtime || Infinity; callback(); }); }, err => { if(err) return callback(err); Object.keys(fileTs).forEach(key => { fileTs[key] += this.FS_ACCURENCY; }); callback(); }); }); compiler.plugin("after-compile", function(compilation, callback) { compilation.compiler._lastCompilationFileDependencies = compilation.fileDependencies; compilation.compiler._lastCompilationContextDependencies = compilation.contextDependencies; callback(); }); } } /* istanbul ignore next */ applyMtime(mtime) { if(this.FS_ACCURENCY > 1 && mtime % 2 !== 0) this.FS_ACCURENCY = 1; else if(this.FS_ACCURENCY > 10 && mtime % 20 !== 0) this.FS_ACCURENCY = 10; else if(this.FS_ACCURENCY > 100 && mtime % 200 !== 0) this.FS_ACCURENCY = 100; else if(this.FS_ACCURENCY > 1000 && mtime % 2000 !== 0) this.FS_ACCURENCY = 1000; } } module.exports = CachePlugin; webpack-3.5.6/lib/CaseSensitiveModulesWarning.js000066400000000000000000000026421315401342100216670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); module.exports = class CaseSensitiveModulesWarning extends WebpackError { constructor(modules) { super(); this.name = "CaseSensitiveModulesWarning"; const sortedModules = this._sort(modules); const modulesList = this._moduleMessages(sortedModules); this.message = "There are multiple modules with names that only differ in casing.\n" + "This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.\n" + `Use equal casing. Compare these module identifiers:\n${modulesList}`; this.origin = this.module = sortedModules[0]; Error.captureStackTrace(this, this.constructor); } _sort(modules) { return modules.slice().sort((a, b) => { a = a.identifier(); b = b.identifier(); /* istanbul ignore next */ if(a < b) return -1; /* istanbul ignore next */ if(a > b) return 1; /* istanbul ignore next */ return 0; }); } _moduleMessages(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"); } }; webpack-3.5.6/lib/Chunk.js000066400000000000000000000263511315401342100153160ustar00rootroot00000000000000/* 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 SortableSet = require("./util/SortableSet"); let debugId = 1000; const sortById = (a, b) => { if(a.id < b.id) return -1; if(b.id < a.id) return 1; return 0; }; const sortByIdentifier = (a, b) => { if(a.identifier() > b.identifier()) return 1; if(a.identifier() < b.identifier()) return -1; return 0; }; class Chunk { constructor(name, module, loc) { this.id = null; this.ids = null; this.debugId = debugId++; this.name = name; this._modules = new SortableSet(undefined, sortByIdentifier); this.entrypoints = []; this.chunks = []; this.parents = []; this.blocks = []; this.origins = []; this.files = []; this.rendered = false; if(module) { this.origins.push({ module, loc, name }); } } get entry() { throw new Error("Chunk.entry was removed. Use hasRuntime()"); } set entry(data) { throw new Error("Chunk.entry was removed. Use hasRuntime()"); } get initial() { throw new Error("Chunk.initial was removed. Use isInitial()"); } set initial(data) { throw new Error("Chunk.initial was removed. Use isInitial()"); } hasRuntime() { if(this.entrypoints.length === 0) return false; return this.entrypoints[0].chunks[0] === this; } isInitial() { return this.entrypoints.length > 0; } hasEntryModule() { return !!this.entryModule; } addToCollection(collection, item) { if(item === this) { return false; } if(collection.indexOf(item) > -1) { return false; } collection.push(item); return true; } addChunk(chunk) { return this.addToCollection(this.chunks, chunk); } addParent(parentChunk) { return this.addToCollection(this.parents, parentChunk); } addModule(module) { if(!this._modules.has(module)) { this._modules.add(module); return true; } return false; } addBlock(block) { return this.addToCollection(this.blocks, block); } removeModule(module) { if(this._modules.delete(module)) { module.removeChunk(this); return true; } return false; } removeChunk(chunk) { const idx = this.chunks.indexOf(chunk); if(idx >= 0) { this.chunks.splice(idx, 1); chunk.removeParent(this); return true; } return false; } removeParent(chunk) { const idx = this.parents.indexOf(chunk); if(idx >= 0) { this.parents.splice(idx, 1); chunk.removeChunk(this); return true; } return false; } addOrigin(module, loc) { this.origins.push({ module, loc, name: this.name }); } setModules(modules) { this._modules = new SortableSet(modules, sortByIdentifier); } getNumberOfModules() { return this._modules.size; } get modulesIterable() { return this._modules; } forEachModule(fn) { this._modules.forEach(fn); } mapModules(fn) { return Array.from(this._modules, fn); } compareTo(otherChunk) { this._modules.sort(); otherChunk._modules.sort(); if(this._modules.size > otherChunk._modules.size) return -1; if(this._modules.size < otherChunk._modules.size) return 1; const a = this._modules[Symbol.iterator](); const b = otherChunk._modules[Symbol.iterator](); while(true) { // eslint-disable-line const aItem = a.next(); const bItem = b.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; } } containsModule(module) { return this._modules.has(module); } getModules() { return Array.from(this._modules); } getModulesIdent() { this._modules.sort(); let str = ""; this._modules.forEach(m => { str += m.identifier() + "#"; }); return str; } remove(reason) { // cleanup modules // Array.from is used here to create a clone, because removeChunk modifies this._modules Array.from(this._modules).forEach(module => { module.removeChunk(this); }); // cleanup parents this.parents.forEach(parentChunk => { // remove this chunk from its parents const idx = parentChunk.chunks.indexOf(this); if(idx >= 0) { parentChunk.chunks.splice(idx, 1); } // cleanup "sub chunks" this.chunks.forEach(chunk => { /** * remove this chunk as "intermediary" and connect * it "sub chunks" and parents directly */ // add parent to each "sub chunk" chunk.addParent(parentChunk); // add "sub chunk" to parent parentChunk.addChunk(chunk); }); }); /** * we need to iterate again over the chunks * to remove this from the chunks parents. * This can not be done in the above loop * as it is not garuanteed that `this.parents` contains anything. */ this.chunks.forEach(chunk => { // remove this as parent of every "sub chunk" const idx = chunk.parents.indexOf(this); if(idx >= 0) { chunk.parents.splice(idx, 1); } }); // cleanup blocks this.blocks.forEach(block => { const idx = block.chunks.indexOf(this); if(idx >= 0) { block.chunks.splice(idx, 1); if(block.chunks.length === 0) { block.chunks = null; block.chunkReason = reason; } } }); } moveModule(module, otherChunk) { module.removeChunk(this); module.addChunk(otherChunk); otherChunk.addModule(module); module.rewriteChunkInReasons(this, [otherChunk]); } replaceChunk(oldChunk, newChunk) { const idx = this.chunks.indexOf(oldChunk); if(idx >= 0) { this.chunks.splice(idx, 1); } if(this !== newChunk && newChunk.addParent(this)) { this.addChunk(newChunk); } } replaceParentChunk(oldParentChunk, newParentChunk) { const idx = this.parents.indexOf(oldParentChunk); if(idx >= 0) { this.parents.splice(idx, 1); } if(this !== newParentChunk && newParentChunk.addChunk(this)) { this.addParent(newParentChunk); } } integrate(otherChunk, reason) { if(!this.canBeIntegrated(otherChunk)) { return false; } // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules const otherChunkModules = Array.from(otherChunk._modules); otherChunkModules.forEach(module => otherChunk.moveModule(module, this)); otherChunk._modules.clear(); otherChunk.parents.forEach(parentChunk => parentChunk.replaceChunk(otherChunk, this)); otherChunk.parents.length = 0; otherChunk.chunks.forEach(chunk => chunk.replaceParentChunk(otherChunk, this)); otherChunk.chunks.length = 0; otherChunk.blocks.forEach(b => { b.chunks = b.chunks ? b.chunks.map(c => { return c === otherChunk ? this : c; }) : [this]; b.chunkReason = reason; this.addBlock(b); }); otherChunk.blocks.length = 0; otherChunk.origins.forEach(origin => { this.origins.push(origin); }); this.origins.forEach(origin => { if(!origin.reasons) { origin.reasons = [reason]; } else if(origin.reasons[0] !== reason) { origin.reasons.unshift(reason); } }); this.chunks = this.chunks.filter(chunk => { return chunk !== otherChunk && chunk !== this; }); this.parents = this.parents.filter(parentChunk => { return parentChunk !== otherChunk && parentChunk !== this; }); return true; } split(newChunk) { this.blocks.forEach(block => { newChunk.blocks.push(block); block.chunks.push(newChunk); }); this.chunks.forEach(chunk => { newChunk.chunks.push(chunk); chunk.parents.push(newChunk); }); this.parents.forEach(parentChunk => { parentChunk.chunks.push(newChunk); newChunk.parents.push(parentChunk); }); this.entrypoints.forEach(entrypoint => { entrypoint.insertChunk(newChunk, this); }); } isEmpty() { return this._modules.size === 0; } updateHash(hash) { hash.update(`${this.id} `); hash.update(this.ids ? this.ids.join(",") : ""); hash.update(`${this.name || ""} `); this._modules.forEach(m => m.updateHash(hash)); } canBeIntegrated(otherChunk) { if(otherChunk.isInitial()) { return false; } if(this.isInitial()) { if(otherChunk.parents.length !== 1 || otherChunk.parents[0] !== this) { return false; } } return true; } addMultiplierAndOverhead(size, options) { const overhead = typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; const multiplicator = this.isInitial() ? (options.entryChunkMultiplicator || 10) : 1; return size * multiplicator + overhead; } modulesSize() { let count = 0; for(const module of this._modules) { count += module.size(); } return count; } size(options) { return this.addMultiplierAndOverhead(this.modulesSize(), options); } 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); } getChunkMaps(includeEntries, realHash) { const chunksProcessed = []; const chunkHashMap = {}; const chunkNameMap = {}; (function addChunk(chunk) { if(chunksProcessed.indexOf(chunk) >= 0) return; chunksProcessed.push(chunk); if(!chunk.hasRuntime() || includeEntries) { chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash; if(chunk.name) chunkNameMap[chunk.id] = chunk.name; } chunk.chunks.forEach(addChunk); }(this)); return { hash: chunkHashMap, name: chunkNameMap }; } sortModules(sortByFn) { this._modules.sortWith(sortByFn || sortById); } sortItems() { this.sortModules(); this.origins.sort((a, b) => { const aIdent = a.module.identifier(); const bIdent = b.module.identifier(); if(aIdent < bIdent) return -1; if(aIdent > bIdent) return 1; return compareLocations(a.loc, b.loc); }); this.origins.forEach(origin => { if(origin.reasons) origin.reasons.sort(); }); this.parents.sort(sortById); this.chunks.sort(sortById); } toString() { return `Chunk[${Array.from(this._modules).join()}]`; } checkConstraints() { const chunk = this; chunk.chunks.forEach((child, idx) => { if(chunk.chunks.indexOf(child) !== idx) throw new Error(`checkConstraints: duplicate child in chunk ${chunk.debugId} ${child.debugId}`); if(child.parents.indexOf(chunk) < 0) throw new Error(`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`); }); chunk.parents.forEach((parentChunk, idx) => { if(chunk.parents.indexOf(parentChunk) !== idx) throw new Error(`checkConstraints: duplicate parent in chunk ${chunk.debugId} ${parentChunk.debugId}`); if(parentChunk.chunks.indexOf(chunk) < 0) throw new Error(`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`); }); } } Object.defineProperty(Chunk.prototype, "modules", { configurable: false, get: util.deprecate(function() { return Array.from(this._modules); }, "Chunk.modules is deprecated. Use Chunk.getNumberOfModules/mapModules/forEachModule/containsModule instead."), set: util.deprecate(function(value) { this.setModules(value); }, "Chunk.modules is deprecated. Use Chunk.addModule/removeModule instead.") }); module.exports = Chunk; webpack-3.5.6/lib/ChunkRenderError.js000066400000000000000000000007761315401342100174730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); class ChunkRenderError extends WebpackError { 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-3.5.6/lib/ChunkTemplate.js000066400000000000000000000021201315401342100167760ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; const Template = require("./Template"); module.exports = class ChunkTemplate extends Template { constructor(outputOptions) { super(outputOptions); } render(chunk, moduleTemplate, dependencyTemplates) { const moduleSources = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates); const core = this.applyPluginsWaterfall("modules", moduleSources, chunk, moduleTemplate, dependencyTemplates); let source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates); if(chunk.hasEntryModule()) { source = this.applyPluginsWaterfall("render-with-entry", source, chunk); } chunk.rendered = true; return new ConcatSource(source, ";"); } updateHash(hash) { hash.update("ChunkTemplate"); hash.update("2"); this.applyPlugins("hash", hash); } updateHashForChunk(hash, chunk) { this.updateHash(hash); this.applyPlugins("hash-for-chunk", hash, chunk); } }; webpack-3.5.6/lib/CompatibilityPlugin.js000066400000000000000000000037401315401342100202330ustar00rootroot00000000000000/* 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 jsonLoaderPath = require.resolve("json-loader"); const matchJson = /\.json$/i; class CompatibilityPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.browserify !== "undefined" && !parserOptions.browserify) return; parser.plugin("call require", (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.request === "." && last.userRequest === "." && last.recursive) parser.state.current.dependencies.pop(); } parser.state.current.addDependency(dep); return true; }); }); params.normalModuleFactory.plugin("after-resolve", (data, done) => { // if this is a json file and there are no loaders active, we use the json-loader in order to avoid parse errors // @see https://github.com/webpack/webpack/issues/3363 if(matchJson.test(data.request) && data.loaders.length === 0) { data.loaders.push({ loader: jsonLoaderPath }); } done(null, data); }); }); } } module.exports = CompatibilityPlugin; webpack-3.5.6/lib/Compilation.js000066400000000000000000001112301315401342100165130ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("async"); const crypto = require("crypto"); const Tapable = require("tapable"); const EntryModuleNotFoundError = require("./EntryModuleNotFoundError"); const ModuleNotFoundError = require("./ModuleNotFoundError"); const ModuleDependencyWarning = require("./ModuleDependencyWarning"); const ModuleDependencyError = require("./ModuleDependencyError"); const Module = require("./Module"); 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 Dependency = require("./Dependency"); const ChunkRenderError = require("./ChunkRenderError"); const CachedSource = require("webpack-sources").CachedSource; const Stats = require("./Stats"); const Semaphore = require("./util/Semaphore"); function byId(a, b) { if(a.id < b.id) return -1; if(a.id > b.id) return 1; return 0; } function iterationBlockVariable(variables, fn) { for(let indexVariable = 0; indexVariable < variables.length; indexVariable++) { let varDep = variables[indexVariable].dependencies; for(let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { fn(varDep[indexVDep]); } } } function iterationOfArrayCallback(arr, fn) { for(let index = 0; index < arr.length; index++) { fn(arr[index]); } } class Compilation extends Tapable { constructor(compiler) { super(); this.compiler = compiler; this.resolvers = compiler.resolvers; this.inputFileSystem = compiler.inputFileSystem; const options = this.options = compiler.options; this.outputOptions = options && options.output; 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.moduleTemplate = new ModuleTemplate(this.outputOptions); this.semaphore = new Semaphore(options.parallelism || 100); this.entries = []; this.preparedChunks = []; this.entrypoints = {}; this.chunks = []; this.namedChunks = {}; this.modules = []; this._modules = {}; this.cache = null; this.records = null; this.nextFreeModuleIndex = undefined; this.nextFreeModuleIndex2 = undefined; this.additionalChunkAssets = []; this.assets = {}; this.errors = []; this.warnings = []; this.children = []; this.dependencyFactories = new Map(); this.dependencyTemplates = new Map(); this.dependencyTemplates.set("hash", ""); this.childrenCounters = {}; } getStats() { return new Stats(this); } templatesPlugin(name, fn) { this.mainTemplate.plugin(name, fn); this.chunkTemplate.plugin(name, fn); } addModule(module, cacheGroup) { const identifier = module.identifier(); if(this._modules[identifier]) { return false; } const cacheName = (cacheGroup || "m") + identifier; if(this.cache && this.cache[cacheName]) { const cacheModule = this.cache[cacheName]; let rebuild = true; if(!cacheModule.error && cacheModule.cacheable && this.fileTimestamps && this.contextTimestamps) { rebuild = cacheModule.needRebuild(this.fileTimestamps, this.contextTimestamps); } if(!rebuild) { cacheModule.disconnect(); this._modules[identifier] = cacheModule; this.modules.push(cacheModule); cacheModule.errors.forEach(err => this.errors.push(err), this); cacheModule.warnings.forEach(err => this.warnings.push(err), this); return cacheModule; } } module.unbuild(); this._modules[identifier] = module; if(this.cache) { this.cache[cacheName] = module; } this.modules.push(module); return true; } getModule(module) { const identifier = module.identifier(); return this._modules[identifier]; } findModule(identifier) { return this._modules[identifier]; } buildModule(module, optional, origin, dependencies, thisCallback) { this.applyPlugins1("build-module", module); if(module.building) return module.building.push(thisCallback); const building = module.building = [thisCallback]; function callback(err) { module.building = undefined; building.forEach(cb => cb(err)); } module.build(this.options, this, this.resolvers.normal, 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); } module.dependencies.sort(Dependency.compare); if(error) { this.applyPlugins2("failed-module", module, error); return callback(error); } this.applyPlugins1("succeed-module", module); return callback(); }); } processModuleDependencies(module, callback) { const dependencies = []; function addDependency(dep) { for(let i = 0; i < dependencies.length; i++) { if(dep.isEqualResource(dependencies[i][0])) { return dependencies[i].push(dep); } } dependencies.push([dep]); } function addDependenciesBlock(block) { if(block.dependencies) { iterationOfArrayCallback(block.dependencies, addDependency); } if(block.blocks) { iterationOfArrayCallback(block.blocks, addDependenciesBlock); } if(block.variables) { iterationBlockVariable(block.variables, addDependency); } } addDependenciesBlock(module); this.addModuleDependencies(module, dependencies, this.bail, null, true, callback); } addModuleDependencies(module, dependencies, bail, cacheGroup, recursive, callback) { let _this = this; const start = _this.profile && Date.now(); const factories = []; for(let i = 0; i < dependencies.length; i++) { const factory = _this.dependencyFactories.get(dependencies[i][0].constructor); if(!factory) { return callback(new Error(`No module factory available for dependency type: ${dependencies[i][0].constructor.name}`)); } factories[i] = [factory, dependencies[i]]; } asyncLib.forEach(factories, function iteratorFactory(item, callback) { const dependencies = item[1]; const errorAndCallback = function errorAndCallback(err) { err.origin = module; _this.errors.push(err); if(bail) { callback(err); } else { callback(); } }; const warningAndCallback = function warningAndCallback(err) { err.origin = module; _this.warnings.push(err); callback(); }; _this.semaphore.acquire(() => { const factory = item[0]; factory.create({ contextInfo: { issuer: module.nameForCondition && module.nameForCondition(), compiler: _this.compiler.name }, context: module.context, dependencies: dependencies }, function factoryCallback(err, dependentModule) { let afterFactory; function isOptional() { return dependencies.filter(d => !d.optional).length === 0; } function errorOrWarningAndCallback(err) { if(isOptional()) { return warningAndCallback(err); } else { return errorAndCallback(err); } } function iterationDependencies(depend) { for(let index = 0; index < depend.length; index++) { const dep = depend[index]; dep.module = dependentModule; dependentModule.addReason(module, dep); } } if(err) { _this.semaphore.release(); return errorOrWarningAndCallback(new ModuleNotFoundError(module, err, dependencies)); } if(!dependentModule) { _this.semaphore.release(); return process.nextTick(callback); } if(_this.profile) { if(!dependentModule.profile) { dependentModule.profile = {}; } afterFactory = Date.now(); dependentModule.profile.factory = afterFactory - start; } dependentModule.issuer = module; const newModule = _this.addModule(dependentModule, cacheGroup); if(!newModule) { // from cache dependentModule = _this.getModule(dependentModule); if(dependentModule.optional) { dependentModule.optional = isOptional(); } iterationDependencies(dependencies); if(_this.profile) { if(!module.profile) { module.profile = {}; } const time = Date.now() - start; if(!module.profile.dependencies || time > module.profile.dependencies) { module.profile.dependencies = time; } } _this.semaphore.release(); return process.nextTick(callback); } if(newModule instanceof Module) { if(_this.profile) { newModule.profile = dependentModule.profile; } newModule.optional = isOptional(); newModule.issuer = dependentModule.issuer; dependentModule = newModule; iterationDependencies(dependencies); if(_this.profile) { const afterBuilding = Date.now(); module.profile.building = afterBuilding - afterFactory; } _this.semaphore.release(); if(recursive) { return process.nextTick(_this.processModuleDependencies.bind(_this, dependentModule, callback)); } else { return process.nextTick(callback); } } dependentModule.optional = isOptional(); iterationDependencies(dependencies); _this.buildModule(dependentModule, isOptional(), module, dependencies, err => { if(err) { _this.semaphore.release(); return errorOrWarningAndCallback(err); } if(_this.profile) { const afterBuilding = Date.now(); dependentModule.profile.building = afterBuilding - afterFactory; } _this.semaphore.release(); if(recursive) { _this.processModuleDependencies(dependentModule, callback); } else { return callback(); } }); }); }); }, function finalCallbackAddModuleDependencies(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. Setting _this to null workarounds the following issue in V8. // https://bugs.chromium.org/p/chromium/issues/detail?id=612191 _this = null; if(err) { return callback(err); } return process.nextTick(callback); }); } _addModuleChain(context, dependency, onModule, callback) { const start = this.profile && Date.now(); 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 moduleFactory = this.dependencyFactories.get(dependency.constructor); 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(this.profile) { if(!module.profile) { module.profile = {}; } afterFactory = Date.now(); module.profile.factory = afterFactory - start; } const result = this.addModule(module); if(!result) { module = this.getModule(module); onModule(module); if(this.profile) { const afterBuilding = Date.now(); module.profile.building = afterBuilding - afterFactory; } this.semaphore.release(); return callback(null, module); } if(result instanceof Module) { if(this.profile) { result.profile = module.profile; } module = result; onModule(module); moduleReady.call(this); return; } onModule(module); this.buildModule(module, false, null, null, (err) => { if(err) { this.semaphore.release(); return errorAndCallback(err); } if(this.profile) { const afterBuilding = Date.now(); module.profile.building = afterBuilding - afterFactory; } moduleReady.call(this); }); function moduleReady() { this.semaphore.release(); this.processModuleDependencies(module, err => { if(err) { return callback(err); } return callback(null, module); }); } }); }); } addEntry(context, entry, name, callback) { const slot = { name: name, module: null }; this.preparedChunks.push(slot); this._addModuleChain(context, entry, (module) => { entry.module = module; this.entries.push(module); module.issuer = null; }, (err, module) => { if(err) { return callback(err); } if(module) { slot.module = module; } else { const idx = this.preparedChunks.indexOf(slot); this.preparedChunks.splice(idx, 1); } return callback(null, module); }); } prefetch(context, dependency, callback) { this._addModuleChain(context, dependency, module => { module.prefetched = true; module.issuer = null; }, callback); } rebuildModule(module, thisCallback) { if(module.variables.length || module.blocks.length) throw new Error("Cannot rebuild a complex module with variables or blocks"); if(module.rebuilding) { return module.rebuilding.push(thisCallback); } const rebuilding = module.rebuilding = [thisCallback]; function callback(err) { module.rebuilding = undefined; rebuilding.forEach(cb => cb(err)); } const deps = module.dependencies.slice(); this.buildModule(module, false, module, null, (err) => { if(err) return callback(err); this.processModuleDependencies(module, (err) => { if(err) return callback(err); deps.forEach(d => { if(d.module && d.module.removeReason(module, d)) { module.forEachChunk(chunk => { if(!d.module.hasReasonForChunk(chunk)) { if(d.module.removeChunk(chunk)) { this.removeChunkFromDependencies(d.module, chunk); } } }); } }); callback(); }); }); } finish() { const modules = this.modules; this.applyPlugins1("finish-modules", modules); for(let index = 0; index < modules.length; index++) { const module = modules[index]; this.reportDependencyErrorsAndWarnings(module, [module]); } } unseal() { this.applyPlugins0("unseal"); this.chunks.length = 0; this.namedChunks = {}; this.additionalChunkAssets.length = 0; this.assets = {}; this.modules.forEach(module => module.unseal()); } seal(callback) { const self = this; self.applyPlugins0("seal"); self.nextFreeModuleIndex = 0; self.nextFreeModuleIndex2 = 0; self.preparedChunks.forEach(preparedChunk => { const module = preparedChunk.module; const chunk = self.addChunk(preparedChunk.name, module); const entrypoint = self.entrypoints[chunk.name] = new Entrypoint(chunk.name); entrypoint.unshiftChunk(chunk); chunk.addModule(module); module.addChunk(chunk); chunk.entryModule = module; self.assignIndex(module); self.assignDepth(module); self.processDependenciesBlockForChunk(module, chunk); }); self.sortModules(self.modules); self.applyPlugins0("optimize"); while(self.applyPluginsBailResult1("optimize-modules-basic", self.modules) || self.applyPluginsBailResult1("optimize-modules", self.modules) || self.applyPluginsBailResult1("optimize-modules-advanced", self.modules)) { /* empty */ } self.applyPlugins1("after-optimize-modules", self.modules); while(self.applyPluginsBailResult1("optimize-chunks-basic", self.chunks) || self.applyPluginsBailResult1("optimize-chunks", self.chunks) || self.applyPluginsBailResult1("optimize-chunks-advanced", self.chunks)) { /* empty */ } self.applyPlugins1("after-optimize-chunks", self.chunks); self.applyPluginsAsyncSeries("optimize-tree", self.chunks, self.modules, function sealPart2(err) { if(err) { return callback(err); } self.applyPlugins2("after-optimize-tree", self.chunks, self.modules); while(self.applyPluginsBailResult("optimize-chunk-modules-basic", self.chunks, self.modules) || self.applyPluginsBailResult("optimize-chunk-modules", self.chunks, self.modules) || self.applyPluginsBailResult("optimize-chunk-modules-advanced", self.chunks, self.modules)) { /* empty */ } self.applyPlugins2("after-optimize-chunk-modules", self.chunks, self.modules); const shouldRecord = self.applyPluginsBailResult("should-record") !== false; self.applyPlugins2("revive-modules", self.modules, self.records); self.applyPlugins1("optimize-module-order", self.modules); self.applyPlugins1("advanced-optimize-module-order", self.modules); self.applyPlugins1("before-module-ids", self.modules); self.applyPlugins1("module-ids", self.modules); self.applyModuleIds(); self.applyPlugins1("optimize-module-ids", self.modules); self.applyPlugins1("after-optimize-module-ids", self.modules); self.sortItemsWithModuleIds(); self.applyPlugins2("revive-chunks", self.chunks, self.records); self.applyPlugins1("optimize-chunk-order", self.chunks); self.applyPlugins1("before-chunk-ids", self.chunks); self.applyChunkIds(); self.applyPlugins1("optimize-chunk-ids", self.chunks); self.applyPlugins1("after-optimize-chunk-ids", self.chunks); self.sortItemsWithChunkIds(); if(shouldRecord) self.applyPlugins2("record-modules", self.modules, self.records); if(shouldRecord) self.applyPlugins2("record-chunks", self.chunks, self.records); self.applyPlugins0("before-hash"); self.createHash(); self.applyPlugins0("after-hash"); if(shouldRecord) self.applyPlugins1("record-hash", self.records); self.applyPlugins0("before-module-assets"); self.createModuleAssets(); if(self.applyPluginsBailResult("should-generate-chunk-assets") !== false) { self.applyPlugins0("before-chunk-assets"); self.createChunkAssets(); } self.applyPlugins1("additional-chunk-assets", self.chunks); self.summarizeDependencies(); if(shouldRecord) self.applyPlugins2("record", self, self.records); self.applyPluginsAsync("additional-assets", err => { if(err) { return callback(err); } self.applyPluginsAsync("optimize-chunk-assets", self.chunks, err => { if(err) { return callback(err); } self.applyPlugins1("after-optimize-chunk-assets", self.chunks); self.applyPluginsAsync("optimize-assets", self.assets, err => { if(err) { return callback(err); } self.applyPlugins1("after-optimize-assets", self.assets); if(self.applyPluginsBailResult("need-additional-seal")) { self.unseal(); return self.seal(callback); } return self.applyPluginsAsync("after-seal", callback); }); }); }); }); } sortModules(modules) { modules.sort((a, b) => { if(a.index < b.index) return -1; if(a.index > b.index) return 1; return 0; }); } 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); } } addChunk(name, module, loc) { if(name) { if(Object.prototype.hasOwnProperty.call(this.namedChunks, name)) { const chunk = this.namedChunks[name]; if(module) { chunk.addOrigin(module, loc); } return chunk; } } const chunk = new Chunk(name, module, loc); this.chunks.push(chunk); if(name) { this.namedChunks[name] = chunk; } return chunk; } assignIndex(module) { const _this = this; const queue = [() => { assignIndexToModule(module); }]; const iteratorAllDependencies = d => { queue.push(() => assignIndexToDependency(d)); }; function assignIndexToModule(module) { // enter module if(typeof module.index !== "number") { module.index = _this.nextFreeModuleIndex++; // leave module queue.push(() => module.index2 = _this.nextFreeModuleIndex2++); // enter it as block assignIndexToDependencyBlock(module); } } function assignIndexToDependency(dependency) { if(dependency.module) { queue.push(() => assignIndexToModule(dependency.module)); } } function assignIndexToDependencyBlock(block) { let allDependencies = []; function iteratorDependency(d) { allDependencies.push(d); } function iteratorBlock(b) { queue.push(() => assignIndexToDependencyBlock(b)); } if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.blocks) { const blocks = block.blocks; let indexBlock = blocks.length; while(indexBlock--) { iteratorBlock(blocks[indexBlock]); } } let indexAll = allDependencies.length; while(indexAll--) { iteratorAllDependencies(allDependencies[indexAll]); } } while(queue.length) { queue.pop()(); } } assignDepth(module) { function assignDepthToModule(module, depth) { // enter module if(typeof module.depth === "number" && module.depth <= depth) return; module.depth = depth; // enter it as block assignDepthToDependencyBlock(module, depth + 1); } function assignDepthToDependency(dependency, depth) { if(dependency.module) { queue.push(() => assignDepthToModule(dependency.module, depth)); } } function assignDepthToDependencyBlock(block, depth) { function iteratorDependency(d) { assignDepthToDependency(d, depth); } function iteratorBlock(b) { assignDepthToDependencyBlock(b, depth); } if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.blocks) { iterationOfArrayCallback(block.blocks, iteratorBlock); } } const queue = [() => { assignDepthToModule(module, 0); }]; while(queue.length) { queue.pop()(); } } processDependenciesBlockForChunk(module, chunk) { let block = module; const initialChunk = chunk; const chunkDependencies = new Map(); // Map> const iteratorBlock = b => { let c; if(!b.chunks) { c = this.addChunk(b.chunkName, b.module, b.loc); b.chunks = [c]; c.addBlock(b); } else { c = b.chunks[0]; } let deps = chunkDependencies.get(chunk); if(!deps) chunkDependencies.set(chunk, deps = []); deps.push({ chunk: c, module }); queue.push({ block: b, module: null, chunk: c }); }; const iteratorDependency = d => { if(!d.module) { return; } if(d.weak) { return; } if(chunk.addModule(d.module)) { d.module.addChunk(chunk); queue.push({ block: d.module, module: d.module, chunk }); } }; const queue = [{ block, module, chunk }]; while(queue.length) { const queueItem = queue.pop(); block = queueItem.block; module = queueItem.module; chunk = queueItem.chunk; if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.blocks) { iterationOfArrayCallback(block.blocks, iteratorBlock); } } chunk = initialChunk; let chunks = new Set(); const queue2 = [{ chunk, chunks }]; const filterFn = dep => { if(chunks.has(dep.chunk)) return false; for(const chunk of chunks) { if(chunk.containsModule(dep.module)) return false; } return true; }; while(queue2.length) { const queueItem = queue2.pop(); chunk = queueItem.chunk; chunks = queueItem.chunks; const deps = chunkDependencies.get(chunk); if(!deps) continue; const depsFiltered = deps.filter(filterFn); for(let i = 0; i < depsFiltered.length; i++) { const dep = depsFiltered[i]; const depChunk = dep.chunk; chunk.addChunk(depChunk); depChunk.addParent(chunk); const newChunks = depsFiltered.length > 1 ? new Set(chunks) : chunks; newChunks.add(chunk); queue2.push({ chunk: depChunk, chunks: newChunks }); } } } removeChunkFromDependencies(block, chunk) { const iteratorDependency = d => { if(!d.module) { return; } if(!d.module.hasReasonForChunk(chunk)) { if(d.module.removeChunk(chunk)) { this.removeChunkFromDependencies(d.module, chunk); } } }; const blocks = block.blocks; for(let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { const chunks = blocks[indexBlock].chunks; for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const blockChunk = chunks[indexChunk]; chunk.removeChunk(blockChunk); blockChunk.removeParent(chunk); this.removeChunkFromDependencies(chunks, blockChunk); } } if(block.dependencies) { iterationOfArrayCallback(block.dependencies, iteratorDependency); } if(block.variables) { iterationBlockVariable(block.variables, iteratorDependency); } } applyModuleIds() { let unusedIds = []; let nextFreeModuleId = 0; let usedIds = []; // TODO consider Map when performance has improved https://gist.github.com/sokra/234c077e1299b7369461f1708519c392 const usedIdMap = Object.create(null); if(this.usedModuleIds) { Object.keys(this.usedModuleIds).forEach(key => { const id = this.usedModuleIds[key]; if(!usedIdMap[id]) { usedIds.push(id); usedIdMap[id] = true; } }); } const modules1 = this.modules; for(let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { const module1 = modules1[indexModule1]; if(module1.id && !usedIdMap[module1.id]) { usedIds.push(module1.id); usedIdMap[module1.id] = true; } } if(usedIds.length > 0) { let usedIdMax = -1; for(let index = 0; index < usedIds.length; index++) { const usedIdKey = usedIds[index]; if(typeof usedIdKey !== "number") { continue; } usedIdMax = Math.max(usedIdMax, usedIdKey); } let lengthFreeModules = nextFreeModuleId = usedIdMax + 1; while(lengthFreeModules--) { if(!usedIdMap[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() { const unusedIds = []; let nextFreeChunkId = 0; function getNextFreeChunkId(usedChunkIds) { const keyChunks = Object.keys(usedChunkIds); let result = -1; for(let index = 0; index < keyChunks.length; index++) { const usedIdKey = keyChunks[index]; const usedIdValue = usedChunkIds[usedIdKey]; if(typeof usedIdValue !== "number") { continue; } result = Math.max(result, usedIdValue); } return result; } if(this.usedChunkIds) { nextFreeChunkId = getNextFreeChunkId(this.usedChunkIds) + 1; let index = nextFreeChunkId; while(index--) { if(this.usedChunkIds[index] !== index) { unusedIds.push(index); } } } const chunks = this.chunks; 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(byId); 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(); } } sortItemsWithChunkIds() { this.chunks.sort(byId); const modules = this.modules; for(let indexModule = 0; indexModule < modules.length; indexModule++) { modules[indexModule].sortItems(true); } const chunks = this.chunks; for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { chunks[indexChunk].sortItems(); } 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); } summarizeDependencies() { function filterDups(array) { const newArray = []; for(let i = 0; i < array.length; i++) { if(i === 0 || array[i - 1] !== array[i]) newArray.push(array[i]); } return newArray; } this.fileDependencies = (this.compilationDependencies || []).slice(); this.contextDependencies = []; this.missingDependencies = []; const children = this.children; for(let indexChildren = 0; indexChildren < children.length; indexChildren++) { const child = children[indexChildren]; this.fileDependencies = this.fileDependencies.concat(child.fileDependencies); this.contextDependencies = this.contextDependencies.concat(child.contextDependencies); this.missingDependencies = this.missingDependencies.concat(child.missingDependencies); } const modules = this.modules; for(let indexModule = 0; indexModule < modules.length; indexModule++) { const module = modules[indexModule]; if(module.fileDependencies) { const fileDependencies = module.fileDependencies; for(let indexFileDep = 0; indexFileDep < fileDependencies.length; indexFileDep++) { this.fileDependencies.push(fileDependencies[indexFileDep]); } } if(module.contextDependencies) { const contextDependencies = module.contextDependencies; for(let indexContextDep = 0; indexContextDep < contextDependencies.length; indexContextDep++) { this.contextDependencies.push(contextDependencies[indexContextDep]); } } } this.errors.forEach(error => { if(Array.isArray(error.missing)) { error.missing.forEach(item => this.missingDependencies.push(item)); } }); this.fileDependencies.sort(); this.fileDependencies = filterDups(this.fileDependencies); this.contextDependencies.sort(); this.contextDependencies = filterDups(this.contextDependencies); this.missingDependencies.sort(); this.missingDependencies = filterDups(this.missingDependencies); } createHash() { const outputOptions = this.outputOptions; const hashFunction = outputOptions.hashFunction; const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; const hash = crypto.createHash(hashFunction); if(outputOptions.hashSalt) hash.update(outputOptions.hashSalt); this.mainTemplate.updateHash(hash); this.chunkTemplate.updateHash(hash); this.moduleTemplate.updateHash(hash); this.children.forEach(function(child) { hash.update(child.hash); }); this.warnings.forEach(function(warning) { hash.update(`${warning.message}`); }); this.errors.forEach(function(error) { hash.update(`${error.message}`); }); // 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 0; }); for(let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const chunkHash = crypto.createHash(hashFunction); if(outputOptions.hashSalt) chunkHash.update(outputOptions.hashSalt); chunk.updateHash(chunkHash); if(chunk.hasRuntime()) { this.mainTemplate.updateHashForChunk(chunkHash, chunk); } else { this.chunkTemplate.updateHashForChunk(chunkHash, chunk); } this.applyPlugins2("chunk-hash", chunk, chunkHash); chunk.hash = chunkHash.digest(hashDigest); hash.update(chunk.hash); chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); } this.fullHash = hash.digest(hashDigest); this.hash = this.fullHash.substr(0, hashDigestLength); } modifyHash(update) { const outputOptions = this.outputOptions; const hashFunction = outputOptions.hashFunction; const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; const hash = crypto.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.assets) { Object.keys(module.assets).forEach((assetName) => { const fileName = this.getPath(assetName); this.assets[fileName] = module.assets[assetName]; this.applyPlugins2("module-asset", module, fileName); }); } } } createChunkAssets() { const outputOptions = this.outputOptions; const filename = outputOptions.filename; const chunkFilename = outputOptions.chunkFilename; for(let i = 0; i < this.chunks.length; i++) { const chunk = this.chunks[i]; chunk.files = []; const chunkHash = chunk.hash; let source; let file; const filenameTemplate = chunk.filenameTemplate ? chunk.filenameTemplate : chunk.isInitial() ? filename : chunkFilename; try { const useChunkHash = !chunk.hasRuntime() || (this.mainTemplate.useChunkHash && this.mainTemplate.useChunkHash(chunk)); const usedHash = useChunkHash ? chunkHash : this.fullHash; const cacheName = "c" + chunk.id; if(this.cache && this.cache[cacheName] && this.cache[cacheName].hash === usedHash) { source = this.cache[cacheName].source; } else { if(chunk.hasRuntime()) { source = this.mainTemplate.render(this.hash, chunk, this.moduleTemplate, this.dependencyTemplates); } else { source = this.chunkTemplate.render(chunk, this.moduleTemplate, this.dependencyTemplates); } if(this.cache) { this.cache[cacheName] = { hash: usedHash, source: source = (source instanceof CachedSource ? source : new CachedSource(source)) }; } } file = this.getPath(filenameTemplate, { noChunkHash: !useChunkHash, chunk }); if(this.assets[file]) throw new Error(`Conflict: Multiple assets emit to the same filename ${file}`); this.assets[file] = source; chunk.files.push(file); this.applyPlugins2("chunk-asset", chunk, file); } catch(err) { this.errors.push(new ChunkRenderError(chunk, file || filenameTemplate, err)); } } } getPath(filename, data) { data = data || {}; data.hash = data.hash || this.hash; return this.mainTemplate.applyPluginsWaterfall("asset-path", filename, data); } createChildCompiler(name, outputOptions, plugins) { var idx = (this.childrenCounters[name] || 0); this.childrenCounters[name] = idx + 1; return this.compiler.createChildCompiler(this, name, idx, outputOptions, plugins); } checkConstraints() { const usedIds = {}; const modules = this.modules; for(let indexModule = 0; indexModule < modules.length; indexModule++) { const moduleId = modules[indexModule].id; if(usedIds[moduleId]) throw new Error(`checkConstraints: duplicate module id ${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}`); chunk.checkConstraints(); } } } module.exports = Compilation; webpack-3.5.6/lib/Compiler.js000066400000000000000000000354621315401342100160230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const Tapable = require("tapable"); const Compilation = require("./Compilation"); const Stats = require("./Stats"); const NormalModuleFactory = require("./NormalModuleFactory"); const ContextModuleFactory = require("./ContextModuleFactory"); const makePathsRelative = require("./util/identifier").makePathsRelative; 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.applyPluginsAsync("watch-run", this, 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.applyPluginsBailResult("should-emit", 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.applyPluginsBailResult("need-additional-pass")) { compilation.needAdditionalPass = true; const stats = new Stats(compilation); stats.startTime = this.startTime; stats.endTime = Date.now(); this.compiler.applyPlugins("done", stats); this.compiler.applyPluginsAsync("additional-pass", 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.applyPlugins("failed", err); this.handler(err, stats); return; } this.compiler.applyPlugins("done", stats); this.handler(null, stats); if(!this.closed) { this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies); } this.callbacks.forEach(cb => 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) => { this.pausedWatcher = this.watcher; this.watcher = null; if(err) return this.handler(err); this.compiler.fileTimestamps = fileTimestamps; this.compiler.contextTimestamps = contextTimestamps; this.invalidate(); }, (fileName, changeTime) => { this.compiler.applyPlugins("invalid", fileName, changeTime); }); } invalidate(callback) { if(callback) { this.callbacks.push(callback); } 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) { if(callback === undefined) callback = function() {}; 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 = () => { this.compiler.applyPlugins("watch-close"); callback(); }; } else { this.compiler.applyPlugins("watch-close"); callback(); } } } class Compiler extends Tapable { constructor() { super(); this.outputPath = ""; this.outputFileSystem = null; this.inputFileSystem = null; this.recordsInputPath = null; this.recordsOutputPath = null; this.records = {}; this.fileTimestamps = {}; this.contextTimestamps = {}; this.resolvers = { normal: null, loader: null, context: null }; let deprecationReported = false; this.parser = { plugin: (hook, fn) => { if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function(parser, options) { parser.plugin(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", (compilation, data) => { data.normalModuleFactory.plugin("parser", parser => { parser.plugin(hook, fn); }); }); }, apply: () => { const args = arguments; if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function(parser, options) { parser.apply(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", (compilation, data) => { data.normalModuleFactory.plugin("parser", parser => { parser.apply.apply(parser, args); }); }); } }; this.options = {}; } watch(watchOptions, handler) { this.fileTimestamps = {}; this.contextTimestamps = {}; const watching = new Watching(this, watchOptions, handler); return watching; } run(callback) { const startTime = Date.now(); const onCompiled = (err, compilation) => { if(err) return callback(err); if(this.applyPluginsBailResult("should-emit", compilation) === false) { const stats = new Stats(compilation); stats.startTime = startTime; stats.endTime = Date.now(); this.applyPlugins("done", stats); return callback(null, stats); } this.emitAssets(compilation, err => { if(err) return callback(err); if(compilation.applyPluginsBailResult("need-additional-pass")) { compilation.needAdditionalPass = true; const stats = new Stats(compilation); stats.startTime = startTime; stats.endTime = Date.now(); this.applyPlugins("done", stats); this.applyPluginsAsync("additional-pass", err => { if(err) return callback(err); this.compile(onCompiled); }); return; } this.emitRecords(err => { if(err) return callback(err); const stats = new Stats(compilation); stats.startTime = startTime; stats.endTime = Date.now(); this.applyPlugins("done", stats); return callback(null, stats); }); }); }; this.applyPluginsAsync("before-run", this, err => { if(err) return callback(err); this.applyPluginsAsync("run", this, err => { if(err) return callback(err); this.readRecords(err => { if(err) return callback(err); this.compile(onCompiled); }); }); }); } runAsChild(callback) { this.compile((err, compilation) => { if(err) return callback(err); this.parentCompilation.children.push(compilation); Object.keys(compilation.assets).forEach(name => { this.parentCompilation.assets[name] = compilation.assets[name]; }); const entries = Object.keys(compilation.entrypoints).map(name => { return compilation.entrypoints[name].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); require("async").forEach(Object.keys(compilation.assets), (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); const source = compilation.assets[file]; if(source.existsAt === targetPath) { source.emitted = false; return callback(); } let content = source.source(); if(!Buffer.isBuffer(content)) { content = new Buffer(content, "utf8"); // eslint-disable-line } 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); afterEmit.call(this); }); }; this.applyPluginsAsync("emit", compilation, err => { if(err) return callback(err); outputPath = compilation.getPath(this.outputPath); this.outputFileSystem.mkdirp(outputPath, emitFiles); }); function afterEmit() { this.applyPluginsAsyncSeries1("after-emit", compilation, err => { if(err) return callback(err); return callback(); }); } } 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); if(idx1 < idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); if(!recordsOutputPathDirectory) return writeFile.call(this); this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { if(err) return callback(err); writeFile.call(this); }); function writeFile() { this.outputFileSystem.writeFile(this.recordsOutputPath, JSON.stringify(this.records, undefined, 2), callback); } } 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 = JSON.parse(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(); if(Array.isArray(plugins)) { plugins.forEach(plugin => childCompiler.apply(plugin)); } for(const name in this._plugins) { if(["make", "compile", "emit", "after-emit", "invalid", "done", "this-compilation"].indexOf(name) < 0) childCompiler._plugins[name] = this._plugins[name].slice(); } childCompiler.name = compilerName; childCompiler.outputPath = this.outputPath; childCompiler.inputFileSystem = this.inputFileSystem; childCompiler.outputFileSystem = null; childCompiler.resolvers = this.resolvers; 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 = {}); if(this.cache) { if(!this.cache.children) this.cache.children = {}; if(!this.cache.children[compilerName]) this.cache.children[compilerName] = []; if(this.cache.children[compilerName][compilerIndex]) childCompiler.cache = this.cache.children[compilerName][compilerIndex]; else this.cache.children[compilerName].push(childCompiler.cache = {}); } 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; 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.applyPlugins("this-compilation", compilation, params); this.applyPlugins("compilation", compilation, params); return compilation; } createNormalModuleFactory() { const normalModuleFactory = new NormalModuleFactory(this.options.context, this.resolvers, this.options.module || {}); this.applyPlugins("normal-module-factory", normalModuleFactory); return normalModuleFactory; } createContextModuleFactory() { const contextModuleFactory = new ContextModuleFactory(this.resolvers, this.inputFileSystem); this.applyPlugins("context-module-factory", contextModuleFactory); return contextModuleFactory; } newCompilationParams() { const params = { normalModuleFactory: this.createNormalModuleFactory(), contextModuleFactory: this.createContextModuleFactory(), compilationDependencies: [] }; return params; } compile(callback) { const params = this.newCompilationParams(); this.applyPluginsAsync("before-compile", params, err => { if(err) return callback(err); this.applyPlugins("compile", params); const compilation = this.newCompilation(params); this.applyPluginsParallel("make", compilation, err => { if(err) return callback(err); compilation.finish(); compilation.seal(err => { if(err) return callback(err); this.applyPluginsAsync("after-compile", compilation, err => { if(err) return callback(err); return callback(null, compilation); }); }); }); }); } } Compiler.Watching = Watching; module.exports = Compiler; webpack-3.5.6/lib/ConstPlugin.js000066400000000000000000000040121315401342100165010ustar00rootroot00000000000000/* 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 request.indexOf("?") < 0 ? "" : request.substr(i); }; class ConstPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", parser => { parser.plugin("statement if", function(statement) { const param = this.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; this.state.current.addDependency(dep); } return bool; } }); parser.plugin("expression ?:", function(expression) { const param = this.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; this.state.current.addDependency(dep); } return bool; } }); parser.plugin("evaluate Identifier __resourceQuery", function(expr) { if(!this.state.module) return; return ParserHelpers.evaluateToString(getQuery(this.state.module.resource))(expr); }); parser.plugin("expression __resourceQuery", function() { if(!this.state.module) return; this.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(this.state.module.resource))); return true; }); }); }); } } module.exports = ConstPlugin; webpack-3.5.6/lib/ContextModule.js000066400000000000000000000317461315401342100170440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const Module = require("./Module"); const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; const AsyncDependenciesBlock = require("./AsyncDependenciesBlock"); const DepBlockHelpers = require("./dependencies/DepBlockHelpers"); const Template = require("./Template"); class ContextModule extends Module { constructor(resolveDependencies, context, recursive, regExp, addon, asyncMode, chunkName) { super(); this.resolveDependencies = resolveDependencies; this.context = context; this.recursive = recursive; this.regExp = regExp; this.addon = addon; this.async = asyncMode; this.cacheable = true; this.contextDependencies = [context]; this.built = false; this.chunkName = chunkName; } prettyRegExp(regexString) { // remove the "/" at the front and the beginning // "/foo/" -> "foo" return regexString.substring(1, regexString.length - 1); } contextify(context, request) { return request.split("!").map(subrequest => { let rp = path.relative(context, subrequest); if(path.sep === "\\") rp = rp.replace(/\\/g, "/"); if(rp.indexOf("../") !== 0) rp = "./" + rp; return rp; }).join("!"); } identifier() { let identifier = this.context; if(this.async) identifier += ` ${this.async}`; if(!this.recursive) identifier += " nonrecursive"; if(this.addon) identifier += ` ${this.addon}`; if(this.regExp) identifier += ` ${this.regExp}`; return identifier; } readableIdentifier(requestShortener) { let identifier = requestShortener.shorten(this.context); if(this.async) identifier += ` ${this.async}`; if(!this.recursive) identifier += " nonrecursive"; if(this.addon) identifier += ` ${requestShortener.shorten(this.addon)}`; if(this.regExp) identifier += ` ${this.prettyRegExp(this.regExp + "")}`; return identifier; } libIdent(options) { let identifier = this.contextify(options.context, this.context); if(this.async) identifier += ` ${this.async}`; if(this.recursive) identifier += " recursive"; if(this.addon) identifier += ` ${this.contextify(options.context, this.addon)}`; if(this.regExp) identifier += ` ${this.prettyRegExp(this.regExp + "")}`; return identifier; } needRebuild(fileTimestamps, contextTimestamps) { const ts = contextTimestamps[this.context]; if(!ts) { return true; } return ts >= this.builtTime; } unbuild() { this.built = false; super.unbuild(); } build(options, compilation, resolver, fs, callback) { this.built = true; this.builtTime = Date.now(); this.resolveDependencies(fs, this.context, this.recursive, this.regExp, (err, dependencies) => { if(err) return callback(err); // Reset children this.dependencies = []; this.blocks = []; // abort if something failed // this will create an empty context if(!dependencies) { callback(); return; } // enhance dependencies with meta info dependencies.forEach(dep => { dep.loc = dep.userRequest; dep.request = this.addon + dep.request; }); if(!this.async || this.async === "eager") { // if we have an sync or eager context // just add all dependencies and continue this.dependencies = dependencies; } else if(this.async === "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(this.chunkName, this); dependencies.forEach(dep => { block.addDependency(dep); }); this.addBlock(block); } } else if(this.async === "weak" || this.async === "async-weak") { // we mark all dependencies as weak dependencies.forEach(dep => dep.weak = true); this.dependencies = dependencies; } else { // if we are lazy create a new async dependency block per dependency // and add all blocks to this context dependencies.forEach((dep, idx) => { let chunkName = this.chunkName; if(chunkName) { if(!/\[(index|request)\]/.test(chunkName)) chunkName += "[index]"; chunkName = chunkName.replace(/\[index\]/g, idx); chunkName = chunkName.replace(/\[request\]/g, Template.toPath(dep.userRequest)); } const block = new AsyncDependenciesBlock(chunkName, dep.module, dep.loc); block.addDependency(dep); this.addBlock(block); }); } 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(function(map, dep) { map[dep.userRequest] = dep.module.id; return map; }, Object.create(null)); } getSyncSource(dependencies, id) { const map = this.getUserRequestMap(dependencies); return `var map = ${JSON.stringify(map, null, "\t")}; function webpackContext(req) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; 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); return `var map = ${JSON.stringify(map, null, "\t")}; function webpackContext(req) { var id = webpackContextResolve(req); if(!__webpack_require__.m[id]) throw new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); return __webpack_require__(id); }; function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }; 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); return `var map = ${JSON.stringify(map, null, "\t")}; function webpackAsyncContext(req) { return webpackAsyncContextResolve(req).then(function(id) { if(!__webpack_require__.m[id]) throw new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); return __webpack_require__(id); }); }; function webpackAsyncContextResolve(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncatched exception popping up in devtools return Promise.resolve().then(function() { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }); }; 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); return `var map = ${JSON.stringify(map, null, "\t")}; function webpackAsyncContext(req) { return webpackAsyncContextResolve(req).then(__webpack_require__); }; function webpackAsyncContextResolve(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncatched exception popping up in devtools return Promise.resolve().then(function() { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }); }; webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.resolve = webpackAsyncContextResolve; webpackAsyncContext.id = ${JSON.stringify(id)}; module.exports = webpackAsyncContext;`; } getLazyOnceSource(block, dependencies, id, outputOptions, requestShortener) { const promise = DepBlockHelpers.getDepBlockPromise(block, outputOptions, requestShortener, "lazy-once context"); const map = this.getUserRequestMap(dependencies); return `var map = ${JSON.stringify(map, null, "\t")}; function webpackAsyncContext(req) { return webpackAsyncContextResolve(req).then(__webpack_require__); }; function webpackAsyncContextResolve(req) { return ${promise}.then(function() { var id = map[req]; if(!(id + 1)) // check for number or string throw new Error("Cannot find module '" + req + "'."); return id; }); }; 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; const map = blocks .filter(block => block.dependencies[0].module) .map((block) => ({ dependency: block.dependencies[0], block: block, userRequest: block.dependencies[0].userRequest })).sort((a, b) => { if(a.userRequest === b.userRequest) return 0; return a.userRequest < b.userRequest ? -1 : 1; }).reduce((map, item) => { const chunks = item.block.chunks || []; if(chunks.length !== 1) { hasMultipleOrNoChunks = true; } map[item.userRequest] = [item.dependency.module.id] .concat(chunks.map(chunk => chunk.id)); return map; }, Object.create(null)); const requestPrefix = hasMultipleOrNoChunks ? "Promise.all(ids.slice(1).map(__webpack_require__.e))" : "__webpack_require__.e(ids[1])"; return `var map = ${JSON.stringify(map, null, "\t")}; function webpackAsyncContext(req) { var ids = map[req]; if(!ids) return Promise.reject(new Error("Cannot find module '" + req + "'.")); return ${requestPrefix}.then(function() { return __webpack_require__(ids[0]); }); }; webpackAsyncContext.keys = function webpackAsyncContextKeys() { return Object.keys(map); }; webpackAsyncContext.id = ${JSON.stringify(id)}; module.exports = webpackAsyncContext;`; } getSourceForEmptyContext(id) { return `function webpackEmptyContext(req) { throw new Error("Cannot find module '" + req + "'."); } 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 // uncatched exception popping up in devtools return Promise.resolve().then(function() { throw new Error("Cannot find module '" + req + "'."); }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`; } getSourceString(asyncMode, outputOptions, requestShortener) { 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, outputOptions, requestShortener); } 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, outputOptions, requestShortener) { return this.getSource( this.getSourceString(this.async, outputOptions, requestShortener) ); } size() { // base penalty const initialSize = 160; // if we dont have dependencies we stop here. return this.dependencies .reduce((size, dependency) => size + 5 + dependency.userRequest.length, initialSize); } } module.exports = ContextModule; webpack-3.5.6/lib/ContextModuleFactory.js000066400000000000000000000107471315401342100203720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("async"); const path = require("path"); const Tapable = require("tapable"); const ContextModule = require("./ContextModule"); const ContextElementDependency = require("./dependencies/ContextElementDependency"); module.exports = class ContextModuleFactory extends Tapable { constructor(resolvers) { super(); this.resolvers = resolvers; } create(data, callback) { const module = this; const context = data.context; const dependencies = data.dependencies; const dependency = dependencies[0]; this.applyPluginsAsyncWaterfall("before-resolve", { context: context, request: dependency.request, recursive: dependency.recursive, regExp: dependency.regExp, async: dependency.async, dependencies: dependencies }, (err, result) => { if(err) return callback(err); // Ignored if(!result) return callback(); const context = result.context; const request = result.request; const recursive = result.recursive; const regExp = result.regExp; const asyncContext = result.async; const dependencies = result.dependencies; let loaders, resource, loadersPrefix = ""; const idx = request.lastIndexOf("!"); if(idx >= 0) { loaders = request.substr(0, idx + 1); let i; for(i = 0; i < loaders.length && loaders[i] === "!"; i++) { loadersPrefix += "!"; } loaders = loaders.substr(i).replace(/!+$/, "").replace(/!!+/g, "!"); if(loaders === "") loaders = []; else loaders = loaders.split("!"); resource = request.substr(idx + 1); } else { loaders = []; resource = request; } const resolvers = module.resolvers; asyncLib.parallel([ function(callback) { resolvers.context.resolve({}, context, resource, function(err, result) { if(err) return callback(err); callback(null, result); }); }, function(callback) { asyncLib.map(loaders, function(loader, callback) { resolvers.loader.resolve({}, context, loader, function(err, result) { if(err) return callback(err); callback(null, result); }); }, callback); } ], (err, result) => { if(err) return callback(err); module.applyPluginsAsyncWaterfall("after-resolve", { loaders: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""), resource: result[0], recursive: recursive, regExp: regExp, async: asyncContext, dependencies: dependencies, resolveDependencies: module.resolveDependencies.bind(module) }, function(err, result) { if(err) return callback(err); // Ignored if(!result) return callback(); return callback(null, new ContextModule(result.resolveDependencies, result.resource, result.recursive, result.regExp, result.loaders, result.async, dependency.chunkName)); }); }); }); } resolveDependencies(fs, resource, recursive, regExp, callback) { if(!regExp || !resource) return callback(null, []); (function addDirectory(directory, callback) { fs.readdir(directory, (err, files) => { if(err) return callback(err); if(!files || files.length === 0) return callback(null, []); asyncLib.map(files.filter(function(p) { return p.indexOf(".") !== 0; }), (seqment, callback) => { const subResource = path.join(directory, seqment); fs.stat(subResource, (err, stat) => { if(err) return callback(err); if(stat.isDirectory()) { if(!recursive) return callback(); addDirectory.call(this, subResource, callback); } else if(stat.isFile()) { const obj = { context: resource, request: "." + subResource.substr(resource.length).replace(/\\/g, "/") }; this.applyPluginsAsyncWaterfall("alternatives", [obj], (err, alternatives) => { if(err) return callback(err); alternatives = alternatives.filter(function(obj) { return regExp.test(obj.request); }).map(function(obj) { const dep = new ContextElementDependency(obj.request); dep.optional = true; return dep; }); callback(null, alternatives); }); } else callback(); }); }, (err, result) => { if(err) return callback(err); if(!result) return callback(null, []); callback(null, result.filter(function(i) { return !!i; }).reduce(function(a, i) { return a.concat(i); }, [])); }); }); }.call(this, resource, callback)); } }; webpack-3.5.6/lib/ContextReplacementPlugin.js000066400000000000000000000076471315401342100212400ustar00rootroot00000000000000/* 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.plugin("context-module-factory", (cmf) => { cmf.plugin("before-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.request)) { if(typeof newContentResource !== "undefined") result.request = newContentResource; if(typeof newContentRecursive !== "undefined") result.recursive = newContentRecursive; if(typeof newContentRegExp !== "undefined") result.regExp = newContentRegExp; if(typeof newContentCallback === "function") { newContentCallback(result); } else { result.dependencies.forEach((d) => { if(d.critical) d.critical = false; }); } } return callback(null, result); }); cmf.plugin("after-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.resource)) { if(typeof newContentResource !== "undefined") result.resource = path.resolve(result.resource, newContentResource); if(typeof newContentRecursive !== "undefined") result.recursive = newContentRecursive; if(typeof 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 { result.dependencies.forEach((d) => { if(d.critical) d.critical = false; }); } } return callback(null, result); }); }); } } const createResolveDependenciesFromContextMap = (createContextMap) => { return function resolveDependenciesFromContextMap(fs, resource, recursive, regExp, callback) { createContextMap(fs, (err, map) => { if(err) return callback(err); const dependencies = Object.keys(map).map((key) => { return new ContextElementDependency(map[key], key); }); callback(null, dependencies); }); }; }; module.exports = ContextReplacementPlugin; webpack-3.5.6/lib/DefinePlugin.js000066400000000000000000000104271315401342100166140ustar00rootroot00000000000000/* 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"); class DefinePlugin { constructor(definitions) { this.definitions = definitions; } apply(compiler) { const definitions = this.definitions; compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", (parser) => { (function walkDefinitions(definitions, prefix) { Object.keys(definitions).forEach((key) => { const code = definitions[key]; if(code && typeof code === "object" && !(code instanceof RegExp)) { walkDefinitions(code, prefix + key + "."); applyObjectDefine(prefix + key, code); return; } applyDefineKey(prefix, key); applyDefine(prefix + key, code); }); }(definitions, "")); function stringifyObj(obj) { return "Object({" + Object.keys(obj).map((key) => { const code = obj[key]; return JSON.stringify(key) + ":" + toCode(code); }).join(",") + "})"; } function toCode(code) { if(code === null) return "null"; else if(code === undefined) return "undefined"; else if(code instanceof RegExp && code.toString) return code.toString(); else if(typeof code === "function" && code.toString) return "(" + code.toString() + ")"; else if(typeof code === "object") return stringifyObj(code); else return code + ""; } function applyDefineKey(prefix, key) { const splittedKey = key.split("."); splittedKey.slice(1).forEach((_, i) => { const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); parser.plugin("can-rename " + fullKey, ParserHelpers.approve); }); } function applyDefine(key, code) { const isTypeof = /^typeof\s+/.test(key); if(isTypeof) key = key.replace(/^typeof\s+/, ""); let recurse = false; let recurseTypeof = false; code = toCode(code); if(!isTypeof) { parser.plugin("can-rename " + key, ParserHelpers.approve); parser.plugin("evaluate Identifier " + key, (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(code); recurse = false; res.setRange(expr.range); return res; }); parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code)); } const typeofCode = isTypeof ? code : "typeof (" + code + ")"; parser.plugin("evaluate typeof " + key, (expr) => { /** * this is needed in case there is a recursion in the DefinePlugin * to prevent an endless recursion * e.g.: new DefinePlugin({ * "typeof a": "tyepof b", * "typeof b": "typeof a" * }); */ if(recurseTypeof) return; recurseTypeof = true; const res = parser.evaluate(typeofCode); recurseTypeof = false; res.setRange(expr.range); return res; }); parser.plugin("typeof " + key, (expr) => { const res = parser.evaluate(typeofCode); if(!res.isString()) return; return ParserHelpers.toConstantDependency(JSON.stringify(res.string)).bind(parser)(expr); }); } function applyObjectDefine(key, obj) { const code = stringifyObj(obj); parser.plugin("can-rename " + key, ParserHelpers.approve); parser.plugin("evaluate Identifier " + key, (expr) => new BasicEvaluatedExpression().setTruthy().setRange(expr.range)); parser.plugin("evaluate typeof " + key, ParserHelpers.evaluateToString("object")); parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code)); parser.plugin("typeof " + key, ParserHelpers.toConstantDependency(JSON.stringify("object"))); } }); }); } } module.exports = DefinePlugin; webpack-3.5.6/lib/DelegatedModule.js000066400000000000000000000044651315401342100172740ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("./Module"); const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; const WebpackMissingModule = require("./dependencies/WebpackMissingModule"); const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); class DelegatedModule extends Module { constructor(sourceRequest, data, type, userRequest, originalRequest) { super(); this.sourceRequest = sourceRequest; this.request = data.id; this.meta = data.meta; this.type = type; this.originalRequest = originalRequest; this.userRequest = userRequest; this.built = false; this.delegated = true; this.delegateData = data; } 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.builtTime = Date.now(); this.cacheable = true; this.dependencies.length = 0; this.addDependency(new DelegatedSourceDependency(this.sourceRequest)); this.addDependency(new DelegatedExportsDependency(this, this.delegateData.exports || true)); callback(); } unbuild() { this.built = false; super.unbuild(); } source() { const sourceModule = this.dependencies[0].module; let str; if(!sourceModule) { str = WebpackMissingModule.moduleCode(this.sourceRequest); } else { str = `module.exports = (__webpack_require__(${JSON.stringify(sourceModule.id)}))`; 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; } } module.exports = DelegatedModule; webpack-3.5.6/lib/DelegatedModuleFactoryPlugin.js000066400000000000000000000036771315401342100220070ustar00rootroot00000000000000/* 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 || ["", ".js"]; } apply(normalModuleFactory) { const scope = this.options.scope; if(scope) { normalModuleFactory.plugin("factory", 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.plugin("module", 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-3.5.6/lib/DelegatedPlugin.js000066400000000000000000000016531315401342100173010ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(DelegatedSourceDependency, params.normalModuleFactory); compilation.dependencyFactories.set(DelegatedExportsDependency, new NullFactory()); }); compiler.plugin("compile", (params) => { params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin(this.options)); }); } } module.exports = DelegatedPlugin; webpack-3.5.6/lib/DependenciesBlock.js000066400000000000000000000027761315401342100176140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DependenciesBlockVariable = require("./DependenciesBlockVariable"); function disconnect(i) { i.disconnect(); } function unseal(i) { i.unseal(); } class DependenciesBlock { constructor() { this.dependencies = []; this.blocks = []; this.variables = []; } addBlock(block) { this.blocks.push(block); block.parent = this; } 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)); } addDependency(dependency) { this.dependencies.push(dependency); } updateHash(hash) { function updateHash(i) { i.updateHash(hash); } this.dependencies.forEach(updateHash); this.blocks.forEach(updateHash); this.variables.forEach(updateHash); } disconnect() { this.dependencies.forEach(disconnect); this.blocks.forEach(disconnect); this.variables.forEach(disconnect); } unseal() { this.blocks.forEach(unseal); } hasDependencies(filter) { if(filter) { if(this.dependencies.some(filter)) { return true; } } else { if(this.dependencies.length > 0) { return true; } } return this.blocks.concat(this.variables).some(item => item.hasDependencies(filter)); } sortItems() { this.blocks.forEach(block => block.sortItems()); } } module.exports = DependenciesBlock; webpack-3.5.6/lib/DependenciesBlockVariable.js000066400000000000000000000024331315401342100212500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ReplaceSource = require("webpack-sources").ReplaceSource; const RawSource = require("webpack-sources").RawSource; class DependenciesBlockVariable { constructor(name, expression, dependencies) { this.name = name; this.expression = expression; this.dependencies = dependencies || []; } updateHash(hash) { hash.update(this.name); hash.update(this.expression); this.dependencies.forEach(d => { d.updateHash(hash); }); } expressionSource(dependencyTemplates, outputOptions, requestShortener) { const source = new ReplaceSource(new RawSource(this.expression)); this.dependencies.forEach(dep => { const template = dependencyTemplates.get(dep.constructor); if(!template) throw new Error(`No template for dependency: ${dep.constructor.name}`); template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); }); return source; } disconnect() { this.dependencies.forEach(d => { d.disconnect(); }); } hasDependencies(filter) { if(filter) { if(this.dependencies.some(filter)) return true; } else { if(this.dependencies.length > 0) return true; } return false; } } module.exports = DependenciesBlockVariable; webpack-3.5.6/lib/Dependency.js000066400000000000000000000017251315401342100163220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const compareLocations = require("./compareLocations"); class Dependency { constructor() { this.module = null; } isEqualResource() { return false; } // Returns the referenced module and export getReference() { if(!this.module) return null; return { module: this.module, importedNames: true, // true: full object, false: only sideeffects/no export, array of strings: the exports with this names }; } // 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 3 compare(a, b) { return compareLocations(a.loc, b.loc); } } Dependency.compare = (a, b) => compareLocations(a.loc, b.loc); module.exports = Dependency; webpack-3.5.6/lib/DllEntryPlugin.js000066400000000000000000000022021315401342100171470ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { const dllModuleFactory = new DllModuleFactory(); const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(DllEntryDependency, dllModuleFactory); compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { compilation.addEntry(this.context, new DllEntryDependency(this.entries.map((e, idx) => { const dep = new SingleEntryDependency(e); dep.loc = `${this.name}:${idx}`; return dep; }), this.name), this.name, callback); }); } } module.exports = DllEntryPlugin; webpack-3.5.6/lib/DllModule.js000066400000000000000000000017651315401342100161310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("./Module"); const RawSource = require("webpack-sources").RawSource; class DllModule extends Module { constructor(context, dependencies, name, type) { super(); this.context = context; this.dependencies = dependencies; this.name = name; this.built = false; this.cacheable = true; this.type = type; } identifier() { return `dll ${this.name}`; } readableIdentifier() { return `dll ${this.name}`; } disconnect() { this.built = false; super.disconnect(); } build(options, compilation, resolver, fs, callback) { this.built = true; return callback(); } source() { return new RawSource("module.exports = __webpack_require__;"); } needRebuild() { return false; } size() { return 12; } updateHash(hash) { hash.update("dll module"); hash.update(this.name || ""); super.updateHash(hash); } } module.exports = DllModule; webpack-3.5.6/lib/DllModuleFactory.js000066400000000000000000000007361315401342100174560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; var Tapable = require("tapable"); var DllModule = require("./DllModule"); class DllModuleFactory extends Tapable { constructor() { super(); } create(data, callback) { const dependency = data.dependencies[0]; callback(null, new DllModule(data.context, dependency.dependencies, dependency.name, dependency.type)); } } module.exports = DllModuleFactory; webpack-3.5.6/lib/DllPlugin.js000066400000000000000000000020311315401342100161250ustar00rootroot00000000000000/* 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"); class DllPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.plugin("entry-option", (context, entry) => { function itemToPlugin(item, name) { if(Array.isArray(item)) return new DllEntryPlugin(context, item, name); else throw new Error("DllPlugin: supply an Array as entry"); } if(typeof entry === "object" && !Array.isArray(entry)) { Object.keys(entry).forEach(name => { compiler.apply(itemToPlugin(entry[name], name)); }); } else { compiler.apply(itemToPlugin(entry, "main")); } return true; }); compiler.apply(new LibManifestPlugin(this.options)); compiler.apply(new FlagInitialModulesAsUsedPlugin()); } } module.exports = DllPlugin; webpack-3.5.6/lib/DllReferencePlugin.js000066400000000000000000000042271315401342100177550ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); const NullFactory = require("./NullFactory"); class DllReferencePlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(DelegatedSourceDependency, normalModuleFactory); compilation.dependencyFactories.set(DelegatedExportsDependency, new NullFactory()); }); compiler.plugin("before-compile", (params, callback) => { const manifest = this.options.manifest; if(typeof manifest === "string") { params.compilationDependencies.push(manifest); compiler.inputFileSystem.readFile(manifest, function(err, result) { if(err) return callback(err); params["dll reference " + manifest] = JSON.parse(result.toString("utf-8")); return callback(); }); } else { return callback(); } }); compiler.plugin("compile", (params) => { let manifest = this.options.manifest; if(typeof manifest === "string") { manifest = params["dll reference " + manifest]; } const name = this.options.name || manifest.name; const sourceType = this.options.sourceType || "var"; const externals = {}; const source = "dll-reference " + name; externals[source] = name; params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(sourceType, externals)); params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin({ source: source, type: this.options.type, scope: this.options.scope, context: this.options.context || compiler.options.context, content: this.options.content || manifest.content, extensions: this.options.extensions })); }); } } module.exports = DllReferencePlugin; webpack-3.5.6/lib/DynamicEntryPlugin.js000066400000000000000000000035531315401342100200320ustar00rootroot00000000000000/* 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"); class DynamicEntryPlugin { constructor(context, entry) { this.context = context; this.entry = entry; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const multiModuleFactory = new MultiModuleFactory(); const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory); compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { 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; DynamicEntryPlugin.createDependency = function(entry, name) { if(Array.isArray(entry)) return MultiEntryPlugin.createDependency(entry, name); else return SingleEntryPlugin.createDependency(entry, name); }; webpack-3.5.6/lib/EntryModuleNotFoundError.js000066400000000000000000000007561315401342100212050ustar00rootroot00000000000000/* 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(); this.name = "EntryModuleNotFoundError"; this.message = "Entry module not found: " + err; this.details = err.details; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = EntryModuleNotFoundError; webpack-3.5.6/lib/EntryOptionPlugin.js000066400000000000000000000017301315401342100177110ustar00rootroot00000000000000/* 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"); function itemToPlugin(context, item, name) { if(Array.isArray(item)) { return new MultiEntryPlugin(context, item, name); } return new SingleEntryPlugin(context, item, name); } module.exports = class EntryOptionPlugin { apply(compiler) { compiler.plugin("entry-option", (context, entry) => { if(typeof entry === "string" || Array.isArray(entry)) { compiler.apply(itemToPlugin(context, entry, "main")); } else if(typeof entry === "object") { Object.keys(entry).forEach(name => compiler.apply(itemToPlugin(context, entry[name], name))); } else if(typeof entry === "function") { compiler.apply(new DynamicEntryPlugin(context, entry)); } return true; }); } }; webpack-3.5.6/lib/Entrypoint.js000066400000000000000000000015731315401342100164200ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class Entrypoint { constructor(name) { this.name = name; this.chunks = []; } unshiftChunk(chunk) { this.chunks.unshift(chunk); chunk.entrypoints.push(this); } insertChunk(chunk, before) { const idx = this.chunks.indexOf(before); if(idx >= 0) { this.chunks.splice(idx, 0, chunk); } else { throw new Error("before chunk not found"); } chunk.entrypoints.push(this); } getFiles() { const files = []; for(let chunkIdx = 0; chunkIdx < this.chunks.length; chunkIdx++) { for(let fileIdx = 0; fileIdx < this.chunks[chunkIdx].files.length; fileIdx++) { if(files.indexOf(this.chunks[chunkIdx].files[fileIdx]) === -1) { files.push(this.chunks[chunkIdx].files[fileIdx]); } } } return files; } } module.exports = Entrypoint; webpack-3.5.6/lib/EnvironmentPlugin.js000066400000000000000000000025441315401342100177270ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Authors Simen Brekken @simenbrekken, Einar Löve @einarlove */ "use strict"; const DefinePlugin = require("./DefinePlugin"); class EnvironmentPlugin { constructor(keys) { if(Array.isArray(keys)) { this.keys = keys; this.defaultValues = {}; } else if(keys && typeof keys === "object") { this.keys = Object.keys(keys); this.defaultValues = keys; } else { this.keys = Array.prototype.slice.call(arguments); this.defaultValues = {}; } } apply(compiler) { const definitions = this.keys.reduce((defs, key) => { const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key]; if(value === undefined) { compiler.plugin("this-compilation", compilation => { const error = new Error( `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}`] = typeof value === "undefined" ? "undefined" : JSON.stringify(value); return defs; }, {}); compiler.apply(new DefinePlugin(definitions)); } } module.exports = EnvironmentPlugin; webpack-3.5.6/lib/ErrorHelpers.js000066400000000000000000000014311315401342100166520ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const loaderFlag = "LOADER_EXECUTION"; exports.cutOffLoaderExecution = (stack) => { stack = stack.split("\n"); for(let i = 0; i < stack.length; i++) if(stack[i].indexOf(loaderFlag) >= 0) stack.length = i; return stack.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; }; webpack-3.5.6/lib/EvalDevToolModulePlugin.js000066400000000000000000000012061315401342100207470ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const EvalDevToolModuleTemplatePlugin = require("./EvalDevToolModuleTemplatePlugin"); class EvalDevToolModulePlugin { constructor(sourceUrlComment, moduleFilenameTemplate) { this.sourceUrlComment = sourceUrlComment; this.moduleFilenameTemplate = moduleFilenameTemplate; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.moduleTemplate.apply(new EvalDevToolModuleTemplatePlugin(this.sourceUrlComment, this.moduleFilenameTemplate)); }); } } module.exports = EvalDevToolModulePlugin; webpack-3.5.6/lib/EvalDevToolModuleTemplatePlugin.js000066400000000000000000000024111315401342100224420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RawSource = require("webpack-sources").RawSource; const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); class EvalDevToolModuleTemplatePlugin { constructor(sourceUrlComment, moduleFilenameTemplate) { this.sourceUrlComment = sourceUrlComment || "\n//# sourceURL=[url]"; this.moduleFilenameTemplate = moduleFilenameTemplate || "webpack:///[resourcePath]?[loaders]"; } apply(moduleTemplate) { moduleTemplate.plugin("module", (source, module) => { const content = source.source(); const str = ModuleFilenameHelpers.createFilename(module, this.moduleFilenameTemplate, moduleTemplate.requestShortener); const footer = ["\n", ModuleFilenameHelpers.createFooter(module, moduleTemplate.requestShortener), this.sourceUrlComment.replace(/\[url\]/g, encodeURI(str).replace(/%2F/g, "/").replace(/%20/g, "_").replace(/%5E/g, "^").replace(/%5C/g, "\\").replace(/^\//, "")) ].join("\n"); return new RawSource(`eval(${JSON.stringify(content + footer)});`); }); moduleTemplate.plugin("hash", hash => { hash.update("EvalDevToolModuleTemplatePlugin"); hash.update("2"); }); } } module.exports = EvalDevToolModuleTemplatePlugin; webpack-3.5.6/lib/EvalSourceMapDevToolModuleTemplatePlugin.js000066400000000000000000000054271315401342100242730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const RawSource = require("webpack-sources").RawSource; const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); class EvalSourceMapDevToolModuleTemplatePlugin { constructor(compilation, options) { this.compilation = compilation; this.sourceMapComment = options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]"; this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resource-path]?[hash]"; this.options = options; } apply(moduleTemplate) { const self = this; const options = this.options; moduleTemplate.plugin("module", function(source, module) { if(source.__EvalSourceMapDevToolData) return source.__EvalSourceMapDevToolData; 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(function(obj, key) { obj[key] = sourceMap[key]; return obj; }, {}); const modules = sourceMap.sources.map(function(source) { const module = self.compilation.findModule(source); return module || source; }); let moduleFilenames = modules.map(function(module) { return ModuleFilenameHelpers.createFilename(module, self.moduleFilenameTemplate, this.requestShortener); }, this); moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function(filename, i, n) { for(let j = 0; j < n; j++) filename += "*"; return filename; }); sourceMap.sources = moduleFilenames; if(sourceMap.sourcesContent) { sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) { return `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], this.requestShortener)}`; }, this); } sourceMap.sourceRoot = options.sourceRoot || ""; sourceMap.file = `${module.id}.js`; const footer = self.sourceMapComment.replace(/\[url\]/g, `data:application/json;charset=utf-8;base64,${new Buffer(JSON.stringify(sourceMap), "utf8").toString("base64")}`) + //eslint-disable-line `\n//# sourceURL=webpack-internal:///${module.id}\n`; // workaround for chrome bug source.__EvalSourceMapDevToolData = new RawSource(`eval(${JSON.stringify(content + footer)});`); return source.__EvalSourceMapDevToolData; }); moduleTemplate.plugin("hash", function(hash) { hash.update("eval-source-map"); hash.update("2"); }); } } module.exports = EvalSourceMapDevToolModuleTemplatePlugin; webpack-3.5.6/lib/EvalSourceMapDevToolPlugin.js000066400000000000000000000017201315401342100214210ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation) => { new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); compilation.moduleTemplate.apply(new EvalSourceMapDevToolModuleTemplatePlugin(compilation, options)); }); } } module.exports = EvalSourceMapDevToolPlugin; webpack-3.5.6/lib/ExportPropertyMainTemplatePlugin.js000066400000000000000000000015011315401342100227420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; function accessorToObjectAccess(accessor) { return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); } class ExportPropertyMainTemplatePlugin { constructor(property) { this.property = property; } apply(compilation) { const mainTemplate = compilation.mainTemplate; compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => { const postfix = `${accessorToObjectAccess([].concat(this.property))}`; return new ConcatSource(source, postfix); }); mainTemplate.plugin("hash", hash => { hash.update("export property"); hash.update(`${this.property}`); }); } } module.exports = ExportPropertyMainTemplatePlugin; webpack-3.5.6/lib/ExtendedAPIPlugin.js000066400000000000000000000033211315401342100175070ustar00rootroot00000000000000/* 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"); const REPLACEMENTS = { __webpack_hash__: "__webpack_require__.h", // eslint-disable-line camelcase __webpack_chunkname__: "__webpack_require__.cn" // eslint-disable-line camelcase }; const REPLACEMENT_TYPES = { __webpack_hash__: "string", // eslint-disable-line camelcase __webpack_chunkname__: "string" // eslint-disable-line camelcase }; class ExtendedAPIPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); compilation.mainTemplate.plugin("require-extensions", function(source, chunk, hash) { const buf = [source]; buf.push(""); buf.push("// __webpack_hash__"); buf.push(`${this.requireFn}.h = ${JSON.stringify(hash)};`); buf.push(""); buf.push("// __webpack_chunkname__"); buf.push(`${this.requireFn}.cn = ${JSON.stringify(chunk.name)};`); return this.asString(buf); }); compilation.mainTemplate.plugin("global-hash", () => true); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { Object.keys(REPLACEMENTS).forEach(key => { parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key])); parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key])); }); }); }); } } module.exports = ExtendedAPIPlugin; webpack-3.5.6/lib/ExternalModule.js000066400000000000000000000064311315401342100171730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("./Module"); const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; const WebpackMissingModule = require("./dependencies/WebpackMissingModule"); const Template = require("./Template"); class ExternalModule extends Module { constructor(request, type, userRequest) { super(); this.request = request; this.userRequest = userRequest; this.type = type; this.built = false; 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.builtTime = Date.now(); 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(${moduleName})${objectLookup};`; } checkExternalVariable(variableToCheck, request) { return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode(request)}}\n`; } getSourceForAmdOrUmdExternal(id, optional, request) { const externalVariable = Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${id}__`); const missingModuleError = optional ? this.checkExternalVariable(externalVariable, request) : ""; return `${missingModuleError}module.exports = ${externalVariable};`; } getSourceForDefaultCase(optional, request) { const missingModuleError = optional ? this.checkExternalVariable(request, request) : ""; return `${missingModuleError}module.exports = ${request};`; } getSourceString() { const request = typeof this.request === "object" ? this.request[this.type] : this.request; switch(this.type) { case "this": case "window": case "global": return this.getSourceForGlobalVariableExternal(request, this.type); case "commonjs": case "commonjs2": return this.getSourceForCommonJsExternal(request); case "amd": case "umd": case "umd2": 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() { return this.getSource( this.getSourceString() ); } size() { return 42; } } module.exports = ExternalModule; webpack-3.5.6/lib/ExternalModuleFactoryPlugin.js000066400000000000000000000054271315401342100217060ustar00rootroot00000000000000/* 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.plugin("factory", factory => (data, callback) => { const context = data.context; const dependency = data.dependencies[0]; function 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(typeof 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; } (function handleExternals(externals, callback) { if(typeof externals === "string") { if(externals === dependency.request) { return handleExternal(dependency.request, callback); } } else if(Array.isArray(externals)) { let i = 0; (function next() { let asyncFlag; const handleExternalsAndCallback = function 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); // eslint-disable-line keyword-spacing asyncFlag = false; }()); 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, function(err, value, type) { if(err) return callback(err); if(typeof 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(); }(this.externals, function(err, module) { if(err) return callback(err); if(!module) return handleExternal(false, callback); return callback(null, module); })); }); } } module.exports = ExternalModuleFactoryPlugin; webpack-3.5.6/lib/ExternalsPlugin.js000066400000000000000000000007721315401342100173710ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; var ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); class ExternalsPlugin { constructor(type, externals) { this.type = type; this.externals = externals; } apply(compiler) { compiler.plugin("compile", (params) => { params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals)); }); } } module.exports = ExternalsPlugin; webpack-3.5.6/lib/FlagDependencyExportsPlugin.js000066400000000000000000000054671315401342100216670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class FlagDependencyExportsPlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("finish-modules", (modules) => { const dependencies = Object.create(null); let module; let moduleWithExports; let moduleProvidedExports; const queue = modules.filter((m) => !m.providedExports); for(let i = 0; i < queue.length; i++) { module = queue[i]; if(module.providedExports !== true) { moduleWithExports = module.meta && module.meta.harmonyModule; moduleProvidedExports = Array.isArray(module.providedExports) ? new Set(module.providedExports) : new Set(); processDependenciesBlock(module); if(!moduleWithExports) { module.providedExports = true; notifyDependencies(); } else if(module.providedExports !== true) { module.providedExports = Array.from(moduleProvidedExports); } } } function processDependenciesBlock(depBlock) { depBlock.dependencies.forEach((dep) => processDependency(dep)); depBlock.variables.forEach((variable) => { variable.dependencies.forEach((dep) => processDependency(dep)); }); depBlock.blocks.forEach(processDependenciesBlock); } function processDependency(dep) { const exportDesc = dep.getExports && dep.getExports(); if(!exportDesc) return; moduleWithExports = true; const exports = exportDesc.exports; const exportDeps = exportDesc.dependencies; if(exportDeps) { exportDeps.forEach((dep) => { const depIdent = dep.identifier(); // if this was not yet initialized // initialize it as an array containing the module and stop const array = dependencies[depIdent]; if(!array) { dependencies[depIdent] = [module]; return; } // check if this module is known // if not, add it to the dependencies for this identifier if(array.indexOf(module) < 0) array.push(module); }); } let changed = false; if(module.providedExports !== true) { if(exports === true) { module.providedExports = true; changed = true; } else if(Array.isArray(exports)) { changed = addToSet(moduleProvidedExports, exports); } } if(changed) { notifyDependencies(); } } function notifyDependencies() { const deps = dependencies[module.identifier()]; if(deps) { deps.forEach((dep) => queue.push(dep)); } } }); function addToSet(a, b) { let changed = false; b.forEach((item) => { if(!a.has(item)) { a.add(item); changed = true; } }); return changed; } }); } } module.exports = FlagDependencyExportsPlugin; webpack-3.5.6/lib/FlagDependencyUsagePlugin.js000066400000000000000000000045201315401342100212540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class FlagDependencyUsagePlugin { apply(compiler) { compiler.plugin("compilation", compilation => { compilation.plugin("optimize-modules-advanced", modules => { modules.forEach(module => module.used = false); const queue = []; compilation.chunks.forEach(chunk => { if(chunk.entryModule) { processModule(chunk.entryModule, true); } }); while(queue.length) { const queueItem = queue.pop(); processDependenciesBlock(queueItem[0], queueItem[1]); } function processModule(module, usedExports) { module.used = true; if(module.usedExports === true) return; else if(usedExports === true) module.usedExports = true; else if(Array.isArray(usedExports)) { var 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; queue.push([module, module.usedExports]); } function processDependenciesBlock(depBlock, usedExports) { depBlock.dependencies.forEach(dep => processDependency(dep)); depBlock.variables.forEach(variable => variable.dependencies.forEach(dep => processDependency(dep))); depBlock.blocks.forEach(block => queue.push([block, usedExports])); } function processDependency(dep) { const reference = dep.getReference && dep.getReference(); if(!reference) return; const module = reference.module; const importedNames = reference.importedNames; const oldUsed = module.used; const oldUsedExports = module.usedExports; if(!oldUsed || (importedNames && (!oldUsedExports || !isSubset(oldUsedExports, importedNames)))) { processModule(module, importedNames); } } }); function addToSet(a, b) { b.forEach(item => { if(a.indexOf(item) < 0) a.push(item); }); return a; } function isSubset(biggerSet, subset) { if(biggerSet === true) return true; if(subset === true) return false; return subset.every(item => biggerSet.indexOf(item) >= 0); } }); } } module.exports = FlagDependencyUsagePlugin; webpack-3.5.6/lib/FlagInitialModulesAsUsedPlugin.js000066400000000000000000000010161315401342100222350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class FlagInitialModulesAsUsedPlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("after-optimize-chunks", (chunks) => { chunks.forEach((chunk) => { if(!chunk.isInitial()) { return; } chunk.forEachModule((module) => { module.usedExports = true; }); }); }); }); } } module.exports = FlagInitialModulesAsUsedPlugin; webpack-3.5.6/lib/FunctionModulePlugin.js000066400000000000000000000013021315401342100203450ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const FunctionModuleTemplatePlugin = require("./FunctionModuleTemplatePlugin"); const RequestShortener = require("./RequestShortener"); class FunctionModulePlugin { constructor(options, requestShortener) { this.options = options; this.requestShortener = requestShortener; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.moduleTemplate.requestShortener = this.requestShortener || new RequestShortener(compiler.context); compilation.moduleTemplate.apply(new FunctionModuleTemplatePlugin()); }); } } module.exports = FunctionModulePlugin; webpack-3.5.6/lib/FunctionModuleTemplatePlugin.js000066400000000000000000000042121315401342100220440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; class FunctionModuleTemplatePlugin { apply(moduleTemplate) { moduleTemplate.plugin("render", function(moduleSource, module) { const source = new ConcatSource(); const defaultArguments = [module.moduleArgument || "module", module.exportsArgument || "exports"]; if((module.arguments && module.arguments.length !== 0) || module.hasDependencies(d => d.requireWebpackRequire !== false)) { defaultArguments.push("__webpack_require__"); } source.add("/***/ (function(" + defaultArguments.concat(module.arguments || []).join(", ") + ") {\n\n"); if(module.strict) source.add("\"use strict\";\n"); source.add(moduleSource); source.add("\n\n/***/ })"); return source; }); moduleTemplate.plugin("package", function(moduleSource, module) { if(this.outputOptions.pathinfo) { const source = new ConcatSource(); const req = module.readableIdentifier(this.requestShortener); source.add("/*!****" + req.replace(/./g, "*") + "****!*\\\n"); source.add(" !*** " + req.replace(/\*\//g, "*_/") + " ***!\n"); source.add(" \\****" + req.replace(/./g, "*") + "****/\n"); if(Array.isArray(module.providedExports)) source.add("/*! exports provided: " + module.providedExports.join(", ") + " */\n"); else if(module.providedExports) source.add("/*! no static exports found */\n"); if(Array.isArray(module.usedExports)) source.add("/*! exports used: " + module.usedExports.join(", ") + " */\n"); else if(module.usedExports) source.add("/*! all exports used */\n"); if(module.optimizationBailout) { module.optimizationBailout.forEach(text => { if(typeof text === "function") text = text(this.requestShortener); source.add(`/*! ${text} */\n`); }); } source.add(moduleSource); return source; } return moduleSource; }); moduleTemplate.plugin("hash", function(hash) { hash.update("FunctionModuleTemplatePlugin"); hash.update("2"); }); } } module.exports = FunctionModuleTemplatePlugin; webpack-3.5.6/lib/HashedModuleIdsPlugin.js000066400000000000000000000021211315401342100204140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const createHash = require("crypto").createHash; class HashedModuleIdsPlugin { constructor(options) { this.options = Object.assign({ hashFunction: "md5", hashDigest: "base64", hashDigestLength: 4 }, options); } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { const usedIds = new Set(); compilation.plugin("before-module-ids", (modules) => { modules.forEach((module) => { 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-3.5.6/lib/HotModuleReplacement.runtime.js000066400000000000000000000404011315401342100220000ustar00rootroot00000000000000/* 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; var hotCurrentHash = $hash$; // eslint-disable-line no-unused-vars var hotRequestTimeout = $requestTimeout$; var hotCurrentModuleData = {}; var hotCurrentChildModule; // eslint-disable-line no-unused-vars var hotCurrentParents = []; // eslint-disable-line no-unused-vars var hotCurrentParentsTemp = []; // eslint-disable-line no-unused-vars function hotCreateRequire(moduleId) { // eslint-disable-line no-unused-vars 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) < 0) installedModules[request].parents.push(moduleId); } else { hotCurrentParents = [moduleId]; hotCurrentChildModule = request; } if(me.children.indexOf(request) < 0) 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") { 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(); } } } }; return fn; } function hotCreateModule(moduleId) { // eslint-disable-line no-unused-vars var hot = { // private stuff _acceptedDependencies: {}, _declinedDependencies: {}, _selfAccepted: false, _selfDeclined: false, _disposeHandlers: [], _main: hotCurrentChildModule !== moduleId, // Module API active: true, accept: function(dep, callback) { if(typeof 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(typeof 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-line no-lone-blocks /*globals chunkId */ hotEnsureUpdateChunk(chunkId); } if(hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) { hotUpdateDownloaded(); } return promise; }); } function hotAddUpdateChunk(chunkId, moreModules) { // eslint-disable-line no-unused-vars 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) >= 0) 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) < 0) 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); var result; if(hotUpdate[id]) { result = getAffectedStuff(moduleId); } else { result = { type: "disposed", moduleId: id }; } 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) >= 0) 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, orginalError: err, // TODO remove in webpack 4 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-3.5.6/lib/HotModuleReplacementPlugin.js000066400000000000000000000226721315401342100215070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("./Template"); const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency"); const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency"); const RawSource = require("webpack-sources").RawSource; 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.plugin("compilation", (compilation, params) => { const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; if(!hotUpdateChunkTemplate) return; const normalModuleFactory = params.normalModuleFactory; 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.plugin("record", function(compilation, records) { if(records.hash === this.hash) return; records.hash = compilation.hash; records.moduleHashs = {}; this.modules.forEach(module => { const identifier = module.identifier(); const hash = require("crypto").createHash("md5"); module.updateHash(hash); records.moduleHashs[identifier] = hash.digest("hex"); }); records.chunkHashs = {}; this.chunks.forEach(chunk => { records.chunkHashs[chunk.id] = chunk.hash; }); records.chunkModuleIds = {}; this.chunks.forEach(chunk => { records.chunkModuleIds[chunk.id] = chunk.mapModules(m => m.id); }); }); let initialPass = false; let recompilation = false; compilation.plugin("after-hash", function() { let records = this.records; if(!records) { initialPass = true; return; } if(!records.hash) initialPass = true; const preHash = records.preHash || "x"; const prepreHash = records.prepreHash || "x"; if(preHash === this.hash) { recompilation = true; this.modifyHash(prepreHash); return; } records.prepreHash = records.hash || "x"; records.preHash = this.hash; this.modifyHash(records.prepreHash); }); compilation.plugin("should-generate-chunk-assets", () => { if(multiStep && !recompilation && !initialPass) return false; }); compilation.plugin("need-additional-pass", () => { if(multiStep && !recompilation && !initialPass) return true; }); compiler.plugin("additional-pass", callback => { if(multiStep) return setTimeout(callback, fullBuildTimeout); return callback(); }); compilation.plugin("additional-chunk-assets", function() { const records = this.records; if(records.hash === this.hash) return; if(!records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds) return; this.modules.forEach(module => { const identifier = module.identifier(); let hash = require("crypto").createHash("md5"); module.updateHash(hash); hash = hash.digest("hex"); module.hotUpdate = records.moduleHashs[identifier] !== hash; }); const hotUpdateMainContent = { h: this.hash, c: {}, }; Object.keys(records.chunkHashs).forEach(function(chunkId) { chunkId = isNaN(+chunkId) ? chunkId : +chunkId; const currentChunk = this.chunks.find(chunk => chunk.id === chunkId); if(currentChunk) { const newModules = currentChunk.getModules().filter(module => module.hotUpdate); const allModules = {}; currentChunk.forEachModule(module => { allModules[module.id] = true; }); const removedModules = records.chunkModuleIds[chunkId].filter(id => !allModules[id]); if(newModules.length > 0 || removedModules.length > 0) { const source = hotUpdateChunkTemplate.render(chunkId, newModules, removedModules, this.hash, this.moduleTemplate, this.dependencyTemplates); const filename = this.getPath(hotUpdateChunkFilename, { hash: records.hash, chunk: currentChunk }); this.additionalChunkAssets.push(filename); this.assets[filename] = source; hotUpdateMainContent.c[chunkId] = true; currentChunk.files.push(filename); this.applyPlugins("chunk-asset", currentChunk, filename); } } else { hotUpdateMainContent.c[chunkId] = false; } }, this); const source = new RawSource(JSON.stringify(hotUpdateMainContent)); const filename = this.getPath(hotUpdateMainFilename, { hash: records.hash }); this.assets[filename] = source; }); compilation.mainTemplate.plugin("hash", hash => { hash.update("HotMainTemplateDecorator"); }); compilation.mainTemplate.plugin("module-require", (_, chunk, hash, varModuleId) => { return `hotCreateRequire(${varModuleId})`; }); compilation.mainTemplate.plugin("require-extensions", function(source) { const buf = [source]; buf.push(""); buf.push("// __webpack_hash__"); buf.push(this.requireFn + ".h = function() { return hotCurrentHash; };"); return this.asString(buf); }); compilation.mainTemplate.plugin("bootstrap", function(source, chunk, hash) { source = this.applyPluginsWaterfall("hot-bootstrap", source, chunk, hash); return this.asString([ source, "", hotInitCode .replace(/\$require\$/g, this.requireFn) .replace(/\$hash\$/g, JSON.stringify(hash)) .replace(/\$requestTimeout\$/g, requestTimeout) .replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : `var chunkId = ${JSON.stringify(chunk.id)};`) ]); }); compilation.mainTemplate.plugin("global-hash", () => true); compilation.mainTemplate.plugin("current-hash", (_, length) => { if(isFinite(length)) return `hotCurrentHash.substr(0, ${length})`; else return "hotCurrentHash"; }); compilation.mainTemplate.plugin("module-obj", function(source, chunk, hash, varModuleId) { return this.asString([ `${source},`, `hot: hotCreateModule(${varModuleId}),`, "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),", "children: []" ]); }); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { parser.plugin("expression __webpack_hash__", ParserHelpers.toConstantDependency("__webpack_require__.h()")); parser.plugin("evaluate typeof __webpack_hash__", ParserHelpers.evaluateToString("string")); parser.plugin("evaluate Identifier module.hot", function(expr) { return ParserHelpers.evaluateToIdentifier("module.hot", !!this.state.compilation.hotUpdateChunkTemplate)(expr); }); parser.plugin("call module.hot.accept", function(expr) { if(!this.state.compilation.hotUpdateChunkTemplate) return false; if(expr.arguments.length >= 1) { const arg = this.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; this.state.module.addDependency(dep); requests.push(request); }); if(expr.arguments.length > 1) this.applyPluginsBailResult("hot accept callback", expr.arguments[1], requests); else this.applyPluginsBailResult("hot accept without callback", expr, requests); } } }); parser.plugin("call module.hot.decline", function(expr) { if(!this.state.compilation.hotUpdateChunkTemplate) return false; if(expr.arguments.length === 1) { const arg = this.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; this.state.module.addDependency(dep); }); } }); parser.plugin("expression module.hot", ParserHelpers.skipTraversal); }); }); } }; const hotInitCode = Template.getFunctionContent(require("./HotModuleReplacement.runtime.js")); webpack-3.5.6/lib/HotUpdateChunkTemplate.js000066400000000000000000000020401315401342100206150ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("./Template"); const Chunk = require("./Chunk"); module.exports = class HotUpdateChunkTemplate extends Template { constructor(outputOptions) { super(outputOptions); } render(id, modules, removedModules, hash, moduleTemplate, dependencyTemplates) { const hotUpdateChunk = new Chunk(); hotUpdateChunk.id = id; hotUpdateChunk.setModules(modules); hotUpdateChunk.removedModules = removedModules; const modulesSource = this.renderChunkModules(hotUpdateChunk, moduleTemplate, dependencyTemplates); const core = this.applyPluginsWaterfall("modules", modulesSource, modules, removedModules, moduleTemplate, dependencyTemplates); const source = this.applyPluginsWaterfall("render", core, modules, removedModules, hash, id, moduleTemplate, dependencyTemplates); return source; } updateHash(hash) { hash.update("HotUpdateChunkTemplate"); hash.update("1"); this.applyPlugins("hash", hash); } }; webpack-3.5.6/lib/IgnorePlugin.js000066400000000000000000000030141315401342100166370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class IgnorePlugin { constructor(resourceRegExp, contextRegExp) { this.resourceRegExp = resourceRegExp; this.contextRegExp = contextRegExp; this.checkIgnore = this.checkIgnore.bind(this); } /* * Only returns true if a "resourceRegExp" exists * and the resource given matches the regexp. */ checkResource(resource) { if(!this.resourceRegExp) { return false; } return this.resourceRegExp.test(resource); } /* * Returns true if contextRegExp does not exist * or if context matches the given regexp. */ checkContext(context) { if(!this.contextRegExp) { return true; } return this.contextRegExp.test(context); } /* * Returns true if result should be ignored. * false if it shouldn't. * * Not that if "contextRegExp" is given, both the "resourceRegExp" * and "contextRegExp" have to match. */ checkResult(result) { if(!result) { return true; } return this.checkResource(result.request) && this.checkContext(result.context); } checkIgnore(result, callback) { // check if result is ignored if(this.checkResult(result)) { return callback(); } return callback(null, result); } apply(compiler) { compiler.plugin("normal-module-factory", (nmf) => { nmf.plugin("before-resolve", this.checkIgnore); }); compiler.plugin("context-module-factory", (cmf) => { cmf.plugin("before-resolve", this.checkIgnore); }); } } module.exports = IgnorePlugin; webpack-3.5.6/lib/JsonpChunkTemplatePlugin.js000066400000000000000000000016631315401342100212020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; class JsonpChunkTemplatePlugin { apply(chunkTemplate) { chunkTemplate.plugin("render", function(modules, chunk) { const jsonpFunction = this.outputOptions.jsonpFunction; const source = new ConcatSource(); source.add(`${jsonpFunction}(${JSON.stringify(chunk.ids)},`); source.add(modules); const entries = [chunk.entryModule].filter(Boolean).map(m => m.id); if(entries.length > 0) { source.add(`,${JSON.stringify(entries)}`); } source.add(")"); return source; }); chunkTemplate.plugin("hash", function(hash) { hash.update("JsonpChunkTemplatePlugin"); hash.update("3"); hash.update(`${this.outputOptions.jsonpFunction}`); hash.update(`${this.outputOptions.library}`); }); } } module.exports = JsonpChunkTemplatePlugin; webpack-3.5.6/lib/JsonpExportMainTemplatePlugin.js000066400000000000000000000015561315401342100222210ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; class JsonpExportMainTemplatePlugin { constructor(name) { this.name = name; } apply(compilation) { const mainTemplate = compilation.mainTemplate; compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => { const name = mainTemplate.applyPluginsWaterfall("asset-path", this.name || "", { hash: hash, chunk: chunk }); return new ConcatSource(`${name}(`, source, ");"); }); mainTemplate.plugin("global-hash-paths", paths => { if(this.name) paths.push(this.name); return paths; }); mainTemplate.plugin("hash", hash => { hash.update("jsonp export"); hash.update(`${this.name}`); }); } } module.exports = JsonpExportMainTemplatePlugin; webpack-3.5.6/lib/JsonpHotUpdateChunkTemplatePlugin.js000066400000000000000000000015241315401342100230140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; class JsonpHotUpdateChunkTemplatePlugin { apply(hotUpdateChunkTemplate) { hotUpdateChunkTemplate.plugin("render", function(modulesSource, modules, removedModules, hash, id) { const source = new ConcatSource(); source.add(`${this.outputOptions.hotUpdateFunction}(${JSON.stringify(id)},`); source.add(modulesSource); source.add(")"); return source; }); hotUpdateChunkTemplate.plugin("hash", function(hash) { hash.update("JsonpHotUpdateChunkTemplatePlugin"); hash.update("3"); hash.update(`${this.outputOptions.hotUpdateFunction}`); hash.update(`${this.outputOptions.library}`); }); } } module.exports = JsonpHotUpdateChunkTemplatePlugin; webpack-3.5.6/lib/JsonpMainTemplate.runtime.js000066400000000000000000000037261315401342100213230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals hotAddUpdateChunk parentHotUpdateCallback document XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ */ module.exports = function() { function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars hotAddUpdateChunk(chunkId, moreModules); if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } //$semicolon function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.type = "text/javascript"; script.charset = "utf-8"; script.src = $require$.p + $hotChunkFilename$; head.appendChild(script); } function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars 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-3.5.6/lib/JsonpMainTemplatePlugin.js000066400000000000000000000167001315401342100210140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("./Template"); class JsonpMainTemplatePlugin { apply(mainTemplate) { mainTemplate.plugin("local-vars", function(source, chunk) { if(chunk.chunks.length > 0) { return this.asString([ source, "", "// objects to store loaded and loading chunks", "var installedChunks = {", this.indent( chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") ), "};" ]); } return source; }); mainTemplate.plugin("jsonp-script", function(_, chunk, hash) { const chunkFilename = this.outputOptions.chunkFilename; const chunkMaps = chunk.getChunkMaps(); const crossOriginLoading = this.outputOptions.crossOriginLoading; const chunkLoadTimeout = this.outputOptions.chunkLoadTimeout; const scriptSrcPath = this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`, chunk: { id: "\" + chunkId + \"", hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hashWithLength(length) { const shortChunkHashMap = Object.create(null); Object.keys(chunkMaps.hash).forEach(chunkId => { 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) + "` } }); return this.asString([ "var script = document.createElement('script');", "script.type = 'text/javascript';", "script.charset = 'utf-8';", "script.async = true;", `script.timeout = ${chunkLoadTimeout};`, crossOriginLoading ? `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` : "", `if (${this.requireFn}.nc) {`, this.indent(`script.setAttribute("nonce", ${this.requireFn}.nc);`), "}", `script.src = ${this.requireFn}.p + ${scriptSrcPath};`, `var timeout = setTimeout(onScriptComplete, ${chunkLoadTimeout});`, "script.onerror = script.onload = onScriptComplete;", "function onScriptComplete() {", this.indent([ "// avoid mem leaks in IE.", "script.onerror = script.onload = null;", "clearTimeout(timeout);", "var chunk = installedChunks[chunkId];", "if(chunk !== 0) {", this.indent([ "if(chunk) {", this.indent("chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));"), "}", "installedChunks[chunkId] = undefined;" ]), "}" ]), "};", ]); }); mainTemplate.plugin("require-ensure", function(_, chunk, hash) { return this.asString([ "var installedChunkData = installedChunks[chunkId];", "if(installedChunkData === 0) {", this.indent([ "return new Promise(function(resolve) { resolve(); });" ]), "}", "", "// a Promise means \"currently loading\".", "if(installedChunkData) {", this.indent([ "return installedChunkData[2];" ]), "}", "", "// setup Promise in chunk cache", "var promise = new Promise(function(resolve, reject) {", this.indent([ "installedChunkData = installedChunks[chunkId] = [resolve, reject];" ]), "});", "installedChunkData[2] = promise;", "", "// start chunk loading", "var head = document.getElementsByTagName('head')[0];", this.applyPluginsWaterfall("jsonp-script", "", chunk, hash), "head.appendChild(script);", "", "return promise;" ]); }); mainTemplate.plugin("require-extensions", function(source, chunk) { if(chunk.chunks.length === 0) return source; return this.asString([ source, "", "// on error function for async loading", `${this.requireFn}.oe = function(err) { console.error(err); throw err; };` ]); }); mainTemplate.plugin("bootstrap", function(source, chunk, hash) { if(chunk.chunks.length > 0) { var jsonpFunction = this.outputOptions.jsonpFunction; return this.asString([ source, "", "// install a JSONP callback for chunk loading", `var parentJsonpFunction = window[${JSON.stringify(jsonpFunction)}];`, `window[${JSON.stringify(jsonpFunction)}] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {`, this.indent([ "// add \"moreModules\" to the modules object,", "// then flag all \"chunkIds\" as loaded and fire callback", "var moduleId, chunkId, i = 0, resolves = [], result;", "for(;i < chunkIds.length; i++) {", this.indent([ "chunkId = chunkIds[i];", "if(installedChunks[chunkId]) {", this.indent("resolves.push(installedChunks[chunkId][0]);"), "}", "installedChunks[chunkId] = 0;" ]), "}", "for(moduleId in moreModules) {", this.indent([ "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {", this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")), "}" ]), "}", "if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);", "while(resolves.length) {", this.indent("resolves.shift()();"), "}", this.entryPointInChildren(chunk) ? [ "if(executeModules) {", this.indent([ "for(i=0; i < executeModules.length; i++) {", this.indent(`result = ${this.requireFn}(${this.requireFn}.s = executeModules[i]);`), "}" ]), "}", "return result;", ] : "" ]), "};" ]); } return source; }); mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) { const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename; const hotUpdateFunction = this.outputOptions.hotUpdateFunction; const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`, chunk: { id: "\" + chunkId + \"" } }); const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "` }); const runtimeSource = Template.getFunctionContent(require("./JsonpMainTemplate.runtime.js")) .replace(/\/\/\$semicolon/g, ";") .replace(/\$require\$/g, this.requireFn) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) .replace(/\$hash\$/g, JSON.stringify(hash)); return `${source} function hotDisposeChunk(chunkId) { delete installedChunks[chunkId]; } var parentHotUpdateCallback = this[${JSON.stringify(hotUpdateFunction)}]; this[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; }); mainTemplate.plugin("hash", function(hash) { hash.update("jsonp"); hash.update("4"); hash.update(`${this.outputOptions.filename}`); hash.update(`${this.outputOptions.chunkFilename}`); hash.update(`${this.outputOptions.jsonpFunction}`); hash.update(`${this.outputOptions.hotUpdateFunction}`); }); } } module.exports = JsonpMainTemplatePlugin; webpack-3.5.6/lib/JsonpTemplatePlugin.js000066400000000000000000000013221315401342100202010ustar00rootroot00000000000000/* 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.plugin("this-compilation", (compilation) => { compilation.mainTemplate.apply(new JsonpMainTemplatePlugin()); compilation.chunkTemplate.apply(new JsonpChunkTemplatePlugin()); compilation.hotUpdateChunkTemplate.apply(new JsonpHotUpdateChunkTemplatePlugin()); }); } } module.exports = JsonpTemplatePlugin; webpack-3.5.6/lib/LibManifestPlugin.js000066400000000000000000000032261315401342100176160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const asyncLib = require("async"); class LibManifestPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.plugin("emit", (compilation, callback) => { asyncLib.forEach(compilation.chunks, (chunk, callback) => { if(!chunk.isInitial()) { 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: chunk.mapModules(module => { if(module.libIdent) { const ident = module.libIdent({ context: this.options.context || compiler.options.context }); if(ident) { return { ident, data: { id: module.id, meta: module.meta, exports: Array.isArray(module.providedExports) ? module.providedExports : undefined } }; } } }).filter(Boolean).reduce((obj, item) => { obj[item.ident] = item.data; return obj; }, Object.create(null)) }; const content = new Buffer(JSON.stringify(manifest), "utf8"); //eslint-disable-line compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => { if(err) return callback(err); compiler.outputFileSystem.writeFile(targetPath, content, callback); }); }, callback); }); } } module.exports = LibManifestPlugin; webpack-3.5.6/lib/LibraryTemplatePlugin.js000066400000000000000000000057671315401342100205350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin"); function accessorToObjectAccess(accessor) { return accessor.map((a) => { return `[${JSON.stringify(a)}]`; }).join(""); } function accessorAccess(base, accessor, joinWith) { accessor = [].concat(accessor); return accessor.map((a, idx) => { a = base ? base + accessorToObjectAccess(accessor.slice(0, idx + 1)) : accessor[0] + accessorToObjectAccess(accessor.slice(1, idx + 1)); if(idx === accessor.length - 1) return a; if(idx === 0 && typeof base === "undefined") return `${a} = typeof ${a} === "object" ? ${a} : {}`; return `${a} = ${a} || {}`; }).join(joinWith || "; "); } class LibraryTemplatePlugin { constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { this.name = name; this.target = target; this.umdNamedDefine = umdNamedDefine; this.auxiliaryComment = auxiliaryComment; this.exportProperty = exportProperty; } apply(compiler) { compiler.plugin("this-compilation", (compilation) => { if(this.exportProperty) { var ExportPropertyMainTemplatePlugin = require("./ExportPropertyMainTemplatePlugin"); compilation.apply(new ExportPropertyMainTemplatePlugin(this.exportProperty)); } switch(this.target) { case "var": compilation.apply(new SetVarMainTemplatePlugin(`var ${accessorAccess(false, this.name)}`)); break; case "assign": compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(undefined, this.name))); break; case "this": case "window": case "global": if(this.name) compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(this.target, this.name))); else compilation.apply(new SetVarMainTemplatePlugin(this.target, true)); break; case "commonjs": if(this.name) compilation.apply(new SetVarMainTemplatePlugin(accessorAccess("exports", this.name))); else compilation.apply(new SetVarMainTemplatePlugin("exports", true)); break; case "commonjs2": case "commonjs-module": compilation.apply(new SetVarMainTemplatePlugin("module.exports")); break; case "amd": var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); compilation.apply(new AmdMainTemplatePlugin(this.name)); break; case "umd": case "umd2": var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); compilation.apply(new UmdMainTemplatePlugin(this.name, { optionalAmdExternalAsGlobal: this.target === "umd2", namedDefine: this.umdNamedDefine, auxiliaryComment: this.auxiliaryComment })); break; case "jsonp": var JsonpExportMainTemplatePlugin = require("./JsonpExportMainTemplatePlugin"); compilation.apply(new JsonpExportMainTemplatePlugin(this.name)); break; default: throw new Error(`${this.target} is not a valid Library target`); } }); } } module.exports = LibraryTemplatePlugin; webpack-3.5.6/lib/LoaderOptionsPlugin.js000066400000000000000000000017411315401342100202030ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); class LoaderOptionsPlugin { constructor(options) { if(typeof options !== "object") options = {}; if(!options.test) options.test = { test: () => true }; this.options = options; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { compilation.plugin("normal-module-loader", (context, module) => { const resource = module.resource; if(!resource) return; const i = resource.indexOf("?"); if(ModuleFilenameHelpers.matchObject(options, i < 0 ? resource : resource.substr(0, i))) { const filterSet = new Set(["include", "exclude", "test"]); Object.keys(options) .filter((key) => !filterSet.has(key)) .forEach((key) => context[key] = options[key]); } }); }); } } module.exports = LoaderOptionsPlugin; webpack-3.5.6/lib/LoaderTargetPlugin.js000066400000000000000000000006371315401342100200010ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation) => { compilation.plugin("normal-module-loader", (loaderContext) => loaderContext.target = this.target); }); } } module.exports = LoaderTargetPlugin; webpack-3.5.6/lib/MainTemplate.js000066400000000000000000000205731315401342100166260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; const OriginalSource = require("webpack-sources").OriginalSource; const PrefixSource = require("webpack-sources").PrefixSource; const Template = require("./Template"); // 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 propery define getter function // __webpack_require__.o = Object.prototype.hasOwnProperty.call // __webpack_require__.n = compatibility get default export // __webpack_require__.h = the webpack hash // __webpack_require__.oe = the uncatched error handler for the webpack runtime // __webpack_require__.nc = the script nonce module.exports = class MainTemplate extends Template { constructor(outputOptions) { super(outputOptions); this.plugin("startup", (source, chunk, hash) => { 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 this.asString(buf); }); this.plugin("render", (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("/******/ ("); const modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates, "/******/ "); source.add(this.applyPluginsWaterfall("modules", modules, chunk, hash, moduleTemplate, dependencyTemplates)); source.add(")"); return source; }); this.plugin("local-vars", (source, chunk, hash) => { return this.asString([ source, "// The module cache", "var installedModules = {};" ]); }); this.plugin("require", (source, chunk, hash) => { return this.asString([ source, "// Check if module is in cache", "if(installedModules[moduleId]) {", this.indent("return installedModules[moduleId].exports;"), "}", "// Create a new module (and put it into the cache)", "var module = installedModules[moduleId] = {", this.indent(this.applyPluginsWaterfall("module-obj", "", chunk, hash, "moduleId")), "};", "", this.asString(outputOptions.strictModuleExceptionHandling ? [ "// Execute the module function", "var threw = true;", "try {", this.indent([ `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule(hash, chunk, "moduleId")});`, "threw = false;" ]), "} finally {", this.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.plugin("module-obj", (source, chunk, hash, varModuleId) => { return this.asString([ "i: moduleId,", "l: false,", "exports: {}" ]); }); this.plugin("require-extensions", (source, chunk, hash) => { const buf = []; if(chunk.chunks.length > 0) { 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(this.indent(this.applyPluginsWaterfall("require-ensure", "throw new Error('Not chunk loading available');", chunk, hash, "chunkId"))); 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(this.indent([ `if(!${this.requireFn}.o(exports, name)) {`, this.indent([ "Object.defineProperty(exports, name, {", this.indent([ "configurable: false,", "enumerable: true,", "get: getter" ]), "});" ]), "}" ])); buf.push("};"); buf.push(""); buf.push("// getDefaultExport function for compatibility with non-harmony modules"); buf.push(this.requireFn + ".n = function(module) {"); buf.push(this.indent([ "var getter = module && module.__esModule ?", this.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 this.asString(buf); }); this.requireFn = "__webpack_require__"; } render(hash, chunk, moduleTemplate, dependencyTemplates) { const buf = []; buf.push(this.applyPluginsWaterfall("bootstrap", "", chunk, hash, moduleTemplate, dependencyTemplates)); buf.push(this.applyPluginsWaterfall("local-vars", "", chunk, hash)); buf.push(""); buf.push("// The require function"); buf.push(`function ${this.requireFn}(moduleId) {`); buf.push(this.indent(this.applyPluginsWaterfall("require", "", chunk, hash))); buf.push("}"); buf.push(""); buf.push(this.asString(this.applyPluginsWaterfall("require-extensions", "", chunk, hash))); buf.push(""); buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash))); let source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", `webpack/bootstrap ${hash}`), chunk, hash, moduleTemplate, dependencyTemplates); if(chunk.hasEntryModule()) { source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash); } if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something"); chunk.rendered = true; return new ConcatSource(source, ";"); } renderRequireFunctionForModule(hash, chunk, varModuleId) { return this.applyPluginsWaterfall("module-require", this.requireFn, chunk, hash, varModuleId); } renderAddModule(hash, chunk, varModuleId, varModule) { return this.applyPluginsWaterfall("add-module", `modules[${varModuleId}] = ${varModule};`, chunk, hash, varModuleId, varModule); } renderCurrentHashCode(hash, length) { length = length || Infinity; return this.applyPluginsWaterfall("current-hash", JSON.stringify(hash.substr(0, length)), length); } entryPointInChildren(chunk) { const checkChildren = (chunk, alreadyCheckedChunks) => { return chunk.chunks.some((child) => { if(alreadyCheckedChunks.indexOf(child) >= 0) return; alreadyCheckedChunks.push(child); return child.hasEntryModule() || checkChildren(child, alreadyCheckedChunks); }); }; return checkChildren(chunk, []); } getPublicPath(options) { return this.applyPluginsWaterfall("asset-path", this.outputOptions.publicPath || "", options); } updateHash(hash) { hash.update("maintemplate"); hash.update("3"); hash.update(this.outputOptions.publicPath + ""); this.applyPlugins("hash", hash); } updateHashForChunk(hash, chunk) { this.updateHash(hash); this.applyPlugins("hash-for-chunk", hash, chunk); } useChunkHash(chunk) { const paths = this.applyPluginsWaterfall("global-hash-paths", []); return !this.applyPluginsBailResult("global-hash", chunk, paths); } }; webpack-3.5.6/lib/MemoryOutputFileSystem.js000066400000000000000000000002131315401342100207310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ module.exports = require("memory-fs"); webpack-3.5.6/lib/Module.js000066400000000000000000000131311315401342100154630ustar00rootroot00000000000000/* 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"); let debugId = 1000; const sortById = (a, b) => { return a.id - b.id; }; const sortByDebugId = (a, b) => { return a.debugId - b.debugId; }; class Module extends DependenciesBlock { constructor() { super(); this.context = null; this.reasons = []; this.debugId = debugId++; this.id = null; this.portableId = null; this.index = null; this.index2 = null; this.depth = null; this.used = null; this.usedExports = null; this.providedExports = null; this._chunks = new SortableSet(undefined, sortById); this._chunksDebugIdent = undefined; this.warnings = []; this.dependenciesWarnings = []; this.errors = []; this.dependenciesErrors = []; this.strict = false; this.meta = {}; this.optimizationBailout = []; } disconnect() { this.reasons.length = 0; this.id = null; this.index = null; this.index2 = null; this.depth = null; this.used = null; this.usedExports = null; this.providedExports = null; this._chunks.clear(); this._chunksDebugIdent = undefined; this.optimizationBailout.length = 0; super.disconnect(); } unseal() { this.id = null; this.index = null; this.index2 = null; this.depth = null; this._chunks.clear(); this._chunksDebugIdent = undefined; super.unseal(); } setChunks(chunks) { this._chunks = new SortableSet(chunks, sortById); this._chunksDebugIdent = undefined; } addChunk(chunk) { this._chunks.add(chunk); this._chunksDebugIdent = undefined; } removeChunk(chunk) { if(this._chunks.delete(chunk)) { this._chunksDebugIdent = undefined; chunk.removeModule(this); return true; } return false; } isInChunk(chunk) { return this._chunks.has(chunk); } getChunkIdsIdent() { if(this._chunksDebugIdent !== undefined) return this._chunksDebugIdent; this._chunks.sortWith(sortByDebugId); const chunks = this._chunks; const list = []; for(const chunk of chunks) { const debugId = chunk.debugId; if(typeof debugId !== "number") { return this._chunksDebugIdent = null; } list.push(debugId); } return this._chunksDebugIdent = list.join(","); } forEachChunk(fn) { this._chunks.forEach(fn); } mapChunks(fn) { return Array.from(this._chunks, fn); } getChunks() { return Array.from(this._chunks); } getNumberOfChunks() { return this._chunks.size; } 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](); while(true) { // eslint-disable-line const aItem = a.next(); const bItem = b.next(); if(aItem.done) return true; if(aItem.value !== bItem.value) return false; } } addReason(module, dependency) { this.reasons.push(new ModuleReason(module, dependency)); } 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) { for(let i = 0; i < this.reasons.length; i++) { if(this.reasons[i].hasChunk(chunk)) return true; } return false; } rewriteChunkInReasons(oldChunk, newChunks) { for(let i = 0; i < this.reasons.length; i++) { this.reasons[i].rewriteChunks(oldChunk, newChunks); } } isUsed(exportName) { if(this.used === null) return exportName; if(!exportName) return !!this.used; 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; if(this.isProvided(exportName)) return Template.numberToIdentifer(idx); return exportName; } isProvided(exportName) { if(!Array.isArray(this.providedExports)) return null; return this.providedExports.indexOf(exportName) >= 0; } toString() { return `Module[${this.id || this.debugId}]`; } needRebuild(fileTimestamps, contextTimestamps) { return true; } updateHash(hash) { hash.update(this.id + "" + this.used); hash.update(JSON.stringify(this.usedExports)); super.updateHash(hash); } sortItems(sortChunks) { super.sortItems(); if(sortChunks) this._chunks.sort(); this.reasons.sort((a, b) => sortById(a.module, b.module)); if(Array.isArray(this.usedExports)) { this.usedExports.sort(); } } unbuild() { this.disconnect(); } } 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"); } }); Object.defineProperty(Module.prototype, "chunks", { configurable: false, get: util.deprecate(function() { return Array.from(this._chunks); }, "Module.chunks: Use Module.forEachChunk/mapChunks/getNumberOfChunks/isInChunk/addChunk/removeChunk instead"), set() { throw new Error("Readonly. Use Module.addChunk/removeChunk to modify chunks."); } }); Module.prototype.identifier = null; Module.prototype.readableIdentifier = null; Module.prototype.build = null; Module.prototype.source = null; Module.prototype.size = null; Module.prototype.nameForCondition = null; module.exports = Module; webpack-3.5.6/lib/ModuleBuildError.js000066400000000000000000000020621315401342100174560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const cutOffLoaderExecution = require("./ErrorHelpers").cutOffLoaderExecution; class ModuleBuildError extends WebpackError { constructor(module, err) { super(); this.name = "ModuleBuildError"; this.message = "Module build failed: "; if(err !== null && typeof err === "object") { if(typeof err.stack === "string" && err.stack) { var stack = cutOffLoaderExecution(err.stack); if(!err.hideStack) { this.message += stack; } else { this.details = stack; if(typeof err.message === "string" && err.message) { this.message += err.message; } else { this.message += err; } } } else if(typeof err.message === "string" && err.message) { this.message += err.message; } else { this.message += err; } } this.module = module; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleBuildError; webpack-3.5.6/lib/ModuleDependencyError.js000066400000000000000000000011321315401342100204720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const formatLocation = require("./formatLocation"); module.exports = class ModuleDependencyError extends WebpackError { constructor(module, err, loc) { super(); this.name = "ModuleDependencyError"; this.message = `${formatLocation(loc)} ${err.message}`; this.details = err.stack.split("\n").slice(1).join("\n"); this.origin = this.module = module; this.error = err; Error.captureStackTrace(this, this.constructor); } }; webpack-3.5.6/lib/ModuleDependencyWarning.js000066400000000000000000000011361315401342100210120ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const formatLocation = require("./formatLocation"); module.exports = class ModuleDependencyWarning extends WebpackError { constructor(module, err, loc) { super(); this.name = "ModuleDependencyWarning"; this.message = `${formatLocation(loc)} ${err.message}`; this.details = err.stack.split("\n").slice(1).join("\n"); this.origin = this.module = module; this.error = err; Error.captureStackTrace(this, this.constructor); } }; webpack-3.5.6/lib/ModuleError.js000066400000000000000000000012121315401342100164720ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const cleanUp = require("./ErrorHelpers").cleanUp; class ModuleError extends WebpackError { constructor(module, err) { super(); this.name = "ModuleError"; this.module = module; this.message = err && typeof err === "object" && err.message ? err.message : err; 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-3.5.6/lib/ModuleFilenameHelpers.js000066400000000000000000000127041315401342100204540ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; 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; function getAfter(str, token) { const idx = str.indexOf(token); return idx < 0 ? "" : str.substr(idx); } function getBefore(str, token) { const idx = str.lastIndexOf(token); return idx < 0 ? "" : str.substr(0, idx); } function getHash(str) { const hash = require("crypto").createHash("md5"); hash.update(str); return hash.digest("hex").substr(0, 4); } function asRegExp(test) { if(typeof test === "string") test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); return test; } ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFilenameTemplate, requestShortener) { 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 moduleFilenameTemplate === "function") { return moduleFilenameTemplate({ identifier: identifier, shortIdentifier: shortIdentifier, resource: resource, resourcePath: resourcePath, absoluteResourcePath: absoluteResourcePath, allLoaders: allLoaders, query: query, moduleId: moduleId, hash: hash }); } return 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); }; ModuleFilenameHelpers.createFooter = function createFooter(module, requestShortener) { if(!module) module = ""; if(typeof module === "string") { return [ "// WEBPACK FOOTER //", `// ${requestShortener.shorten(module)}` ].join("\n"); } else { return [ "//////////////////", "// WEBPACK FOOTER", `// ${module.readableIdentifier(requestShortener)}`, `// module id = ${module.id}`, `// module chunks = ${module.mapChunks(c => c.id).join(" ")}` ].join("\n"); } }; ModuleFilenameHelpers.replaceDuplicates = function 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 = function matchPart(str, test) { if(!test) return true; test = asRegExp(test); if(Array.isArray(test)) { return test.map(asRegExp).filter(function(regExp) { return regExp.test(str); }).length > 0; } else { return test.test(str); } }; ModuleFilenameHelpers.matchObject = function 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-3.5.6/lib/ModuleNotFoundError.js000066400000000000000000000011411315401342100201500ustar00rootroot00000000000000/* 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, dependencies) { super(); this.name = "ModuleNotFoundError"; this.message = "Module not found: " + err; this.details = err.details; this.missing = err.missing; this.module = module; this.origin = module; this.dependencies = dependencies; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleNotFoundError; webpack-3.5.6/lib/ModuleParseError.js000066400000000000000000000020521315401342100174700ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); class ModuleParseError extends WebpackError { constructor(module, source, err) { super(); this.name = "ModuleParseError"; this.message = "Module parse failed: " + module.request + " " + err.message; this.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 this.message += "\n(Source code omitted for this binary file)"; } else { source = source.split("\n"); this.message += "\n| " + source.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| "); } } else { this.message += "\n" + err.stack; } this.module = module; this.error = err; Error.captureStackTrace(this, this.constructor); } } module.exports = ModuleParseError; webpack-3.5.6/lib/ModuleReason.js000066400000000000000000000022131315401342100166320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const util = require("util"); class ModuleReason { constructor(module, dependency) { this.module = module; this.dependency = dependency; this._chunks = null; } hasChunk(chunk) { if(this._chunks) { if(this._chunks.has(chunk)) return true; } else if(this.module._chunks.has(chunk)) return true; return false; } rewriteChunks(oldChunk, newChunks) { if(!this._chunks) { if(!this.module._chunks.has(oldChunk)) return; this._chunks = new Set(this.module._chunks); } if(this._chunks.has(oldChunk)) { this._chunks.delete(oldChunk); for(let i = 0; i < newChunks.length; i++) { this._chunks.add(newChunks[i]); } } } } Object.defineProperty(ModuleReason.prototype, "chunks", { configurable: false, get: util.deprecate(function() { return this._chunks ? Array.from(this._chunks) : null; }, "ModuleReason.chunks: Use ModuleReason.hasChunk/rewriteChunks instead"), set() { throw new Error("Readonly. Use ModuleReason.rewriteChunks to modify chunks."); } }); module.exports = ModuleReason; webpack-3.5.6/lib/ModuleTemplate.js000066400000000000000000000015361315401342100171650ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("./Template"); module.exports = class ModuleTemplate extends Template { constructor(outputOptions) { super(outputOptions); } render(module, dependencyTemplates, chunk) { const moduleSource = module.source(dependencyTemplates, this.outputOptions, this.requestShortener); const moduleSourcePostModule = this.applyPluginsWaterfall("module", moduleSource, module, chunk, dependencyTemplates); const moduleSourcePostRender = this.applyPluginsWaterfall("render", moduleSourcePostModule, module, chunk, dependencyTemplates); return this.applyPluginsWaterfall("package", moduleSourcePostRender, module, chunk, dependencyTemplates); } updateHash(hash) { hash.update("1"); this.applyPlugins("hash", hash); } }; webpack-3.5.6/lib/ModuleWarning.js000066400000000000000000000012761315401342100170200ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); const cleanUp = require("./ErrorHelpers").cleanUp; class ModuleWarning extends WebpackError { constructor(module, warning) { super(); this.name = "ModuleWarning"; this.module = module; this.message = warning && typeof warning === "object" && warning.message ? warning.message : warning; 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-3.5.6/lib/MovedToPluginWarningPlugin.js000066400000000000000000000012421315401342100214770ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; module.exports = class MovedToPluginWarningPlugin { constructor(optionName, pluginName) { this.optionName = optionName; this.pluginName = pluginName; } apply(compiler) { const optionName = this.optionName; const pluginName = this.pluginName; compiler.plugin("compilation", (compilation) => { compilation.warnings.push(new Error `webpack options: DEPRECATED option ${optionName} will be moved to the ${pluginName}. Use this instead. For more info about the usage of the ${pluginName} see https://webpack.js.org/plugins/`); }); } }; webpack-3.5.6/lib/MultiCompiler.js000066400000000000000000000105441315401342100170300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Tapable = require("tapable"); const asyncLib = require("async"); const MultiWatching = require("./MultiWatching"); const MultiStats = require("./MultiStats"); module.exports = class MultiCompiler extends Tapable { constructor(compilers) { super(); 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 = []; this.compilers.forEach((compiler, idx) => { let compilerDone = false; compiler.plugin("done", stats => { if(!compilerDone) { compilerDone = true; doneCompilers++; } compilerStats[idx] = stats; if(doneCompilers === this.compilers.length) { this.applyPlugins("done", new MultiStats(compilerStats)); } }); compiler.plugin("invalid", () => { if(compilerDone) { compilerDone = false; doneCompilers--; } this.applyPlugins("invalid"); }); }, this); } 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) { this.compilers.forEach(compiler => { compiler.inputFileSystem = value; }); } set outputFileSystem(value) { this.compilers.forEach(compiler => { compiler.outputFileSystem = value; }); } runWithDependencies(compilers, fn, callback) { let fulfilledNames = {}; let remainingCompilers = compilers; const isDependencyFulfilled = (d) => fulfilledNames[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[compiler.name] = true; runCompilers(callback); }); }, callback); }; runCompilers(callback); } watch(watchOptions, handler) { let watchings = []; let allStats = this.compilers.map(() => null); let compilerStatus = this.compilers.map(() => false); 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) { const allStats = this.compilers.map(() => null); 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 callback(err); callback(null, new MultiStats(allStats)); }); } purgeInputFileSystem() { this.compilers.forEach((compiler) => { if(compiler.inputFileSystem && compiler.inputFileSystem.purge) compiler.inputFileSystem.purge(); }); } }; webpack-3.5.6/lib/MultiEntryPlugin.js000066400000000000000000000024041315401342100175320ustar00rootroot00000000000000/* 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"); module.exports = class MultiEntryPlugin { constructor(context, entries, name) { this.context = context; this.entries = entries; this.name = name; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const multiModuleFactory = new MultiModuleFactory(); const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory); compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { const dep = MultiEntryPlugin.createDependency(this.entries, this.name); compilation.addEntry(this.context, dep, this.name, callback); }); } static createDependency(entries, name) { return new MultiEntryDependency(entries.map((e, idx) => { const dep = new SingleEntryDependency(e); dep.loc = name + ":" + (100000 + idx); return dep; }), name); } }; webpack-3.5.6/lib/MultiModule.js000066400000000000000000000032641315401342100165040ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("./Module"); const RawSource = require("webpack-sources").RawSource; class MultiModule extends Module { constructor(context, dependencies, name) { super(); this.context = context; this.dependencies = dependencies; this.name = name; this.built = false; this.cacheable = true; } identifier() { return `multi ${this.dependencies.map((d) => d.request).join(" ")}`; } readableIdentifier(requestShortener) { return `multi ${this.dependencies.map((d) => requestShortener.shorten(d.request)).join(" ")}`; } disconnect() { this.built = false; super.disconnect(); } build(options, compilation, resolver, fs, callback) { this.built = true; return callback(); } needRebuild() { return false; } size() { return 16 + this.dependencies.length * 12; } updateHash(hash) { hash.update("multi module"); hash.update(this.name || ""); super.updateHash(hash); } source(dependencyTemplates, outputOptions) { const str = []; this.dependencies.forEach(function(dep, idx) { if(dep.module) { if(idx === this.dependencies.length - 1) str.push("module.exports = "); str.push("__webpack_require__("); if(outputOptions.pathinfo) str.push(`/*! ${dep.request} */`); str.push(`${JSON.stringify(dep.module.id)}`); str.push(")"); } else { str.push("(function webpackMissingModule() { throw new Error("); str.push(JSON.stringify(`Cannot find module "${dep.request}"`)); str.push("); }())"); } str.push(";\n"); }, this); return new RawSource(str.join("")); } } module.exports = MultiModule; webpack-3.5.6/lib/MultiModuleFactory.js000066400000000000000000000007101315401342100200250ustar00rootroot00000000000000/* 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(); } create(data, callback) { const dependency = data.dependencies[0]; callback(null, new MultiModule(data.context, dependency.dependencies, dependency.name)); } }; webpack-3.5.6/lib/MultiStats.js000066400000000000000000000041771315401342100163610ustar00rootroot00000000000000/* 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 = typeof options.version === "undefined" ? jsons.every(j => j.version) : options.version !== false; const showHash = typeof options.hash === "undefined" ? jsons.every(j => j.hash) : options.hash !== false; jsons.forEach(j => { if(showVersion) 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-3.5.6/lib/MultiWatching.js000066400000000000000000000012351315401342100170170ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("async"); class MultiWatching { constructor(watchings, compiler) { this.watchings = watchings; this.compiler = compiler; } invalidate() { this.watchings.forEach((watching) => watching.invalidate()); } close(callback) { if(callback === undefined) callback = () => { /*do nothing*/ }; asyncLib.forEach(this.watchings, (watching, finishedCallback) => { watching.close(finishedCallback); }, err => { this.compiler.applyPlugins("watch-close"); callback(err); }); } } module.exports = MultiWatching; webpack-3.5.6/lib/NamedChunksPlugin.js000066400000000000000000000011571315401342100176220ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation) => { compilation.plugin("before-chunk-ids", (chunks) => { chunks.forEach((chunk) => { if(chunk.id === null) { chunk.id = this.nameResolver(chunk); } }); }); }); } } module.exports = NamedChunksPlugin; webpack-3.5.6/lib/NamedModulesPlugin.js000066400000000000000000000011241315401342100177710ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class NamedModulesPlugin { constructor(options) { this.options = options || {}; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("before-module-ids", (modules) => { modules.forEach((module) => { if(module.id === null && module.libIdent) { module.id = module.libIdent({ context: this.options.context || compiler.options.context }); } }); }); }); } } module.exports = NamedModulesPlugin; webpack-3.5.6/lib/NewWatchingPlugin.js000066400000000000000000000005621315401342100176370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class NewWatchingPlugin { apply(compiler) { compiler.plugin("compilation", function(compilation) { compilation.warnings.push(new Error("The 'NewWatchingPlugin' is no longer necessary (now default)")); }); } } module.exports = NewWatchingPlugin; webpack-3.5.6/lib/NoEmitOnErrorsPlugin.js000066400000000000000000000007521315401342100203070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class NoEmitOnErrorsPlugin { apply(compiler) { compiler.plugin("should-emit", (compilation) => { if(compilation.errors.length > 0) return false; }); compiler.plugin("compilation", (compilation) => { compilation.plugin("should-record", () => { if(compilation.errors.length > 0) return false; }); }); } } module.exports = NoEmitOnErrorsPlugin; webpack-3.5.6/lib/NoErrorsPlugin.js000066400000000000000000000013011315401342100171620ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; let deprecationReported = false; class NoErrorsPlugin { apply(compiler) { compiler.plugin("should-emit", (compilation) => { if(!deprecationReported) { compilation.warnings.push("webpack: Using NoErrorsPlugin is deprecated.\n" + "Use NoEmitOnErrorsPlugin instead.\n"); deprecationReported = true; } if(compilation.errors.length > 0) return false; }); compiler.plugin("compilation", (compilation) => { compilation.plugin("should-record", () => { if(compilation.errors.length > 0) return false; }); }); } } module.exports = NoErrorsPlugin; webpack-3.5.6/lib/NodeStuffPlugin.js000066400000000000000000000074031315401342100173170ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(parserOptions.node === false) return; let localOptions = options; if(parserOptions.node) localOptions = Object.assign({}, localOptions, parserOptions.node); function setConstant(expressionName, value) { parser.plugin(`expression ${expressionName}`, function() { this.state.current.addVariable(expressionName, JSON.stringify(value)); return true; }); } function setModuleConstant(expressionName, fn) { parser.plugin(`expression ${expressionName}`, function() { this.state.current.addVariable(expressionName, JSON.stringify(fn(this.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.plugin("evaluate Identifier __filename", function(expr) { if(!this.state.module) return; const resource = this.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.plugin("evaluate Identifier __dirname", function(expr) { if(!this.state.module) return; return ParserHelpers.evaluateToString(this.state.module.context)(expr); }); parser.plugin("expression require.main", ParserHelpers.toConstantDependency("__webpack_require__.c[__webpack_require__.s]")); parser.plugin( "expression require.extensions", ParserHelpers.expressionIsUnsupported("require.extensions is not supported by webpack. Use a loader instead.") ); parser.plugin("expression module.loaded", ParserHelpers.toConstantDependency("module.l")); parser.plugin("expression module.id", ParserHelpers.toConstantDependency("module.i")); parser.plugin("expression module.exports", function() { const module = this.state.module; const isHarmony = module.meta && module.meta.harmonyModule; if(!isHarmony) return true; }); parser.plugin("evaluate Identifier module.hot", ParserHelpers.evaluateToIdentifier("module.hot", false)); parser.plugin("expression module", function() { const module = this.state.module; const isHarmony = module.meta && module.meta.harmonyModule; let moduleJsPath = path.join(__dirname, "..", "buildin", isHarmony ? "harmony-module.js" : "module.js"); if(module.context) { moduleJsPath = path.relative(this.state.module.context, moduleJsPath); if(!/^[A-Z]:/i.test(moduleJsPath)) { moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`; } } return ParserHelpers.addParsedVariableToModule(this, "module", `require(${JSON.stringify(moduleJsPath)})(module)`); }); }); }); } } module.exports = NodeStuffPlugin; webpack-3.5.6/lib/NormalModule.js000066400000000000000000000370611315401342100166440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const NativeModule = require("module"); const crypto = require("crypto"); const SourceMapSource = require("webpack-sources").SourceMapSource; const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; const ReplaceSource = require("webpack-sources").ReplaceSource; const CachedSource = require("webpack-sources").CachedSource; const LineToLineMappedSource = require("webpack-sources").LineToLineMappedSource; 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 runLoaders = require("loader-runner").runLoaders; const getContext = require("loader-runner").getContext; function asString(buf) { if(Buffer.isBuffer(buf)) { return buf.toString("utf-8"); } return buf; } function contextify(context, request) { return request.split("!").map(function(r) { const splitPath = r.split("?"); splitPath[0] = path.relative(context, splitPath[0]); if(path.sep === "\\") splitPath[0] = splitPath[0].replace(/\\/g, "/"); if(splitPath[0].indexOf("../") !== 0) splitPath[0] = "./" + splitPath[0]; return splitPath.join("?"); }).join("!"); } 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); } } const dependencyTemplatesHashMap = new WeakMap(); class NormalModule extends Module { constructor(request, userRequest, rawRequest, loaders, resource, parser) { super(); this.request = request; this.userRequest = userRequest; this.rawRequest = rawRequest; this.parser = parser; this.resource = resource; this.context = getContext(resource); this.loaders = loaders; this.fileDependencies = []; this.contextDependencies = []; this.warnings = []; this.errors = []; this.error = null; this._source = null; this.assets = {}; this.built = false; this._cachedSource = null; } identifier() { return this.request; } readableIdentifier(requestShortener) { return requestShortener.shorten(this.userRequest); } libIdent(options) { return contextify(options.context, this.userRequest); } nameForCondition() { const idx = this.resource.indexOf("?"); if(idx >= 0) return this.resource.substr(0, idx); return this.resource; } 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 loaderContext = { version: 2, emitWarning: (warning) => { if(!(warning instanceof Error)) warning = new NonErrorEmittedError(warning); this.warnings.push(new ModuleWarning(this, warning)); }, emitError: (error) => { if(!(error instanceof Error)) error = new NonErrorEmittedError(error); this.errors.push(new ModuleError(this, error)); }, exec: (code, filename) => { const module = new NativeModule(filename, this); 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); }, resolveSync(context, request) { return resolver.resolveSync({}, context, request); }, emitFile: (name, content, sourceMap) => { this.assets[name] = this.createSourceForAsset(name, content, sourceMap); }, options: options, webpack: true, sourceMap: !!this.useSourceMap, _module: this, _compilation: compilation, _compiler: compilation.compiler, fs: fs, }; compilation.applyPlugins("normal-module-loader", loaderContext, this); if(options.loader) Object.assign(loaderContext, options.loader); return loaderContext; } 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); } return new OriginalSource(source, identifier); } doBuild(options, compilation, resolver, fs, callback) { this.cacheable = false; 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.cacheable = result.cacheable; this.fileDependencies = result.fileDependencies; this.contextDependencies = result.contextDependencies; } if(err) { const error = new ModuleBuildError(this, err); return callback(error); } const resourceBuffer = result.resourceBuffer; const source = result.result[0]; const sourceMap = result.result[1]; if(!Buffer.isBuffer(source) && typeof source !== "string") { const error = new ModuleBuildError(this, new Error("Final loader didn't return a Buffer or String")); return callback(error); } this._source = this.createSource(asString(source), resourceBuffer, sourceMap); return callback(); }); } disconnect() { this.built = false; super.disconnect(); } markModuleAsErrored(error) { this.meta = null; this.error = error; this.errors.push(this.error); this._source = new RawSource("throw new Error(" + JSON.stringify(this.error.message) + ");"); } 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; } build(options, compilation, resolver, fs, callback) { this.buildTimestamp = Date.now(); this.built = true; this._source = null; this.error = null; this.errors.length = 0; this.warnings.length = 0; this.meta = {}; return this.doBuild(options, compilation, resolver, fs, (err) => { this.dependencies.length = 0; this.variables.length = 0; this.blocks.length = 0; this._cachedSource = null; // if we have an error mark module as failed and exit if(err) { this.markModuleAsErrored(err); 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)) { return callback(); } try { this.parser.parse(this._source.source(), { current: this, module: this, compilation: compilation, options: options }); } catch(e) { const source = this._source.source(); const error = new ModuleParseError(this, source, e); this.markModuleAsErrored(error); return callback(); } return callback(); }); } getHashDigest(dependencyTemplates) { let dtHash = dependencyTemplatesHashMap.get("hash"); const hash = crypto.createHash("md5"); this.updateHash(hash); hash.update(`${dtHash}`); return hash.digest("hex"); } sourceDependency(dependency, dependencyTemplates, source, outputOptions, requestShortener) { const template = dependencyTemplates.get(dependency.constructor); if(!template) throw new Error("No template for dependency: " + dependency.constructor.name); template.apply(dependency, source, outputOptions, requestShortener, dependencyTemplates); } sourceVariables(variable, availableVars, dependencyTemplates, outputOptions, requestShortener) { const name = variable.name; const expr = variable.expressionSource(dependencyTemplates, outputOptions, requestShortener); 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(block) { if(this === block) { return this.exportsArgument || "exports"; } return "this"; } /* * creates the end part of a IIFE around the module to inject a variable name * (function(...){ * }.call(...)) <- this part */ variableInjectionFunctionWrapperEndCode(varExpressions, block) { const firstParam = this.contextArgument(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); } sourceBlock(block, availableVars, dependencyTemplates, source, outputOptions, requestShortener) { block.dependencies.forEach((dependency) => this.sourceDependency( dependency, dependencyTemplates, source, outputOptions, requestShortener)); /** * 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 paramter in a IIFE the expression as its value. */ const vars = block.variables.reduce((result, value) => { const variable = this.sourceVariables( value, availableVars, dependencyTemplates, outputOptions, requestShortener); 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( 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] : (this._source.size() + 1); source.insert(start + 0.5, varStartCode); source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode); } } block.blocks.forEach((block) => this.sourceBlock( block, availableVars.concat(vars), dependencyTemplates, source, outputOptions, requestShortener ) ); } source(dependencyTemplates, outputOptions, requestShortener) { const hashDigest = this.getHashDigest(dependencyTemplates); if(this._cachedSource && this._cachedSource.hash === hashDigest) { return this._cachedSource.source; } if(!this._source) { return new RawSource("throw new Error('No source available');"); } const source = new ReplaceSource(this._source); this._cachedSource = { source: source, hash: hashDigest }; this.sourceBlock(this, [], dependencyTemplates, source, outputOptions, requestShortener); return new CachedSource(source); } originalSource() { return this._source; } getHighestTimestamp(keys, timestampsByKey) { let highestTimestamp = 0; for(let i = 0; i < keys.length; i++) { const key = keys[i]; const timestamp = timestampsByKey[key]; // if there is no timestamp yet, early return with Infinity if(!timestamp) return Infinity; highestTimestamp = Math.max(highestTimestamp, timestamp); } return highestTimestamp; } needRebuild(fileTimestamps, contextTimestamps) { const highestFileDepTimestamp = this.getHighestTimestamp( this.fileDependencies, fileTimestamps); // if the hightest is Infinity, we need a rebuild // exit early here. if(highestFileDepTimestamp === Infinity) { return true; } const highestContextDepTimestamp = this.getHighestTimestamp( this.contextDependencies, contextTimestamps); // Again if the hightest is Infinity, we need a rebuild // exit early here. if(highestContextDepTimestamp === Infinity) { return true; } // else take the highest of file and context timestamps and compare // to last build timestamp return Math.max(highestContextDepTimestamp, highestFileDepTimestamp) >= this.buildTimestamp; } size() { return this._source ? this._source.size() : -1; } updateHashWithSource(hash) { if(!this._source) { hash.update("null"); return; } hash.update("source"); this._source.updateHash(hash); } updateHashWithMeta(hash) { hash.update("meta"); hash.update(JSON.stringify(this.meta)); } updateHash(hash) { this.updateHashWithSource(hash); this.updateHashWithMeta(hash); super.updateHash(hash); } } module.exports = NormalModule; webpack-3.5.6/lib/NormalModuleFactory.js000066400000000000000000000206201315401342100201650ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const asyncLib = require("async"); const Tapable = require("tapable"); const NormalModule = require("./NormalModule"); const RawModule = require("./RawModule"); const Parser = require("./Parser"); const RuleSet = require("./RuleSet"); function 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); } function identToLoaderRequest(resultString) { const idx = resultString.indexOf("?"); let options; if(idx >= 0) { options = resultString.substr(idx + 1); resultString = resultString.substr(0, idx); return { loader: resultString, options }; } else { return { loader: resultString }; } } class NormalModuleFactory extends Tapable { constructor(context, resolvers, options) { super(); this.resolvers = resolvers; this.ruleSet = new RuleSet(options.rules || options.loaders); this.cachePredicate = typeof options.unsafeCache === "function" ? options.unsafeCache : Boolean.bind(null, options.unsafeCache); this.context = context || ""; this.parserCache = {}; this.plugin("factory", () => (result, callback) => { let resolver = this.applyPluginsWaterfall0("resolver", 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.applyPluginsAsyncWaterfall("after-resolve", data, (err, result) => { if(err) return callback(err); // Ignored if(!result) return callback(); let createdModule = this.applyPluginsBailResult("create-module", result); if(!createdModule) { if(!result.request) { return callback(new Error("Empty dependency (no request)")); } createdModule = new NormalModule( result.request, result.userRequest, result.rawRequest, result.loaders, result.resource, result.parser ); } createdModule = this.applyPluginsWaterfall0("module", createdModule); return callback(null, createdModule); }); }); }); this.plugin("resolver", () => (data, callback) => { const contextInfo = data.contextInfo; const context = data.context; const request = data.request; const noAutoLoaders = /^-?!/.test(request); const noPrePostAutoLoaders = /^!!/.test(request); const noPostAutoLoaders = /^-!/.test(request); let elements = request.replace(/^-?!+/, "").replace(/!!+/g, "!").split("!"); let resource = elements.pop(); elements = elements.map(identToLoaderRequest); asyncLib.parallel([ callback => this.resolveRequestArray(contextInfo, context, elements, this.resolvers.loader, callback), callback => { if(resource === "" || resource[0] === "?") return callback(null, { resource }); this.resolvers.normal.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 { loaders.forEach(item => { if(typeof item.options === "string" && /^\?/.test(item.options)) { item.options = this.ruleSet.findOptionsByIdent(item.options.substr(1)); } }); } catch(e) { return callback(e); } if(resource === false) { // ignored return callback(null, new RawModule( "/* (ignored) */", `ignored ${context} ${request}`, `${request} (ignored)` ) ); } const userRequest = loaders.map(loaderToIdent).concat([resource]).join("!"); let resourcePath = 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, resourceQuery, issuer: contextInfo.issuer, compiler: contextInfo.compiler }); const settings = {}; const useLoadersPost = []; const useLoaders = []; const useLoadersPre = []; result.forEach(r => { if(r.type === "use") { if(r.enforce === "post" && !noPostAutoLoaders && !noPrePostAutoLoaders) useLoadersPost.push(r.value); else if(r.enforce === "pre" && !noPrePostAutoLoaders) useLoadersPre.push(r.value); else if(!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders) useLoaders.push(r.value); } else { settings[r.type] = r.value; } }); asyncLib.parallel([ this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPost, this.resolvers.loader), this.resolveRequestArray.bind(this, contextInfo, this.context, useLoaders, this.resolvers.loader), this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPre, this.resolvers.loader) ], (err, results) => { if(err) return callback(err); loaders = results[0].concat(loaders, results[1], results[2]); process.nextTick(() => { callback(null, { context: context, request: loaders.map(loaderToIdent).concat([resource]).join("!"), dependencies: data.dependencies, userRequest, rawRequest: request, loaders, resource, resourceResolveData, parser: this.getParser(settings.parser) }); }); }); }); }); } create(data, callback) { const dependencies = data.dependencies; const cacheEntry = dependencies[0].__NormalModuleFactoryCache; if(cacheEntry) return callback(null, cacheEntry); const context = data.context || this.context; const request = dependencies[0].request; const contextInfo = data.contextInfo || {}; this.applyPluginsAsyncWaterfall("before-resolve", { contextInfo, context, request, dependencies }, (err, result) => { if(err) return callback(err); // Ignored if(!result) return callback(); const factory = this.applyPluginsWaterfall0("factory", null); // Ignored if(!factory) return callback(); factory(result, (err, module) => { if(err) return callback(err); if(module && this.cachePredicate(module)) { dependencies.forEach(d => d.__NormalModuleFactoryCache = 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/guides/migrating/#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(parserOptions) { let ident = "null"; if(parserOptions) { if(parserOptions.ident) ident = parserOptions.ident; else ident = JSON.stringify(parserOptions); } const parser = this.parserCache[ident]; if(parser) return parser; return this.parserCache[ident] = this.createParser(parserOptions); } createParser(parserOptions) { const parser = new Parser(); this.applyPlugins2("parser", parser, parserOptions || {}); return parser; } } module.exports = NormalModuleFactory; webpack-3.5.6/lib/NormalModuleReplacementPlugin.js000066400000000000000000000022571315401342100222020ustar00rootroot00000000000000/* 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.plugin("normal-module-factory", (nmf) => { nmf.plugin("before-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.request)) { if(typeof newResource === "function") { newResource(result); } else { result.request = newResource; } } return callback(null, result); }); nmf.plugin("after-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.resource)) { if(typeof newResource === "function") { newResource(result); } else { result.resource = path.resolve(path.dirname(result.resource), newResource); } } return callback(null, result); }); }); } } module.exports = NormalModuleReplacementPlugin; webpack-3.5.6/lib/NullFactory.js000066400000000000000000000003311315401342100164760ustar00rootroot00000000000000/* 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-3.5.6/lib/OptionsApply.js000066400000000000000000000003101315401342100166720ustar00rootroot00000000000000/* 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-3.5.6/lib/OptionsDefaulter.js000066400000000000000000000036211315401342100175300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; function getProperty(obj, name) { name = name.split("."); for(var i = 0; i < name.length - 1; i++) { obj = obj[name[i]]; if(typeof obj !== "object" || !obj) return; } return obj[name.pop()]; } function setProperty(obj, name, value) { name = name.split("."); for(var i = 0; i < name.length - 1; i++) { if(typeof obj[name[i]] !== "object" && typeof obj[name[i]] !== "undefined") 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) { // TODO: change this for webpack 4: 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), options); break; case "make": if(getProperty(options, name) === undefined) setProperty(options, name, this.defaults[name].call(this, options), options); break; case "append": { let oldValue = getProperty(options, name); if(!Array.isArray(oldValue)) oldValue = []; oldValue.push.apply(oldValue, this.defaults[name]); setProperty(options, name, oldValue); break; } default: throw new Error("OptionsDefaulter cannot process " + this.config[name]); } } // TODO: change this for webpack 4: return options; } set(name, config, def) { if(arguments.length === 3) { this.defaults[name] = def; this.config[name] = config; } else { this.defaults[name] = config; delete this.config[name]; } } } module.exports = OptionsDefaulter; webpack-3.5.6/lib/Parser.js000066400000000000000000001276461315401342100155130ustar00rootroot00000000000000/* 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-dynamic-import").default; const Tapable = require("tapable"); const json5 = require("json5"); const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); function joinRanges(startRange, endRange) { if(!endRange) return startRange; if(!startRange) return endRange; return [startRange[0], endRange[1]]; } const ECMA_VERSION = 2017; const POSSIBLE_AST_OPTIONS = [{ ranges: true, locations: true, ecmaVersion: ECMA_VERSION, sourceType: "module", plugins: { dynamicImport: true } }, { ranges: true, locations: true, ecmaVersion: ECMA_VERSION, sourceType: "script", plugins: { dynamicImport: true } }]; class Parser extends Tapable { constructor(options) { super(); this.options = options; this.scope = undefined; this.state = undefined; this.comments = undefined; this.initializeEvaluating(); } initializeEvaluating() { this.plugin("evaluate Literal", 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.plugin("evaluate LogicalExpression", function(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.plugin("evaluate BinaryExpression", function(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()) { res.setWrapped( new BasicEvaluatedExpression() .setString(left.string + right.prefix.string) .setRange(joinRanges(left.range, right.prefix.range)), right.postfix); } else if(right.isWrapped()) { res.setWrapped( new BasicEvaluatedExpression() .setString(left.string) .setRange(left.range), right.postfix); } else { res.setWrapped(left, null); } } else if(left.isNumber()) { if(right.isString()) { res.setString(left.number + right.string); } else if(right.isNumber()) { res.setNumber(left.number + right.number); } } else if(left.isWrapped()) { if(left.postfix && left.postfix.isString() && right.isString()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.string) .setRange(joinRanges(left.postfix.range, right.range)) ); } else if(left.postfix && left.postfix.isString() && right.isNumber()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() .setString(left.postfix.string + right.number) .setRange(joinRanges(left.postfix.range, right.range)) ); } else if(right.isString()) { res.setWrapped(left.prefix, right); } else if(right.isNumber()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() .setString(right.number + "") .setRange(right.range)); } else { res.setWrapped(left.prefix, new BasicEvaluatedExpression()); } } else { if(right.isString()) { res.setWrapped(null, right); } } 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 === "==" || 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); } } }); this.plugin("evaluate UnaryExpression", function(expr) { if(expr.operator === "typeof") { let res; let name; if(expr.argument.type === "Identifier") { name = this.scope.renames["$" + expr.argument.name] || expr.argument.name; if(this.scope.definitions.indexOf(name) === -1) { res = this.applyPluginsBailResult1("evaluate typeof " + name, expr); if(res !== undefined) return res; } } if(expr.argument.type === "MemberExpression") { const exprName = this.getNameForExpression(expr.argument); if(exprName && exprName.free) { res = this.applyPluginsBailResult1("evaluate typeof " + exprName.name, 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); else if(arg.isNumber()) return new BasicEvaluatedExpression().setString("number").setRange(expr.range); else if(arg.isBoolean()) return new BasicEvaluatedExpression().setString("boolean").setRange(expr.range); else 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); } else if(argument.isTruthy()) { return new BasicEvaluatedExpression().setBoolean(false).setRange(expr.range); } else if(argument.isFalsy()) { return new BasicEvaluatedExpression().setBoolean(true).setRange(expr.range); } else if(argument.isString()) { return new BasicEvaluatedExpression().setBoolean(!argument.string).setRange(expr.range); } else if(argument.isNumber()) { return new BasicEvaluatedExpression().setBoolean(!argument.number).setRange(expr.range); } } }); this.plugin("evaluate typeof undefined", function(expr) { return new BasicEvaluatedExpression().setString("undefined").setRange(expr.range); }); this.plugin("evaluate Identifier", function(expr) { const name = this.scope.renames["$" + expr.name] || expr.name; if(this.scope.definitions.indexOf(expr.name) === -1) { const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr); if(result) return result; return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range); } else { return this.applyPluginsBailResult1("evaluate defined Identifier " + name, expr); } }); this.plugin("evaluate ThisExpression", function(expr) { const name = this.scope.renames.$this; if(name) { const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr); if(result) return result; return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range); } }); this.plugin("evaluate MemberExpression", function(expression) { let exprName = this.getNameForExpression(expression); if(exprName) { if(exprName.free) { const result = this.applyPluginsBailResult1("evaluate Identifier " + exprName.name, expression); if(result) return result; return new BasicEvaluatedExpression().setIdentifier(exprName.name).setRange(expression.range); } else { return this.applyPluginsBailResult1("evaluate defined Identifier " + exprName.name, expression); } } }); this.plugin("evaluate CallExpression", function(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; return this.applyPluginsBailResult("evaluate CallExpression ." + property, expr, param); }); this.plugin("evaluate CallExpression .replace", function(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.plugin("evaluate CallExpression ." + fn, function(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 {any[]} quasis quasis * @param {any[]} expressions expressions * @return {BasicEvaluatedExpression[]} Simplified template */ function getSimplifiedTemplateResult(kind, quasis, expressions) { const parts = []; for(let i = 0; i < quasis.length; i++) { parts.push(new BasicEvaluatedExpression().setString(quasis[i].value[kind]).setRange(quasis[i].range)); if(i > 0) { const prevExpr = parts[parts.length - 2], lastExpr = parts[parts.length - 1]; const expr = this.evaluateExpression(expressions[i - 1]); if(!(expr.isString() || expr.isNumber())) continue; prevExpr.setString(prevExpr.string + (expr.isString() ? expr.string : expr.number) + lastExpr.string); prevExpr.setRange([prevExpr.range[0], lastExpr.range[1]]); parts.pop(); } } return parts; } this.plugin("evaluate TemplateLiteral", function(node) { const parts = getSimplifiedTemplateResult.call(this, "cooked", node.quasis, node.expressions); if(parts.length === 1) { return parts[0].setRange(node.range); } return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range); }); this.plugin("evaluate TaggedTemplateExpression", function(node) { if(this.evaluateExpression(node.tag).identifier !== "String.raw") return; const parts = getSimplifiedTemplateResult.call(this, "raw", node.quasi.quasis, node.quasi.expressions); return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range); }); }); this.plugin("evaluate CallExpression .split", function(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.plugin("evaluate ConditionalExpression", function(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.plugin("evaluate ArrayExpression", function(expr) { const items = expr.elements.map(function(element) { return element !== null && this.evaluateExpression(element); }, this); if(!items.every(Boolean)) return; return new BasicEvaluatedExpression().setItems(items).setRange(expr.range); }); } getRenameIdentifier(expr) { const result = this.evaluateExpression(expr); if(!result) return; if(result.isIdentifier()) return result.identifier; return; } walkClass(classy) { if(classy.superClass) this.walkExpression(classy.superClass); if(classy.body && classy.body.type === "ClassBody") { classy.body.body.forEach(methodDefinition => { if(methodDefinition.type === "MethodDefinition") this.walkMethodDefinition(methodDefinition); }); } } 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) { const handler = this["prewalk" + statement.type]; if(handler) handler.call(this, statement); } walkStatement(statement) { if(this.applyPluginsBailResult1("statement", statement) !== undefined) return; const handler = this["walk" + statement.type]; if(handler) handler.call(this, statement); } // 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.applyPluginsBailResult1("statement if", 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 result = this.applyPluginsBailResult1("label " + statement.label.name, statement); if(result !== true) 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.prewalkStatement(statement.left); this.prewalkStatement(statement.body); } walkForInStatement(statement) { if(statement.left.type === "VariableDeclaration") this.walkStatement(statement.left); else this.walkExpression(statement.left); this.walkExpression(statement.right); this.walkStatement(statement.body); } prewalkForOfStatement(statement) { if(statement.left.type === "VariableDeclaration") this.prewalkStatement(statement.left); this.prewalkStatement(statement.body); } walkForOfStatement(statement) { if(statement.left.type === "VariableDeclaration") this.walkStatement(statement.left); else this.walkExpression(statement.left); this.walkExpression(statement.right); this.walkStatement(statement.body); } // Declarations prewalkFunctionDeclaration(statement) { if(statement.id) { this.scope.renames["$" + statement.id.name] = undefined; this.scope.definitions.push(statement.id.name); } } walkFunctionDeclaration(statement) { statement.params.forEach(param => { this.walkPattern(param); }); this.inScope(statement.params, () => { if(statement.body.type === "BlockStatement") { this.prewalkStatement(statement.body); this.walkStatement(statement.body); } else { this.walkExpression(statement.body); } }); } prewalkImportDeclaration(statement) { const source = statement.source.value; this.applyPluginsBailResult("import", statement, source); statement.specifiers.forEach(function(specifier) { const name = specifier.local.name; this.scope.renames["$" + name] = undefined; this.scope.definitions.push(name); switch(specifier.type) { case "ImportDefaultSpecifier": this.applyPluginsBailResult("import specifier", statement, source, "default", name); break; case "ImportSpecifier": this.applyPluginsBailResult("import specifier", statement, source, specifier.imported.name, name); break; case "ImportNamespaceSpecifier": this.applyPluginsBailResult("import specifier", statement, source, null, name); break; } }, this); } prewalkExportNamedDeclaration(statement) { let source; if(statement.source) { source = statement.source.value; this.applyPluginsBailResult("export import", statement, source); } else { this.applyPluginsBailResult1("export", statement); } if(statement.declaration) { if(/Expression$/.test(statement.declaration.type)) { throw new Error("Doesn't occur?"); } else { if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) { const pos = this.scope.definitions.length; this.prewalkStatement(statement.declaration); const newDefs = this.scope.definitions.slice(pos); for(let index = newDefs.length - 1; index >= 0; index--) { const def = newDefs[index]; this.applyPluginsBailResult("export specifier", 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.applyPluginsBailResult("export import specifier", statement, source, specifier.local.name, name, specifierIndex); else this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name, specifierIndex); break; } } } } } walkExportNamedDeclaration(statement) { if(statement.declaration) { this.walkStatement(statement.declaration); } } prewalkExportDefaultDeclaration(statement) { if(/Declaration$/.test(statement.declaration.type)) { const pos = this.scope.definitions.length; this.prewalkStatement(statement.declaration); const newDefs = this.scope.definitions.slice(pos); for(let index = 0, len = newDefs.length; index < len; index++) { const def = newDefs[index]; this.applyPluginsBailResult("export specifier", statement, def, "default"); } } } walkExportDefaultDeclaration(statement) { this.applyPluginsBailResult1("export", statement); if(/Declaration$/.test(statement.declaration.type)) { if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) { this.walkStatement(statement.declaration); } } else { this.walkExpression(statement.declaration); if(!this.applyPluginsBailResult("export expression", statement, statement.declaration)) { this.applyPluginsBailResult("export specifier", statement, statement.declaration, "default"); } } } prewalkExportAllDeclaration(statement) { const source = statement.source.value; this.applyPluginsBailResult("export import", statement, source); this.applyPluginsBailResult("export import specifier", statement, source, null, null, 0); } prewalkVariableDeclaration(statement) { if(statement.declarations) this.prewalkVariableDeclarators(statement.declarations); } walkVariableDeclaration(statement) { if(statement.declarations) this.walkVariableDeclarators(statement.declarations); } prewalkClassDeclaration(statement) { if(statement.id) { this.scope.renames["$" + statement.id.name] = undefined; this.scope.definitions.push(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) { this.inScope([catchClause.param], () => { this.prewalkStatement(catchClause.body); this.walkStatement(catchClause.body); }); } prewalkVariableDeclarators(declarators) { declarators.forEach(declarator => { switch(declarator.type) { case "VariableDeclarator": { this.enterPattern(declarator.id, (name, decl) => { if(!this.applyPluginsBailResult1("var-" + declarator.kind + " " + name, decl)) { if(!this.applyPluginsBailResult1("var " + name, decl)) { this.scope.renames["$" + name] = undefined; if(this.scope.definitions.indexOf(name) < 0) this.scope.definitions.push(name); } } }); break; } } }); } walkVariableDeclarators(declarators) { declarators.forEach(declarator => { switch(declarator.type) { case "VariableDeclarator": { const renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init); if(renameIdentifier && declarator.id.type === "Identifier" && this.applyPluginsBailResult1("can-rename " + renameIdentifier, declarator.init)) { // renaming with "var a = b;" if(!this.applyPluginsBailResult1("rename " + renameIdentifier, declarator.init)) { this.scope.renames["$" + declarator.id.name] = this.scope.renames["$" + renameIdentifier] || renameIdentifier; const idx = this.scope.definitions.indexOf(declarator.id.name); if(idx >= 0) this.scope.definitions.splice(idx, 1); } } else { this.walkPattern(declarator.id); if(declarator.init) this.walkExpression(declarator.init); } break; } } }); } walkPattern(pattern) { if(pattern.type === "Identifier") return; if(this["walk" + pattern.type]) this["walk" + pattern.type](pattern); } 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(let expressionsIndex = 0, len = expressions.length; expressionsIndex < len; expressionsIndex++) { const expression = expressions[expressionsIndex]; if(expression) this.walkExpression(expression); } } walkExpression(expression) { if(this["walk" + expression.type]) return this["walk" + expression.type](expression); } walkAwaitExpression(expression) { const argument = expression.argument; if(this["walk" + argument.type]) return this["walk" + argument.type](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.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) { expression.params.forEach(param => { this.walkPattern(param); }); this.inScope(expression.params, () => { if(expression.body.type === "BlockStatement") { this.prewalkStatement(expression.body); this.walkStatement(expression.body); } else { this.walkExpression(expression.body); } }); } walkArrowFunctionExpression(expression) { expression.params.forEach(param => { this.walkPattern(param); }); this.inScope(expression.params, () => { if(expression.body.type === "BlockStatement") { 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 result = this.applyPluginsBailResult1("typeof " + exprName.name, 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) { this.walkLeftRightExpression(expression); } walkAssignmentExpression(expression) { const renameIdentifier = this.getRenameIdentifier(expression.right); if(expression.left.type === "Identifier" && renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, expression.right)) { // renaming "a = b;" if(!this.applyPluginsBailResult1("rename " + renameIdentifier, expression.right)) { this.scope.renames["$" + expression.left.name] = renameIdentifier; const idx = this.scope.definitions.indexOf(expression.left.name); if(idx >= 0) this.scope.definitions.splice(idx, 1); } } else if(expression.left.type === "Identifier") { if(!this.applyPluginsBailResult1("assigned " + expression.left.name, expression)) { this.walkExpression(expression.right); } this.scope.renames["$" + expression.left.name] = undefined; if(!this.applyPluginsBailResult1("assign " + expression.left.name, expression)) { this.walkExpression(expression.left); } } else { this.walkExpression(expression.right); this.walkPattern(expression.left); this.enterPattern(expression.left, (name, decl) => { this.scope.renames["$" + name] = undefined; }); } } walkConditionalExpression(expression) { const result = this.applyPluginsBailResult1("expression ?:", 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) { 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); } walkCallExpression(expression) { let result; function walkIIFE(functionExpression, options, currentThis) { function renameArgOrThis(argOrThis) { const renameIdentifier = this.getRenameIdentifier(argOrThis); if(renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, argOrThis)) { if(!this.applyPluginsBailResult1("rename " + renameIdentifier, argOrThis)) return renameIdentifier; } this.walkExpression(argOrThis); } const params = functionExpression.params; const renameThis = currentThis ? renameArgOrThis.call(this, currentThis) : null; const args = options.map(renameArgOrThis, this); this.inScope(params.filter(function(identifier, idx) { return !args[idx]; }), () => { if(renameThis) { this.scope.renames.$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["$" + params[i].name] = param; } if(functionExpression.body.type === "BlockStatement") { this.prewalkStatement(functionExpression.body); this.walkStatement(functionExpression.body); } else this.walkExpression(functionExpression.body); }); } if(expression.callee.type === "MemberExpression" && expression.callee.object.type === "FunctionExpression" && !expression.callee.computed && (["call", "bind"]).indexOf(expression.callee.property.name) >= 0 && expression.arguments && expression.arguments.length > 0 ) { // (function(...) { }.call/bind(?, ...)) walkIIFE.call(this, expression.callee.object, expression.arguments.slice(1), expression.arguments[0]); } else if(expression.callee.type === "FunctionExpression" && expression.arguments) { // (function(...) { }(...)) walkIIFE.call(this, expression.callee, expression.arguments); } else if(expression.callee.type === "Import") { result = this.applyPluginsBailResult1("import-call", expression); if(result === true) return; if(expression.arguments) this.walkExpressions(expression.arguments); } else { const callee = this.evaluateExpression(expression.callee); if(callee.isIdentifier()) { result = this.applyPluginsBailResult1("call " + callee.identifier, expression); if(result === true) return; let identifier = callee.identifier.replace(/\.[^.]+$/, ".*"); if(identifier !== callee.identifier) { result = this.applyPluginsBailResult1("call " + identifier, 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) { let result = this.applyPluginsBailResult1("expression " + exprName.name, expression); if(result === true) return; result = this.applyPluginsBailResult1("expression " + exprName.nameGeneral, expression); if(result === true) return; } this.walkExpression(expression.object); if(expression.computed === true) this.walkExpression(expression.property); } walkIdentifier(expression) { if(this.scope.definitions.indexOf(expression.name) === -1) { const result = this.applyPluginsBailResult1("expression " + (this.scope.renames["$" + expression.name] || expression.name), expression); if(result === true) return; } } inScope(params, fn) { const oldScope = this.scope; this.scope = { inTry: false, inShorthand: false, definitions: oldScope.definitions.slice(), renames: Object.create(oldScope.renames) }; this.scope.renames.$this = undefined; for(let paramIndex = 0, len = params.length; paramIndex < len; paramIndex++) { const param = params[paramIndex]; if(typeof param !== "string") { this.enterPattern(param, param => { this.scope.renames["$" + param] = undefined; this.scope.definitions.push(param); }); } else { this.scope.renames["$" + param] = undefined; this.scope.definitions.push(param); } } fn(); this.scope = oldScope; } enterPattern(pattern, onIdent) { if(pattern && this["enter" + pattern.type]) this["enter" + pattern.type](pattern, onIdent); } 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 result = this.applyPluginsBailResult1("evaluate " + expression.type, expression); if(result !== undefined) return result; } catch(e) { console.warn(e); // ignore error } return new BasicEvaluatedExpression().setRange(expression.range); } 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 }; } else if(right.code) { return { range: [left.range[0], right.range ? right.range[1] : left.range[1]], value: left.value + right.value, code: true }; } else { return { range: [left.range[0], right.range[1]], value: left.value + right.value }; } } break; case "ConditionalExpression": { const consequent = this.parseCalculatedString(expression.consequent); const alternate = this.parseCalculatedString(expression.alternate); const items = []; if(consequent.conditional) Array.prototype.push.apply(items, consequent.conditional); else if(!consequent.code) items.push(consequent); else break; if(alternate.conditional) Array.prototype.push.apply(items, alternate.conditional); else if(!alternate.code) items.push(alternate); else break; return { value: "", code: true, conditional: items }; } case "Literal": return { range: expression.range, value: expression.value + "" }; } return { value: "", code: true }; } parseStringArray(expression) { if(expression.type !== "ArrayExpression") { return [this.parseString(expression)]; } const arr = []; if(expression.elements) expression.elements.forEach(function(expr) { arr.push(this.parseString(expr)); }, this); return arr; } parseCalculatedStringArray(expression) { if(expression.type !== "ArrayExpression") { return [this.parseCalculatedString(expression)]; } const arr = []; if(expression.elements) expression.elements.forEach(function(expr) { arr.push(this.parseCalculatedString(expr)); }, this); return arr; } parse(source, initialState) { let ast; const comments = []; for(let i = 0, len = POSSIBLE_AST_OPTIONS.length; i < len; i++) { if(!ast) { try { comments.length = 0; POSSIBLE_AST_OPTIONS[i].onComment = comments; ast = acorn.parse(source, POSSIBLE_AST_OPTIONS[i]); } catch(e) { // ignore the error } } } if(!ast) { // for the error ast = acorn.parse(source, { ranges: true, locations: true, ecmaVersion: ECMA_VERSION, sourceType: "module", plugins: { dynamicImport: true }, onComment: comments }); } if(!ast || typeof ast !== "object") throw new Error("Source couldn't be parsed"); const oldScope = this.scope; const oldState = this.state; const oldComments = this.comments; this.scope = { inTry: false, definitions: [], renames: {} }; const state = this.state = initialState || {}; this.comments = comments; if(this.applyPluginsBailResult("program", ast, comments) === undefined) { this.prewalkStatements(ast.body); this.walkStatements(ast.body); } this.scope = oldScope; this.state = oldState; this.comments = oldComments; return state; } evaluate(source) { const ast = acorn.parse("(" + source + ")", { ranges: true, locations: true, ecmaVersion: ECMA_VERSION, sourceType: "module", plugins: { dynamicImport: true } }); if(!ast || typeof ast !== "object" || ast.type !== "Program") throw new Error("evaluate: Source couldn't be parsed"); if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") throw new Error("evaluate: Source is not a expression"); return this.evaluateExpression(ast.body[0].expression); } getComments(range) { return this.comments.filter(comment => comment.range[0] >= range[0] && comment.range[1] <= range[1]); } getCommentOptions(range) { const comments = this.getComments(range); if(comments.length === 0) return null; const options = comments.map(comment => { try { return json5.parse(`{${comment.value}}`); } catch(e) { return {}; } }); return options.reduce((o, i) => Object.assign(o, i), {}); } 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.indexOf(expr.name) === -1; exprName.push(this.scope.renames["$" + expr.name] || expr.name); } else if(expr.type === "ThisExpression" && this.scope.renames.$this) { free = true; exprName.push(this.scope.renames.$this); } else if(expr.type === "ThisExpression") { free = false; exprName.push("this"); } else { return null; } let prefix = ""; for(let i = exprName.length - 1; i >= 1; i--) prefix += exprName[i] + "."; const name = prefix + exprName[0]; const nameGeneral = prefix + "*"; return { name, nameGeneral, free }; } } Parser.ECMA_VERSION = ECMA_VERSION; module.exports = Parser; webpack-3.5.6/lib/ParserHelpers.js000066400000000000000000000047231315401342100170240ustar00rootroot00000000000000/* 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 = function(parser, name, expression) { if(!parser.state.current.addVariable) return false; var deps = []; parser.parse(expression, { current: { addDependency: function(dep) { dep.userRequest = name; deps.push(dep); } }, module: parser.state.module }); parser.state.current.addVariable(name, expression, deps); return true; }; ParserHelpers.requireFileAsExpression = function(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 = function(value) { return function constDependency(expr) { var dep = new ConstDependency(value, expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); return true; }; }; ParserHelpers.evaluateToString = function(value) { return function stringExpression(expr) { return new BasicEvaluatedExpression().setString(value).setRange(expr.range); }; }; ParserHelpers.evaluateToBoolean = function(value) { return function booleanExpression(expr) { return new BasicEvaluatedExpression().setBoolean(value).setRange(expr.range); }; }; ParserHelpers.evaluateToIdentifier = function(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 = function(message) { return function unsupportedExpression(expr) { var dep = new ConstDependency("(void 0)", expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); if(!this.state.module) return; this.state.module.warnings.push(new UnsupportedFeatureWarning(this.state.module, message)); return true; }; }; ParserHelpers.skipTraversal = function skipTraversal() { return true; }; ParserHelpers.approve = function approve() { return true; }; webpack-3.5.6/lib/PrefetchPlugin.js000066400000000000000000000014331315401342100171570ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { compilation.prefetch(this.context || compiler.context, new PrefetchDependency(this.request), callback); }); } } module.exports = PrefetchPlugin; webpack-3.5.6/lib/ProgressPlugin.js000066400000000000000000000134551315401342100172320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ProgressPlugin { constructor(options) { if(typeof options === "function") { options = { handler: options }; } options = options || {}; this.profile = options.profile; this.handler = options.handler; } apply(compiler) { const handler = this.handler || defaultHandler; const profile = this.profile; if(compiler.compilers) { const states = new Array(compiler.compilers.length); compiler.compilers.forEach(function(compiler, idx) { compiler.apply(new ProgressPlugin(function(p, msg) { states[idx] = Array.prototype.slice.apply(arguments); handler.apply(null, [ states.map(state => state && state[0] || 0).reduce((a, b) => a + b) / states.length, `[${idx}] ${msg}` ].concat(Array.prototype.slice.call(arguments, 2))); })); }); } else { let lastModulesCount = 0; let moduleCount = 500; let doneModules = 0; const activeModules = []; const update = function update(module) { handler( 0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6, "building modules", `${doneModules}/${moduleCount} modules`, `${activeModules.length} active`, activeModules[activeModules.length - 1] ); }; const moduleDone = function moduleDone(module) { doneModules++; const ident = module.identifier(); if(ident) { const idx = activeModules.indexOf(ident); if(idx >= 0) activeModules.splice(idx, 1); } update(); }; compiler.plugin("compilation", function(compilation) { if(compilation.compiler.isChild()) return; lastModulesCount = moduleCount; moduleCount = 0; doneModules = 0; handler(0, "compiling"); compilation.plugin("build-module", function(module) { moduleCount++; const ident = module.identifier(); if(ident) { activeModules.push(ident); } update(); }); compilation.plugin("failed-module", moduleDone); compilation.plugin("succeed-module", moduleDone); const syncHooks = { "seal": [0.71, "sealing"], "optimize": [0.72, "optimizing"], "optimize-modules-basic": [0.73, "basic module optimization"], "optimize-modules": [0.74, "module optimization"], "optimize-modules-advanced": [0.75, "advanced module optimization"], "optimize-chunks-basic": [0.76, "basic chunk optimization"], "optimize-chunks": [0.77, "chunk optimization"], "optimize-chunks-advanced": [0.78, "advanced chunk optimization"], // optimize-tree "optimize-chunk-modules": [0.80, "chunk modules optimization"], "optimize-chunk-modules-advanced": [0.81, "advanced chunk modules optimization"], "revive-modules": [0.82, "module reviving"], "optimize-module-order": [0.83, "module order optimization"], "optimize-module-ids": [0.84, "module id optimization"], "revive-chunks": [0.85, "chunk reviving"], "optimize-chunk-order": [0.86, "chunk order optimization"], "optimize-chunk-ids": [0.87, "chunk id optimization"], "before-hash": [0.88, "hashing"], "before-module-assets": [0.89, "module assets processing"], "before-chunk-assets": [0.90, "chunk assets processing"], "additional-chunk-assets": [0.91, "additional chunk assets processing"], "record": [0.92, "recording"] }; Object.keys(syncHooks).forEach(name => { let pass = 0; const settings = syncHooks[name]; compilation.plugin(name, () => { if(pass++ > 0) handler(settings[0], settings[1], `pass ${pass}`); else handler(settings[0], settings[1]); }); }); compilation.plugin("optimize-tree", (chunks, modules, callback) => { handler(0.79, "module and chunk tree optimization"); callback(); }); compilation.plugin("additional-assets", callback => { handler(0.91, "additional asset processing"); callback(); }); compilation.plugin("optimize-chunk-assets", (chunks, callback) => { handler(0.92, "chunk asset optimization"); callback(); }); compilation.plugin("optimize-assets", (assets, callback) => { handler(0.94, "asset optimization"); callback(); }); }); compiler.plugin("emit", (compilation, callback) => { handler(0.95, "emitting"); callback(); }); compiler.plugin("done", () => { handler(1, ""); }); } let lineCaretPosition = 0, lastState, lastStateTime; function defaultHandler(percentage, msg) { let state = msg; const details = Array.prototype.slice.call(arguments, 2); if(percentage < 1) { percentage = Math.floor(percentage * 100); msg = `${percentage}% ${msg}`; if(percentage < 100) { msg = ` ${msg}`; } if(percentage < 10) { msg = ` ${msg}`; } details.forEach(detail => { if(!detail) return; if(detail.length > 40) { detail = `...${detail.substr(detail.length - 37)}`; } 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; } } goToLineStart(msg); process.stderr.write(msg); } function 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); } } } module.exports = ProgressPlugin; webpack-3.5.6/lib/ProvidePlugin.js000066400000000000000000000034551315401342100170350ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", (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.plugin(`can-rename ${name}`, ParserHelpers.approve); }); } parser.plugin(`expression ${name}`, function(expr) { let nameIdentifier = name; const scopedName = name.indexOf(".") >= 0; 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(this, nameIdentifier, expression)) { return false; } if(scopedName) { ParserHelpers.toConstantDependency(nameIdentifier).bind(this)(expr); } return true; }); }); }); }); } } module.exports = ProvidePlugin; webpack-3.5.6/lib/RawModule.js000066400000000000000000000022271315401342100161410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Module = require("./Module"); const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; module.exports = class RawModule extends Module { constructor(source, identifier, readableIdentifier) { super(); this.sourceStr = source; this.identifierStr = identifier || this.sourceStr; this.readableIdentifierStr = readableIdentifier || this.identifierStr; this.cacheable = true; 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.builtTime = Date.now(); 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-3.5.6/lib/RecordIdsPlugin.js000066400000000000000000000103471315401342100173010ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const identifierUtils = require("./util/identifier"); class RecordIdsPlugin { apply(compiler) { compiler.plugin("compilation", compilation => { compilation.plugin("record-modules", (modules, records) => { if(!records.modules) records.modules = {}; if(!records.modules.byIdentifier) records.modules.byIdentifier = {}; if(!records.modules.usedIds) records.modules.usedIds = {}; modules.forEach(function(module) { if(!module.portableId) module.portableId = identifierUtils.makePathsRelative(compiler.context, module.identifier()); const identifier = module.portableId; records.modules.byIdentifier[identifier] = module.id; records.modules.usedIds[module.id] = module.id; }); }); compilation.plugin("revive-modules", (modules, records) => { if(!records.modules) return; if(records.modules.byIdentifier) { const usedIds = {}; modules.forEach(function(module) { if(module.id !== null) return; if(!module.portableId) module.portableId = identifierUtils.makePathsRelative(compiler.context, module.identifier()); const identifier = module.portableId; const id = records.modules.byIdentifier[identifier]; if(id === undefined) return; if(usedIds[id]) return; usedIds[id] = true; module.id = id; }); } compilation.usedModuleIds = records.modules.usedIds; }); function getDepBlockIdent(chunk, block) { const ident = []; if(block.chunks.length > 1) ident.push(block.chunks.indexOf(chunk)); while(block.parent) { const p = block.parent; const idx = p.blocks.indexOf(block); const l = p.blocks.length - 1; ident.push(`${idx}/${l}`); block = block.parent; } if(!block.identifier) return null; ident.push(identifierUtils.makePathsRelative(compiler.context, block.identifier())); return ident.reverse().join(":"); } compilation.plugin("record-chunks", (chunks, records) => { records.nextFreeChunkId = compilation.nextFreeChunkId; if(!records.chunks) records.chunks = {}; if(!records.chunks.byName) records.chunks.byName = {}; if(!records.chunks.byBlocks) records.chunks.byBlocks = {}; records.chunks.usedIds = {}; chunks.forEach(chunk => { const name = chunk.name; const blockIdents = chunk.blocks.map(getDepBlockIdent.bind(null, chunk)).filter(Boolean); if(name) records.chunks.byName[name] = chunk.id; blockIdents.forEach((blockIdent) => { records.chunks.byBlocks[blockIdent] = chunk.id; }); records.chunks.usedIds[chunk.id] = chunk.id; }); }); compilation.plugin("revive-chunks", (chunks, records) => { if(!records.chunks) return; const usedIds = {}; if(records.chunks.byName) { chunks.forEach(function(chunk) { if(chunk.id !== null) return; if(!chunk.name) return; const id = records.chunks.byName[chunk.name]; if(id === undefined) return; if(usedIds[id]) return; usedIds[id] = true; chunk.id = id; }); } if(records.chunks.byBlocks) { const argumentedChunks = chunks.filter(chunk => chunk.id === null).map(chunk => ({ chunk, blockIdents: chunk.blocks.map(getDepBlockIdent.bind(null, chunk)).filter(Boolean) })).filter(arg => arg.blockIdents.length > 0); let blockIdentsCount = {}; argumentedChunks.forEach((arg, idx) => { arg.blockIdents.forEach(blockIdent => { const id = records.chunks.byBlocks[blockIdent]; if(typeof id !== "number") return; const accessor = `${id}:${idx}`; blockIdentsCount[accessor] = (blockIdentsCount[accessor] || 0) + 1; }); }); blockIdentsCount = Object.keys(blockIdentsCount).map(accessor => [blockIdentsCount[accessor]].concat(accessor.split(":").map(Number))).sort((a, b) => b[0] - a[0]); blockIdentsCount.forEach(function(arg) { const id = arg[1]; if(usedIds[id]) return; const idx = arg[2]; const chunk = argumentedChunks[idx].chunk; if(chunk.id !== null) return; usedIds[id] = true; chunk.id = id; }); } compilation.usedChunkIds = records.chunks.usedIds; }); }); } } module.exports = RecordIdsPlugin; webpack-3.5.6/lib/RequestShortener.js000066400000000000000000000043551315401342100175700ustar00rootroot00000000000000/* 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 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 endsWithSeperator = SEPARATOR_REGEXP.test(dirname); const parentDirectory = endsWithSeperator ? 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); } } shorten(request) { if(!request) return request; request = normalizeBackSlashDirection(request); if(this.buildinsAsModule && this.buildinsRegExp) request = request.replace(this.buildinsRegExp, "!(webpack)"); if(this.currentDirectoryRegExp) request = request.replace(this.currentDirectoryRegExp, "!."); if(this.parentDirectoryRegExp) request = request.replace(this.parentDirectoryRegExp, "!.."); if(!this.buildinsAsModule && this.buildinsRegExp) request = request.replace(this.buildinsRegExp, "!(webpack)"); request = request.replace(INDEX_JS_REGEXP, "$1"); return request.replace(FRONT_OR_BACK_BANG_REGEXP, ""); } } module.exports = RequestShortener; webpack-3.5.6/lib/RequireJsStuffPlugin.js000066400000000000000000000022361315401342100203420ustar00rootroot00000000000000/* 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.plugin("compilation", function(compilation, params) { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", function(parser, parserOptions) { if(typeof parserOptions.requireJs !== "undefined" && !parserOptions.requireJs) return; parser.plugin("call require.config", ParserHelpers.toConstantDependency("undefined")); parser.plugin("call requirejs.config", ParserHelpers.toConstantDependency("undefined")); parser.plugin("expression require.version", ParserHelpers.toConstantDependency(JSON.stringify("0.0.0"))); parser.plugin("expression requirejs.onError", ParserHelpers.toConstantDependency("__webpack_require__.oe")); }); }); } }; webpack-3.5.6/lib/RuleSet.js000066400000000000000000000255371315401342100156360ustar00rootroot00000000000000/* 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"; 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; 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.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"].indexOf(key) < 0; }); keys.forEach((key) => { newRule[key] = rule[key]; }); function 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; } function 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(Array.isArray(newRule.use)) { newRule.use.forEach((item) => { 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(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 normalizeUseItemFunction(use, data) { const result = use(data); if(typeof result === "string") { return RuleSet.normalizeUseItem(result); } return result; } static normalizeUseItemString(useItemString) { const idx = useItemString.indexOf("?"); if(idx >= 0) { return { loader: useItemString.substr(0, idx), options: useItemString.substr(idx + 1) }; } return { loader: useItemString }; } static normalizeUseItem(item, ident) { if(typeof item === "function") return item; 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"].indexOf(key) < 0; }); keys.forEach(function(key) { 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.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(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", "resourceQuery", "compiler", "issuer", "rules", "oneOf", "use", "enforce"].indexOf(key) < 0; }); keys.forEach((key) => { result.push({ type: key, value: rule[key] }); }); if(rule.use) { rule.use.forEach((use) => { result.push({ type: "use", value: typeof use === "function" ? RuleSet.normalizeUseItemFunction(use, data) : use, enforce: rule.enforce }); }); } 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; } }; function notMatcher(matcher) { return function(str) { return !matcher(str); }; } function orMatcher(items) { return function(str) { for(let i = 0; i < items.length; i++) { if(items[i](str)) return true; } return false; }; } function andMatcher(items) { return function(str) { for(let i = 0; i < items.length; i++) { if(!items[i](str)) return false; } return true; }; } webpack-3.5.6/lib/SetVarMainTemplatePlugin.js000066400000000000000000000022431315401342100211240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; class SetVarMainTemplatePlugin { constructor(varExpression, copyObject) { this.varExpression = varExpression; this.copyObject = copyObject; } apply(compilation) { const mainTemplate = compilation.mainTemplate; compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => { const varExpression = mainTemplate.applyPluginsWaterfall("asset-path", 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); } }); mainTemplate.plugin("global-hash-paths", (paths) => { if(this.varExpression) paths.push(this.varExpression); return paths; }); mainTemplate.plugin("hash", hash => { hash.update("set var"); hash.update(`${this.varExpression}`); hash.update(`${this.copyObject}`); }); } } module.exports = SetVarMainTemplatePlugin; webpack-3.5.6/lib/SingleEntryPlugin.js000066400000000000000000000016351315401342100176660ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); class SingleEntryPlugin { constructor(context, entry, name) { this.context = context; this.entry = entry; this.name = name; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { const dep = SingleEntryPlugin.createDependency(this.entry, this.name); compilation.addEntry(this.context, dep, this.name, callback); }); } static createDependency(entry, name) { const dep = new SingleEntryDependency(entry); dep.loc = name; return dep; } } module.exports = SingleEntryPlugin; webpack-3.5.6/lib/SizeFormatHelpers.js000066400000000000000000000006641315401342100176530ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Sean Larkin @thelarkinn */ "use strict"; const SizeFormatHelpers = exports; SizeFormatHelpers.formatSize = size => { if(size <= 0) { return "0 bytes"; } const abbreviations = ["bytes", "kB", "MB", "GB"]; const index = Math.floor(Math.log(size) / Math.log(1000)); return `${+(size / Math.pow(1000, index)).toPrecision(3)} ${abbreviations[index]}`; }; webpack-3.5.6/lib/SourceMapDevToolModuleOptionsPlugin.js000066400000000000000000000017601315401342100233370ustar00rootroot00000000000000/* 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.plugin("build-module", module => { module.useSourceMap = true; }); } if(options.lineToLine === true) { compilation.plugin("build-module", module => { module.lineToLine = true; }); } else if(options.lineToLine) { compilation.plugin("build-module", 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-3.5.6/lib/SourceMapDevToolPlugin.js000066400000000000000000000167731315401342100206270ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const path = require("path"); const crypto = require("crypto"); const RequestShortener = require("./RequestShortener"); const ConcatSource = require("webpack-sources").ConcatSource; const RawSource = require("webpack-sources").RawSource; const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); const basename = (name) => { if(name.indexOf("/") < 0) return name; return name.substr(name.lastIndexOf("/") + 1); }; function getTaskForFile(file, chunk, options, compilation) { const asset = compilation.assets[file]; if(asset.__SourceMapDevToolFile === file && asset.__SourceMapDevToolData) { const data = asset.__SourceMapDevToolData; for(const cachedFile in data) { compilation.assets[cachedFile] = data[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 { constructor(options) { if(arguments.length > 1) throw new Error("SourceMapDevToolPlugin only takes one argument (pass an options object)"); // TODO: remove in webpack 3 if(typeof options === "string") { options = { sourceMapFilename: options }; } if(!options) options = {}; this.sourceMapFilename = options.filename; this.sourceMappingURLComment = options.append === false ? false : options.append || "\n//# sourceMappingURL=[url]"; this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resourcePath]"; this.fallbackModuleFilenameTemplate = options.fallbackModuleFilenameTemplate || "webpack:///[resourcePath]?[hash]"; this.options = options; } apply(compiler) { const sourceMapFilename = this.sourceMapFilename; const sourceMappingURLComment = this.sourceMappingURLComment; const moduleFilenameTemplate = this.moduleFilenameTemplate; const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; const requestShortener = new RequestShortener(compiler.context); const options = this.options; options.test = options.test || /\.(js|css)($|\?)/i; const matchObject = ModuleFilenameHelpers.matchObject.bind(undefined, options); compiler.plugin("compilation", compilation => { new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); compilation.plugin("after-optimize-chunk-assets", function(chunks) { const moduleToSourceNameMapping = new Map(); const tasks = []; chunks.forEach(function(chunk) { chunk.files.forEach(file => { if(matchObject(file)) { 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, requestShortener)); } } task.modules = modules; tasks.push(task); } } }); }); 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, fallbackModuleFilenameTemplate, 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(function(task) { 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(sourceMap.sourcesContent && !options.noSources) { sourceMap.sourcesContent = sourceMap.sourcesContent.map((content, i) => `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], requestShortener)}`); } else { sourceMap.sourcesContent = undefined; } sourceMap.sourceRoot = options.sourceRoot || ""; sourceMap.file = file; asset.__SourceMapDevToolFile = file; asset.__SourceMapDevToolData = {}; 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, query, basename: basename(filename) }); if(sourceMapFile.indexOf("[contenthash]") !== -1) { sourceMapFile = sourceMapFile.replace(/\[contenthash\]/g, crypto.createHash("md5").update(sourceMapString).digest("hex")); } const sourceMapUrl = path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/"); if(currentSourceMappingURLComment !== false) { asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl)); } asset.__SourceMapDevToolData[sourceMapFile] = compilation.assets[sourceMapFile] = new RawSource(sourceMapString); chunk.files.push(sourceMapFile); } else { asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment .replace(/\[map\]/g, () => sourceMapString) .replace(/\[url\]/g, () => `data:application/json;charset=utf-8;base64,${new Buffer(sourceMapString, "utf-8").toString("base64")}`) // eslint-disable-line ); } }); }); }); } } module.exports = SourceMapDevToolPlugin; webpack-3.5.6/lib/Stats.js000066400000000000000000000667151315401342100153540ustar00rootroot00000000000000/* 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 optionsOrFallback = function() { let optionValues = []; optionValues.push.apply(optionValues, arguments); return optionValues.find(optionValue => typeof optionValue !== "undefined"); }; class Stats { constructor(compilation) { this.compilation = compilation; this.hash = compilation.hash; } 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 surpressed const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => { if(typeof filter === "string") { return warning => warning.indexOf(filter) > -1; } 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)); }); } hasWarnings() { return this.compilation.warnings.length > 0; } hasErrors() { return this.compilation.errors.length > 0; } // 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) => typeof v !== "undefined" ? v : typeof options.all !== "undefined" ? options.all : def; const testAgainstGivenOption = (item) => { if(typeof item === "string") { const regExp = new RegExp(`[\\\\/]${item.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")}([\\\\/]|$|!|\\?)`); // eslint-disable-line no-useless-escape 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; }; const compilation = this.compilation; const context = optionsOrFallback(options.context, process.cwd()); const requestShortener = new RequestShortener(context); const showPerformance = optionOrLocalFallback(options.performance, true); const showHash = optionOrLocalFallback(options.hash, true); const showVersion = optionOrLocalFallback(options.version, true); const showTimings = optionOrLocalFallback(options.timings, true); const showAssets = optionOrLocalFallback(options.assets, true); const showEntrypoints = optionOrLocalFallback(options.entrypoints, !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 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, ""); 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; } return i++ < maxModules; }; }; 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; return a[fieldKey] < b[fieldKey] ? -1 : 1; }; const sortByField = (field) => (a, b) => { if(!field) { return 0; } const fieldKey = this.normalizeFieldKey(field); // if a field is prefixed with a "!" the sort is reversed! const sortIsRegular = this.sortOrderRegular(field); return sortByFieldAndOrder(fieldKey, sortIsRegular ? a : b, sortIsRegular ? b : a); }; 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.isInitial() ? " [initial]" : ""}\n`; } if(e.file) { text += `${e.file}\n`; } if(e.module && e.module.readableIdentifier && typeof e.module.readableIdentifier === "function") { text += `${e.module.readableIdentifier(requestShortener)}\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.dependencies && e.origin) { text += `\n @ ${e.origin.readableIdentifier(requestShortener)}`; e.dependencies.forEach(dep => { if(!dep.loc) return; if(typeof dep.loc === "string") return; const locInfo = formatLocation(dep.loc); if(!locInfo) return; 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(compilation.needAdditionalPass) { obj.needAdditionalPass = true; } if(showPublicPath) { obj.publicPath = this.compilation.mainTemplate.getPublicPath({ hash: this.compilation.hash }); } if(showAssets) { const assetsByFile = {}; const compilationAssets = Object.keys(compilation.assets); obj.assetsByChunkName = {}; obj.assets = compilationAssets.map(asset => { const obj = { name: asset, size: compilation.assets[asset].size(), chunks: [], chunkNames: [], emitted: compilation.assets[asset].emitted }; if(showPerformance) { obj.isOverSizeLimit = compilation.assets[asset].isOverSizeLimit; } assetsByFile[asset] = obj; return obj; }).filter(createAssetFilter()); obj.filteredAssets = compilationAssets.length - obj.assets.length; compilation.chunks.forEach(chunk => { chunk.files.forEach(asset => { if(assetsByFile[asset]) { chunk.ids.forEach(id => { 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)); } if(showEntrypoints) { obj.entrypoints = {}; Object.keys(compilation.entrypoints).forEach(name => { const ep = compilation.entrypoints[name]; obj.entrypoints[name] = { chunks: ep.chunks.map(c => c.id), assets: ep.chunks.reduce((array, c) => array.concat(c.files || []), []) }; if(showPerformance) { obj.entrypoints[name].isOverSizeLimit = ep.isOverSizeLimit; } }); } function fnModule(module) { const obj = { id: module.id, identifier: module.identifier(), name: module.readableIdentifier(requestShortener), index: module.index, index2: module.index2, size: module.size(), cacheable: !!module.cacheable, built: !!module.built, optional: !!module.optional, prefetched: !!module.prefetched, chunks: module.mapChunks(chunk => chunk.id), assets: Object.keys(module.assets || {}), issuer: module.issuer && module.issuer.identifier(), issuerId: module.issuer && module.issuer.id, issuerName: module.issuer && module.issuer.readableIdentifier(requestShortener), profile: module.profile, failed: !!module.error, errors: module.errors && module.dependenciesErrors && (module.errors.length + module.dependenciesErrors.length), warnings: module.errors && module.dependenciesErrors && (module.warnings.length + module.dependenciesWarnings.length) }; if(showReasons) { obj.reasons = module.reasons.filter(reason => reason.dependency && reason.module).map(reason => { const obj = { moduleId: reason.module.id, moduleIdentifier: reason.module.identifier(), module: reason.module.readableIdentifier(requestShortener), moduleName: reason.module.readableIdentifier(requestShortener), type: reason.dependency.type, userRequest: reason.dependency.userRequest }; const locInfo = formatLocation(reason.dependency.loc); if(locInfo) obj.loc = locInfo; return obj; }).sort((a, b) => a.moduleId - b.moduleId); } if(showUsedExports) { obj.usedExports = module.used ? module.usedExports : false; } if(showProvidedExports) { obj.providedExports = Array.isArray(module.providedExports) ? module.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(showSource && module._source) { obj.source = module._source.source(); } return obj; } if(showChunks) { obj.chunks = compilation.chunks.map(chunk => { const obj = { id: chunk.id, rendered: chunk.rendered, initial: chunk.isInitial(), entry: chunk.hasRuntime(), recorded: chunk.recorded, extraAsync: !!chunk.extraAsync, size: chunk.mapModules(m => m.size()).reduce((size, moduleSize) => size + moduleSize, 0), names: chunk.name ? [chunk.name] : [], files: chunk.files.slice(), hash: chunk.renderedHash, parents: chunk.parents.map(c => c.id) }; if(showChunkModules) { obj.modules = chunk .getModules() .sort(sortByField("depth")) .filter(createModuleFilter()) .map(fnModule); obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length; obj.modules.sort(sortByField(sortModules)); } if(showChunkOrigins) { obj.origins = chunk.origins.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), name: origin.name, reasons: origin.reasons || [] })); } return obj; }); obj.chunks.sort(sortByField(sortChunks)); } if(showModules) { obj.modules = compilation.modules .slice() .sort(sortByField("depth")) .filter(createModuleFilter()) .map(fnModule); obj.filteredModules = compilation.modules.length - obj.modules.length; obj.modules.sort(sortByField(sortModules)); } 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(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 }] ]; obj.assets.forEach(asset => { 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(); } if(obj.entrypoints) { Object.keys(obj.entrypoints).forEach(name => { const ep = obj.entrypoints[name]; colors.normal("Entrypoint "); colors.bold(name); if(ep.isOverSizeLimit) { colors.normal(" "); colors.yellow("[big]"); } colors.normal(" ="); ep.assets.forEach(asset => { colors.normal(" "); colors.green(asset); }); newline(); }); } const modulesByIdentifier = {}; if(obj.modules) { obj.modules.forEach(module => { modulesByIdentifier[`$${module.identifier}`] = module; }); } else if(obj.chunks) { obj.chunks.forEach(chunk => { if(chunk.modules) { chunk.modules.forEach(module => { modulesByIdentifier[`$${module.identifier}`] = module; }); } }); } const processModuleAttributes = (module) => { colors.normal(" "); colors.normal(SizeFormatHelpers.formatSize(module.size)); if(module.chunks) { module.chunks.forEach(chunk => { colors.normal(" {"); colors.yellow(chunk); colors.normal("}"); }); } if(typeof module.depth === "number") { colors.normal(` [depth ${module.depth}]`); } if(!module.cacheable) { colors.red(" [not cacheable]"); } if(module.optional) { colors.yellow(" [optional]"); } if(module.built) { colors.green(" [built]"); } 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 === false || module.usedExports.length === 0) colors.cyan("[no exports used]"); else colors.cyan(`[only some exports used: ${module.usedExports.join(", ")}]`); newline(); } } if(Array.isArray(module.optimizationBailout)) { module.optimizationBailout.forEach(item => { colors.normal(prefix); colors.yellow(item); newline(); }); } if(module.reasons) { module.reasons.forEach(reason => { colors.normal(prefix); colors.normal(reason.type); colors.normal(" "); colors.cyan(reason.userRequest); colors.normal(" ["); colors.normal(reason.moduleId); colors.normal("] "); colors.magenta(reason.module); if(reason.loc) { colors.normal(" "); colors.normal(reason.loc); } newline(); }); } if(module.profile) { colors.normal(prefix); let sum = 0; const path = []; let current = module; while(current.issuer) { path.push(current = current.issuer); } path.reverse().forEach(module => { colors.normal("["); colors.normal(module.id); colors.normal("] "); if(module.profile) { const time = (module.profile.factory || 0) + (module.profile.building || 0); coloredTime(time); sum += time; colors.normal(" "); } colors.normal("->"); }); Object.keys(module.profile).forEach(key => { colors.normal(` ${key}:`); const time = module.profile[key]; coloredTime(time); sum += time; }); colors.normal(" = "); coloredTime(sum); newline(); } }; const processModulesList = (obj, prefix) => { if(obj.modules) { obj.modules.forEach(module => { colors.normal(prefix); if(module.id < 1000) colors.normal(" "); if(module.id < 100) colors.normal(" "); if(module.id < 10) colors.normal(" "); colors.normal("["); colors.normal(module.id); colors.normal("] "); colors.bold(module.name || module.identifier); processModuleAttributes(module); newline(); processModuleContent(module, prefix + " "); }); 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) { obj.chunks.forEach(chunk => { 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)); chunk.parents.forEach(id => { colors.normal(" {"); colors.yellow(id); colors.normal("}"); }); 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]"); } newline(); if(chunk.origins) { chunk.origins.forEach(origin => { colors.normal(" > "); if(origin.reasons && origin.reasons.length) { colors.yellow(origin.reasons.join(" ")); colors.normal(" "); } if(origin.name) { colors.normal(origin.name); 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) { obj.warnings.forEach(warning => { newline(); colors.yellow(`WARNING in ${warning}`); newline(); }); } if(obj._showErrors && obj.errors) { obj.errors.forEach(error => { newline(); colors.red(`ERROR in ${error}`); newline(); }); } if(obj.children) { obj.children.forEach(child => { 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, modules: false, chunks: true, chunkModules: true, chunkOrigins: true, depth: true, reasons: true, usedExports: true, providedExports: true, optimizationBailout: true, errorDetails: true, publicPath: true, exclude: () => false, maxModules: Infinity, }; case "detailed": return { entrypoints: 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-3.5.6/lib/Template.js000066400000000000000000000115151315401342100160150ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Tapable = require("tapable"); const ConcatSource = require("webpack-sources").ConcatSource; 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?\{\n?|\n?\}$/g; const INDENT_MULTILINE_REGEX = /^\t/mg; const IDENTIFIER_NAME_REPLACE_REGEX = /^[^a-zA-Z$_]/; const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$_]/g; const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; module.exports = class Template extends Tapable { constructor(outputOptions) { super(); this.outputOptions = outputOptions || {}; } static getFunctionContent(fn) { return fn.toString().replace(FUNCTION_CONTENT_REGEX, "").replace(INDENT_MULTILINE_REGEX, ""); } static toIdentifier(str) { if(typeof str !== "string") return ""; return str.replace(IDENTIFIER_NAME_REPLACE_REGEX, "_").replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); } 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 static numberToIdentifer(n) { // lower case if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); // upper case n -= DELTA_A_TO_Z; if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); // fall back to _ + number n -= DELTA_A_TO_Z; return "_" + n; } indent(str) { if(Array.isArray(str)) { return str.map(this.indent.bind(this)).join("\n"); } else { str = str.trimRight(); if(!str) return ""; var ind = (str[0] === "\n" ? "" : "\t"); return ind + str.replace(/\n([^\n])/g, "\n\t$1"); } } prefix(str, prefix) { if(Array.isArray(str)) { str = str.join("\n"); } str = str.trim(); if(!str) return ""; const ind = (str[0] === "\n" ? "" : prefix); return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); } asString(str) { if(Array.isArray(str)) { return str.join("\n"); } return str; } getModulesArrayBounds(modules) { if(!modules.every(moduleIdIsNumber)) return false; var maxId = -Infinity; var minId = Infinity; modules.forEach(function(module) { if(maxId < module.id) maxId = module.id; if(minId > module.id) minId = module.id; }); if(minId < 16 + ("" + minId).length) { // add minId x ',' instead of 'Array(minId).concat(...)' minId = 0; } var objectOverhead = modules.map(function(module) { var idLength = (module.id + "").length; return idLength + 2; }).reduce(function(a, b) { return a + b; }, -1); var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId; return arrayOverhead < objectOverhead ? [minId, maxId] : false; } renderChunkModules(chunk, moduleTemplate, dependencyTemplates, prefix) { if(!prefix) prefix = ""; var source = new ConcatSource(); if(chunk.getNumberOfModules() === 0) { source.add("[]"); return source; } var removedModules = chunk.removedModules; var allModules = chunk.mapModules(function(module) { return { id: module.id, source: moduleTemplate.render(module, dependencyTemplates, chunk) }; }); if(removedModules && removedModules.length > 0) { removedModules.forEach(function(id) { allModules.push({ id: id, source: "false" }); }); } var bounds = this.getModulesArrayBounds(allModules); if(bounds) { // Render a spare array var minId = bounds[0]; var maxId = bounds[1]; if(minId !== 0) source.add("Array(" + minId + ").concat("); source.add("[\n"); var modules = {}; allModules.forEach(function(module) { modules[module.id] = module; }); for(var idx = minId; idx <= maxId; idx++) { var module = modules[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(function(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; } }; function stringifyIdSortPredicate(a, b) { var aId = a.id + ""; var bId = b.id + ""; if(aId < bId) return -1; if(aId > bId) return 1; return 0; } function moduleIdIsNumber(module) { return typeof module.id === "number"; } webpack-3.5.6/lib/TemplatedPathPlugin.js000066400000000000000000000077701315401342100201650ustar00rootroot00000000000000/* 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_NAME = /\[name\]/gi, REGEXP_ID = /\[id\]/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_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i"); // TODO: remove in webpack 3 // Backwards compatibility; expose regexes on Template object const Template = require("./Template"); Template.REGEXP_HASH = REGEXP_HASH; Template.REGEXP_CHUNKHASH = REGEXP_CHUNKHASH; Template.REGEXP_NAME = REGEXP_NAME; Template.REGEXP_ID = REGEXP_ID; Template.REGEXP_FILE = REGEXP_FILE; Template.REGEXP_QUERY = REGEXP_QUERY; Template.REGEXP_FILEBASE = REGEXP_FILEBASE; const withHashLength = (replacer, handlerFn) => { return function(_, hashLength) { const length = hashLength && parseInt(hashLength, 10); if(length && handlerFn) { return handlerFn(length); } const hash = replacer.apply(this, arguments); return length ? hash.slice(0, length) : hash; }; }; const getReplacer = (value, allowEmpty) => { return function(match) { // last argument in replacer is the entire input string const input = arguments[arguments.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}`; } }; }; 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; if(data.noChunkHash && REGEXP_CHUNKHASH_FOR_TEST.test(path)) { throw new Error(`Cannot use [chunkhash] 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_ID, getReplacer(chunkId)) .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.plugin("compilation", compilation => { const mainTemplate = compilation.mainTemplate; mainTemplate.plugin("asset-path", replacePathVariables); mainTemplate.plugin("global-hash", function(chunk, paths) { const outputOptions = this.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_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.plugin("hash-for-chunk", function(hash, chunk) { const outputOptions = this.outputOptions; const chunkFilename = outputOptions.chunkFilename || outputOptions.filename; if(REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) hash.update(JSON.stringify(chunk.getChunkMaps(true, true).hash)); if(REGEXP_NAME_FOR_TEST.test(chunkFilename)) hash.update(JSON.stringify(chunk.getChunkMaps(true, true).name)); }); }); } } module.exports = TemplatedPathPlugin; webpack-3.5.6/lib/UmdMainTemplatePlugin.js000066400000000000000000000153761315401342100204600ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; const OriginalSource = require("webpack-sources").OriginalSource; const Template = require("./Template"); function accessorToObjectAccess(accessor) { return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); } function accessorAccess(base, accessor) { accessor = [].concat(accessor); return accessor.map((a, idx) => { a = base + accessorToObjectAccess(accessor.slice(0, idx + 1)); if(idx === accessor.length - 1) return a; return `${a} = ${a} || {}`; }).join(", "); } class UmdMainTemplatePlugin { 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; } apply(compilation) { const mainTemplate = compilation.mainTemplate; compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => { let externals = chunk.getModules().filter(m => m.external); const optionalExternals = []; let requiredExternals = []; if(this.optionalAmdExternalAsGlobal) { externals.forEach(m => { if(m.optional) { optionalExternals.push(m); } else { requiredExternals.push(m); } }); externals = requiredExternals.concat(optionalExternals); } else { requiredExternals = externals; } function replaceKeys(str) { return mainTemplate.applyPluginsWaterfall("asset-path", str, { hash, chunk }); } function externalsDepsArray(modules) { return `[${replaceKeys(modules.map(m => JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request)).join(", "))}]`; } function externalsRootArray(modules) { return replaceKeys(modules.map(m => { let request = m.request; if(typeof request === "object") request = request.root; return `root${accessorToObjectAccess([].concat(request))}`; }).join(", ")); } function externalsRequireArray(type) { return replaceKeys(externals.map(m => { let expr; let request = m.request; if(typeof request === "object") request = request[type]; if(typeof 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(", ")); } function externalsArguments(modules) { return modules.map(m => Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`)).join(", "); } function 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"; } return new ConcatSource(new OriginalSource( "(function webpackUniversalModuleDefinition(root, factory) {\n" + (this.auxiliaryComment && typeof this.auxiliaryComment === "string" ? " //" + this.auxiliaryComment + "\n" : this.auxiliaryComment.commonjs2 ? " //" + this.auxiliaryComment.commonjs2 + "\n" : "" ) + " if(typeof exports === 'object' && typeof module === 'object')\n" + " module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" + (this.auxiliaryComment && typeof this.auxiliaryComment === "string" ? " //" + this.auxiliaryComment + "\n" : this.auxiliaryComment.amd ? " //" + this.auxiliaryComment.amd + "\n" : "" ) + " 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 ? (this.auxiliaryComment && typeof this.auxiliaryComment === "string" ? " //" + this.auxiliaryComment + "\n" : this.auxiliaryComment.commonjs ? " //" + this.auxiliaryComment.commonjs + "\n" : "" ) + " else if(typeof exports === 'object')\n" + " exports[" + libraryName(this.names.commonjs || this.names.root) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" + (this.auxiliaryComment && typeof this.auxiliaryComment === "string" ? " //" + this.auxiliaryComment + "\n" : this.auxiliaryComment.root ? " //" + this.auxiliaryComment.root + "\n" : "" ) + " 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" ) + "})(this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, ";\n})"); }); mainTemplate.plugin("global-hash-paths", (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.plugin("hash", (hash) => { hash.update("umd"); hash.update(`${this.names.root}`); hash.update(`${this.names.amd}`); hash.update(`${this.names.commonjs}`); }); } } module.exports = UmdMainTemplatePlugin; webpack-3.5.6/lib/UnsupportedFeatureWarning.js000066400000000000000000000007301315401342100214310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const WebpackError = require("./WebpackError"); class UnsupportedFeatureWarning extends WebpackError { constructor(module, message) { super(); this.name = "UnsupportedFeatureWarning"; this.message = message; this.origin = this.module = module; Error.captureStackTrace(this, this.constructor); } } module.exports = UnsupportedFeatureWarning; webpack-3.5.6/lib/UseStrictPlugin.js000066400000000000000000000021571315401342100173500ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConstDependency = require("./dependencies/ConstDependency"); class UseStrictPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { params.normalModuleFactory.plugin("parser", (parser) => { const parserInstance = parser; parser.plugin("program", (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; parserInstance.state.current.addDependency(dep); parserInstance.state.module.strict = true; } }); }); }); } } module.exports = UseStrictPlugin; webpack-3.5.6/lib/WarnCaseSensitiveModulesPlugin.js000066400000000000000000000016331315401342100223470ustar00rootroot00000000000000/* 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.plugin("compilation", compilation => { compilation.plugin("seal", () => { const moduleWithoutCase = Object.create(null); compilation.modules.forEach(module => { const identifier = module.identifier().toLowerCase(); if(moduleWithoutCase[identifier]) { moduleWithoutCase[identifier].push(module); } else { moduleWithoutCase[identifier] = [module]; } }); Object.keys(moduleWithoutCase).forEach(key => { if(moduleWithoutCase[key].length > 1) compilation.warnings.push(new CaseSensitiveModulesWarning(moduleWithoutCase[key])); }); }); }); } } module.exports = WarnCaseSensitiveModulesPlugin; webpack-3.5.6/lib/WatchIgnorePlugin.js000066400000000000000000000024441315401342100176340ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class WatchIgnorePlugin { constructor(paths) { this.paths = paths; } apply(compiler) { compiler.plugin("after-environment", () => { compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths); }); } } module.exports = WatchIgnorePlugin; 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); this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, options, (err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps) => { if(err) return callback(err); ignoredFiles.forEach(path => { fileTimestamps[path] = 1; }); ignoredDirs.forEach(path => { dirTimestamps[path] = 1; }); callback(err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps); }, callbackUndelayed); } } webpack-3.5.6/lib/WebpackError.js000066400000000000000000000004031315401342100166220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Jarid Margolin @jaridmargolin */ "use strict"; module.exports = class WebpackError extends Error { inspect() { return this.stack + (this.details ? `\n${this.details}` : ""); } }; webpack-3.5.6/lib/WebpackOptionsApply.js000066400000000000000000000255601315401342100202050ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const OptionsApply = require("./OptionsApply"); 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 RequireJsStuffPlugin = require("./RequireJsStuffPlugin"); 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 AMDPlugin = require("./dependencies/AMDPlugin"); const RequireContextPlugin = require("./dependencies/RequireContextPlugin"); const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin"); const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin"); const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin"); const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin"); const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin"); const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin"); const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin"); const OccurrenceOrderPlugin = require("./optimize/OccurrenceOrderPlugin"); const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin"); const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin"); const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin"); const ResolverFactory = require("enhanced-resolve").ResolverFactory; class WebpackOptionsApply extends OptionsApply { constructor() { super(); } 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; compiler.dependencies = options.dependencies; if(typeof options.target === "string") { let JsonpTemplatePlugin; let NodeSourcePlugin; let NodeTargetPlugin; let NodeTemplatePlugin; switch(options.target) { case "web": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); compiler.apply( new JsonpTemplatePlugin(options.output), new FunctionModulePlugin(options.output), new NodeSourcePlugin(options.node), new LoaderTargetPlugin(options.target) ); break; case "webworker": { let WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); compiler.apply( new WebWorkerTemplatePlugin(), new FunctionModulePlugin(options.output), new NodeSourcePlugin(options.node), new LoaderTargetPlugin(options.target) ); break; } case "node": case "async-node": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); compiler.apply( new NodeTemplatePlugin({ asyncChunkLoading: options.target === "async-node" }), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new LoaderTargetPlugin("node") ); break; case "node-webkit": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply( new JsonpTemplatePlugin(options.output), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new ExternalsPlugin("commonjs", "nw.gui"), new LoaderTargetPlugin(options.target) ); break; case "atom": case "electron": case "electron-main": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply( new NodeTemplatePlugin({ asyncChunkLoading: true }), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new ExternalsPlugin("commonjs", [ "app", "auto-updater", "browser-window", "content-tracing", "dialog", "electron", "global-shortcut", "ipc", "ipc-main", "menu", "menu-item", "power-monitor", "power-save-blocker", "protocol", "session", "web-contents", "tray", "clipboard", "crash-reporter", "native-image", "screen", "shell" ]), new LoaderTargetPlugin(options.target) ); break; case "electron-renderer": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply( new JsonpTemplatePlugin(options.output), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new ExternalsPlugin("commonjs", [ "desktop-capturer", "electron", "ipc", "ipc-renderer", "remote", "web-frame", "clipboard", "crash-reporter", "native-image", "screen", "shell" ]), new LoaderTargetPlugin(options.target) ); break; default: throw new Error("Unsupported target '" + options.target + "'."); } } else if(options.target !== false) { options.target(compiler); } else { throw new Error("Unsupported target '" + options.target + "'."); } if(options.output.library || options.output.libraryTarget !== "var") { let LibraryTemplatePlugin = require("./LibraryTemplatePlugin"); compiler.apply(new LibraryTemplatePlugin(options.output.library, options.output.libraryTarget, options.output.umdNamedDefine, options.output.auxiliaryComment || "", options.output.libraryExport)); } if(options.externals) { ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply(new ExternalsPlugin(options.output.libraryTarget, options.externals)); } let noSources; let legacy; let modern; let comment; if(options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)) { const hidden = options.devtool.indexOf("hidden") >= 0; const inline = options.devtool.indexOf("inline") >= 0; const evalWrapped = options.devtool.indexOf("eval") >= 0; const cheap = options.devtool.indexOf("cheap") >= 0; const moduleMaps = options.devtool.indexOf("module") >= 0; noSources = options.devtool.indexOf("nosources") >= 0; legacy = options.devtool.indexOf("@") >= 0; modern = options.devtool.indexOf("#") >= 0; 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; let Plugin = evalWrapped ? EvalSourceMapDevToolPlugin : SourceMapDevToolPlugin; compiler.apply(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, })); } else if(options.devtool && options.devtool.indexOf("eval") >= 0) { legacy = options.devtool.indexOf("@") >= 0; modern = options.devtool.indexOf("#") >= 0; comment = legacy && modern ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" : legacy ? "\n//@ sourceURL=[url]" : modern ? "\n//# sourceURL=[url]" : null; compiler.apply(new EvalDevToolModulePlugin(comment, options.output.devtoolModuleFilenameTemplate)); } compiler.apply(new EntryOptionPlugin()); compiler.applyPluginsBailResult("entry-option", options.context, options.entry); compiler.apply( new CompatibilityPlugin(), new HarmonyModulesPlugin(options.module), new AMDPlugin(options.module, options.amd || {}), new CommonJsPlugin(options.module), new LoaderPlugin(), new NodeStuffPlugin(options.node), new RequireJsStuffPlugin(), new APIPlugin(), new ConstPlugin(), new UseStrictPlugin(), new RequireIncludePlugin(), new RequireEnsurePlugin(), new RequireContextPlugin(options.resolve.modules, options.resolve.extensions, options.resolve.mainFiles), new ImportPlugin(options.module), new SystemPlugin(options.module) ); compiler.apply( new EnsureChunkConditionsPlugin(), new RemoveParentModulesPlugin(), new RemoveEmptyChunksPlugin(), new MergeDuplicateChunksPlugin(), new FlagIncludedChunksPlugin(), new OccurrenceOrderPlugin(true), new FlagDependencyExportsPlugin(), new FlagDependencyUsagePlugin() ); if(options.performance) { compiler.apply(new SizeLimitsPlugin(options.performance)); } compiler.apply(new TemplatedPathPlugin()); compiler.apply(new RecordIdsPlugin()); compiler.apply(new WarnCaseSensitiveModulesPlugin()); if(options.cache) { let CachePlugin = require("./CachePlugin"); compiler.apply(new CachePlugin(typeof options.cache === "object" ? options.cache : null)); } compiler.applyPlugins("after-plugins", compiler); if(!compiler.inputFileSystem) throw new Error("No input filesystem provided"); compiler.resolvers.normal = ResolverFactory.createResolver(Object.assign({ fileSystem: compiler.inputFileSystem }, options.resolve)); compiler.resolvers.context = ResolverFactory.createResolver(Object.assign({ fileSystem: compiler.inputFileSystem, resolveToContext: true }, options.resolve)); compiler.resolvers.loader = ResolverFactory.createResolver(Object.assign({ fileSystem: compiler.inputFileSystem }, options.resolveLoader)); compiler.applyPlugins("after-resolvers", compiler); return options; } } module.exports = WebpackOptionsApply; webpack-3.5.6/lib/WebpackOptionsDefaulter.js000066400000000000000000000110151315401342100210210ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const OptionsDefaulter = require("./OptionsDefaulter"); const Template = require("./Template"); class WebpackOptionsDefaulter extends OptionsDefaulter { constructor() { super(); this.set("devtool", false); this.set("cache", true); 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", true); 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; return filename.indexOf("[name]") >= 0 ? filename.replace("[name]", "[id]") : "[id]." + filename; }); this.set("output.library", ""); this.set("output.hotUpdateFunction", "make", (options) => { return Template.toIdentifier("webpackHotUpdate" + options.output.library); }); this.set("output.jsonpFunction", "make", (options) => { return Template.toIdentifier("webpackJsonp" + options.output.library); }); this.set("output.libraryTarget", "var"); this.set("output.path", process.cwd()); 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.chunkLoadTimeout", 120000); this.set("output.hashFunction", "md5"); 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 => { if(typeof value === "boolean") { return value; } else { return Object.assign({}, value); } }); this.set("performance.maxAssetSize", 250000); this.set("performance.maxEntrypointSize", 250000); this.set("performance.hints", false); this.set("resolve", "call", value => Object.assign({}, value)); this.set("resolve.unsafeCache", true); this.set("resolve.modules", ["node_modules"]); this.set("resolve.extensions", [".js", ".json"]); this.set("resolve.mainFiles", ["index"]); this.set("resolve.aliasFields", "make", (options) => { if(options.target === "web" || options.target === "webworker") return ["browser"]; else return []; }); this.set("resolve.mainFields", "make", (options) => { if(options.target === "web" || options.target === "webworker") 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-3.5.6/lib/WebpackOptionsValidationError.js000066400000000000000000000171311315401342100222170ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Gajus Kuizinas @gajus */ "use strict"; const WebpackError = require("./WebpackError"); const webpackOptionsSchema = require("../schemas/webpackOptionsSchema.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 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(); this.name = "WebpackOptionsValidationError"; this.message = "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.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.indexOf(innerSchema) >= 0) return "(recursive)"; return WebpackOptionsValidationError.formatSchema(innerSchema, prevSchemas.concat(schema)); }; if(schema.type === "string") { if(schema.minLength === 1) return "non-empty string"; else if(schema.minLength > 1) return `string (min length ${schema.minLength})`; return "string"; } else if(schema.type === "boolean") { return "boolean"; } else if(schema.type === "number") { return "number"; } else if(schema.type === "object") { if(schema.properties) { const required = schema.required || []; return `object { ${Object.keys(schema.properties).map(property => { if(required.indexOf(property) < 0) return property + "?"; return property; }).concat(schema.additionalProperties ? ["..."] : []).join(", ")} }`; } if(schema.additionalProperties) { return `object { : ${formatInnerSchema(schema.additionalProperties)} }`; } return "object"; } else 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, 0, 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.\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 2 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) { return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}\n` + `Details:\n${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.`; case "string": return `${dataPath} should be a string.`; case "boolean": return `${dataPath} should be a boolean.`; case "number": return `${dataPath} should be a number.`; 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 === "minLength" || err.keyword === "minItems") { if(err.params.limit === 1) return `${dataPath} should not be empty.`; else return `${dataPath} ${err.message}`; } else if(err.keyword === "absolutePath") { const baseMessage = `${dataPath}: ${err.message}`; 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 { // eslint-disable-line no-fallthrough return `${dataPath} ${err.message} (${JSON.stringify(err, 0, 2)}).\n${getSchemaPartText(err.parentSchema)}`; } } } module.exports = WebpackOptionsValidationError; webpack-3.5.6/lib/compareLocations.js000066400000000000000000000015001315401342100175350ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; module.exports = function compareLocations(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(a.start && b.start) { 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(a.index < b.index) return -1; if(a.index > b.index) return 1; return 0; } else { return 0; } } }; webpack-3.5.6/lib/dependencies/000077500000000000000000000000001315401342100163275ustar00rootroot00000000000000webpack-3.5.6/lib/dependencies/AMDDefineDependency.js000066400000000000000000000123501315401342100224010ustar00rootroot00000000000000/* 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; } 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-3.5.6/lib/dependencies/AMDDefineDependencyParserPlugin.js000066400000000000000000000212571315401342100247430ustar00rootroot00000000000000/* 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"); function 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; } class AMDDefineDependencyParserPlugin { constructor(options) { this.options = options; } apply(parser) { const options = this.options; parser.plugin("call define", (expr) => { let array, fn, obj, namedModule; switch(expr.arguments.length) { case 1: if(expr.arguments[0].type === "FunctionExpression" || isBoundFunctionExpression(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(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(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(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(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(expr.arguments[2].type === "FunctionExpression" || isBoundFunctionExpression(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(fn.type === "FunctionExpression") fnParams = fn.params; else if(isBoundFunctionExpression(fn)) { fnParams = fn.callee.object.params; fnParamsOffset = fn.arguments.length - 1; if(fnParamsOffset < 0) fnParamsOffset = 0; } } let fnRenames = Object.create(parser.scope.renames); let identifiers; if(array) { identifiers = {}; const param = parser.evaluateExpression(array); const result = parser.applyPluginsBailResult("call define:amd:array", expr, param, identifiers, namedModule); if(!result) return; if(fnParams) fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { if(identifiers[idx]) { fnRenames["$" + param.name] = identifiers[idx]; return false; } return true; }); } else { identifiers = ["require", "exports", "module"]; if(fnParams) fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { if(identifiers[idx]) { fnRenames["$" + param.name] = identifiers[idx]; return false; } return true; }); } let inTry; if(fn && fn.type === "FunctionExpression") { 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"].indexOf(i.name) < 0), () => { 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 = new AMDDefineDependency( 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; }); parser.plugin("call define:amd:array", (expr, param, identifiers, namedModule) => { if(param.isArray()) { param.items.forEach((param, idx) => { if(param.isString() && ["require", "module", "exports"].indexOf(param.string) >= 0) identifiers[idx] = param.string; const result = parser.applyPluginsBailResult("call define:amd:item", expr, param, namedModule); if(result === undefined) { parser.applyPluginsBailResult("call define:amd:context", 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"].indexOf(request) >= 0) { identifiers[idx] = request; dep = request; } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, request)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule); dep.loc = expr.loc; parser.state.current.addDependency(dep); } else { dep = new AMDRequireItemDependency(request); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); } deps.push(dep); }); const dep = new AMDRequireArrayDependency(deps, param.range); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }); parser.plugin("call define:amd:item", (expr, param, namedModule) => { if(param.isConditional()) { param.options.forEach((param) => { const result = parser.applyPluginsBailResult("call define:amd:item", expr, param); if(result === undefined) { parser.applyPluginsBailResult("call define:amd:context", 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"].indexOf(param.string) >= 0) { dep = new ConstDependency(param.string, param.range); } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, param.string, namedModule)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule, param.range); } else { dep = new AMDRequireItemDependency(param.string, param.range); } dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }); parser.plugin("call define:amd:context", (expr, param) => { const dep = ContextDependencyHelpers.create(AMDRequireContextDependency, param.range, param, expr, options); if(!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; }); } } module.exports = AMDDefineDependencyParserPlugin; webpack-3.5.6/lib/dependencies/AMDPlugin.js000066400000000000000000000124571315401342100204560ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; const contextModuleFactory = params.contextModuleFactory; 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()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.amd !== "undefined" && !parserOptions.amd) return; function setExpressionToModule(outerExpr, module) { parser.plugin("expression " + outerExpr, (expr) => { const dep = new AMDRequireItemDependency(module, expr.range); dep.userRequest = outerExpr; dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; }); } parser.apply( new AMDRequireDependenciesBlockParserPlugin(options), new AMDDefineDependencyParserPlugin(options) ); setExpressionToModule("require.amd", "!!webpack amd options"); setExpressionToModule("define.amd", "!!webpack amd options"); setExpressionToModule("define", "!!webpack amd define"); parser.plugin("expression __webpack_amd_options__", () => parser.state.current.addVariable("__webpack_amd_options__", JSON.stringify(amdOptions))); parser.plugin("evaluate typeof define.amd", ParserHelpers.evaluateToString(typeof amdOptions)); parser.plugin("evaluate typeof require.amd", ParserHelpers.evaluateToString(typeof amdOptions)); parser.plugin("evaluate Identifier define.amd", ParserHelpers.evaluateToIdentifier("define.amd", true)); parser.plugin("evaluate Identifier require.amd", ParserHelpers.evaluateToIdentifier("require.amd", true)); parser.plugin("typeof define", ParserHelpers.toConstantDependency(JSON.stringify("function"))); parser.plugin("evaluate typeof define", ParserHelpers.evaluateToString("function")); parser.plugin("can-rename define", ParserHelpers.approve); parser.plugin("rename define", (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.plugin("typeof require", ParserHelpers.toConstantDependency(JSON.stringify("function"))); parser.plugin("evaluate typeof require", ParserHelpers.evaluateToString("function")); }); }); compiler.plugin("after-resolvers", () => { compiler.resolvers.normal.apply( new AliasPlugin("described-resolve", { name: "amdefine", alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js") }, "resolve"), new AliasPlugin("described-resolve", { name: "webpack amd options", alias: path.join(__dirname, "..", "..", "buildin", "amd-options.js") }, "resolve"), new AliasPlugin("described-resolve", { name: "webpack amd define", alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js") }, "resolve") ); }); } } module.exports = AMDPlugin; webpack-3.5.6/lib/dependencies/AMDRequireArrayDependency.js000066400000000000000000000027441315401342100236300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); const webpackMissingModuleModule = require("./WebpackMissingModule").module; 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, outputOptions, requestShortener) { const content = this.getContent(dep, outputOptions, requestShortener); source.replace(dep.range[0], dep.range[1] - 1, content); } getContent(dep, outputOptions, requestShortener) { const requires = dep.depsArray.map((dependency) => { const optionalComment = this.optionalComment(outputOptions.pathinfo, requestShortener.shorten(dependency.request)); return this.contentForDependency(dependency, optionalComment); }); return `[${requires.join(", ")}]`; } optionalComment(pathInfo, shortenedRequest) { if(!pathInfo) { return ""; } return `/*! ${shortenedRequest} */ `; } contentForDependency(dep, comment) { if(typeof dep === "string") { return dep; } if(dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `__webpack_require__(${comment}${stringifiedId})`; } return webpackMissingModuleModule(dep.request); } }; module.exports = AMDRequireArrayDependency; webpack-3.5.6/lib/dependencies/AMDRequireContextDependency.js000066400000000000000000000014011315401342100241630ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const CriticalDependencyWarning = require("./CriticalDependencyWarning"); class AMDRequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } getWarnings() { if(this.critical) { return [ new CriticalDependencyWarning(this.critical) ]; } } } AMDRequireContextDependency.Template = require("./ContextDependencyTemplateAsRequireCall"); module.exports = AMDRequireContextDependency; webpack-3.5.6/lib/dependencies/AMDRequireDependenciesBlock.js000066400000000000000000000021101315401342100240770ustar00rootroot00000000000000/* 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) { super(null, module, loc); this.expr = expr; this.outerRange = expr.range; this.arrayRange = arrayRange; this.functionRange = functionRange; 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 = new AMDRequireDependency(this); dep.loc = loc; this.addDependency(dep); } }; webpack-3.5.6/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js000066400000000000000000000141641315401342100264470ustar00rootroot00000000000000/* 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"].indexOf(i.name) < 0; }), () => { 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) { const options = this.options; parser.plugin("call require", (expr) => { let param; let dep; let result; const old = parser.state.current; if(expr.arguments.length >= 1) { param = parser.evaluateExpression(expr.arguments[0]); dep = new AMDRequireDependenciesBlock( 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 ); parser.state.current = dep; } if(expr.arguments.length === 1) { parser.inScope([], () => { result = parser.applyPluginsBailResult("call require:amd:array", 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 = parser.applyPluginsBailResult("call require:amd:array", 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)); 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; } }); parser.plugin("call require:amd:array", (expr, param) => { if(param.isArray()) { param.items.forEach((param) => { const result = parser.applyPluginsBailResult("call require:amd:item", expr, param); if(result === undefined) { parser.applyPluginsBailResult("call require:amd:context", expr, param); } }); return true; } else if(param.isConstArray()) { const deps = []; param.array.forEach((request) => { let dep, localModule; if(request === "require") { dep = "__webpack_require__"; } else if(["exports", "module"].indexOf(request) >= 0) { dep = request; } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, request)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule); dep.loc = expr.loc; parser.state.current.addDependency(dep); } else { dep = new AMDRequireItemDependency(request); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); } deps.push(dep); }); const dep = new AMDRequireArrayDependency(deps, param.range); dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }); parser.plugin("call require:amd:item", (expr, param) => { if(param.isConditional()) { param.options.forEach((param) => { const result = parser.applyPluginsBailResult("call require:amd:item", expr, param); if(result === undefined) { parser.applyPluginsBailResult("call require:amd:context", expr, param); } }); 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.moduleArgument || "module", param.range); } else if(param.string === "exports") { dep = new ConstDependency(parser.state.module.exportsArgument || "exports", param.range); } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, param.string)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule, param.range); } else { dep = new AMDRequireItemDependency(param.string, param.range); } dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }); parser.plugin("call require:amd:context", (expr, param) => { const dep = ContextDependencyHelpers.create(AMDRequireContextDependency, param.range, param, expr, options); if(!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; }); } } module.exports = AMDRequireDependenciesBlockParserPlugin; webpack-3.5.6/lib/dependencies/AMDRequireDependency.js000066400000000000000000000061451315401342100226300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); const DepBlockHelpers = require("./DepBlockHelpers"); class AMDRequireDependency extends NullDependency { constructor(block) { super(); this.block = block; } } AMDRequireDependency.Template = class AMDRequireDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const depBlock = dep.block; const wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, "require"); // has array range but no function range if(depBlock.arrayRange && !depBlock.functionRange) { const startBlock = wrapper[0] + "function() {"; const endBlock = `;}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`; 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 = wrapper[0] + "function() {("; const endBlock = `.call(exports, __webpack_require__, exports, module));}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`; 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 = wrapper[0] + "function() { "; const errorRangeBlock = `}${depBlock.functionBindThis ? ".bind(this)" : ""}${wrapper[1]}`; const endBlock = `${depBlock.errorCallbackBindThis ? ".bind(this)" : ""}${wrapper[2]}`; 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 = wrapper[0] + "function() { "; const endBlock = `}${depBlock.functionBindThis ? ".bind(this)" : ""}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`; 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-3.5.6/lib/dependencies/AMDRequireItemDependency.js000066400000000000000000000010571315401342100234440ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/CommonJsPlugin.js000066400000000000000000000101321315401342100215660ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; const contextModuleFactory = params.contextModuleFactory; 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()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.commonjs !== "undefined" && !parserOptions.commonjs) return; const requireExpressions = ["require", "require.resolve", "require.resolveWeak"]; for(let expression of requireExpressions) { parser.plugin(`typeof ${expression}`, ParserHelpers.toConstantDependency(JSON.stringify("function"))); parser.plugin(`evaluate typeof ${expression}`, ParserHelpers.evaluateToString("function")); parser.plugin(`evaluate Identifier ${expression}`, ParserHelpers.evaluateToIdentifier(expression, true)); } parser.plugin("evaluate typeof module", ParserHelpers.evaluateToString("object")); parser.plugin("assign require", (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.push("require"); return true; }); parser.plugin("can-rename require", () => true); parser.plugin("rename require", (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.plugin("typeof module", () => true); parser.plugin("evaluate typeof exports", ParserHelpers.evaluateToString("object")); parser.apply( new CommonJsRequireDependencyParserPlugin(options), new RequireResolveDependencyParserPlugin(options) ); }); }); } } module.exports = CommonJsPlugin; webpack-3.5.6/lib/dependencies/CommonJsRequireContextDependency.js000066400000000000000000000015631315401342100253200ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const CriticalDependencyWarning = require("./CriticalDependencyWarning"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class CommonJsRequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "cjs require context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } } CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = CommonJsRequireContextDependency; webpack-3.5.6/lib/dependencies/CommonJsRequireDependency.js000066400000000000000000000010351315401342100237450ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/CommonJsRequireDependencyParserPlugin.js000066400000000000000000000066041315401342100263100ustar00rootroot00000000000000/* 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; parser.plugin("expression require.cache", ParserHelpers.toConstantDependency("__webpack_require__.c")); parser.plugin("expression require", (expr) => { const dep = new CommonJsRequireContextDependency(options.unknownContextRequest, options.unknownContextRecursive, options.unknownContextRegExp, 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; }); parser.plugin("call require", (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); param.options.forEach(function(param) { const result = parser.applyPluginsBailResult("call require:commonjs:item", expr, param); 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); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; } else { const result = parser.applyPluginsBailResult("call require:commonjs:item", expr, param); if(result === undefined) { parser.applyPluginsBailResult("call require:commonjs:context", expr, param); } else { const dep = new RequireHeaderDependency(expr.callee.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); } return true; } }); parser.plugin("call require:commonjs:item", (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; } }); parser.plugin("call require:commonjs:context", (expr, param) => { const dep = ContextDependencyHelpers.create(CommonJsRequireContextDependency, expr.range, param, expr, options); if(!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; }); } } module.exports = CommonJsRequireDependencyParserPlugin; webpack-3.5.6/lib/dependencies/ConstDependency.js000066400000000000000000000012731315401342100217550ustar00rootroot00000000000000/* 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) { super(); this.expression = expression; this.range = range; } 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-3.5.6/lib/dependencies/ContextDependency.js000066400000000000000000000012431315401342100223100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); class ContextDependency extends Dependency { constructor(request, recursive, regExp) { super(); this.request = request; this.userRequest = request; this.recursive = recursive; this.regExp = regExp; this.async = false; } isEqualResource(other) { if(!(other instanceof ContextDependency)) return false; return this.request === other.request && this.recursive === other.recursive && this.regExp === other.regExp && this.async === other.async; } } module.exports = ContextDependency; webpack-3.5.6/lib/dependencies/ContextDependencyHelpers.js000066400000000000000000000053201315401342100236330ustar00rootroot00000000000000/* 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 * @return {string} Escaped string */ function quotemeta(str) { return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); } ContextDependencyHelpers.create = function(Dep, range, param, expr, options, chunkName) { let dep; let prefix; let postfix; let prefixRange; let valueRange; let idx; let context; let regExp; if(param.isTemplateString()) { prefix = param.quasis[0].string; postfix = param.quasis.length > 1 ? param.quasis[param.quasis.length - 1].string : ""; prefixRange = [param.quasis[0].range[0], param.quasis[0].range[1]]; valueRange = param.range; idx = prefix.lastIndexOf("/"); context = "."; if(idx >= 0) { context = prefix.substr(0, idx); prefix = `.${prefix.substr(idx)}`; } // If there are more than two quasis, maybe the generated RegExp can be more precise? regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`); dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName); dep.loc = expr.loc; dep.replaces = [{ range: prefixRange, value: prefix }]; 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())) { prefix = param.prefix && param.prefix.isString() ? param.prefix.string : ""; postfix = param.postfix && param.postfix.isString() ? param.postfix.string : ""; prefixRange = param.prefix && param.prefix.isString() ? param.prefix.range : null; valueRange = [prefixRange ? prefixRange[1] : param.range[0], param.range[1]]; idx = prefix.lastIndexOf("/"); context = "."; if(idx >= 0) { context = prefix.substr(0, idx); prefix = `.${prefix.substr(idx)}`; } regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`); dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName); dep.loc = expr.loc; dep.prepend = param.prefix && param.prefix.isString() ? prefix : null; dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression"; return dep; } else { dep = new Dep(options.exprContextRequest, options.exprContextRecursive, options.exprContextRegExp, range, param.range, chunkName); dep.loc = expr.loc; dep.critical = options.exprContextCritical && "the request of a dependency is an expression"; return dep; } }; webpack-3.5.6/lib/dependencies/ContextDependencyTemplateAsId.js000066400000000000000000000023501315401342100245450ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ContextDependencyTemplateAsId { apply(dep, source, outputOptions, requestShortener) { const comment = outputOptions.pathinfo ? "/*! " + requestShortener.shorten(dep.request) + " */ " : ""; if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { 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, ")"); source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); } else { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve"); } } else { const content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } } module.exports = ContextDependencyTemplateAsId; webpack-3.5.6/lib/dependencies/ContextDependencyTemplateAsRequireCall.js000066400000000000000000000025341315401342100264250ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ContextDependencyTemplateAsRequireCall { apply(dep, source, outputOptions, requestShortener) { const comment = outputOptions.pathinfo ? "/*! " + requestShortener.shorten(dep.request) + " */ " : ""; const containsDeps = dep.module && dep.module.dependencies && dep.module.dependencies.length > 0; const isAsync = dep.module && dep.module.async; if(dep.module && (isAsync || containsDeps)) { 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, ")"); source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); } else { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"); } } else { const content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } } module.exports = ContextDependencyTemplateAsRequireCall; webpack-3.5.6/lib/dependencies/ContextElementDependency.js000066400000000000000000000006661315401342100236320ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/CriticalDependencyWarning.js000066400000000000000000000007051315401342100237460ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/DelegatedExportsDependency.js000066400000000000000000000011131315401342100241230ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; 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 { module: this.originModule, importedNames: true }; } getExports() { return { exports: this.exports }; } } module.exports = DelegatedExportsDependency; webpack-3.5.6/lib/dependencies/DelegatedSourceDependency.js000066400000000000000000000005611315401342100237250ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/DepBlockHelpers.js000066400000000000000000000026451315401342100217020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const DepBlockHelpers = exports; DepBlockHelpers.getLoadDepBlockWrapper = (depBlock, outputOptions, requestShortener, name) => { const promiseCode = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener, name); return [ promiseCode + ".then(", ").catch(", ")" ]; }; DepBlockHelpers.getDepBlockPromise = (depBlock, outputOptions, requestShortener, name) => { if(depBlock.chunks) { const chunks = depBlock.chunks.filter(chunk => !chunk.hasRuntime() && chunk.id !== null); const pathChunkCheck = outputOptions.pathinfo && depBlock.chunkName; const shortChunkName = requestShortener.shorten(depBlock.chunkName); const chunkReason = asComment(depBlock.chunkReason); const requireChunkId = chunk => "__webpack_require__.e(" + JSON.stringify(chunk.id) + ")"; name = asComment(name); if(chunks.length === 1) { const chunkId = JSON.stringify(chunks[0].id); return `__webpack_require__.e${name}(${chunkId}${pathChunkCheck ? "/*! " + shortChunkName + " */" : ""}${chunkReason})`; } else if(chunks.length > 0) { return `Promise.all${name}(${pathChunkCheck ? "/*! " + shortChunkName + " */" : ""}[${chunks.map(requireChunkId).join(", ")}])`; } } return "new Promise(function(resolve) { resolve(); })"; }; function asComment(str) { if(!str) return ""; return `/* ${str} */`; } webpack-3.5.6/lib/dependencies/DllEntryDependency.js000066400000000000000000000006071315401342100224240ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/HarmonyAcceptDependency.js000066400000000000000000000022001315401342100234130ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); const makeHarmonyImportStatement = require("./HarmonyImportDependency").makeImportStatement; 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, outputOptions, requestShortener) { const content = dep.dependencies .map(dependency => makeHarmonyImportStatement( false, dependency, outputOptions, requestShortener )).join(""); if(dep.hasCallback) { source.insert(dep.range[0], `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(`); source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); return; } source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); } }; module.exports = HarmonyAcceptDependency; webpack-3.5.6/lib/dependencies/HarmonyAcceptImportDependency.js000066400000000000000000000011071315401342100246130ustar00rootroot00000000000000/* 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, importedVar, range) { super(request, importedVar, range); } get type() { return "harmony accept"; } } HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate { apply(dep, source, outputOptions, requestShortener) {} }; module.exports = HarmonyAcceptImportDependency; webpack-3.5.6/lib/dependencies/HarmonyCompatibilityDependency.js000066400000000000000000000014701315401342100250350ustar00rootroot00000000000000/* 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) { const usedExports = dep.originModule.usedExports; if(usedExports && !Array.isArray(usedExports)) { const exportName = dep.originModule.exportsArgument || "exports"; const content = `Object.defineProperty(${exportName}, "__esModule", { value: true });\n`; source.insert(-10, content); } } }; module.exports = HarmonyCompatibilityDependency; webpack-3.5.6/lib/dependencies/HarmonyDetectionParserPlugin.js000066400000000000000000000030141315401342100244730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); module.exports = class HarmonyDetectionParserPlugin { apply(parser) { parser.plugin("program", (ast) => { var isHarmony = ast.body.some(statement => { return /^(Import|Export).*Declaration$/.test(statement.type); }); if(isHarmony) { const module = parser.state.module; const dep = new HarmonyCompatibilityDependency(module); dep.loc = { start: { line: -1, column: 0 }, end: { line: -1, column: 0 }, index: -2 }; module.addDependency(dep); module.meta.harmonyModule = true; module.strict = true; module.exportsArgument = "__webpack_exports__"; } }); var nonHarmonyIdentifiers = ["define", "exports"]; nonHarmonyIdentifiers.forEach(identifer => { parser.plugin(`evaluate typeof ${identifer}`, nullInHarmony); parser.plugin(`typeof ${identifer}`, skipInHarmony); parser.plugin(`evaluate ${identifer}`, nullInHarmony); parser.plugin(`expression ${identifer}`, skipInHarmony); parser.plugin(`call ${identifer}`, skipInHarmony); }); function skipInHarmony() { const module = this.state.module; if(module && module.meta && module.meta.harmonyModule) return true; } function nullInHarmony() { const module = this.state.module; if(module && module.meta && module.meta.harmonyModule) return null; } } }; webpack-3.5.6/lib/dependencies/HarmonyExportDependencyParserPlugin.js000066400000000000000000000063621315401342100260460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); const HarmonyImportDependency = require("./HarmonyImportDependency"); const HarmonyModulesHelpers = require("./HarmonyModulesHelpers"); module.exports = class HarmonyExportDependencyParserPlugin { apply(parser) { parser.plugin("export", 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.plugin("export import", (statement, source) => { const dep = new HarmonyImportDependency(source, HarmonyModulesHelpers.getNewModuleVar(parser.state, source), statement.range); dep.loc = Object.create(statement.loc); dep.loc.index = -1; parser.state.current.addDependency(dep); parser.state.lastHarmonyImport = dep; return true; }); parser.plugin("export expression", (statement, expr) => { const dep = new HarmonyExportExpressionDependency(parser.state.module, expr.range, statement.range); dep.loc = Object.create(statement.loc); dep.loc.index = -1; parser.state.current.addDependency(dep); return true; }); parser.plugin("export declaration", statement => {}); parser.plugin("export specifier", (statement, id, name, idx) => { const rename = parser.scope.renames[`$${id}`]; let dep; if(rename === "imported var") { const settings = parser.state.harmonySpecifier[`$${id}`]; dep = new HarmonyExportImportedSpecifierDependency(parser.state.module, settings[0], settings[1], settings[2], name); } else { const immutable = statement.declaration && isImmutableStatement(statement.declaration); const hoisted = statement.declaration && isHoistedStatement(statement.declaration); dep = new HarmonyExportSpecifierDependency(parser.state.module, id, name, !immutable || hoisted ? -2 : (statement.range[1] + 0.5), immutable); } dep.loc = Object.create(statement.loc); dep.loc.index = idx; parser.state.current.addDependency(dep); return true; }); parser.plugin("export import specifier", (statement, source, id, name, idx) => { const dep = new HarmonyExportImportedSpecifierDependency(parser.state.module, parser.state.lastHarmonyImport, HarmonyModulesHelpers.getModuleVar(parser.state, source), id, name); dep.loc = Object.create(statement.loc); dep.loc.index = idx; parser.state.current.addDependency(dep); return true; }); } }; function isImmutableStatement(statement) { if(statement.type === "FunctionDeclaration") return true; if(statement.type === "ClassDeclaration") return true; if(statement.type === "VariableDeclaration" && statement.kind === "const") return true; return false; } function isHoistedStatement(statement) { if(statement.type === "FunctionDeclaration") return true; return false; } webpack-3.5.6/lib/dependencies/HarmonyExportExpressionDependency.js000066400000000000000000000026101315401342100255620ustar00rootroot00000000000000/* 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) { super(); this.originModule = originModule; this.range = range; this.rangeStatement = rangeStatement; } get type() { return "harmony export expression"; } getExports() { return { exports: ["default"] }; } describeHarmonyExport() { return { exportedName: "default", precedence: 1, }; } } 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 + "("); 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 || "exports"; if(used) { return `/* harmony default export */ ${exportsName}[${JSON.stringify(used)}] = `; } return "/* unused harmony default export */ var _unused_webpack_default_export = "; } }; module.exports = HarmonyExportExpressionDependency; webpack-3.5.6/lib/dependencies/HarmonyExportHeaderDependency.js000066400000000000000000000013221315401342100246120ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/HarmonyExportImportedSpecifierDependency.js000066400000000000000000000215551315401342100270510ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); const HarmonyModulesHelpers = require("./HarmonyModulesHelpers"); class HarmonyExportImportedSpecifierDependency extends NullDependency { constructor(originModule, importDependency, importedVar, id, name) { super(); this.originModule = originModule; this.importDependency = importDependency; this.importedVar = importedVar; this.id = id; this.name = name; } get type() { return "harmony export imported specifier"; } getReference() { const name = this.name; const used = this.originModule.isUsed(name); const active = HarmonyModulesHelpers.isActive(this.originModule, this); const importedModule = this.importDependency.module; if(!importedModule || !used || !active || !this.originModule.usedExports) return null; const hasUsedExports = Array.isArray(this.originModule.usedExports); if(name) { const nameIsNotInUsedExports = hasUsedExports && this.originModule.usedExports.indexOf(name) < 0; if(nameIsNotInUsedExports) return null; // export { name as name } if(this.id) { return { module: importedModule, importedNames: [this.id] }; } // export { * as name } return { module: importedModule, importedNames: true }; } const hasProvidedExports = Array.isArray(importedModule.providedExports); // export * if(hasUsedExports) { // reexport * with known used exports const activeExports = HarmonyModulesHelpers.getActiveExports(this.originModule, this); const importedNames = this.originModule.usedExports.filter(id => { const notInActiveExports = activeExports.indexOf(id) < 0; const notDefault = id !== "default"; if(hasProvidedExports) { const inProvidedExports = importedModule.providedExports.indexOf(id) >= 0; return notInActiveExports && notDefault && inProvidedExports; } else { return notInActiveExports && notDefault; } }); return { module: importedModule, importedNames }; } if(hasProvidedExports) { return { module: importedModule, importedNames: importedModule.providedExports.filter(id => id !== "default"), }; } return { module: importedModule, importedNames: true, }; } getExports() { if(this.name) { return { exports: [this.name] }; } const importedModule = this.importDependency.module; if(!importedModule) { // no imported module available return { exports: null }; } if(Array.isArray(importedModule.providedExports)) { return { exports: importedModule.providedExports.filter(id => id !== "default"), dependencies: [importedModule] }; } if(importedModule.providedExports) { return { exports: true }; } return { exports: null, dependencies: [importedModule] }; } describeHarmonyExport() { const importedModule = this.importDependency.module; if(!this.name && importedModule && Array.isArray(importedModule.providedExports)) { // for a star export and when we know which exports are provided, we can tell so return { exportedName: importedModule.providedExports, precedence: 3 }; } return { exportedName: this.name, precedence: this.name ? 2 : 3 }; } updateHash(hash) { super.updateHash(hash); const hashValue = this.getHashValue(this.importDependency.module); hash.update(hashValue); } getHashValue(importedModule) { if(!importedModule) { return ""; } const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); const stringifiedProvidedExport = JSON.stringify(importedModule.providedExports); return importedModule.used + stringifiedUsedExport + stringifiedProvidedExport; } } module.exports = HarmonyExportImportedSpecifierDependency; HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const content = this.getContent(dep); source.insert(-1, content); } getContent(dep) { const name = dep.importedVar; const used = dep.originModule.isUsed(dep.name); const importedModule = dep.importDependency.module; const active = HarmonyModulesHelpers.isActive(dep.originModule, dep); const importsExportsUnknown = !importedModule || !Array.isArray(importedModule.providedExports); const getReexportStatement = this.reexportStatementCreator(dep.originModule, importsExportsUnknown, name); // we want to rexport something, but the export isn't used if(!used) { return "/* unused harmony reexport " + dep.name + " */\n"; } // we want to reexport something but another exports overrides this one if(!active) { return "/* inactive harmony reexport " + (dep.name || "namespace") + " */\n"; } // we want to reexport the default export from a non-hamory module const isNotAHarmonyModule = !(importedModule && (!importedModule.meta || importedModule.meta.harmonyModule)); if(dep.name && dep.id === "default" && isNotAHarmonyModule) { return "/* harmony reexport (default from non-hamory) */ " + getReexportStatement(JSON.stringify(used), null); } // we want to reexport a key as new key if(dep.name && dep.id) { var idUsed = importedModule && importedModule.isUsed(dep.id); return "/* harmony reexport (binding) */ " + getReexportStatement(JSON.stringify(used), JSON.stringify(idUsed)); } // we want to reexport the module object as named export if(dep.name) { return "/* harmony reexport (module object) */ " + getReexportStatement(JSON.stringify(used), ""); } // we know which exports are used if(Array.isArray(dep.originModule.usedExports)) { const activeExports = HarmonyModulesHelpers.getActiveExports(dep.originModule, dep); const items = dep.originModule.usedExports.map(function(id) { if(id === "default") return; if(activeExports.indexOf(id) >= 0) return; if(importedModule.isProvided(id) === false) return; var exportUsed = dep.originModule.isUsed(id); var idUsed = importedModule && importedModule.isUsed(id); return [exportUsed, idUsed]; }).filter(Boolean); if(items.length === 0) { return "/* unused harmony namespace reexport */\n"; } return items.map(function(item) { return "/* harmony namespace reexport (by used) */ " + getReexportStatement(JSON.stringify(item[0]), JSON.stringify(item[1])); }).join(""); } // not sure which exports are used, but we know which are provided if(dep.originModule.usedExports && importedModule && Array.isArray(importedModule.providedExports)) { const activeExports = HarmonyModulesHelpers.getActiveExports(dep.originModule, dep); const items = importedModule.providedExports.map(function(id) { if(id === "default") return; if(activeExports.indexOf(id) >= 0) return; var exportUsed = dep.originModule.isUsed(id); var idUsed = importedModule && importedModule.isUsed(id); return [exportUsed, idUsed]; }).filter(Boolean); if(items.length === 0) { return "/* empty harmony namespace reexport */\n"; } return items.map(function(item) { return "/* harmony namespace reexport (by provided) */ " + getReexportStatement(JSON.stringify(item[0]), JSON.stringify(item[1])); }).join(""); } // not sure which exports are used and provided if(dep.originModule.usedExports) { const activeExports = HarmonyModulesHelpers.getActiveExports(dep.originModule, dep); let content = "/* harmony namespace reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + name + ") "; // Filter out exports which are defined by other exports // and filter out default export because it cannot be reexported with * if(activeExports.length > 0) content += "if(" + JSON.stringify(activeExports.concat("default")) + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; else content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; const exportsName = dep.originModule.exportsArgument || "exports"; return content + `(function(key) { __webpack_require__.d(${exportsName}, key, function() { return ${name}[key]; }) }(__WEBPACK_IMPORT_KEY__));\n`; } return "/* unused harmony reexport namespace */\n"; } reexportStatementCreator(module, importsExportsUnknown, name) { const exportsName = module.exportsArgument || "exports"; const getReexportStatement = (key, valueKey) => { const conditional = this.getConditional(importsExportsUnknown, valueKey, name); const returnValue = this.getReturnValue(valueKey); return `${conditional}__webpack_require__.d(${exportsName}, ${key}, function() { return ${name}${returnValue}; });\n`; }; return getReexportStatement; } getConditional(importsExportsUnknown, valueKey, name) { if(!importsExportsUnknown || !valueKey) { return ""; } return `if(__webpack_require__.o(${name}, ${valueKey})) `; } getReturnValue(valueKey) { if(valueKey === null) { return "_default.a"; } return valueKey && "[" + valueKey + "]"; } }; webpack-3.5.6/lib/dependencies/HarmonyExportSpecifierDependency.js000066400000000000000000000032661315401342100253440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); const HarmonyModulesHelpers = require("./HarmonyModulesHelpers"); class HarmonyExportSpecifierDependency extends NullDependency { constructor(originModule, id, name, position, immutable) { super(); this.originModule = originModule; this.id = id; this.name = name; this.position = position; this.immutable = immutable; } get type() { return "harmony export specifier"; } getExports() { return { exports: [this.name] }; } describeHarmonyExport() { return { exportedName: this.name, precedence: 1 }; } } HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate { apply(dep, source) { const content = this.getPrefix(dep) + this.getContent(dep); source.insert(dep.position, content); } getPrefix(dep) { return dep.position > 0 ? "\n" : ""; } getContent(dep) { const used = dep.originModule.isUsed(dep.name); const active = HarmonyModulesHelpers.isActive(dep.originModule, dep); if(!used) { return `/* unused harmony export ${(dep.name || "namespace")} */\n`; } if(!active) { return `/* inactive harmony export ${(dep.name || "namespace")} */\n`; } const exportsName = dep.originModule.exportsArgument || "exports"; if(dep.immutable) { return `/* harmony export (immutable) */ ${exportsName}[${JSON.stringify(used)}] = ${dep.id};\n`; } return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify(used)}, function() { return ${dep.id}; });\n`; } }; module.exports = HarmonyExportSpecifierDependency; webpack-3.5.6/lib/dependencies/HarmonyImportDependency.js000066400000000000000000000040451315401342100234770ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; var ModuleDependency = require("./ModuleDependency"); class HarmonyImportDependency extends ModuleDependency { constructor(request, importedVar, range) { super(request); this.range = range; this.importedVar = importedVar; } get type() { return "harmony import"; } getReference() { if(!this.module) return null; return { module: this.module, importedNames: false }; } updateHash(hash) { super.updateHash(hash); hash.update((this.module && (!this.module.meta || this.module.meta.harmonyModule)) + ""); } } HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const content = makeImportStatement(true, dep, outputOptions, requestShortener); source.replace(dep.range[0], dep.range[1] - 1, ""); source.insert(-1, content); } }; function getOptionalComment(pathinfo, shortenedRequest) { if(!pathinfo) { return ""; } return `/*! ${shortenedRequest} */ `; } function makeImportStatement(declare, dep, outputOptions, requestShortener) { const comment = getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request)); const declaration = declare ? "var " : ""; const newline = declare ? "\n" : " "; if(!dep.module) { const stringifiedError = JSON.stringify(`Cannot find module "${dep.request}"`); return `throw new Error(${stringifiedError});${newline}`; } if(dep.importedVar) { const isHarmonyModule = dep.module.meta && dep.module.meta.harmonyModule; const content = `/* harmony import */ ${declaration}${dep.importedVar} = __webpack_require__(${comment}${JSON.stringify(dep.module.id)});${newline}`; if(isHarmonyModule) { return content; } return `${content}/* harmony import */ ${declaration}${dep.importedVar}_default = __webpack_require__.n(${dep.importedVar});${newline}`; } return ""; } HarmonyImportDependency.makeImportStatement = makeImportStatement; module.exports = HarmonyImportDependency; webpack-3.5.6/lib/dependencies/HarmonyImportDependencyParserPlugin.js000066400000000000000000000121421315401342100260300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyImportDependency = require("./HarmonyImportDependency"); const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency"); const HarmonyAcceptDependency = require("./HarmonyAcceptDependency"); const HarmonyModulesHelpers = require("./HarmonyModulesHelpers"); module.exports = class HarmonyImportDependencyParserPlugin { constructor(moduleOptions) { this.strictExportPresence = moduleOptions.strictExportPresence; this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports; } apply(parser) { parser.plugin("import", (statement, source) => { const dep = new HarmonyImportDependency(source, HarmonyModulesHelpers.getNewModuleVar(parser.state, source), statement.range); dep.loc = statement.loc; parser.state.current.addDependency(dep); parser.state.lastHarmonyImport = dep; return true; }); parser.plugin("import specifier", (statement, source, id, name) => { parser.scope.definitions.length--; parser.scope.renames[`$${name}`] = "imported var"; if(!parser.state.harmonySpecifier) parser.state.harmonySpecifier = {}; parser.state.harmonySpecifier[`$${name}`] = [parser.state.lastHarmonyImport, HarmonyModulesHelpers.getModuleVar(parser.state, source), id]; return true; }); parser.plugin("expression imported var", (expr) => { const name = expr.name; const settings = parser.state.harmonySpecifier[`$${name}`]; const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], settings[2], name, expr.range, this.strictExportPresence); dep.shorthand = parser.scope.inShorthand; dep.directImport = true; dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; }); parser.plugin("expression imported var.*", (expr) => { const name = expr.object.name; const settings = parser.state.harmonySpecifier[`$${name}`]; if(settings[2] !== null) return false; const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], 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.current.addDependency(dep); return true; }); if(this.strictThisContextOnImports) { // only in case when we strictly follow the spec we need a special case here parser.plugin("call imported var.*", (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[`$${name}`]; if(settings[2] !== null) return false; const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], 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.current.addDependency(dep); if(expr.arguments) parser.walkExpressions(expr.arguments); return true; }); } parser.plugin("call imported var", (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[`$${name}`]; const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], settings[2], name, expr.range, this.strictExportPresence); dep.directImport = true; dep.callArgs = args; dep.call = fullExpr; dep.loc = expr.loc; parser.state.current.addDependency(dep); if(args) parser.walkExpressions(args); return true; }); parser.plugin("hot accept callback", (expr, requests) => { const dependencies = requests .filter(request => HarmonyModulesHelpers.checkModuleVar(parser.state, request)) .map(request => { const dep = new HarmonyAcceptImportDependency(request, HarmonyModulesHelpers.getModuleVar(parser.state, request), expr.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); return dep; }); if(dependencies.length > 0) { const dep = new HarmonyAcceptDependency(expr.range, dependencies, true); dep.loc = expr.loc; parser.state.current.addDependency(dep); } }); parser.plugin("hot accept without callback", (expr, requests) => { const dependencies = requests .filter(request => HarmonyModulesHelpers.checkModuleVar(parser.state, request)) .map(request => { const dep = new HarmonyAcceptImportDependency(request, HarmonyModulesHelpers.getModuleVar(parser.state, request), expr.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); return dep; }); if(dependencies.length > 0) { const dep = new HarmonyAcceptDependency(expr.range, dependencies, false); dep.loc = expr.loc; parser.state.current.addDependency(dep); } }); } }; webpack-3.5.6/lib/dependencies/HarmonyImportSpecifierDependency.js000066400000000000000000000070771315401342100253410ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); class HarmonyImportSpecifierDependency extends NullDependency { constructor(importDependency, importedVar, id, name, range, strictExportPresence) { super(); this.importDependency = importDependency; this.importedVar = importedVar; this.id = id; this.name = name; this.range = range; this.strictExportPresence = strictExportPresence; this.namespaceObjectAsContext = false; this.callArgs = undefined; this.call = undefined; this.directImport = undefined; } get type() { return "harmony import specifier"; } getReference() { if(!this.importDependency.module) return null; return { module: this.importDependency.module, importedNames: this.id && !this.namespaceObjectAsContext ? [this.id] : true }; } getWarnings() { if(this.strictExportPresence) { return []; } return this._getErrors(); } getErrors() { if(this.strictExportPresence) { return this._getErrors(); } return []; } _getErrors() { const importedModule = this.importDependency.module; if(!importedModule || !importedModule.meta || !importedModule.meta.harmonyModule) { return; } if(!this.id) { return; } if(importedModule.isProvided(this.id) !== false) { return; } const idIsNotNameMessage = this.id !== this.name ? ` (imported as '${this.name}')` : ""; const errorMessage = `"export '${this.id}'${idIsNotNameMessage} was not found in '${this.importDependency.userRequest}'`; const err = new Error(errorMessage); err.hideStack = true; return [err]; } updateHash(hash) { super.updateHash(hash); const importedModule = this.importDependency.module; hash.update((importedModule && importedModule.id) + ""); hash.update((importedModule && this.id) + ""); hash.update((importedModule && this.importedVar) + ""); hash.update((importedModule && this.id && importedModule.isUsed(this.id)) + ""); hash.update((importedModule && (!importedModule.meta || importedModule.meta.harmonyModule)) + ""); hash.update((importedModule && (importedModule.used + JSON.stringify(importedModule.usedExports))) + ""); } } HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate { apply(dep, source) { const content = this.getContent(dep); source.replace(dep.range[0], dep.range[1] - 1, content); } getContent(dep) { const importedModule = dep.importDependency.module; const defaultImport = dep.directImport && dep.id === "default" && !(importedModule && (!importedModule.meta || importedModule.meta.harmonyModule)); const shortHandPrefix = this.getShortHandPrefix(dep); const importedVar = dep.importedVar; const importedVarSuffix = this.getImportVarSuffix(dep, defaultImport, importedModule); if(dep.call && defaultImport) { return `${shortHandPrefix}${importedVar}_default()`; } if(dep.call && dep.id) { return `${shortHandPrefix}Object(${importedVar}${importedVarSuffix})`; } return `${shortHandPrefix}${importedVar}${importedVarSuffix}`; } getImportVarSuffix(dep, defaultImport, importedModule) { if(defaultImport) { return "_default.a"; } if(dep.id) { const used = importedModule ? importedModule.isUsed(dep.id) : dep.id; const optionalComment = dep.id !== used ? " /* " + dep.id + " */" : ""; return `[${JSON.stringify(used)}${optionalComment}]`; } return ""; } getShortHandPrefix(dep) { if(!dep.shorthand) { return ""; } return dep.name + ": "; } }; module.exports = HarmonyImportSpecifierDependency; webpack-3.5.6/lib/dependencies/HarmonyModulesHelpers.js000066400000000000000000000047451315401342100231700ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class HarmonyModulesHelpers { static getModuleVar(state, request) { if(!state.harmonyModules) state.harmonyModules = []; let idx = state.harmonyModules.indexOf(request); if(idx < 0) { idx = state.harmonyModules.length; state.harmonyModules.push(request); } return `__WEBPACK_IMPORTED_MODULE_${idx}_${request.replace(/[^A-Za-z0-9_]/g, "_").replace(/__+/g, "_")}__`; } static getNewModuleVar(state, request) { if(state.harmonyModules && state.harmonyModules.indexOf(request) >= 0) return null; return this.getModuleVar(state, request); } static checkModuleVar(state, request) { if(!state.harmonyModules || state.harmonyModules.indexOf(request) < 0) return null; return this.getModuleVar(state, request); } // checks if an harmony dependency is active in a module according to // precedence rules. static isActive(module, depInQuestion) { const desc = depInQuestion.describeHarmonyExport(); if(!desc.exportedName) return true; let before = true; for(let idx = 0; idx < module.dependencies.length; idx++) { const dep = module.dependencies[idx]; if(dep === depInQuestion) { before = false; continue; } if(!dep.describeHarmonyExport) continue; const d = dep.describeHarmonyExport(); if(!d || !d.exportedName) continue; if(d.exportedName === desc.exportedName) { if(d.precedence < desc.precedence) { return false; } if(d.precedence === desc.precedence && !before) { return false; } } } return true; } // get a list of named exports defined in a module // doesn't include * reexports. static getActiveExports(module, currentDependency) { const desc = currentDependency && currentDependency.describeHarmonyExport(); var currentIndex = currentDependency ? module.dependencies.indexOf(currentDependency) : -1; return module.dependencies.map((dep, idx) => { return { dep: dep, idx: idx }; }).reduce((arr, data) => { const dep = data.dep; if(!dep.describeHarmonyExport) return arr; const d = dep.describeHarmonyExport(); if(!d) return arr; if(!desc || (d.precedence < desc.precedence) || (d.precedence === desc.precedence && data.idx < currentIndex)) { var names = [].concat(d.exportedName); names.forEach(function(name) { if(name && arr.indexOf(name) < 0) arr.push(name); }); } return arr; }, []); } } module.exports = HarmonyModulesHelpers; webpack-3.5.6/lib/dependencies/HarmonyModulesPlugin.js000066400000000000000000000072121315401342100230140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyImportDependency = require("./HarmonyImportDependency"); const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); const HarmonyCompatiblilityDependency = require("./HarmonyCompatibilityDependency"); 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"); class HarmonyModulesPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(HarmonyImportDependency, normalModuleFactory); compilation.dependencyTemplates.set(HarmonyImportDependency, new HarmonyImportDependency.Template()); compilation.dependencyFactories.set(HarmonyImportSpecifierDependency, new NullFactory()); compilation.dependencyTemplates.set(HarmonyImportSpecifierDependency, new HarmonyImportSpecifierDependency.Template()); compilation.dependencyFactories.set(HarmonyCompatiblilityDependency, new NullFactory()); compilation.dependencyTemplates.set(HarmonyCompatiblilityDependency, new HarmonyCompatiblilityDependency.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, new NullFactory()); 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()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.harmony !== "undefined" && !parserOptions.harmony) return; parser.apply( new HarmonyDetectionParserPlugin(), new HarmonyImportDependencyParserPlugin(this.options), new HarmonyExportDependencyParserPlugin() ); }); }); } } module.exports = HarmonyModulesPlugin; webpack-3.5.6/lib/dependencies/ImportContextDependency.js000066400000000000000000000015761315401342100235140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const CriticalDependencyWarning = require("./CriticalDependencyWarning"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class ImportContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange, chunkName) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; this.chunkName = chunkName; } get type() { return "import() context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } } ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = ImportContextDependency; webpack-3.5.6/lib/dependencies/ImportDependenciesBlock.js000066400000000000000000000010231315401342100234150ustar00rootroot00000000000000/* 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 { constructor(request, range, chunkName, module, loc) { super(chunkName, module, loc); this.range = range; const dep = new ImportDependency(request, this); dep.loc = loc; this.addDependency(dep); } }; webpack-3.5.6/lib/dependencies/ImportDependency.js000066400000000000000000000030661315401342100221430ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const DepBlockHelpers = require("./DepBlockHelpers"); const webpackMissingPromiseModule = require("./WebpackMissingModule").promise; class ImportDependency extends ModuleDependency { constructor(request, block) { super(request); this.block = block; } get type() { return "import()"; } } ImportDependency.Template = class ImportDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const depBlock = dep.block; const promise = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener, "import()"); const comment = this.getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request)); const content = this.getContent(promise, dep, comment); source.replace(depBlock.range[0], depBlock.range[1] - 1, content); } getOptionalComment(pathinfo, shortenedRequest) { if(!pathinfo) { return ""; } return `/*! ${shortenedRequest} */ `; } getContent(promise, dep, comment) { if(promise && dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `${promise}.then(__webpack_require__.bind(null, ${comment}${stringifiedId}))`; } if(dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `new Promise(function(resolve) { resolve(__webpack_require__(${comment}${stringifiedId})); })`; } return webpackMissingPromiseModule(dep.request); } }; module.exports = ImportDependency; webpack-3.5.6/lib/dependencies/ImportEagerContextDependency.js000066400000000000000000000013011315401342100244420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ImportContextDependency = require("./ImportContextDependency"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class ImportEagerContextDependency extends ImportContextDependency { constructor(request, recursive, regExp, range, valueRange, chunkName) { super(request, recursive, regExp, range, valueRange, chunkName); this.async = "eager"; } get type() { return "import() context eager"; } } ImportEagerContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = ImportEagerContextDependency; webpack-3.5.6/lib/dependencies/ImportEagerDependency.js000066400000000000000000000022711315401342100231040ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const webpackMissingPromiseModule = require("./WebpackMissingModule").promise; class ImportEagerDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "import()"; } } ImportEagerDependency.Template = class ImportEagerDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const comment = this.getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request)); const content = this.getContent(dep, comment); source.replace(dep.range[0], dep.range[1] - 1, content); } getOptionalComment(pathinfo, shortenedRequest) { if(!pathinfo) { return ""; } return `/*! ${shortenedRequest} */ `; } getContent(dep, comment) { if(dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `new Promise(function(resolve) { resolve(__webpack_require__(${comment}${stringifiedId})); })`; } return webpackMissingPromiseModule(dep.request); } }; module.exports = ImportEagerDependency; webpack-3.5.6/lib/dependencies/ImportLazyContextDependency.js000066400000000000000000000012741315401342100243470ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ImportContextDependency = require("./ImportContextDependency"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class ImportLazyContextDependency extends ImportContextDependency { constructor(request, recursive, regExp, range, valueRange, chunkName) { super(request, recursive, regExp, range, valueRange, chunkName); this.async = "lazy"; } get type() { return "import() context lazy"; } } ImportLazyContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = ImportLazyContextDependency; webpack-3.5.6/lib/dependencies/ImportLazyOnceContextDependency.js000066400000000000000000000013221315401342100251460ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ImportContextDependency = require("./ImportContextDependency"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class ImportLazyOnceContextDependency extends ImportContextDependency { constructor(request, recursive, regExp, range, valueRange, chunkName) { super(request, recursive, regExp, range, valueRange, chunkName); this.async = "lazy-once"; } get type() { return "import() context lazy-once"; } } ImportLazyOnceContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = ImportLazyOnceContextDependency; webpack-3.5.6/lib/dependencies/ImportParserPlugin.js000066400000000000000000000071251315401342100225000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ImportEagerContextDependency = require("./ImportEagerContextDependency"); const ImportWeakDependency = require("./ImportWeakDependency"); const ImportWeakContextDependency = require("./ImportWeakContextDependency"); const ImportLazyOnceContextDependency = require("./ImportLazyOnceContextDependency"); const ImportLazyContextDependency = require("./ImportLazyContextDependency"); const ImportDependenciesBlock = require("./ImportDependenciesBlock"); const ImportEagerDependency = require("./ImportEagerDependency"); const ContextDependencyHelpers = require("./ContextDependencyHelpers"); const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); class ImportParserPlugin { constructor(options) { this.options = options; } apply(parser) { const options = this.options; parser.plugin(["call System.import", "import-call"], (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"; const importOptions = parser.getCommentOptions(expr.range); if(importOptions) { if(typeof 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}.`)); else chunkName = importOptions.webpackChunkName; } if(typeof 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}.`)); else mode = importOptions.webpackMode; } } 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}.`)); } if(mode === "eager") { const dep = new ImportEagerDependency(param.string, expr.range); parser.state.current.addDependency(dep); } else if(mode === "weak") { const dep = new ImportWeakDependency(param.string, expr.range); parser.state.current.addDependency(dep); } else { const depBlock = new ImportDependenciesBlock(param.string, expr.range, chunkName, parser.state.module, expr.loc); 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}.`)); } let Dep = ImportLazyContextDependency; if(mode === "eager") { Dep = ImportEagerContextDependency; } else if(mode === "weak") { Dep = ImportWeakContextDependency; } else if(mode === "lazy-once") { Dep = ImportLazyOnceContextDependency; } const dep = ContextDependencyHelpers.create(Dep, expr.range, param, expr, options, chunkName); if(!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; parser.state.current.addDependency(dep); return true; } }); } } module.exports = ImportParserPlugin; webpack-3.5.6/lib/dependencies/ImportPlugin.js000066400000000000000000000051161315401342100213210ustar00rootroot00000000000000/* 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 ImportEagerContextDependency = require("./ImportEagerContextDependency"); const ImportWeakContextDependency = require("./ImportWeakContextDependency"); const ImportLazyOnceContextDependency = require("./ImportLazyOnceContextDependency"); const ImportLazyContextDependency = require("./ImportLazyContextDependency"); const ImportParserPlugin = require("./ImportParserPlugin"); class ImportPlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; const contextModuleFactory = params.contextModuleFactory; 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(ImportEagerContextDependency, contextModuleFactory); compilation.dependencyTemplates.set(ImportEagerContextDependency, new ImportEagerContextDependency.Template()); compilation.dependencyFactories.set(ImportWeakContextDependency, contextModuleFactory); compilation.dependencyTemplates.set(ImportWeakContextDependency, new ImportWeakContextDependency.Template()); compilation.dependencyFactories.set(ImportLazyOnceContextDependency, contextModuleFactory); compilation.dependencyTemplates.set(ImportLazyOnceContextDependency, new ImportLazyOnceContextDependency.Template()); compilation.dependencyFactories.set(ImportLazyContextDependency, contextModuleFactory); compilation.dependencyTemplates.set(ImportLazyContextDependency, new ImportLazyContextDependency.Template()); normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.import !== "undefined" && !parserOptions.import) return; parser.apply( new ImportParserPlugin(options) ); }); }); } } module.exports = ImportPlugin; webpack-3.5.6/lib/dependencies/ImportWeakContextDependency.js000066400000000000000000000013021315401342100243070ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ImportContextDependency = require("./ImportContextDependency"); const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); class ImportWeakContextDependency extends ImportContextDependency { constructor(request, recursive, regExp, range, valueRange, chunkName) { super(request, recursive, regExp, range, valueRange, chunkName); this.async = "async-weak"; } get type() { return "import() context weak"; } } ImportWeakContextDependency.Template = ContextDependencyTemplateAsRequireCall; module.exports = ImportWeakContextDependency; webpack-3.5.6/lib/dependencies/ImportWeakDependency.js000066400000000000000000000024721315401342100227530ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); const webpackMissingPromiseModule = require("./WebpackMissingModule").promise; class ImportWeakDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; this.weak = true; } get type() { return "import() weak"; } } ImportWeakDependency.Template = class ImportDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const comment = this.getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request)); const content = this.getContent(dep, comment); source.replace(dep.range[0], dep.range[1] - 1, content); } getOptionalComment(pathinfo, shortenedRequest) { if(!pathinfo) { return ""; } return `/*! ${shortenedRequest} */ `; } getContent(dep, comment) { if(dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `Promise.resolve(${comment}${stringifiedId}).then(function(id) { if(!__webpack_require__.m[id]) throw new Error("Module '" + id + "' is not available (weak dependency)"); return __webpack_require__(id); })`; } return webpackMissingPromiseModule(dep.request); } }; module.exports = ImportWeakDependency; webpack-3.5.6/lib/dependencies/LoaderDependency.js000066400000000000000000000005251315401342100220740ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class LoaderDependency extends ModuleDependency { constructor(request) { super(request); } get type() { return "loader"; } } module.exports = LoaderDependency; webpack-3.5.6/lib/dependencies/LoaderPlugin.js000066400000000000000000000037041315401342100212560ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const LoaderDependency = require("./LoaderDependency"); class LoaderPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(LoaderDependency, normalModuleFactory); }); compiler.plugin("compilation", (compilation) => { compilation.plugin("normal-module-loader", (loaderContext, module) => { loaderContext.loadModule = function loadModule(request, callback) { const dep = new LoaderDependency(request); dep.loc = request; compilation.addModuleDependencies(module, [ [dep] ], true, "lm", false, (err) => { if(err) return callback(err); if(!dep.module) return callback(new Error("Cannot load the module")); if(dep.module.building) dep.module.building.push(next); else next(); function next(err) { if(err) return callback(err); if(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.fileDependencies) { dep.module.fileDependencies.forEach((dep) => loaderContext.addDependency(dep)); } if(dep.module.contextDependencies) { dep.module.contextDependencies.forEach((dep) => loaderContext.addContextDependency(dep)); } return callback(null, source, map, dep.module); } }); }; }); }); } } module.exports = LoaderPlugin; webpack-3.5.6/lib/dependencies/LocalModule.js000066400000000000000000000006211315401342100210640ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/LocalModuleDependency.js000066400000000000000000000011311315401342100230600ustar00rootroot00000000000000/* 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) { super(); localModule.flagUsed(); this.localModule = localModule; this.range = range; } } LocalModuleDependency.Template = class LocalModuleDependencyTemplate { apply(dep, source) { if(!dep.range) return; source.replace(dep.range[0], dep.range[1] - 1, dep.localModule.variableName()); } }; module.exports = LocalModuleDependency; webpack-3.5.6/lib/dependencies/LocalModulesHelpers.js000066400000000000000000000021751315401342100226000ustar00rootroot00000000000000/* 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("/"), segs = mod.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 path.join("/"); }; LocalModulesHelpers.addLocalModule = (state, name) => { if(!state.localModules) state.localModules = []; var 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(var i = 0; i < state.localModules.length; i++) { if(state.localModules[i].name === name) return state.localModules[i]; } return null; }; module.exports = LocalModulesHelpers; webpack-3.5.6/lib/dependencies/ModuleDependency.js000066400000000000000000000007241315401342100221140ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); class ModuleDependency extends Dependency { constructor(request) { super(); this.request = request; this.userRequest = request; } isEqualResource(other) { if(!(other instanceof ModuleDependency)) return false; return this.request === other.request; } } module.exports = ModuleDependency; webpack-3.5.6/lib/dependencies/ModuleDependencyTemplateAsId.js000066400000000000000000000011401315401342100243420ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ModuleDependencyTemplateAsId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = comment + JSON.stringify(dep.module.id); else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } module.exports = ModuleDependencyTemplateAsId; webpack-3.5.6/lib/dependencies/ModuleDependencyTemplateAsRequireId.js000066400000000000000000000012101315401342100256750ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ModuleDependencyTemplateAsRequireId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`; else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } module.exports = ModuleDependencyTemplateAsRequireId; webpack-3.5.6/lib/dependencies/ModuleHotAcceptDependency.js000066400000000000000000000010671315401342100237100ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/ModuleHotDeclineDependency.js000066400000000000000000000010731315401342100240510ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/MultiEntryDependency.js000066400000000000000000000006151315401342100230020ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Dependency = require("../Dependency"); class MultiEntryDependency extends Dependency { constructor(dependencies, name) { super(); this.dependencies = dependencies; this.name = name; } get type() { return "multi entry"; } } module.exports = MultiEntryDependency; webpack-3.5.6/lib/dependencies/NullDependency.js000066400000000000000000000006241315401342100216000ustar00rootroot00000000000000/* 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"; } isEqualResource() { return false; } updateHash() {} } NullDependency.Template = class NullDependencyTemplate { apply() {} }; module.exports = NullDependency; webpack-3.5.6/lib/dependencies/PrefetchDependency.js000066400000000000000000000005331315401342100224250ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/RequireContextDependency.js000066400000000000000000000012311315401342100236420ustar00rootroot00000000000000/* 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(request, recursive, regExp, asyncMode, range) { super(request, recursive, regExp); this.range = range; if(asyncMode) { this.async = asyncMode; } } get type() { return "require.context"; } } RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; module.exports = RequireContextDependency; webpack-3.5.6/lib/dependencies/RequireContextDependencyParserPlugin.js000066400000000000000000000026241315401342100262050ustar00rootroot00000000000000/* 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.plugin("call require.context", expr => { let regExp = /^\.\/.*$/; let recursive = true; let asyncMode; switch(expr.arguments.length) { case 4: { const asyncModeExpr = parser.evaluateExpression(expr.arguments[3]); if(!asyncModeExpr.isString()) return; asyncMode = asyncModeExpr.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(requestExpr.string, recursive, regExp, asyncMode, expr.range); dep.loc = expr.loc; dep.optional = parser.scope.inTry; parser.state.current.addDependency(dep); return true; } } }); } }; webpack-3.5.6/lib/dependencies/RequireContextPlugin.js000066400000000000000000000064131315401342100230310ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { const contextModuleFactory = params.contextModuleFactory; const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(RequireContextDependency, contextModuleFactory); compilation.dependencyTemplates.set(RequireContextDependency, new RequireContextDependency.Template()); compilation.dependencyFactories.set(ContextElementDependency, normalModuleFactory); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.requireContext !== "undefined" && !parserOptions.requireContext) return; parser.apply(new RequireContextDependencyParserPlugin()); }); params.contextModuleFactory.plugin("alternatives", (items, callback) => { if(items.length === 0) return callback(null, items); callback(null, 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), [])); }); params.contextModuleFactory.plugin("alternatives", (items, callback) => { if(items.length === 0) return callback(null, items); callback(null, 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), [])); }); params.contextModuleFactory.plugin("alternatives", (items, callback) => { if(items.length === 0) return callback(null, items); callback(null, 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-3.5.6/lib/dependencies/RequireEnsureDependenciesBlock.js000066400000000000000000000014771315401342100247560ustar00rootroot00000000000000/* 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); 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-3.5.6/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js000066400000000000000000000064151315401342100273070ustar00rootroot00000000000000/* 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.plugin("call require.ensure", 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([], () => { dependenciesItems.forEach(ee => { if(ee.isString()) { const edep = new RequireEnsureItemDependency(ee.string, ee.range); 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-3.5.6/lib/dependencies/RequireEnsureDependency.js000066400000000000000000000026701315401342100234670ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const NullDependency = require("./NullDependency"); const DepBlockHelpers = require("./DepBlockHelpers"); class RequireEnsureDependency extends NullDependency { constructor(block) { super(); this.block = block; } get type() { return "require.ensure"; } } RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const depBlock = dep.block; const wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, "require.ensure"); const errorCallbackExists = depBlock.expr.arguments.length === 4 || (!depBlock.chunkName && depBlock.expr.arguments.length === 3); const startBlock = wrapper[0] + "("; const middleBlock = `).bind(null, __webpack_require__)${wrapper[1]}`; const endBlock = `${middleBlock}__webpack_require__.oe${wrapper[2]}`; 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, wrapper[2]); } else { source.replace(depBlock.expr.arguments[1].range[1], depBlock.expr.range[1] - 1, endBlock); } } }; module.exports = RequireEnsureDependency; webpack-3.5.6/lib/dependencies/RequireEnsureItemDependency.js000066400000000000000000000007551315401342100243100ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/RequireEnsurePlugin.js000066400000000000000000000030121315401342100226360ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.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()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.requireEnsure !== "undefined" && !parserOptions.requireEnsure) return; parser.apply(new RequireEnsureDependenciesBlockParserPlugin()); parser.plugin("evaluate typeof require.ensure", ParserHelpers.evaluateToString("function")); parser.plugin("typeof require.ensure", ParserHelpers.toConstantDependency(JSON.stringify("function"))); }); }); } } module.exports = RequireEnsurePlugin; webpack-3.5.6/lib/dependencies/RequireHeaderDependency.js000066400000000000000000000012511315401342100234100ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/RequireIncludeDependency.js000066400000000000000000000015711315401342100236100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class RequireIncludeDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "require.include"; } } RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const comment = this.getOptionalComment(outputOptions.pathinfo && dep.module, requestShortener.shorten(dep.request)); source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); } getOptionalComment(shouldHaveComment, shortenedRequest) { if(shouldHaveComment) { return ""; } return `/*! require.include ${shortenedRequest} */`; } }; module.exports = RequireIncludeDependency; webpack-3.5.6/lib/dependencies/RequireIncludeDependencyParserPlugin.js000066400000000000000000000011561315401342100261430ustar00rootroot00000000000000/* 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.plugin("call require.include", 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-3.5.6/lib/dependencies/RequireIncludePlugin.js000066400000000000000000000022721315401342100227670ustar00rootroot00000000000000/* 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.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(RequireIncludeDependency, normalModuleFactory); compilation.dependencyTemplates.set(RequireIncludeDependency, new RequireIncludeDependency.Template()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.requireInclude !== "undefined" && !parserOptions.requireInclude) return; parser.apply(new RequireIncludeDependencyParserPlugin()); parser.plugin("evaluate typeof require.include", ParserHelpers.evaluateToString("function")); parser.plugin("typeof require.include", ParserHelpers.toConstantDependency(JSON.stringify("function"))); }); }); } } module.exports = RequireIncludePlugin; webpack-3.5.6/lib/dependencies/RequireResolveContextDependency.js000066400000000000000000000015251315401342100252100ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ContextDependency = require("./ContextDependency"); const CriticalDependencyWarning = require("./CriticalDependencyWarning"); const ContextDependencyTemplateAsId = require("./ContextDependencyTemplateAsId"); class RequireResolveContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } } RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; module.exports = RequireResolveContextDependency; webpack-3.5.6/lib/dependencies/RequireResolveDependency.js000066400000000000000000000010161315401342100236360ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/RequireResolveDependencyParserPlugin.js000066400000000000000000000052151315401342100261770ustar00rootroot00000000000000/* 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; parser.plugin("call require.resolve", (expr) => { return parser.applyPluginsBailResult("call require.resolve(Weak)", expr, false); }); parser.plugin("call require.resolveWeak", (expr) => { return parser.applyPluginsBailResult("call require.resolve(Weak)", expr, true); }); parser.plugin("call require.resolve(Weak)", (expr, weak) => { if(expr.arguments.length !== 1) return; const param = parser.evaluateExpression(expr.arguments[0]); if(param.isConditional()) { param.options.forEach((option) => { const result = parser.applyPluginsBailResult("call require.resolve(Weak):item", expr, option, weak); if(result === undefined) { parser.applyPluginsBailResult("call require.resolve(Weak):context", expr, option, weak); } }); const dep = new RequireResolveHeaderDependency(expr.callee.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; } else { const result = parser.applyPluginsBailResult("call require.resolve(Weak):item", expr, param, weak); if(result === undefined) { parser.applyPluginsBailResult("call require.resolve(Weak):context", expr, param, weak); } const dep = new RequireResolveHeaderDependency(expr.callee.range); dep.loc = expr.loc; parser.state.current.addDependency(dep); return true; } }); parser.plugin("call require.resolve(Weak):item", (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; } }); parser.plugin("call require.resolve(Weak):context", (expr, param, weak) => { const dep = ContextDependencyHelpers.create(RequireResolveContextDependency, param.range, param, expr, options); if(!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; dep.async = weak ? "weak" : false; parser.state.current.addDependency(dep); return true; }); } } module.exports = RequireResolveDependencyParserPlugin; webpack-3.5.6/lib/dependencies/RequireResolveHeaderDependency.js000066400000000000000000000013211315401342100247460ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/SingleEntryDependency.js000066400000000000000000000005451315401342100231330ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ModuleDependency = require("./ModuleDependency"); class SingleEntryDependency extends ModuleDependency { constructor(request) { super(request); } get type() { return "single entry"; } } module.exports = SingleEntryDependency; webpack-3.5.6/lib/dependencies/SystemPlugin.js000066400000000000000000000031111315401342100213240ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ParserHelpers = require("../ParserHelpers"); class SystemPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { if(typeof parserOptions.system !== "undefined" && !parserOptions.system) return; function setNotSupported(name) { parser.plugin("evaluate typeof " + name, ParserHelpers.evaluateToString("undefined")); parser.plugin("expression " + name, ParserHelpers.expressionIsUnsupported(name + " is not supported by webpack.") ); } parser.plugin("typeof System.import", ParserHelpers.toConstantDependency(JSON.stringify("function"))); parser.plugin("evaluate typeof System.import", ParserHelpers.evaluateToString("function")); parser.plugin("typeof System", ParserHelpers.toConstantDependency(JSON.stringify("object"))); parser.plugin("evaluate typeof System", ParserHelpers.evaluateToString("object")); setNotSupported("System.set"); setNotSupported("System.get"); setNotSupported("System.register"); parser.plugin("expression System", function() { const systemPolyfillRequire = ParserHelpers.requireFileAsExpression( this.state.module.context, require.resolve("../../buildin/system.js")); return ParserHelpers.addParsedVariableToModule(this, "System", systemPolyfillRequire); }); }); }); } } module.exports = SystemPlugin; webpack-3.5.6/lib/dependencies/UnsupportedDependency.js000066400000000000000000000012011315401342100232060ustar00rootroot00000000000000/* 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, outputOptions, requestShortener) { source.replace(dep.range[0], dep.range[1], webpackMissingModule(dep.request)); } }; module.exports = UnsupportedDependency; webpack-3.5.6/lib/dependencies/WebpackMissingModule.js000066400000000000000000000012151315401342100227400ustar00rootroot00000000000000/* 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-3.5.6/lib/dependencies/getFunctionExpression.js000066400000000000000000000024541315401342100232370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ module.exports = function(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]] }; } // (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-3.5.6/lib/formatLocation.js000066400000000000000000000024201315401342100172160ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const formatPosition = (pos) => { if(pos === null) return ""; const typeOfPos = typeof pos; switch(typeOfPos) { case "string": return pos; case "number": return `${pos}`; case "object": if(typeof pos.line === "number" && typeof pos.column === "number") return `${pos.line}:${pos.column}`; else if(typeof pos.line === "number") return `${pos.line}:?`; else if(typeof pos.index === "number") return `+${pos.index}`; else return ""; default: return ""; } }; const formatLocation = (loc) => { if(loc === null) return ""; const typeOfLoc = typeof loc; switch(typeOfLoc) { case "string": return loc; case "number": return `${loc}`; case "object": if(loc.start && loc.end) { if(typeof loc.start.line === "number" && typeof loc.end.line === "number" && typeof loc.end.column === "number" && loc.start.line === loc.end.line) return `${formatPosition(loc.start)}-${loc.end.column}`; return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; } if(loc.start) return formatPosition(loc.start); return formatPosition(loc); default: return ""; } }; module.exports = formatLocation; webpack-3.5.6/lib/node/000077500000000000000000000000001315401342100146265ustar00rootroot00000000000000webpack-3.5.6/lib/node/NodeChunkTemplatePlugin.js000066400000000000000000000011671315401342100217220ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; class NodeChunkTemplatePlugin { apply(chunkTemplate) { chunkTemplate.plugin("render", function(modules, chunk) { const source = new ConcatSource(); source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = `); source.add(modules); source.add(";"); return source; }); chunkTemplate.plugin("hash", function(hash) { hash.update("node"); hash.update("3"); }); } } module.exports = NodeChunkTemplatePlugin; webpack-3.5.6/lib/node/NodeEnvironmentPlugin.js000066400000000000000000000016641315401342100214640ustar00rootroot00000000000000/* 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.plugin("before-run", (compiler, callback) => { if(compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); callback(); }); } } module.exports = NodeEnvironmentPlugin; webpack-3.5.6/lib/node/NodeHotUpdateChunkTemplatePlugin.js000066400000000000000000000015121315401342100235320ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; class NodeHotUpdateChunkTemplatePlugin { apply(hotUpdateChunkTemplate) { hotUpdateChunkTemplate.plugin("render", (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.plugin("hash", function(hash) { hash.update("NodeHotUpdateChunkTemplatePlugin"); hash.update("3"); hash.update(this.outputOptions.hotUpdateFunction + ""); hash.update(this.outputOptions.library + ""); }); } } module.exports = NodeHotUpdateChunkTemplatePlugin; webpack-3.5.6/lib/node/NodeMainTemplate.runtime.js000066400000000000000000000013271315401342100220370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*global installedChunks $hotChunkFilename$ hotAddUpdateChunk $hotMainFilename$ */ module.exports = function() { function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars var chunk = require("./" + $hotChunkFilename$); hotAddUpdateChunk(chunk.id, chunk.modules); } function hotDownloadManifest() { // eslint-disable-line no-unused-vars try { var update = require("./" + $hotMainFilename$); } catch(e) { return Promise.resolve(); } return Promise.resolve(update); } function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars delete installedChunks[chunkId]; } }; webpack-3.5.6/lib/node/NodeMainTemplateAsync.runtime.js000066400000000000000000000023451315401342100230360ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*global installedChunks $hotChunkFilename$ $require$ hotAddUpdateChunk $hotMainFilename$ */ module.exports = function() { function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars 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); else throw err; } var chunk = {}; require("vm").runInThisContext("(function(exports) {" + content + "\n})", filename)(chunk); hotAddUpdateChunk(chunk.id, chunk.modules); }); } function hotDownloadManifest() { // eslint-disable-line no-unused-vars 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); }); }); } function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars delete installedChunks[chunkId]; } }; webpack-3.5.6/lib/node/NodeMainTemplatePlugin.js000066400000000000000000000156701315401342100215420ustar00rootroot00000000000000/* 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 asyncChunkLoading = this.asyncChunkLoading; mainTemplate.plugin("local-vars", function(source, chunk) { if(chunk.chunks.length > 0) { return this.asString([ source, "", "// object to store loaded chunks", "// \"0\" means \"already loaded\"", "var installedChunks = {", this.indent(chunk.ids.map((id) => `${id}: 0`).join(",\n")), "};" ]); } return source; }); mainTemplate.plugin("require-extensions", function(source, chunk) { if(chunk.chunks.length > 0) { return this.asString([ source, "", "// uncatched error handler for webpack runtime", `${this.requireFn}.oe = function(err) {`, this.indent([ "process.nextTick(function() {", this.indent("throw err; // catch this error by using System.import().catch()"), "});" ]), "};" ]); } return source; }); mainTemplate.plugin("require-ensure", function(_, chunk, hash) { const chunkFilename = this.outputOptions.chunkFilename; const chunkMaps = chunk.getChunkMaps(); const insertMoreModules = [ "var moreModules = chunk.modules, chunkIds = chunk.ids;", "for(var moduleId in moreModules) {", this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")), "}" ]; if(asyncChunkLoading) { return this.asString([ "// \"0\" is the signal for \"already loaded\"", "if(installedChunks[chunkId] === 0)", this.indent([ "return Promise.resolve();" ]), "// array of [resolve, reject, promise] means \"currently loading\"", "if(installedChunks[chunkId])", this.indent([ "return installedChunks[chunkId][2];" ]), "// load the chunk and return promise to it", "var promise = new Promise(function(resolve, reject) {", this.indent([ "installedChunks[chunkId] = [resolve, reject];", "var filename = __dirname + " + this.applyPluginsWaterfall("asset-path", JSON.stringify(`/${chunkFilename}`), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, chunk: { id: "\" + chunkId + \"", hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hashWithLength: (length) => { const shortChunkHashMap = {}; Object.keys(chunkMaps.hash).forEach((chunkId) => { 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) + "` } }) + ";", "require('fs').readFile(filename, 'utf-8', function(err, content) {", this.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++) {", this.indent([ "if(installedChunks[chunkIds[i]])", this.indent([ "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);" ]), "installedChunks[chunkIds[i]] = 0;" ]), "}", "for(i = 0; i < callbacks.length; i++)", this.indent("callbacks[i]();") ])), "});" ]), "});", "return installedChunks[chunkId][2] = promise;" ]); } else { const request = this.applyPluginsWaterfall("asset-path", JSON.stringify(`./${chunkFilename}`), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, chunk: { id: "\" + chunkId + \"", hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hashWithLength: (length) => { const shortChunkHashMap = {}; Object.keys(chunkMaps.hash).forEach((chunkId) => { 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) + "` } }); return this.asString([ "// \"0\" is the signal for \"already loaded\"", "if(installedChunks[chunkId] !== 0) {", this.indent([ `var chunk = require(${request});` ].concat(insertMoreModules).concat([ "for(var i = 0; i < chunkIds.length; i++)", this.indent("installedChunks[chunkIds[i]] = 0;") ])), "}", "return Promise.resolve();" ]); } }); mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) { const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename; const chunkMaps = chunk.getChunkMaps(); const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, chunk: { id: "\" + chunkId + \"", hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, hashWithLength: (length) => { const shortChunkHashMap = {}; Object.keys(chunkMaps.hash).forEach((chunkId) => { 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 = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "` }); return Template.getFunctionContent(asyncChunkLoading ? require("./NodeMainTemplateAsync.runtime.js") : require("./NodeMainTemplate.runtime.js")) .replace(/\$require\$/g, this.requireFn) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename); }); mainTemplate.plugin("hash", function(hash) { hash.update("node"); hash.update("3"); hash.update(this.outputOptions.filename + ""); hash.update(this.outputOptions.chunkFilename + ""); }); } }; webpack-3.5.6/lib/node/NodeOutputFileSystem.js000066400000000000000000000007671315401342100213110ustar00rootroot00000000000000/* 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-3.5.6/lib/node/NodeSourcePlugin.js000066400000000000000000000062301315401342100204120ustar00rootroot00000000000000/* 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; function 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; } function addExpression(parser, name, module, type, suffix) { suffix = suffix || ""; parser.plugin(`expression ${name}`, function() { if(this.state.module && this.state.module.resource === getPathToModule(module, type)) return; const mockModule = ParserHelpers.requireFileAsExpression(this.state.module.context, getPathToModule(module, type)); return ParserHelpers.addParsedVariableToModule(this, name, mockModule + suffix); }); } compiler.plugin("compilation", function(compilation, params) { params.normalModuleFactory.plugin("parser", function(parser, parserOptions) { if(parserOptions.node === false) return; let localOptions = options; if(parserOptions.node) localOptions = Object.assign({}, localOptions, parserOptions.node); if(localOptions.global) { parser.plugin("expression global", function() { const retrieveGlobalModule = ParserHelpers.requireFileAsExpression(this.state.module.context, require.resolve("../../buildin/global.js")); return ParserHelpers.addParsedVariableToModule(this, "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"); } }); }); compiler.plugin("after-resolvers", (compiler) => { Object.keys(nodeLibsBrowser).forEach((lib) => { if(options[lib] !== false) { compiler.resolvers.normal.apply( new AliasPlugin("described-resolve", { name: lib, onlyModule: true, alias: getPathToModule(lib, options[lib]) }, "resolve") ); } }); }); } }; webpack-3.5.6/lib/node/NodeTargetPlugin.js000066400000000000000000000005341315401342100204010ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ExternalsPlugin = require("../ExternalsPlugin"); class NodeTargetPlugin { apply(compiler) { new ExternalsPlugin("commonjs", Object.keys(process.binding("natives"))).apply(compiler); } } module.exports = NodeTargetPlugin; webpack-3.5.6/lib/node/NodeTemplatePlugin.js000066400000000000000000000015131315401342100207240ustar00rootroot00000000000000/* 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.plugin("this-compilation", (compilation) => { compilation.mainTemplate.apply(new NodeMainTemplatePlugin(this.asyncChunkLoading)); compilation.chunkTemplate.apply(new NodeChunkTemplatePlugin()); compilation.hotUpdateChunkTemplate.apply(new NodeHotUpdateChunkTemplatePlugin()); }); } } module.exports = NodeTemplatePlugin; webpack-3.5.6/lib/node/NodeWatchFileSystem.js000066400000000000000000000040461315401342100210510ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Watchpack = require("watchpack"); 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); this.watcher.once("aggregated", (changes, removals) => { changes = changes.concat(removals); if(this.inputFileSystem && this.inputFileSystem.purge) { this.inputFileSystem.purge(changes); } const times = this.watcher.getTimes(); callback(null, changes.filter(file => files.indexOf(file) >= 0).sort(), changes.filter(file => dirs.indexOf(file) >= 0).sort(), changes.filter(file => missing.indexOf(file) >= 0).sort(), times, times); }); this.watcher.watch(files.concat(missing), dirs.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(); } } }; } } module.exports = NodeWatchFileSystem; webpack-3.5.6/lib/optimize/000077500000000000000000000000001315401342100155415ustar00rootroot00000000000000webpack-3.5.6/lib/optimize/AggressiveMergingPlugin.js000066400000000000000000000057601315401342100226760ustar00rootroot00000000000000/* 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; function getParentsWeight(chunk) { return chunk.parents.map((p) => { return p.isInitial() ? options.entryChunkMultiplicator || 10 : 1; }).reduce((a, b) => { return a + b; }, 0); } compiler.plugin("this-compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (chunks) => { let combinations = []; chunks.forEach((a, idx) => { if(a.isInitial()) return; for(let i = 0; i < idx; i++) { const b = chunks[i]; if(b.isInitial()) continue; combinations.push({ a, b, improvement: undefined }); } }); combinations.forEach((pair) => { 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 if(options.moveToParents) { const aOnly = ab - b; const bOnly = ab - a; const common = a + b - ab; newSize = common + getParentsWeight(pair.b) * aOnly + getParentsWeight(pair.a) * bOnly; } 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(options.moveToParents) { const commonModules = pair.b.modules.filter((m) => { return pair.a.modules.indexOf(m) >= 0; }); const aOnlyModules = pair.b.modules.filter((m) => { return commonModules.indexOf(m) < 0; }); const bOnlyModules = pair.a.modules.filter((m) => { return commonModules.indexOf(m) < 0; }); aOnlyModules.forEach((m) => { pair.b.removeModule(m); m.removeChunk(pair.b); pair.b.parents.forEach((c) => { c.addModule(m); m.addChunk(c); }); }); bOnlyModules.forEach((m) => { pair.a.removeModule(m); m.removeChunk(pair.a); pair.a.parents.forEach((c) => { c.addModule(m); m.addChunk(c); }); }); } if(pair.b.integrate(pair.a, "aggressive-merge")) { chunks.splice(chunks.indexOf(pair.a), 1); return true; } }); }); } } module.exports = AggressiveMergingPlugin; webpack-3.5.6/lib/optimize/AggressiveSplittingPlugin.js000066400000000000000000000155731315401342100232660ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const identifierUtils = require("../util/identifier"); function moveModuleBetween(oldChunk, newChunk) { return function(module) { oldChunk.moveModule(module, newChunk); }; } function isNotAEntryModule(entryModule) { return function(module) { return entryModule !== module; }; } function copyWithReason(obj) { const newObj = {}; Object.keys(obj).forEach((key) => { newObj[key] = obj[key]; }); if(!newObj.reasons || newObj.reasons.indexOf("aggressive-splitted") < 0) newObj.reasons = (newObj.reasons || []).concat("aggressive-splitted"); return newObj; } class AggressiveSplittingPlugin { constructor(options) { 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.plugin("this-compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (chunks) => { // Precompute stuff const nameToModuleMap = new Map(); compilation.modules.forEach(m => { const name = identifierUtils.makePathsRelative(compiler.context, m.identifier(), compilation.cache); nameToModuleMap.set(name, m); }); const savedSplits = compilation.records && compilation.records.aggressiveSplits || []; const usedSplits = compilation._aggressiveSplittingSplits ? savedSplits.concat(compilation._aggressiveSplittingSplits) : savedSplits; const minSize = this.options.minSize; const maxSize = this.options.maxSize; // 1. try to restore to recorded splitting for(let j = 0; j < usedSplits.length; j++) { const splitData = usedSplits[j]; const selectedModules = splitData.modules.map(name => nameToModuleMap.get(name)); // Does the modules exist at all? if(selectedModules.every(Boolean)) { // Find all chunks containing all modules in the split for(let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; // Cheap check if chunk is suitable at all if(chunk.getNumberOfModules() < splitData.modules.length) continue; // Check if all modules are in the chunk if(selectedModules.every(m => chunk.containsModule(m))) { // Is chunk identical to the split or do we need to split it? if(chunk.getNumberOfModules() > splitData.modules.length) { // split the chunk into two parts const newChunk = compilation.addChunk(); selectedModules.forEach(moveModuleBetween(chunk, newChunk)); chunk.split(newChunk); chunk.name = null; newChunk._fromAggressiveSplitting = true; if(j < savedSplits.length) newChunk._fromAggressiveSplittingIndex = j; if(splitData.id !== null && splitData.id !== undefined) { newChunk.id = splitData.id; } newChunk.origins = chunk.origins.map(copyWithReason); chunk.origins = chunk.origins.map(copyWithReason); return true; } else { // chunk is identical to the split if(j < savedSplits.length) chunk._fromAggressiveSplittingIndex = j; chunk.name = null; if(splitData.id !== null && splitData.id !== undefined) { chunk.id = splitData.id; } } } } } } // 2. for any other chunk which isn't splitted yet, split it for(let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const size = chunk.size(this.options); if(size > maxSize && chunk.getNumberOfModules() > 1) { const newChunk = compilation.addChunk(); 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; }); for(let k = 0; k < modules.length; k++) { chunk.moveModule(modules[k], newChunk); const newSize = newChunk.size(this.options); const chunkSize = chunk.size(this.options); // break early if it's fine if(chunkSize < maxSize && newSize < maxSize && newSize >= minSize && chunkSize >= minSize) break; if(newSize > maxSize && k === 0) { // break if there is a single module which is bigger than maxSize break; } if(newSize > maxSize || chunkSize < minSize) { // move it back newChunk.moveModule(modules[k], chunk); // check if it's fine now if(newSize < maxSize && newSize >= minSize && chunkSize >= minSize) break; } } if(newChunk.getNumberOfModules() > 0) { chunk.split(newChunk); chunk.name = null; newChunk.origins = chunk.origins.map(copyWithReason); chunk.origins = chunk.origins.map(copyWithReason); compilation._aggressiveSplittingSplits = (compilation._aggressiveSplittingSplits || []).concat({ modules: newChunk.mapModules(m => identifierUtils.makePathsRelative(compiler.context, m.identifier(), compilation.cache)) }); return true; } else { chunks.splice(chunks.indexOf(newChunk), 1); } } } }); compilation.plugin("record-hash", (records) => { // 3. save to made splittings to records const minSize = this.options.minSize; if(!records.aggressiveSplits) records.aggressiveSplits = []; compilation.chunks.forEach((chunk) => { if(chunk.hasEntryModule()) return; const size = chunk.size(this.options); const incorrectSize = size < minSize; const modules = chunk.mapModules(m => identifierUtils.makePathsRelative(compiler.context, m.identifier(), compilation.cache)); if(typeof chunk._fromAggressiveSplittingIndex === "undefined") { if(incorrectSize) return; chunk.recorded = true; records.aggressiveSplits.push({ modules: modules, hash: chunk.hash, id: chunk.id }); } else { const splitData = records.aggressiveSplits[chunk._fromAggressiveSplittingIndex]; if(splitData.hash !== chunk.hash || incorrectSize) { if(chunk._fromAggressiveSplitting) { chunk._aggressiveSplittingInvalid = true; splitData.invalid = true; } else { splitData.hash = chunk.hash; } } } }); records.aggressiveSplits = records.aggressiveSplits.filter((splitData) => { return !splitData.invalid; }); }); compilation.plugin("need-additional-seal", (callback) => { const invalid = compilation.chunks.some((chunk) => { return chunk._aggressiveSplittingInvalid; }); if(invalid) return true; }); }); } } module.exports = AggressiveSplittingPlugin; webpack-3.5.6/lib/optimize/ChunkModuleIdRangePlugin.js000066400000000000000000000026131315401342100227300ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class ChunkModuleIdRangePlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { compilation.plugin("module-ids", (modules) => { const chunk = this.chunks.find((chunk) => chunk.name === options.name); if(!chunk) throw new Error("ChunkModuleIdRangePlugin: Chunk with name '" + options.name + "' was not found"); let currentId = options.start; let chunkModules; if(options.order) { chunkModules = chunk.modules.slice(); switch(options.order) { case "index": chunkModules.sort((a, b) => { return a.index - b.index; }); break; case "index2": chunkModules.sort((a, b) => { return a.index2 - b.index2; }); break; default: throw new Error("ChunkModuleIdRangePlugin: unexpected value of order"); } } else { chunkModules = modules.filter((m) => { return m.chunks.indexOf(chunk) >= 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-3.5.6/lib/optimize/CommonsChunkPlugin.js000066400000000000000000000312741315401342100216710ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; let nextIdent = 0; class CommonsChunkPlugin { constructor(options) { if(arguments.length > 1) { throw new Error(`Deprecation notice: CommonsChunkPlugin now only takes a single argument. Either an options object *or* the name of the chunk. Example: if your old code looked like this: new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js') You would change it to: new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }) The available options are: name: string names: string[] filename: string minChunks: number chunks: string[] children: boolean async: boolean minSize: number`); } const normalizedOptions = this.normalizeOptions(options); this.chunkNames = normalizedOptions.chunkNames; this.filenameTemplate = normalizedOptions.filenameTemplate; this.minChunks = normalizedOptions.minChunks; this.selectedChunks = normalizedOptions.selectedChunks; this.children = normalizedOptions.children; this.async = normalizedOptions.async; this.minSize = normalizedOptions.minSize; this.ident = __filename + (nextIdent++); } normalizeOptions(options) { if(Array.isArray(options)) { return { chunkNames: options, }; } if(typeof options === "string") { return { chunkNames: [options], }; } // options.children and options.chunk may not be used together if(options.children && options.chunks) { throw new Error("You can't and it does not make any sense to use \"children\" and \"chunk\" options together."); } /** * options.async and options.filename are also not possible together * as filename specifies how the chunk is called but "async" implies * that webpack will take care of loading this file. */ if(options.async && options.filename) { throw new Error(`You can not specify a filename if you use the "async" option. You can however specify the name of the async chunk by passing the desired string as the "async" option.`); } /** * Make sure this is either an array or undefined. * "name" can be a string and * "names" a string or an array */ const chunkNames = options.name || options.names ? [].concat(options.name || options.names) : undefined; return { chunkNames: chunkNames, filenameTemplate: options.filename, minChunks: options.minChunks, selectedChunks: options.chunks, children: options.children, async: options.async, minSize: options.minSize }; } apply(compiler) { compiler.plugin("this-compilation", (compilation) => { compilation.plugin(["optimize-chunks", "optimize-extracted-chunks"], (chunks) => { // only optimize once if(compilation[this.ident]) return; compilation[this.ident] = true; /** * Creates a list of "common"" chunks based on the options. * The list is made up of preexisting or newly created chunks. * - If chunk has the name as specified in the chunkNames it is put in the list * - If no chunk with the name as given in chunkNames exists a new chunk is created and added to the list * * These chunks are the "targets" for extracted modules. */ const targetChunks = this.getTargetChunks(chunks, compilation, this.chunkNames, this.children, this.async); // iterate over all our new chunks targetChunks.forEach((targetChunk, idx) => { /** * These chunks are subject to get "common" modules extracted and moved to the common chunk */ const affectedChunks = this.getAffectedChunks(compilation, chunks, targetChunk, targetChunks, idx, this.selectedChunks, this.async, this.children); // bail if no chunk is affected if(!affectedChunks) { return; } // If we are async create an async chunk now // override the "commonChunk" with the newly created async one and use it as commonChunk from now on let asyncChunk; if(this.async) { // If async chunk is one of the affected chunks, just use it asyncChunk = affectedChunks.filter(c => c.name === this.async)[0]; // Elsewise create a new one if(!asyncChunk) { asyncChunk = this.createAsyncChunk( compilation, targetChunks.length <= 1 || typeof this.async !== "string" ? this.async : targetChunk.name ? `${this.async}-${targetChunk.name}` : true, targetChunk ); } targetChunk = asyncChunk; } /** * Check which modules are "common" and could be extracted to a "common" chunk */ const extractableModules = this.getExtractableModules(this.minChunks, affectedChunks, targetChunk); // If the minSize option is set check if the size extracted from the chunk is reached // else bail out here. // As all modules/commons are interlinked with each other, common modules would be extracted // if we reach this mark at a later common chunk. (quirky I guess). if(this.minSize) { const modulesSize = this.calculateModulesSize(extractableModules); // if too small, bail if(modulesSize < this.minSize) return; } // Remove modules that are moved to commons chunk from their original chunks // return all chunks that are affected by having modules removed - we need them later (apparently) const chunksWithExtractedModules = this.extractModulesAndReturnAffectedChunks(extractableModules, affectedChunks); // connect all extracted modules with the common chunk this.addExtractedModulesToTargetChunk(targetChunk, extractableModules); // set filenameTemplate for chunk if(this.filenameTemplate) targetChunk.filenameTemplate = this.filenameTemplate; // if we are async connect the blocks of the "reallyUsedChunk" - the ones that had modules removed - // with the commonChunk and get the origins for the asyncChunk (remember "asyncChunk === commonChunk" at this moment). // bail out if(this.async) { this.moveExtractedChunkBlocksToTargetChunk(chunksWithExtractedModules, targetChunk); asyncChunk.origins = this.extractOriginsOfChunksWithExtractedModules(chunksWithExtractedModules); return; } // we are not in "async" mode // connect used chunks with commonChunk - shouldnt this be reallyUsedChunks here? this.makeTargetChunkParentOfAffectedChunks(affectedChunks, targetChunk); }); return true; }); }); } getTargetChunks(allChunks, compilation, chunkNames, children, asyncOption) { const asyncOrNoSelectedChunk = children || asyncOption; // we have specified chunk names if(chunkNames) { // map chunks by chunkName for quick access const allChunksNameMap = allChunks.reduce((map, chunk) => { if(chunk.name) { map.set(chunk.name, chunk); } return map; }, new Map()); // Ensure we have a chunk per specified chunk name. // Reuse existing chunks if possible return chunkNames.map(chunkName => { if(allChunksNameMap.has(chunkName)) { return allChunksNameMap.get(chunkName); } // add the filtered chunks to the compilation return compilation.addChunk(chunkName); }); } // we dont have named chunks specified, so we just take all of them if(asyncOrNoSelectedChunk) { return allChunks; } /** * No chunk name(s) was specified nor is this an async/children commons chunk */ throw new Error(`You did not specify any valid target chunk settings. Take a look at the "name"/"names" or async/children option.`); } getAffectedChunks(compilation, allChunks, targetChunk, targetChunks, currentIndex, selectedChunks, asyncOption, children) { const asyncOrNoSelectedChunk = children || asyncOption; if(Array.isArray(selectedChunks)) { return allChunks.filter(chunk => { const notCommmonChunk = chunk !== targetChunk; const isSelectedChunk = selectedChunks.indexOf(chunk.name) > -1; return notCommmonChunk && isSelectedChunk; }); } if(asyncOrNoSelectedChunk) { // nothing to do here if(!targetChunk.chunks) { return []; } return targetChunk.chunks.filter((chunk) => { // we only are interested in on-demand chunks if(chunk.isInitial()) return false; // we can only move modules from this chunk if the "commonChunk" is the only parent if(!asyncOption) return chunk.parents.length === 1; return true; }); } /** * past this point only entry chunks are allowed to become commonChunks */ if(targetChunk.parents.length > 0) { compilation.errors.push(new Error("CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (" + targetChunk.name + ")")); return; } /** * If we find a "targetchunk" that is also a normal chunk (meaning it is probably specified as an entry) * and the current target chunk comes after that and the found chunk has a runtime* * make that chunk be an 'affected' chunk of the current target chunk. * * To understand what that means take a look at the "examples/chunkhash", this basically will * result in the runtime to be extracted to the current target chunk. * * *runtime: the "runtime" is the "webpack"-block you may have seen in the bundles that resolves modules etc. */ return allChunks.filter((chunk) => { const found = targetChunks.indexOf(chunk); if(found >= currentIndex) return false; return chunk.hasRuntime(); }); } createAsyncChunk(compilation, asyncOption, targetChunk) { const asyncChunk = compilation.addChunk(typeof asyncOption === "string" ? asyncOption : undefined); asyncChunk.chunkReason = "async commons chunk"; asyncChunk.extraAsync = true; asyncChunk.addParent(targetChunk); targetChunk.addChunk(asyncChunk); return asyncChunk; } // If minChunks is a function use that // otherwhise check if a module is used at least minChunks or 2 or usedChunks.length time getModuleFilter(minChunks, targetChunk, usedChunksLength) { if(typeof minChunks === "function") { return minChunks; } const minCount = (minChunks || Math.max(2, usedChunksLength)); const isUsedAtLeastMinTimes = (module, count) => count >= minCount; return isUsedAtLeastMinTimes; } getExtractableModules(minChunks, usedChunks, targetChunk) { if(minChunks === Infinity) { return []; } // count how many chunks contain a module const commonModulesToCountMap = usedChunks.reduce((map, chunk) => { for(const module of chunk.modulesIterable) { const count = map.has(module) ? map.get(module) : 0; map.set(module, count + 1); } return map; }, new Map()); // filter by minChunks const moduleFilterCount = this.getModuleFilter(minChunks, targetChunk, usedChunks.length); // filter by condition const moduleFilterCondition = (module, chunk) => { if(!module.chunkCondition) { return true; } return module.chunkCondition(chunk); }; return Array.from(commonModulesToCountMap).filter(entry => { const module = entry[0]; const count = entry[1]; // if the module passes both filters, keep it. return moduleFilterCount(module, count) && moduleFilterCondition(module, targetChunk); }).map(entry => entry[0]); } calculateModulesSize(modules) { return modules.reduce((totalSize, module) => totalSize + module.size(), 0); } extractModulesAndReturnAffectedChunks(reallyUsedModules, usedChunks) { return reallyUsedModules.reduce((affectedChunksSet, module) => { for(const chunk of usedChunks) { // removeChunk returns true if the chunk was contained and succesfully removed // false if the module did not have a connection to the chunk in question if(module.removeChunk(chunk)) { affectedChunksSet.add(chunk); } } return affectedChunksSet; }, new Set()); } addExtractedModulesToTargetChunk(chunk, modules) { for(const module of modules) { chunk.addModule(module); module.addChunk(chunk); } } makeTargetChunkParentOfAffectedChunks(usedChunks, commonChunk) { for(const chunk of usedChunks) { // set commonChunk as new sole parent chunk.parents = [commonChunk]; // add chunk to commonChunk commonChunk.addChunk(chunk); for(const entrypoint of chunk.entrypoints) { entrypoint.insertChunk(commonChunk, chunk); } } } moveExtractedChunkBlocksToTargetChunk(chunks, targetChunk) { for(const chunk of chunks) { if(chunk === targetChunk) continue; for(const block of chunk.blocks) { if(block.chunks.indexOf(targetChunk) === -1) { block.chunks.unshift(targetChunk); } targetChunk.addBlock(block); } } } extractOriginsOfChunksWithExtractedModules(chunks) { const origins = []; for(const chunk of chunks) { for(const origin of chunk.origins) { const newOrigin = Object.create(origin); newOrigin.reasons = (origin.reasons || []).concat("async commons"); origins.push(newOrigin); } } return origins; } } module.exports = CommonsChunkPlugin; webpack-3.5.6/lib/optimize/ConcatenatedModule.js000066400000000000000000000700001315401342100216320ustar00rootroot00000000000000/* 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 acorn = require("acorn"); const escope = require("escope"); const ReplaceSource = require("webpack-sources/lib/ReplaceSource"); const ConcatSource = require("webpack-sources/lib/ConcatSource"); const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); 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 HarmonyModulesHelpers = require("../dependencies/HarmonyModulesHelpers"); function ensureNsObjSource(info, moduleToInfoMap, requestShortener) { if(!info.hasNamespaceObject) { info.hasNamespaceObject = true; const name = info.exportMap.get(true); const nsObj = [`var ${name} = {};`]; for(const exportName of info.module.providedExports) { const finalName = getFinalName(info, exportName, moduleToInfoMap, requestShortener, false); nsObj.push(`__webpack_require__.d(${name}, ${JSON.stringify(exportName)}, function() { return ${finalName}; });`); } info.namespaceObjectSource = nsObj.join("\n") + "\n"; } } function getExternalImport(importedModule, info, exportName, asCall) { if(exportName === true) return info.name; const used = importedModule.isUsed(exportName); if(!used) return "/* unused reexport */undefined"; if(info.interop && exportName === "default") { return asCall ? `${info.interopName}()` : `${info.interopName}.a`; } // TODO use Template.toNormalComment when merging with pure-module const comment = used !== exportName ? ` /* ${exportName} */` : ""; const reference = `${info.name}[${JSON.stringify(used)}${comment}]`; if(asCall) return `Object(${reference})`; return reference; } function getFinalName(info, exportName, moduleToInfoMap, requestShortener, asCall) { switch(info.type) { case "concatenated": { const directExport = info.exportMap.get(exportName); if(directExport) { if(exportName === true) ensureNsObjSource(info, moduleToInfoMap, requestShortener); 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) { const refInfo = moduleToInfoMap.get(reexport.module); if(refInfo) { // module is in the concatenation return getFinalName(refInfo, reexport.exportName, moduleToInfoMap, requestShortener, asCall); } } 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(" ")})`; // TODO use Template.toNormalComment when merging with pure-module return `/* ${problem} */ undefined`; } case "external": { const importedModule = info.module; return getExternalImport(importedModule, info, exportName, asCall); } } } function getSymbolsFromScope(s, untilScope) { const allUsedNames = new Set(); let scope = s; while(scope) { if(untilScope === scope) break; scope.variables.forEach(variable => allUsedNames.add(variable.name)); scope = scope.upper; } return allUsedNames; } function 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; } function reduceSet(a, b) { for(const item of b) a.add(item); return a; } function getPathInAst(ast, node) { if(ast === node) { return []; } const nr = node.range; var i; if(Array.isArray(ast)) { for(i = 0; i < ast.length; i++) { const enterResult = enterNode(ast[i]); if(typeof 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(typeof pathResult !== "undefined") return pathResult; } else if(value && typeof value === "object") { const enterResult = enterNode(value); if(typeof enterResult !== "undefined") return enterResult; } } } function enterNode(n) { 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; } } class ConcatenatedModule extends Module { constructor(rootModule, modules) { super(); super.setChunks(rootModule._chunks); this.rootModule = rootModule; this.usedExports = rootModule.usedExports; this.providedExports = rootModule.providedExports; this.optimizationBailout = rootModule.optimizationBailout; this.used = rootModule.used; this.index = rootModule.index; this.index2 = rootModule.index2; this.depth = rootModule.depth; this.built = modules.some(m => m.built); this.cacheable = modules.every(m => m.cacheable); const modulesSet = new Set(modules); this.reasons = rootModule.reasons.filter(reason => !(reason.dependency instanceof HarmonyImportDependency) || !modulesSet.has(reason.module)); this.meta = rootModule.meta; this.moduleArgument = rootModule.moduleArgument; this.exportsArgument = rootModule.exportsArgument; this.strict = true; this._numberOfConcatenatedModules = modules.length; this.dependencies = []; this.dependenciesWarnings = []; this.dependenciesErrors = []; this.fileDependencies = []; this.contextDependencies = []; this.warnings = []; this.errors = []; this.assets = {}; this._orderedConcatenationList = this._createOrderedConcatenationList(rootModule, modulesSet); for(const info of this._orderedConcatenationList) { if(info.type === "concatenated") { const m = info.module; // populate dependencies m.dependencies.filter(dep => !(dep instanceof HarmonyImportDependency) || !modulesSet.has(dep.module)) .forEach(d => this.dependencies.push(d)); // populate dep warning m.dependenciesWarnings.forEach(depWarning => this.dependenciesWarnings.push(depWarning)); // populate dep errors m.dependenciesErrors.forEach(depError => this.dependenciesErrors.push(depError)); // populate file dependencies if(m.fileDependencies) m.fileDependencies.forEach(file => this.fileDependencies.push(file)); // populate context dependencies if(m.contextDependencies) m.contextDependencies.forEach(context => this.contextDependencies.push(context)); // populate warnings m.warnings.forEach(warning => this.warnings.push(warning)); // populate errors m.errors.forEach(error => this.errors.push(error)); Object.assign(this.assets, m.assets); } } } get modules() { return this._orderedConcatenationList .filter(info => info.type === "concatenated") .map(info => info.module); } identifier() { return this._orderedConcatenationList.map(info => { switch(info.type) { case "concatenated": return info.module.identifier(); } }).filter(Boolean).join(" "); } 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); } _createOrderedConcatenationList(rootModule, modulesSet) { const list = []; const set = new Set(); function getConcatenatedImports(module) { // TODO need changes when merging with the pure-module branch const allDeps = module.dependencies .filter(dep => dep instanceof HarmonyImportDependency && dep.module); return allDeps.map(dep => () => dep.module); } function enterModule(getModule) { const module = getModule(); 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; } source(dependencyTemplates, outputOptions, 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(); info.module.dependencies.forEach(dep => { if(dep instanceof HarmonyExportSpecifierDependency) { exportMap.set(dep.name, dep.id); } else if(dep instanceof HarmonyExportExpressionDependency) { exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); } else if(dep instanceof HarmonyExportImportedSpecifierDependency) { const exportName = dep.name; const importName = dep.id; const importedModule = dep.importDependency.module; if(exportName && importName) { reexportMap.set(exportName, { module: importedModule, exportName: importName, dependency: dep }); } else if(exportName) { reexportMap.set(exportName, { module: importedModule, exportName: true, dependency: dep }); } else { var activeExports = new Set(HarmonyModulesHelpers.getActiveExports(dep.originModule, dep)); importedModule.providedExports.forEach(name => { if(activeExports.has(name) || name === "default") return; reexportMap.set(name, { module: importedModule, exportName: name, dependency: dep }); }); } } }); return { type: "concatenated", module: info.module, index: idx, ast: undefined, source: undefined, globalScope: undefined, moduleScope: undefined, internalNames: new Map(), exportMap: exportMap, reexportMap: reexportMap, hasNamespaceObject: false, namespaceObjectSource: null }; } case "external": return { type: "external", module: info.module, index: idx, name: undefined, interopName: undefined, interop: undefined }; default: throw new Error(`Unsupported concatenation entry type ${info.type}`); } }); // Create mapping from module to info const moduleToInfoMap = new Map(); modulesWithInfo.forEach(m => 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(HarmonyImportDependency, new HarmonyImportDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyImportDependency), moduleToInfoMap )); innerDependencyTemplates.set(HarmonyExportSpecifierDependency, new HarmonyExportSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportSpecifierDependency), this.rootModule )); innerDependencyTemplates.set(HarmonyExportExpressionDependency, new HarmonyExportExpressionDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportExpressionDependency), this.rootModule, moduleToInfoMap )); innerDependencyTemplates.set(HarmonyExportImportedSpecifierDependency, new HarmonyExportImportedSpecifierDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyExportImportedSpecifierDependency), this.rootModule, moduleToInfoMap )); innerDependencyTemplates.set(HarmonyCompatibilityDependency, new HarmonyCompatibilityDependencyConcatenatedTemplate( dependencyTemplates.get(HarmonyCompatibilityDependency), this.rootModule, moduleToInfoMap )); innerDependencyTemplates.set("hash", innerDependencyTemplates.get("hash") + this.rootModule.identifier()); // Generate source code and analyse scopes // Prepare a ReplaceSource for the final source modulesWithInfo.forEach(info => { if(info.type === "concatenated") { const m = info.module; const source = m.source(innerDependencyTemplates, outputOptions, requestShortener); const code = source.source(); let ast; try { ast = acorn.parse(code, { ranges: true, locations: true, ecmaVersion: Parser.ECMA_VERSION, 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 = escope.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.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" ]); // get all global names modulesWithInfo.forEach(info => { if(info.globalScope) { info.globalScope.through.forEach(reference => { const name = reference.identifier.name; if(/^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?__$/.test(name)) { for(const s of getSymbolsFromScope(reference.from, info.moduleScope)) { allUsedNames.add(s); } } else { allUsedNames.add(name); } }); } }); // generate names for symbols modulesWithInfo.forEach(info => { 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); info.moduleScope.variables.forEach(variable => { const name = variable.name; if(allUsedNames.has(name)) { const references = getAllReferences(variable); const symbolsInReferences = references.map(ref => getSymbolsFromScope(ref.from, info.moduleScope)).reduce(reduceSet, new Set()); 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": { info.interop = info.module.meta && !info.module.meta.harmonyModule; const externalName = this.findNewName("", allUsedNames, null, info.module.readableIdentifier(requestShortener)); allUsedNames.add(externalName); info.name = externalName; if(info.interop) { const externalNameInterop = this.findNewName("default", allUsedNames, null, info.module.readableIdentifier(requestShortener)); allUsedNames.add(externalNameInterop); info.interopName = externalNameInterop; } break; } } }); // Find and replace referenced to modules modulesWithInfo.forEach(info => { if(info.type === "concatenated") { info.globalScope.through.forEach(reference => { const name = reference.identifier.name; const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?__$/.exec(name); if(match) { const referencedModule = modulesWithInfo[+match[1]]; let exportName; if(match[2] === "ns") { exportName = true; } else { const exportData = match[2]; exportName = new Buffer(exportData, "hex").toString("utf-8"); // eslint-disable-line node/no-deprecated-api } const asCall = !!match[3]; const finalName = getFinalName(referencedModule, exportName, moduleToInfoMap, requestShortener, asCall); 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) { result.add(`Object.defineProperty(${this.exportsArgument || "exports"}, "__esModule", { value: true });\n`); } // define required namespace objects (must be before evaluation modules) modulesWithInfo.forEach(info => { if(info.namespaceObjectSource) { result.add(info.namespaceObjectSource); } }); // evaluate modules in order modulesWithInfo.forEach(info => { 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.interop) { result.add(`var ${info.interopName} = /*#__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; } 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; } apply(dep, source, outputOptions, requestShortener, dependencyTemplates) { const module = dep.importDependency.module; const info = this.modulesMap.get(module); if(!info) { this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); return; } let content; if(dep.id === null) { content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__`; } else if(dep.namespaceObjectAsContext) { content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__[${JSON.stringify(dep.id)}]`; } else { const exportData = new Buffer(dep.id, "utf-8").toString("hex"); // eslint-disable-line node/no-deprecated-api content = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${dep.call ? "_call" : ""}__`; } if(dep.shorthand) { content = dep.name + ": " + content; } source.replace(dep.range[0], dep.range[1] - 1, content); } } class HarmonyImportDependencyConcatenatedTemplate { constructor(originalTemplate, modulesMap) { this.originalTemplate = originalTemplate; this.modulesMap = modulesMap; } apply(dep, source, outputOptions, requestShortener, dependencyTemplates) { const module = dep.module; const info = this.modulesMap.get(module); if(!info) { this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); return; } source.replace(dep.range[0], dep.range[1] - 1, ""); } } class HarmonyExportSpecifierDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; } apply(dep, source, outputOptions, requestShortener, dependencyTemplates) { if(dep.originModule === this.rootModule) { this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); } } } class HarmonyExportExpressionDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; } apply(dep, source, outputOptions, requestShortener, 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 || "exports"; if(used) content += `${exportsName}[${JSON.stringify(used)}] = `; } if(dep.range) { source.replace(dep.rangeStatement[0], dep.range[0] - 1, content + "("); source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); return; } source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); } } class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule, modulesMap) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; this.modulesMap = modulesMap; } getExports(dep) { const active = HarmonyModulesHelpers.isActive(dep.originModule, dep); if(!active) return []; const importModule = dep.importDependency.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" const activeExports = new Set(HarmonyModulesHelpers.getActiveExports(dep.originModule, dep)); return importModule.providedExports.filter(exp => exp !== "default" && !activeExports.has(exp)).map(exp => { return { name: exp, id: exp, module: importModule }; }); } apply(dep, source, outputOptions, requestShortener, dependencyTemplates) { if(dep.originModule === this.rootModule) { if(this.modulesMap.get(dep.importDependency.module)) { const exportDefs = this.getExports(dep); exportDefs.forEach(def => { const info = this.modulesMap.get(def.module); const used = dep.originModule.isUsed(def.name); if(!used) { source.insert(-1, `/* unused concated harmony import ${dep.name} */\n`); } let finalName; if(def.id === true) { finalName = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__`; } else { const exportData = new Buffer(def.id, "utf-8").toString("hex"); // eslint-disable-line node/no-deprecated-api finalName = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}__`; } const exportsName = this.rootModule.exportsArgument || "exports"; const content = `/* concated harmony reexport */__webpack_require__.d(${exportsName}, ${JSON.stringify(used)}, function() { return ${finalName}; });\n`; source.insert(-1, content); }); } else { this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); } } } } class HarmonyCompatibilityDependencyConcatenatedTemplate { constructor(originalTemplate, rootModule, modulesMap) { this.originalTemplate = originalTemplate; this.rootModule = rootModule; this.modulesMap = modulesMap; } apply(dep, source, outputOptions, requestShortener, dependencyTemplates) { // do nothing } } module.exports = ConcatenatedModule; webpack-3.5.6/lib/optimize/DedupePlugin.js000066400000000000000000000005751315401342100204730ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class DedupePlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.warnings.push(new Error("DedupePlugin: This plugin was removed from webpack. Remove it from your configuration.")); }); } } module.exports = DedupePlugin; webpack-3.5.6/lib/optimize/EnsureChunkConditionsPlugin.js000066400000000000000000000021641315401342100235450ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class EnsureChunkConditionsPlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { const triesMap = new Map(); compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => { let changed = false; chunks.forEach((chunk) => { chunk.forEachModule((module) => { if(!module.chunkCondition) return; if(!module.chunkCondition(chunk)) { let usedChunks = triesMap.get(module); if(!usedChunks) triesMap.set(module, usedChunks = new Set()); usedChunks.add(chunk); const newChunks = []; chunk.parents.forEach((parent) => { if(!usedChunks.has(parent)) { parent.addModule(module); module.addChunk(parent); newChunks.push(parent); } }); module.rewriteChunkInReasons(chunk, newChunks); chunk.removeModule(module); changed = true; } }); }); if(changed) return true; }); }); } } module.exports = EnsureChunkConditionsPlugin; webpack-3.5.6/lib/optimize/FlagIncludedChunksPlugin.js000066400000000000000000000016631315401342100227610ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class FlagIncludedChunksPlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunk-ids", (chunks) => { chunks.forEach((chunkA) => { chunks.forEach((chunkB) => { // as we iterate the same iterables twice // skip if we find ourselves if(chunkA === chunkB) return; // instead of swapping A and B just bail // as we loop twice the current A will be B and B then A if(chunkA.getNumberOfModules() < chunkB.getNumberOfModules()) return; if(chunkB.getNumberOfModules() === 0) return; // is chunkB in chunkA? for(const m of chunkB.modulesIterable) { if(!chunkA.containsModule(m)) return; } chunkA.ids.push(chunkB.id); }); }); }); }); } } module.exports = FlagIncludedChunksPlugin; webpack-3.5.6/lib/optimize/LimitChunkCountPlugin.js000066400000000000000000000036071315401342100223440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class LimitChunkCountPlugin { constructor(options) { if(options !== undefined && typeof options !== "object" || Array.isArray(options)) { throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.js.org/plugins/"); } this.options = options || {}; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (chunks) => { const maxChunks = options.maxChunks; if(!maxChunks) return; if(maxChunks < 1) return; if(chunks.length <= maxChunks) return; if(chunks.length > maxChunks) { const sortedExtendedPairCombinations = 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; }, []).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 diff = b[0] - a[0]; if(diff !== 0) return diff; return a[1] - b[1]; }); 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-3.5.6/lib/optimize/MergeDuplicateChunksPlugin.js000066400000000000000000000013441315401342100233260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class MergeDuplicateChunksPlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunks-basic", (chunks) => { const map = Object.create(null); chunks.slice().forEach((chunk) => { if(chunk.hasRuntime() || chunk.hasEntryModule()) return; const ident = chunk.getModulesIdent(); const otherChunk = map[ident]; if(otherChunk) { if(otherChunk.integrate(chunk, "duplicate")) chunks.splice(chunks.indexOf(chunk), 1); return; } map[ident] = chunk; }); }); }); } } module.exports = MergeDuplicateChunksPlugin; webpack-3.5.6/lib/optimize/MinChunkSizePlugin.js000066400000000000000000000042261315401342100216310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class MinChunkSizePlugin { constructor(options) { if(typeof options !== "object" || Array.isArray(options)) { throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.js.org/plugins/"); } this.options = options; } apply(compiler) { const options = this.options; const minChunkSize = options.minChunkSize; compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (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-3.5.6/lib/optimize/ModuleConcatenationPlugin.js000066400000000000000000000244751315401342100232250ustar00rootroot00000000000000/* 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 HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); function formatBailoutReason(msg) { return "ModuleConcatenation bailout: " + msg; } class ModuleConcatenationPlugin { constructor(options) { if(typeof options !== "object") options = {}; this.options = options; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { parser.plugin("call eval", () => { parser.state.module.meta.hasEval = true; }); }); const bailoutReasonMap = new Map(); function setBailoutReason(module, reason) { bailoutReasonMap.set(module, reason); module.optimizationBailout.push(typeof reason === "function" ? (rs) => formatBailoutReason(reason(rs)) : formatBailoutReason(reason)); } function getBailoutReason(module, requestShortener) { const reason = bailoutReasonMap.get(module); if(typeof reason === "function") return reason(requestShortener); return reason; } compilation.plugin("optimize-chunk-modules", (chunks, modules) => { const relevantModules = []; const possibleInners = new Set(); for(const module of modules) { // Only harmony modules are valid for optimization if(!module.meta || !module.meta.harmonyModule || !module.dependencies.some(d => d instanceof HarmonyCompatibilityDependency)) { setBailoutReason(module, "Module is not an ECMAScript module"); continue; } // Because of variable renaming we can't use modules with eval if(module.meta && module.meta.hasEval) { setBailoutReason(module, "Module uses eval()"); continue; } // Exports must be known (and not dynamic) if(!Array.isArray(module.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.getChunks().some(chunk => chunk.entryModule === module)) { setBailoutReason(module, "Module is an entry point"); continue; } // Module must only be used by Harmony Imports const nonHarmonyReasons = module.reasons.filter(reason => !(reason.dependency instanceof HarmonyImportDependency)); if(nonHarmonyReasons.length > 0) { const importingModules = new Set(nonHarmonyReasons.map(r => r.module)); const importingModuleTypes = new Map(Array.from(importingModules).map(m => [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(); return `Module is referenced from these modules with unsupported syntax: ${names.join(", ")}`; }); 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(currentRoot)) { const problem = this.tryToAdd(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.modules) { 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 newModule = new ConcatenatedModule(concatConfiguration.rootModule, Array.from(concatConfiguration.modules)); concatConfiguration.sortWarnings(); for(const warning of concatConfiguration.warnings) { 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 concatConfiguration.modules) { usedModules.add(m); chunks.forEach(chunk => chunk.removeModule(m)); } chunks.forEach(chunk => { chunk.addModule(newModule); newModule.addChunk(chunk); if(chunk.entryModule === concatConfiguration.rootModule) chunk.entryModule = newModule; }); compilation.modules.push(newModule); newModule.reasons.forEach(reason => reason.dependency.module = newModule); newModule.dependencies.forEach(dep => { if(dep.module) { dep.module.reasons.forEach(reason => { if(reason.dependency === dep) reason.module = newModule; }); } }); } compilation.modules = compilation.modules.filter(m => !usedModules.has(m)); }); }); } getImports(module) { return Array.from(new Set(module.dependencies // Only harmony Dependencies .filter(dep => dep instanceof HarmonyImportDependency && dep.module) // Dependencies are simple enough to concat them .filter(dep => { return !module.dependencies.some(d => d instanceof HarmonyExportImportedSpecifierDependency && d.importDependency === dep && !d.id && !Array.isArray(dep.module.providedExports) ); }) // Take the imported module .map(dep => dep.module) )); } tryToAdd(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) { const problem = this.tryToAdd(testConfig, reason.module, possibleModules, failureCache); if(problem) { failureCache.set(module, problem); // cache failures for performance return problem; } } // Eagerly try to add imports too if possible for(const imp of this.getImports(module)) { const problem = this.tryToAdd(testConfig, imp, possibleModules, failureCache); if(problem) { config.addWarning(module, problem); } } // Commit experimental changes config.set(testConfig); return null; } } class ConcatConfiguration { constructor(rootModule) { this.rootModule = rootModule; this.modules = new Set([rootModule]); this.warnings = new Map(); } 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); } sortWarnings() { this.warnings = new Map(Array.from(this.warnings).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; })); } clone() { const clone = new ConcatConfiguration(this.rootModule); for(const module of this.modules) clone.add(module); for(const pair of this.warnings) clone.addWarning(pair[0], pair[1]); return clone; } set(config) { this.rootModule = config.rootModule; this.modules = new Set(config.modules); this.warnings = new Map(config.warnings); } } module.exports = ModuleConcatenationPlugin; webpack-3.5.6/lib/optimize/OccurrenceOrderPlugin.js000066400000000000000000000060271315401342100223470ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; 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.plugin("compilation", (compilation) => { compilation.plugin("optimize-module-order", (modules) => { const occursInInitialChunksMap = new Map(); const occursInAllChunksMap = new Map(); const initialChunkChunkMap = new Map(); const entryCountMap = new Map(); modules.forEach(m => { let initial = 0; let entry = 0; m.forEachChunk(c => { if(c.isInitial()) 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; return sum + r.module.getNumberOfChunks(); }; if(preferEntry) { modules.forEach(m => { const result = m.reasons.reduce(countOccursInEntry, 0) + initialChunkChunkMap.get(m) + entryCountMap.get(m); occursInInitialChunksMap.set(m, result); }); } modules.forEach(m => { const result = m.reasons.reduce(countOccurs, 0) + m.getNumberOfChunks() + entryCountMap.get(m); occursInAllChunksMap.set(m, result); }); 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; if(a.index > b.index) return 1; if(a.index < b.index) return -1; return 0; }); }); compilation.plugin("optimize-chunk-order", (chunks) => { const occursInInitialChunksMap = new Map(); chunks.forEach(c => { const result = c.parents.reduce((sum, p) => { if(p.isInitial()) return sum + 1; return sum; }, 0); return occursInInitialChunksMap.set(c, result); }); function occurs(c) { return c.blocks.length; } 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 = occurs(a); const bOccurs = occurs(b); if(aOccurs > bOccurs) return -1; if(aOccurs < bOccurs) return 1; return a.compareTo(b); }); }); }); } } module.exports = OccurrenceOrderPlugin; webpack-3.5.6/lib/optimize/RemoveEmptyChunksPlugin.js000066400000000000000000000011111315401342100227000ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class RemoveEmptyChunksPlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => { chunks.filter((chunk) => chunk.isEmpty() && !chunk.hasRuntime() && !chunk.hasEntryModule()) .forEach((chunk) => { chunk.remove("empty"); chunks.splice(chunks.indexOf(chunk), 1); }); }); }); } } module.exports = RemoveEmptyChunksPlugin; webpack-3.5.6/lib/optimize/RemoveParentModulesPlugin.js000066400000000000000000000037561315401342100232310ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; function hasModule(chunk, module, checkedChunks) { if(chunk.containsModule(module)) return [chunk]; if(chunk.parents.length === 0) return false; return allHaveModule(chunk.parents.filter((c) => { return !checkedChunks.has(c); }), module, checkedChunks); } function allHaveModule(someChunks, module, checkedChunks) { if(!checkedChunks) checkedChunks = new Set(); var chunks = new Set(); for(var i = 0; i < someChunks.length; i++) { checkedChunks.add(someChunks[i]); var subChunks = hasModule(someChunks[i], module, checkedChunks); if(!subChunks) return false; for(var index = 0; index < subChunks.length; index++) { var item = subChunks[index]; chunks.add(item); } } return chunks; } class RemoveParentModulesPlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => { for(var index = 0; index < chunks.length; index++) { var chunk = chunks[index]; if(chunk.parents.length === 0) continue; // TODO consider Map when performance has improved https://gist.github.com/sokra/b36098368da7b8f6792fd7c85fca6311 var cache = Object.create(null); var modules = chunk.getModules(); for(var i = 0; i < modules.length; i++) { var module = modules[i]; var dId = module.getChunkIdsIdent(); var parentChunksWithModule; if(dId === null) { parentChunksWithModule = allHaveModule(chunk.parents, module); } else if(dId in cache) { parentChunksWithModule = cache[dId]; } else { parentChunksWithModule = cache[dId] = allHaveModule(chunk.parents, module); } if(parentChunksWithModule) { module.rewriteChunkInReasons(chunk, Array.from(parentChunksWithModule)); chunk.removeModule(module); } } } }); }); } } module.exports = RemoveParentModulesPlugin; webpack-3.5.6/lib/optimize/UglifyJsPlugin.js000066400000000000000000000003201315401342100210050ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); module.exports = UglifyJsPlugin; webpack-3.5.6/lib/performance/000077500000000000000000000000001315401342100162025ustar00rootroot00000000000000webpack-3.5.6/lib/performance/AssetsOverSizeLimitWarning.js000066400000000000000000000014621315401342100240210ustar00rootroot00000000000000/* 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) { super(); this.name = "AssetsOverSizeLimitWarning"; this.assets = assetsOverSizeLimit; const assetLists = this.assets.map(asset => `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})`).join(""); this.message = `asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize(assetLimit)}). This can impact web performance. Assets: ${assetLists}`; Error.captureStackTrace(this, this.constructor); } }; webpack-3.5.6/lib/performance/EntrypointsOverSizeLimitWarning.js000066400000000000000000000017131315401342100251140ustar00rootroot00000000000000/* 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) { super(); this.name = "EntrypointsOverSizeLimitWarning"; this.entrypoints = entrypoints; const entrypointList = this.entrypoints.map(entrypoint => `\n ${ entrypoint.name } (${ SizeFormatHelpers.formatSize(entrypoint.size) })\n${ entrypoint.files.map(asset => ` ${asset}`).join("\n") }`).join(""); this.message = `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`; Error.captureStackTrace(this, this.constructor); } }; webpack-3.5.6/lib/performance/NoAsyncChunksWarning.js000066400000000000000000000011551315401342100226160ustar00rootroot00000000000000/* 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(); this.name = "NoAsyncChunksWarning"; this.message = "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/"; Error.captureStackTrace(this, this.constructor); } }; webpack-3.5.6/lib/performance/SizeLimitsPlugin.js000066400000000000000000000055301315401342100220160ustar00rootroot00000000000000/* 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 => !(/\.map$/.test(asset))); compiler.plugin("after-emit", (compilation, callback) => { const warnings = []; const getEntrypointSize = entrypoint => entrypoint.getFiles() .filter(assetFilter) .map(file => compilation.assets[file]) .filter(Boolean) .map(asset => asset.size()) .reduce((currentSize, nextSize) => currentSize + nextSize, 0); const assetsOverSizeLimit = []; Object.keys(compilation.assets) .filter(assetFilter) .forEach(assetName => { const asset = compilation.assets[assetName]; const size = asset.size(); if(size > assetSizeLimit) { assetsOverSizeLimit.push({ name: assetName, size: size, }); asset.isOverSizeLimit = true; } }); const entrypointsOverLimit = []; Object.keys(compilation.entrypoints) .forEach(key => { const entry = compilation.entrypoints[key]; const size = getEntrypointSize(entry, compilation); if(size > entrypointSizeLimit) { entrypointsOverLimit.push({ name: key, 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.isInitial()).length > 0; if(!hasAsyncChunks) { warnings.push(new NoAsyncChunksWarning()); } if(hints === "error") { Array.prototype.push.apply(compilation.errors, warnings); } else { Array.prototype.push.apply(compilation.warnings, warnings); } } } callback(); }); } }; webpack-3.5.6/lib/prepareOptions.js000066400000000000000000000012541315401342100172530ustar00rootroot00000000000000"use strict"; module.exports = function prepareOptions(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; }; function handleExport(options) { const isES6DefaultExported = ( typeof options === "object" && options !== null && typeof options.default !== "undefined" ); options = isES6DefaultExported ? options.default : options; return options; } function handleFunction(options, argv) { if(typeof options === "function") { options = options(argv.env, argv); } return options; } webpack-3.5.6/lib/removeAndDo.js000066400000000000000000000006061315401342100164440ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; module.exports = function removeAndDo(collection, thing, action) { const idx = this[collection].indexOf(thing); const hasThingInCollection = idx >= 0; if(hasThingInCollection) { this[collection].splice(idx, 1); thing[action](this); } return hasThingInCollection; }; webpack-3.5.6/lib/util/000077500000000000000000000000001315401342100146565ustar00rootroot00000000000000webpack-3.5.6/lib/util/Semaphore.js000066400000000000000000000010271315401342100171370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; class Semaphore { constructor(available) { this.available = available; this.waiters = []; } acquire(callback) { if(this.available > 0) { this.available--; callback(); } else { this.waiters.push(callback); } } release() { if(this.waiters.length > 0) { const callback = this.waiters.pop(); process.nextTick(callback); } else { this.available++; } } } module.exports = Semaphore; webpack-3.5.6/lib/util/SortableSet.js000066400000000000000000000015561315401342100174520ustar00rootroot00000000000000"use strict"; module.exports = class SortableSet extends Set { constructor(initialIterable, defaultSort) { super(initialIterable); this._sortFn = defaultSort; this._lastActiveSortFn = null; } /** * @param {any} value - value to add to set * @returns {SortableSet} - returns itself */ add(value) { this._lastActiveSortFn = null; super.add(value); return this; } /** * @param {Function} sortFn - function to sort the set * @returns {void} */ sortWith(sortFn) { if(this.size === 0 || 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) { this.add(sortedArray[i]); } this._lastActiveSortFn = sortFn; } /** * @returns {void} */ sort() { this.sortWith(this._sortFn); } }; webpack-3.5.6/lib/util/identifier.js000066400000000000000000000020711315401342100173360ustar00rootroot00000000000000"use strict"; const path = require("path"); const looksLikeAbsolutePath = (maybeAbsolutePath) => { return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath); }; const normalizePathSeparator = (p) => p.replace(/\\/g, "/"); const _makePathsRelative = (context, identifier) => { return identifier .split(/([|! ])/) .map(str => looksLikeAbsolutePath(str) ? normalizePathSeparator(path.relative(context, str)) : str) .join(""); }; 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(typeof contextCache === "undefined") { relativePaths.set(context, contextCache = new Map()); } else { cachedResult = contextCache.get(identifier); } if(typeof cachedResult !== "undefined") { return cachedResult; } else { const relativePath = _makePathsRelative(context, identifier); contextCache.set(identifier, relativePath); return relativePath; } }; webpack-3.5.6/lib/validateSchema.js000066400000000000000000000030321315401342100171470ustar00rootroot00000000000000/* 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); function validateSchema(schema, options) { if(Array.isArray(options)) { const errors = options.map((options) => validateObject(schema, options)); errors.forEach((list, idx) => { list.forEach(function applyPrefix(err) { err.dataPath = `[${idx}]${err.dataPath}`; if(err.children) { err.children.forEach(applyPrefix); } }); }); return errors.reduce((arr, items) => { return arr.concat(items); }, []); } else { return validateObject(schema, options); } } function validateObject(schema, options) { const validate = ajv.compile(schema); const valid = validate(options); return valid ? [] : filterErrors(validate.errors); } function filterErrors(errors) { let newErrors = []; errors.forEach((err) => { 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-3.5.6/lib/web/000077500000000000000000000000001315401342100144565ustar00rootroot00000000000000webpack-3.5.6/lib/web/WebEnvironmentPlugin.js000066400000000000000000000006211315401342100211340ustar00rootroot00000000000000/* 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-3.5.6/lib/webpack.js000066400000000000000000000127731315401342100156650ustar00rootroot00000000000000/* 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/webpackOptionsSchema.json"); function 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") { // TODO webpack 4: process returns options new WebpackOptionsDefaulter().process(options); compiler = new Compiler(); compiler.context = options.context; compiler.options = options; new NodeEnvironmentPlugin().apply(compiler); if(options.plugins && Array.isArray(options.plugins)) { compiler.apply.apply(compiler, options.plugins); } compiler.applyPlugins("environment"); compiler.applyPlugins("after-environment"); 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; webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; webpack.WebpackOptionsApply = WebpackOptionsApply; webpack.Compiler = Compiler; webpack.MultiCompiler = MultiCompiler; webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin; webpack.validate = validateSchema.bind(this, webpackOptionsSchema); webpack.validateSchema = validateSchema; webpack.WebpackOptionsValidationError = WebpackOptionsValidationError; function exportPlugins(obj, mappings) { Object.keys(mappings).forEach(name => { Object.defineProperty(obj, name, { configurable: false, enumerable: true, get: mappings[name] }); }); } exportPlugins(exports, { "DefinePlugin": () => require("./DefinePlugin"), "NormalModuleReplacementPlugin": () => require("./NormalModuleReplacementPlugin"), "ContextReplacementPlugin": () => require("./ContextReplacementPlugin"), "IgnorePlugin": () => require("./IgnorePlugin"), "WatchIgnorePlugin": () => require("./WatchIgnorePlugin"), "BannerPlugin": () => require("./BannerPlugin"), "PrefetchPlugin": () => require("./PrefetchPlugin"), "AutomaticPrefetchPlugin": () => require("./AutomaticPrefetchPlugin"), "ProvidePlugin": () => require("./ProvidePlugin"), "HotModuleReplacementPlugin": () => require("./HotModuleReplacementPlugin"), "SourceMapDevToolPlugin": () => require("./SourceMapDevToolPlugin"), "EvalSourceMapDevToolPlugin": () => require("./EvalSourceMapDevToolPlugin"), "EvalDevToolModulePlugin": () => require("./EvalDevToolModulePlugin"), "CachePlugin": () => require("./CachePlugin"), "ExtendedAPIPlugin": () => require("./ExtendedAPIPlugin"), "ExternalsPlugin": () => require("./ExternalsPlugin"), "JsonpTemplatePlugin": () => require("./JsonpTemplatePlugin"), "LibraryTemplatePlugin": () => require("./LibraryTemplatePlugin"), "LoaderTargetPlugin": () => require("./LoaderTargetPlugin"), "MemoryOutputFileSystem": () => require("./MemoryOutputFileSystem"), "ProgressPlugin": () => require("./ProgressPlugin"), "SetVarMainTemplatePlugin": () => require("./SetVarMainTemplatePlugin"), "UmdMainTemplatePlugin": () => require("./UmdMainTemplatePlugin"), "NoErrorsPlugin": () => require("./NoErrorsPlugin"), "NoEmitOnErrorsPlugin": () => require("./NoEmitOnErrorsPlugin"), "NewWatchingPlugin": () => require("./NewWatchingPlugin"), "EnvironmentPlugin": () => require("./EnvironmentPlugin"), "DllPlugin": () => require("./DllPlugin"), "DllReferencePlugin": () => require("./DllReferencePlugin"), "LoaderOptionsPlugin": () => require("./LoaderOptionsPlugin"), "NamedModulesPlugin": () => require("./NamedModulesPlugin"), "NamedChunksPlugin": () => require("./NamedChunksPlugin"), "HashedModuleIdsPlugin": () => require("./HashedModuleIdsPlugin"), "ModuleFilenameHelpers": () => require("./ModuleFilenameHelpers") }); exportPlugins(exports.optimize = {}, { "AggressiveMergingPlugin": () => require("./optimize/AggressiveMergingPlugin"), "AggressiveSplittingPlugin": () => require("./optimize/AggressiveSplittingPlugin"), "CommonsChunkPlugin": () => require("./optimize/CommonsChunkPlugin"), "ChunkModuleIdRangePlugin": () => require("./optimize/ChunkModuleIdRangePlugin"), "DedupePlugin": () => require("./optimize/DedupePlugin"), "LimitChunkCountPlugin": () => require("./optimize/LimitChunkCountPlugin"), "MinChunkSizePlugin": () => require("./optimize/MinChunkSizePlugin"), "ModuleConcatenationPlugin": () => require("./optimize/ModuleConcatenationPlugin"), "OccurrenceOrderPlugin": () => require("./optimize/OccurrenceOrderPlugin"), "UglifyJsPlugin": () => require("./optimize/UglifyJsPlugin") }); webpack-3.5.6/lib/webpack.web.js000066400000000000000000000016771315401342100164420ustar00rootroot00000000000000/* 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"); function webpack(options, callback) { new WebpackOptionsDefaulter().process(options); const compiler = new Compiler(); compiler.options = options; 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-3.5.6/lib/webworker/000077500000000000000000000000001315401342100157105ustar00rootroot00000000000000webpack-3.5.6/lib/webworker/WebWorkerChunkTemplatePlugin.js000066400000000000000000000016351315401342100240260ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; const Template = require("../Template"); class WebWorkerChunkTemplatePlugin { apply(chunkTemplate) { chunkTemplate.plugin("render", function(modules, chunk) { const chunkCallbackName = this.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (this.outputOptions.library || "")); const source = new ConcatSource(); source.add(`${chunkCallbackName}(${JSON.stringify(chunk.ids)},`); source.add(modules); source.add(")"); return source; }); chunkTemplate.plugin("hash", function(hash) { hash.update("webworker"); hash.update("3"); hash.update(`${this.outputOptions.chunkCallbackName}`); hash.update(`${this.outputOptions.library}`); }); } } module.exports = WebWorkerChunkTemplatePlugin; webpack-3.5.6/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js000066400000000000000000000020171315401342100256370ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const ConcatSource = require("webpack-sources").ConcatSource; const Template = require("../Template"); class WebWorkerHotUpdateChunkTemplatePlugin { apply(hotUpdateChunkTemplate) { hotUpdateChunkTemplate.plugin("render", function(modulesSource, modules, removedModules, hash, id) { const chunkCallbackName = this.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (this.outputOptions.library || "")); const source = new ConcatSource(); source.add(chunkCallbackName + "(" + JSON.stringify(id) + ","); source.add(modulesSource); source.add(")"); return source; }); hotUpdateChunkTemplate.plugin("hash", function(hash) { hash.update("WebWorkerHotUpdateChunkTemplatePlugin"); hash.update("3"); hash.update(this.outputOptions.hotUpdateFunction + ""); hash.update(this.outputOptions.library + ""); }); } } module.exports = WebWorkerHotUpdateChunkTemplatePlugin; webpack-3.5.6/lib/webworker/WebWorkerMainTemplate.runtime.js000066400000000000000000000036331315401342100241450ustar00rootroot00000000000000/* 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() { function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars hotAddUpdateChunk(chunkId, moreModules); if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } //$semicolon function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars importScripts($require$.p + $hotChunkFilename$); } function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars 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); } }; }); } function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars delete installedChunks[chunkId]; } }; webpack-3.5.6/lib/webworker/WebWorkerMainTemplatePlugin.js000066400000000000000000000075371315401342100236510ustar00rootroot00000000000000/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Template = require("../Template"); class WebWorkerMainTemplatePlugin { apply(mainTemplate) { mainTemplate.plugin("local-vars", function(source, chunk) { if(chunk.chunks.length > 0) { return this.asString([ source, "", "// object to store loaded chunks", "// \"1\" means \"already loaded\"", "var installedChunks = {", this.indent( chunk.ids.map((id) => `${id}: 1`).join(",\n") ), "};" ]); } return source; }); mainTemplate.plugin("require-ensure", function(_, chunk, hash) { const chunkFilename = this.outputOptions.chunkFilename; return this.asString([ "return new Promise(function(resolve) {", this.indent([ "// \"1\" is the signal for \"already loaded\"", "if(!installedChunks[chunkId]) {", this.indent([ "importScripts(" + this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, chunk: { id: "\" + chunkId + \"" } }) + ");" ]), "}", "resolve();" ]), "});" ]); }); mainTemplate.plugin("bootstrap", function(source, chunk, hash) { if(chunk.chunks.length > 0) { const chunkCallbackName = this.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (this.outputOptions.library || "")); return this.asString([ source, `this[${JSON.stringify(chunkCallbackName)}] = function webpackChunkCallback(chunkIds, moreModules) {`, this.indent([ "for(var moduleId in moreModules) {", this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")), "}", "while(chunkIds.length)", this.indent("installedChunks[chunkIds.pop()] = 1;") ]), "};" ]); } return source; }); mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) { const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename; const hotUpdateFunction = this.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (this.outputOptions.library || "")); const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, chunk: { id: "\" + chunkId + \"" } }); const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), { hash: `" + ${this.renderCurrentHashCode(hash)} + "`, hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`, }); return source + "\n" + `var parentHotUpdateCallback = this[${JSON.stringify(hotUpdateFunction)}];\n` + `this[${JSON.stringify(hotUpdateFunction)}] = ` + Template.getFunctionContent(require("./WebWorkerMainTemplate.runtime.js")) .replace(/\/\/\$semicolon/g, ";") .replace(/\$require\$/g, this.requireFn) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) .replace(/\$hash\$/g, JSON.stringify(hash)); }); mainTemplate.plugin("hash", function(hash) { hash.update("webworker"); hash.update("3"); hash.update(`${this.outputOptions.publicPath}`); hash.update(`${this.outputOptions.filename}`); hash.update(`${this.outputOptions.chunkFilename}`); hash.update(`${this.outputOptions.chunkCallbackName}`); hash.update(`${this.outputOptions.library}`); }); } } module.exports = WebWorkerMainTemplatePlugin; webpack-3.5.6/lib/webworker/WebWorkerTemplatePlugin.js000066400000000000000000000013731315401342100230340ustar00rootroot00000000000000/* 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.plugin("this-compilation", compilation => { compilation.mainTemplate.apply(new WebWorkerMainTemplatePlugin()); compilation.chunkTemplate.apply(new WebWorkerChunkTemplatePlugin()); compilation.hotUpdateChunkTemplate.apply(new WebWorkerHotUpdateChunkTemplatePlugin()); }); } } module.exports = WebWorkerTemplatePlugin; webpack-3.5.6/open-bot.yaml000066400000000000000000000243501315401342100155460ustar00rootroot00000000000000bot: "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 mocha 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=test fetch: travis_job.log string_cleanup: id: logResult value: "{{{fetch}}}" remove: - "^[\\s\\S]+?\\d+\\s+pending\n+" - "npm ERR!.*\n" - "\n*=============================================================================\n[\\s\\S]*" actions: comment: identifier: "ci-result" message: |- @{{commit.author.login}} Please review the following output log for errors: ``` text {{{logResult}}} ``` See [complete report here]({{status.target_url}}). set: id: report_ci value: nope # Report specific error message if linting fails - filters: ensure: value: "{{report_ci}}" equals: yep commit: true status: context: "continuous-integration/travis-ci/pr" travis_job: state: "failed" config: env: JOB_PART=lint fetch: travis_job.log string_cleanup: id: logResult value: "{{{fetch}}}" remove: - "^[\\s\\S]+?npm run travis:\\$JOB_PART\n*" - "npm ERR!.*\n" - "\n*The command \"npm run travis:\\$JOB_PART\" exited [\\s\\S]*" actions: comment: identifier: "ci-result" message: |- @{{commit.author.login}} The tests look fine, but there are code style issue in your Pull Request. Please review the following: ``` text {{{logResult}}} ``` 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 codedov 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" 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" ensure: value: "{{status.state}}" equals: "failure" actions: label: add: "PR: tests-needed" - filters: open: true pull_request: mergeable: true status: context: "codecov/patch" 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 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 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 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 label to pull request to other branch - filters: pull_request: base_ref: "^(?!master)" actions: label: "PR: non-master" # add small label to small pull requests - filters: open: true pull_request: additions: "<= 10" deletions: "<= 10" changed_files: "<= 2" actions: label: "PR: small" # 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.* # 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}}. Orginal 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. # Check issues every week - filters: open: true actions: schedule: 1d webpack-3.5.6/package.json000066400000000000000000000101561315401342100154240ustar00rootroot00000000000000{ "name": "webpack", "version": "3.5.6", "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.", "dependencies": { "acorn": "^5.0.0", "acorn-dynamic-import": "^2.0.0", "ajv": "^5.1.5", "ajv-keywords": "^2.0.0", "async": "^2.1.2", "enhanced-resolve": "^3.4.0", "escope": "^3.6.0", "interpret": "^1.0.0", "json-loader": "^0.5.4", "json5": "^0.5.1", "loader-runner": "^2.3.0", "loader-utils": "^1.1.0", "memory-fs": "~0.4.1", "mkdirp": "~0.5.0", "node-libs-browser": "^2.0.0", "source-map": "^0.5.3", "supports-color": "^4.2.1", "tapable": "^0.2.7", "uglifyjs-webpack-plugin": "^0.4.6", "watchpack": "^1.4.0", "webpack-sources": "^1.0.1", "yargs": "^8.0.2" }, "license": "MIT", "devDependencies": { "beautify-lint": "^1.0.3", "benchmark": "^2.1.1", "bundle-loader": "~0.5.0", "codacy-coverage": "^2.0.1", "codecov.io": "^0.1.2", "coffee-loader": "~0.7.1", "coffee-script": "^1.10.0", "coveralls": "^2.11.2", "css-loader": "^0.28.3", "es6-promise-polyfill": "^1.1.1", "eslint": "^4.3.0", "eslint-plugin-node": "^5.1.1", "express": "~4.13.1", "extract-text-webpack-plugin": "^3.0.0", "file-loader": "^0.11.2", "i18n-webpack-plugin": "^1.0.0", "istanbul": "^0.4.5", "jade": "^1.11.0", "jade-loader": "~0.8.0", "js-beautify": "^1.5.10", "less": "^2.5.1", "less-loader": "^4.0.3", "lodash": "^4.17.4", "mocha": "^3.2.0", "mocha-lcov-reporter": "^1.0.0", "nsp": "^2.6.1", "raw-loader": "~0.5.0", "react": "^15.2.1", "react-dom": "^15.2.1", "script-loader": "~0.7.0", "should": "^11.1.1", "simple-git": "^1.65.0", "sinon": "^2.3.2", "style-loader": "^0.18.1", "url-loader": "~0.5.0", "val-loader": "^1.0.2", "vm-browserify": "~0.0.0", "webpack-dev-middleware": "^1.9.0", "worker-loader": "^0.8.0" }, "engines": { "node": ">=4.3.0 <5.0.0 || >=5.10" }, "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/", "hot/", "web_modules/", "schemas/" ], "scripts": { "test": "mocha test/*.test.js --max-old-space-size=4096 --harmony --check-leaks", "travis:test": "npm run cover:min", "travis:lint": "npm run lint-files && npm run nsp", "travis:benchmark": "npm run benchmark", "appveyor:test": "node node_modules\\mocha\\bin\\mocha --max-old-space-size=4096 --harmony test/*.test.js", "appveyor:benchmark": "npm run benchmark", "circleci:test": "node node_modules/mocha/bin/mocha --max-old-space-size=4096 --harmony test/*.test.js", "circleci:lint": "npm run lint-files && npm run nsp", "build:examples": "cd examples && node buildAll.js", "pretest": "npm run lint-files", "lint-files": "npm run lint && npm run beautify-lint", "lint": "eslint lib bin hot buildin \"test/**/webpack.config.js\" \"test/binCases/**/test.js\" \"examples/**/webpack.config.js\"", "fix": "npm run lint -- --fix", "beautify-lint": "beautify-lint \"lib/**/*.js\" \"hot/**/*.js\" \"bin/**/*.js\" \"benchmark/*.js\" \"test/*.js\"", "nsp": "nsp check --output summary", "benchmark": "mocha --max-old-space-size=4096 --harmony test/*.benchmark.js -R spec", "cover": "node --max-old-space-size=4096 --harmony ./node_modules/istanbul/lib/cli.js cover -x '**/*.runtime.js' node_modules/mocha/bin/_mocha -- test/*.test.js", "cover:min": "node --max-old-space-size=4096 --harmony ./node_modules/.bin/istanbul cover -x '**/*.runtime.js' --report lcovonly node_modules/mocha/bin/_mocha -- test/*.test.js", "publish-patch": "npm run lint && npm run beautify-lint && mocha && npm version patch && git push && git push --tags && npm publish" } } webpack-3.5.6/schemas/000077500000000000000000000000001315401342100145565ustar00rootroot00000000000000webpack-3.5.6/schemas/ajv.absolutePath.js000066400000000000000000000014141315401342100203260ustar00rootroot00000000000000"use strict"; 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 { keyword: "absolutePath", params: { absolutePath: data }, message: message, parentSchema: schema, }; }; module.exports = (ajv) => ajv.addKeyword("absolutePath", { errors: true, type: "string", compile(expected, schema) { function callback(data) { const passes = expected === /^(?:[A-Za-z]:\\|\/)/.test(data); if(!passes) { callback.errors = [getErrorFor(expected, data, schema)]; } return passes; } callback.errors = []; return callback; } }); webpack-3.5.6/schemas/webpackOptionsSchema.json000066400000000000000000000762051315401342100215740ustar00rootroot00000000000000{ "additionalProperties": false, "definitions": { "common.arrayOfStringOrStringArrayValues": { "items": { "anyOf": [ { "minLength": 1, "type": "string" }, { "items": { "minLength": 1, "type": "string" }, "type": "array" } ] }, "type": "array" }, "common.arrayOfStringValues": { "items": { "minLength": 1, "type": "string" }, "type": "array" }, "common.nonEmptyArrayOfUniqueStringValues": { "items": { "minLength": 1, "type": "string" }, "minItems": 1, "type": "array", "uniqueItems": true }, "entry": { "description": "The entry point(s) of the compilation.", "oneOf": [ { "minProperties": 1, "additionalProperties": { "oneOf": [ { "description": "The string is resolved to a module which is loaded upon startup.", "minLength": 1, "type": "string" }, { "description": "All modules are loaded upon startup. The last one is exported.", "$ref": "#/definitions/common.nonEmptyArrayOfUniqueStringValues" } ] }, "description": "Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.", "type": "object" }, { "description": "The string is resolved to a module which is loaded upon startup.", "minLength": 1, "type": "string" }, { "allOf": [ { "$ref": "#/definitions/common.nonEmptyArrayOfUniqueStringValues" } ], "description": "All modules are loaded upon startup. The last one is exported." }, { "description": "function returning an entry object or a promise.", "instanceof": "Function" } ] }, "externals": { "anyOf": [ { "description": "An exact matched dependency becomes external. The same string is used as external dependency.", "type": "string" }, { "additionalProperties": { "anyOf": [ { "type": "string" }, { "type": "object" }, { "type": "boolean" } ] }, "description": "If an dependency matches exactly a property of the object, the property value is used as dependency.", "type": "object" }, { "description": "`function(context, request, callback(err, result))` The function is called on each dependency.", "instanceof": "Function" }, { "description": "Every matched dependency becomes external.", "instanceof": "RegExp" }, { "items": { "$ref": "#/definitions/externals" }, "type": "array" } ], "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`." }, "module": { "additionalProperties": false, "description": "Options affecting the normal modules (`NormalModuleFactory`).", "properties": { "exprContextCritical": { "type": "boolean" }, "exprContextRecursive": { "type": "boolean" }, "exprContextRegExp": { "anyOf": [ { "type": "boolean" }, { "instanceof": "RegExp" } ] }, "exprContextRequest": { "type": "string" }, "loaders": { "allOf": [ { "$ref": "#/definitions/ruleSet-rules" } ], "description": "An array of automatically applied loaders." }, "noParse": { "description": "Don't parse files matching. It's matched against the full resolved request.", "anyOf": [ { "items": { "instanceof": "RegExp" }, "minItems": 1, "type": "array" }, { "instanceof": "RegExp" }, { "instanceof": "Function" }, { "items": { "type": "string", "absolutePath": true }, "minItems": 1, "type": "array" }, { "type": "string", "absolutePath": true } ] }, "rules": { "allOf": [ { "$ref": "#/definitions/ruleSet-rules" } ], "description": "An array of rules applied for modules." }, "unknownContextCritical": { "type": "boolean" }, "unknownContextRecursive": { "type": "boolean" }, "unknownContextRegExp": { "anyOf": [ { "type": "boolean" }, { "instanceof": "RegExp" } ] }, "unknownContextRequest": { "type": "string" }, "unsafeCache": { "anyOf": [ { "type": "boolean" }, { "instanceof": "Function" } ] }, "wrappedContextCritical": { "type": "boolean" }, "wrappedContextRecursive": { "type": "boolean" }, "wrappedContextRegExp": { "instanceof": "RegExp" }, "strictExportPresence": { "type": "boolean" }, "strictThisContextOnImports": { "type": "boolean" } }, "type": "object" }, "output": { "additionalProperties": false, "description": "Options affecting the output of the compilation. `output` options tell webpack how to write the compiled files to disk.", "properties": { "auxiliaryComment": { "description": "Add a comment in the UMD wrapper.", "anyOf": [ { "description": "Append the same comment above each import style.", "type": "string" }, { "additionalProperties": false, "description": "Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.", "properties": { "amd": { "type": "string" }, "commonjs": { "type": "string" }, "commonjs2": { "type": "string" }, "root": { "type": "string" } }, "type": "object" } ] }, "chunkFilename": { "description": "The filename of non-entry chunks as relative path inside the `output.path` directory.", "type": "string", "absolutePath": false }, "crossOriginLoading": { "description": "This option enables cross-origin loading of chunks.", "enum": [ false, "anonymous", "use-credentials" ] }, "chunkLoadTimeout": { "description": "Number of milliseconds before chunk request expires", "type": "number" }, "devtoolFallbackModuleFilenameTemplate": { "description": "Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.", "anyOf": [ { "type": "string" }, { "instanceof": "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.", "properties": { "exclude": { "type": "string" }, "include": { "type": "string" }, "test": { "type": "string" } }, "type": "object" } ] }, "devtoolModuleFilenameTemplate": { "description": "Filename template string of function for the sources array in a generated SourceMap.", "anyOf": [ { "type": "string" }, { "instanceof": "Function" } ] }, "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.", "type": "string", "absolutePath": false }, "hashDigest": { "minLength": 1, "type": "string" }, "hashDigestLength": { "minimum": 1, "type": "number" }, "hashFunction": { "minLength": 1, "type": "string" }, "hashSalt": { "minLength": 1, "type": "string" }, "hotUpdateChunkFilename": { "description": "The filename of the Hot Update Chunks. They are inside the output.path directory.", "type": "string", "absolutePath": false }, "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.", "type": "string", "absolutePath": false }, "jsonpFunction": { "description": "The JSONP function used by webpack for async loading of chunks.", "type": "string" }, "library": { "anyOf": [ { "type": "string" }, { "items": { "type": "string" }, "type": "array" }, { "type": "object", "properties": { "root": { "type": "string" }, "amd": { "type": "string" }, "commonjs": { "type": "string" } } } ], "description": "If set, export the bundle as library. `output.library` is the name." }, "libraryTarget": { "enum": [ "var", "assign", "this", "window", "global", "commonjs", "commonjs2", "commonjs-module", "amd", "umd", "umd2", "jsonp" ] }, "libraryExport": { "anyOf": [ { "type": "string" }, { "$ref": "#/definitions/common.arrayOfStringValues" } ] }, "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.", "type": "string" }, "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" } }, "type": "object" }, "resolve": { "additionalProperties": false, "properties": { "alias": { "anyOf": [ { "additionalProperties": { "type": "string" }, "type": "object" }, { "items": { "additionalProperties": false, "properties": { "alias": { "type": "string" }, "name": { "type": "string" }, "onlyModule": { "type": "boolean" } }, "type": "object" }, "type": "array" } ] }, "aliasFields": { "$ref": "#/definitions/common.arrayOfStringOrStringArrayValues" }, "cachePredicate": { "instanceof": "Function" }, "cacheWithContext": { "type": "boolean" }, "descriptionFiles": { "$ref": "#/definitions/common.arrayOfStringValues" }, "enforceExtension": { "type": "boolean" }, "enforceModuleExtension": { "type": "boolean" }, "extensions": { "$ref": "#/definitions/common.arrayOfStringValues" }, "fileSystem": {}, "mainFields": { "$ref": "#/definitions/common.arrayOfStringOrStringArrayValues" }, "mainFiles": { "$ref": "#/definitions/common.arrayOfStringValues" }, "moduleExtensions": { "$ref": "#/definitions/common.arrayOfStringValues" }, "modules": { "$ref": "#/definitions/common.arrayOfStringValues" }, "plugins": { "type": "array" }, "resolver": {}, "symlinks": { "type": "boolean" }, "unsafeCache": { "anyOf": [ { "type": "boolean" }, { "additionalProperties": true, "type": "object" } ] }, "useSyncFileSystemCalls": { "type": "boolean" } }, "type": "object" }, "ruleSet-condition": { "anyOf": [ { "instanceof": "RegExp" }, { "minLength": 1, "type": "string" }, { "instanceof": "Function" }, { "$ref": "#/definitions/ruleSet-conditions" }, { "additionalProperties": false, "properties": { "and": { "$ref": "#/definitions/ruleSet-conditions" }, "exclude": { "$ref": "#/definitions/ruleSet-condition" }, "include": { "$ref": "#/definitions/ruleSet-condition" }, "not": { "$ref": "#/definitions/ruleSet-conditions" }, "or": { "$ref": "#/definitions/ruleSet-conditions" }, "test": { "$ref": "#/definitions/ruleSet-condition" } }, "type": "object" } ] }, "ruleSet-conditions": { "items": { "$ref": "#/definitions/ruleSet-condition" }, "type": "array" }, "ruleSet-loader": { "minLength": 1, "type": "string" }, "ruleSet-query": { "anyOf": [ { "type": "object" }, { "type": "string" } ] }, "ruleSet-rule": { "additionalProperties": false, "properties": { "enforce": { "enum": [ "pre", "post" ] }, "exclude": { "allOf": [ { "$ref": "#/definitions/ruleSet-condition" }, { "absolutePath": true } ] }, "include": { "allOf": [ { "$ref": "#/definitions/ruleSet-condition" }, { "absolutePath": true } ] }, "issuer": { "allOf": [ { "$ref": "#/definitions/ruleSet-condition" }, { "absolutePath": true } ] }, "loader": { "anyOf": [ { "$ref": "#/definitions/ruleSet-loader" }, { "$ref": "#/definitions/ruleSet-use" } ] }, "loaders": { "$ref": "#/definitions/ruleSet-use" }, "oneOf": { "$ref": "#/definitions/ruleSet-rules" }, "options": { "$ref": "#/definitions/ruleSet-query" }, "parser": { "additionalProperties": true, "type": "object" }, "query": { "$ref": "#/definitions/ruleSet-query" }, "resource": { "allOf": [ { "$ref": "#/definitions/ruleSet-condition" }, { "absolutePath": true } ] }, "resourceQuery": { "$ref": "#/definitions/ruleSet-condition" }, "compiler": { "$ref": "#/definitions/ruleSet-condition" }, "rules": { "$ref": "#/definitions/ruleSet-rules" }, "test": { "allOf": [ { "$ref": "#/definitions/ruleSet-condition" }, { "absolutePath": true } ] }, "use": { "$ref": "#/definitions/ruleSet-use" } }, "type": "object" }, "ruleSet-rules": { "items": { "$ref": "#/definitions/ruleSet-rule" }, "type": "array" }, "ruleSet-use": { "anyOf": [ { "$ref": "#/definitions/ruleSet-use-item" }, { "instanceof": "Function" }, { "items": { "$ref": "#/definitions/ruleSet-use-item" }, "type": "array" } ] }, "ruleSet-use-item": { "anyOf": [ { "$ref": "#/definitions/ruleSet-loader" }, { "instanceof": "Function" }, { "additionalProperties": false, "properties": { "loader": { "$ref": "#/definitions/ruleSet-loader" }, "options": { "$ref": "#/definitions/ruleSet-query" }, "query": { "$ref": "#/definitions/ruleSet-query" } }, "type": "object" } ] }, "filter-item-types": { "anyOf": [ { "instanceof": "RegExp" }, { "type": "string" }, { "instanceof": "Function" } ] }, "filter-types": { "anyOf": [ { "$ref": "#/definitions/filter-item-types" }, { "type": "array", "items": { "$ref": "#/definitions/filter-item-types" } } ] } }, "properties": { "amd": { "description": "Set the value of `require.amd` and `define.amd`." }, "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.", "items": { "type": "string" }, "type": "array" }, "devServer": { "type": "object" }, "devtool": { "description": "A developer tool to enhance debugging.", "anyOf": [ { "type": "string" }, { "enum": [ false ] } ] }, "entry": { "$ref": "#/definitions/entry" }, "externals": { "$ref": "#/definitions/externals" }, "loader": { "description": "Custom values available in the loader context.", "type": "object" }, "module": { "$ref": "#/definitions/module" }, "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 ] }, { "additionalProperties": { "enum": [ false, true, "mock", "empty" ] }, "properties": { "Buffer": { "enum": [ false, true, "mock" ] }, "__dirname": { "enum": [ false, true, "mock" ] }, "__filename": { "enum": [ false, true, "mock" ] }, "console": { "enum": [ false, true, "mock" ] }, "global": { "type": "boolean" }, "process": { "enum": [ false, true, "mock" ] } }, "type": "object" } ] }, "output": { "$ref": "#/definitions/output" }, "parallelism": { "description": "The number of parallel processed modules in the compilation.", "minimum": 1, "type": "number" }, "performance": { "description": "Configuration for web performance recommendations.", "anyOf": [ { "enum": [ false ] }, { "additionalProperties": false, "properties": { "assetFilter": { "description": "Filter function to select assets that are checked", "instanceof": "Function" }, "hints": { "description": "Sets the format of the hints: warnings, errors or nothing at all", "enum": [ false, "warning", "error" ] }, "maxEntrypointSize": { "description": "Total size of an entry point (in bytes)", "type": "number" }, "maxAssetSize": { "description": "Filesize limit (in bytes) when exceeded, that webpack will provide performance hints", "type": "number" } }, "type": "object" } ] }, "plugins": { "description": "Add additional plugins to the compiler.", "type": "array" }, "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": { "$ref": "#/definitions/resolve" }, "resolveLoader": { "$ref": "#/definitions/resolve" }, "stats": { "description": "Used by the webpack CLI program to pass stats options.", "anyOf": [ { "type": "object", "properties": { "context": { "type": "string", "description": "context directory for request shortening", "absolutePath": true }, "hash": { "type": "boolean", "description": "add the hash of the compilation" }, "version": { "type": "boolean", "description": "add webpack version information" }, "timings": { "type": "boolean", "description": "add timing information" }, "assets": { "type": "boolean", "description": "add assets information" }, "chunks": { "type": "boolean", "description": "add chunk information" }, "chunkModules": { "type": "boolean", "description": "add built modules information to chunk information" }, "modules": { "type": "boolean", "description": "add built modules information" }, "children": { "type": "boolean", "description": "add children information" }, "cached": { "type": "boolean", "description": "add also information about cached (not built) modules" }, "reasons": { "type": "boolean", "description": "add information about the reasons why modules are included" }, "source": { "type": "boolean", "description": "add the source code of modules" }, "warningsFilter": { "description": "Suppress warnings that match the specified filters. Filters can be Strings, RegExps or Functions", "$ref": "#/definitions/filter-types" }, "excludeAssets": { "description": "Suppress assets that match the specified filters. Filters can be Strings, RegExps or Functions", "$ref": "#/definitions/filter-types" }, "excludeModules": { "description": "Suppress modules that match the specified filters. Filters can be Strings, RegExps or Functions", "$ref": "#/definitions/filter-types" }, "exclude": { "description": "Please use excludeModules instead.", "$ref": "#/definitions/filter-types" }, "errorDetails": { "type": "boolean", "description": "add details to errors (like resolving log)" }, "chunkOrigins": { "type": "boolean", "description": "add the origins of chunks and chunk merging info" }, "modulesSort": { "type": "string", "description": "sort the modules by that field" }, "moduleTrace": { "type": "boolean", "description": "add dependencies and origin of warnings/errors" }, "chunksSort": { "type": "string", "description": "sort the chunks by that field" }, "assetsSort": { "type": "string", "description": "sort the assets by that field" }, "providedExports": { "type": "boolean", "description": "show exports provided by modules" }, "usedExports": { "type": "boolean", "description": "show exports used by modules" }, "optimizationBailout": { "type": "boolean", "description": "show reasons why optimization bailed out for modules" } } }, { "type": "boolean" }, { "enum": [ "none", "errors-only", "minimal", "normal", "detailed", "verbose" ] } ] }, "target": { "anyOf": [ { "enum": [ "web", "webworker", "node", "async-node", "node-webkit", "atom", "electron", "electron-main", "electron-renderer" ] }, { "instanceof": "Function" } ] }, "watch": { "description": "Enter watch mode, which rebuilds on file change.", "type": "boolean" }, "watchOptions": { "properties": { "aggregateTimeout": { "description": "Delay the rebuilt after the first change. Value is a time in ms.", "type": "number" }, "poll": { "anyOf": [ { "description": "`true`: use polling.", "type": "boolean" }, { "description": "`number`: use polling with specified interval.", "type": "number" } ] } }, "type": "object" } }, "required": [ "entry" ], "type": "object" } webpack-3.5.6/test/000077500000000000000000000000001315401342100141125ustar00rootroot00000000000000webpack-3.5.6/test/AmdMainTemplatePlugin.test.js000066400000000000000000000123141315401342100216100ustar00rootroot00000000000000/* global describe, beforeEach, it */ "use strict"; const should = require("should"); const sinon = require("sinon"); const TemplatePluginEnvironment = require("./helpers/TemplatePluginEnvironment"); const ConcatSource = require("webpack-sources").ConcatSource; const AmdMainTemplatePlugin = require("../lib/AmdMainTemplatePlugin"); describe("AmdMainTemplatePlugin", () => { let env; const applyTemplatePluginWithOptions = function(Plugin, name) { const plugin = new Plugin(name); const templatePluginEnvironment = new TemplatePluginEnvironment(); const environment = templatePluginEnvironment.getEnvironmentStub(); environment.mainTemplate.applyPluginsWaterfall = () => "templateName"; plugin.apply(environment); return templatePluginEnvironment; }; const setupPluginAndGetEventBinding = function(name) { const templatePlugin = applyTemplatePluginWithOptions(AmdMainTemplatePlugin, name); const eventBindings = templatePlugin.getEventBindings(); return eventBindings[0]; }; beforeEach(() => { env = { modulesListWithExternals: [{ id: "module-1", external: true, request: { amd: "external-amd-module" } }, { id: "module-2", external: true, request: "external-non-amd-module" }, { id: "module-3", external: true }, { id: "module-4", external: false }] }; }); it("has apply function", () => new AmdMainTemplatePlugin().apply.should.be.a.Function()); describe("when applied", () => { beforeEach(() => env.templatePlugin = applyTemplatePluginWithOptions(AmdMainTemplatePlugin, "foo")); describe("event handlers", () => { beforeEach(() => env.eventBindings = env.templatePlugin.getEventBindings()); it("binds one handlers", () => env.eventBindings.length.should.be.exactly(1)); describe("render-with-entry handler", () => { beforeEach(() => env.eventBinding = env.eventBindings[0]); it("binds to render-with-entry event", () => env.eventBinding.name.should.be.exactly("render-with-entry")); describe("with name", () => { beforeEach(() => { env.chunk = { getModules: () => env.modulesListWithExternals }; env.eventBinding = setupPluginAndGetEventBinding("foo"); }); it("creates source wrapper with module name and external dependencies", () => { const source = env.eventBinding.handler("moduleSource()", env.chunk, "bar"); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("define(\"templateName\", [\"external-amd-module\",\"external-non-amd-module\",null], function(__WEBPACK_EXTERNAL_MODULE_module_1__, __WEBPACK_EXTERNAL_MODULE_module_2__, __WEBPACK_EXTERNAL_MODULE_module_3__) { return moduleSource()});"); }); }); describe("with external dependencies", () => { beforeEach(() => { env.chunk = { getModules: () => env.modulesListWithExternals }; env.eventBinding = setupPluginAndGetEventBinding(); }); it("creates source wrapper with external dependencies", () => { const source = env.eventBinding.handler("moduleSource()", env.chunk, "bar"); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("define([\"external-amd-module\",\"external-non-amd-module\",null], function(__WEBPACK_EXTERNAL_MODULE_module_1__, __WEBPACK_EXTERNAL_MODULE_module_2__, __WEBPACK_EXTERNAL_MODULE_module_3__) { return moduleSource()});"); }); }); describe("with only local dependencies", () => { beforeEach(() => { const externalFlag = { external: false }; const noExternals = env.modulesListWithExternals.map((module) => Object.assign(module, externalFlag)); env.chunk = { getModules: () => env.modulesListWithExternals }; env.eventBinding = setupPluginAndGetEventBinding(); }); it("creates source wrapper with callback only", () => { const source = env.eventBinding.handler("moduleSource()", env.chunk, "bar"); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("define(function() { return moduleSource()});"); }); }); }); }); describe("main template event handlers", () => { beforeEach(() => env.mainTemplateBindings = env.templatePlugin.getMainTemplateBindings()); it("binds two handlers", () => env.mainTemplateBindings.length.should.be.exactly(2)); describe("global-hash-paths handler", () => { beforeEach(() => env.mainTemplateBinding = env.mainTemplateBindings[0]); it("binds to global-hash-paths event", () => env.mainTemplateBinding.name.should.be.exactly("global-hash-paths")); it("adds name to path array", () => env.mainTemplateBinding.handler([]).should.deepEqual(["foo"])); }); describe("hash handler", () => { beforeEach(() => env.mainTemplateBinding = env.mainTemplateBindings[1]); it("binds to hash event", () => env.mainTemplateBinding.name.should.be.exactly("hash")); it("updates hash", () => { const hash = { update: sinon.spy() }; env.mainTemplateBinding.handler(hash); hash.update.callCount.should.be.exactly(2); hash.update.firstCall.args[0].should.be.exactly("exports amd"); hash.update.secondCall.args[0].should.be.exactly("foo"); }); }); }); }); }); webpack-3.5.6/test/BenchmarkTestCases.benchmark.js000066400000000000000000000163251315401342100221210ustar00rootroot00000000000000"use strict"; const should = require("should"); const path = require("path"); const fs = require("fs"); const asyncLib = require("async"); var Test = require("mocha/lib/test"); const webpack = require("../lib/webpack"); const Benchmark = require("benchmark"); 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) {} try { fs.mkdirSync(baselinesPath); } catch(e) {} before(function(done) { this.timeout(270000); 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) {} 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); doLoadWebpack(); }); }); }); } function doLoadWebpack() { const baselineWebpack = require(path.resolve(baselinePath, "lib/webpack.js")); baselines.push({ name: baselineInfo.name, rev: baselineRevision, webpack: baselineWebpack }); callback(); } }, done) }); }); 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.920, 2.353, 2.132, 2.015, 1.943, 1.895, 1.860, 1.833, 1.812, 1.796, 1.782, 1.771, 1.761, 1.753, 1.746, 1.740, 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.660, 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 }); }); } tests.forEach(testName => { const testDirectory = path.join(casesPath, testName); let headStats = null; const suite = describe(testName, function() {}); it(`${testName} create benchmarks`, function() { baselines.forEach(baseline => { let baselineStats = null; function it(title, fn) { const test = new Test(title, fn); suite.addTest(test); } it(`should benchmark ${baseline.name} (${baseline.rev})`, function(done) { this.timeout(180000); const outputDirectory = path.join(__dirname, "js", "benchmark", `baseline-${baseline.name}`, testName); const config = Object.create(require(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); console.log(` ${baseline.name} ${stats.text}`); if(baseline.name === "HEAD") headStats = stats; else baselineStats = stats; done(); }); }); 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-3.5.6/test/BinTestCases.test.js000066400000000000000000000075621315401342100177670ustar00rootroot00000000000000/* globals describe it before */ "use strict"; const should = require("should"); const path = require("path"); const fs = require("fs"); const spawn = require("child_process").spawn; function loadOptsFile(optsPath) { // Options file parser from Mocha // https://github.com/mochajs/mocha/blob/2bb2b9fa35818db7a02e5068364b0c417436b1af/bin/options.js#L25-L31 return fs.readFileSync(optsPath, "utf8") .replace(/\\\s/g, "%20") .split(/\s/) .filter(Boolean) .map(function(value) { return value.replace(/%20/g, " "); }); } function getTestSpecificArguments(testDirectory) { try { return loadOptsFile(path.join(testDirectory, "test.opts")); } catch(e) { return null; } } function convertToArrayOfLines(outputArray) { if(outputArray.length === 0) return outputArray; return outputArray.join("").split("\n"); } const casesPath = path.join(__dirname, "binCases"); const defaultArgs = loadOptsFile(path.join(casesPath, "test.opts")); describe("BinTestCases", function() { const categoryDirectories = fs.readdirSync(casesPath).filter((folder) => { return fs.statSync(path.join(casesPath, folder)).isDirectory(); }); const categories = categoryDirectories.map(function(categoryDirectory) { return { name: categoryDirectory, tests: fs.readdirSync(path.join(casesPath, categoryDirectory)) }; }); categories.forEach(function(category) { describe(category.name, function() { category.tests.forEach(function(testName) { const testDirectory = path.join(casesPath, category.name, testName); const testArgs = getTestSpecificArguments(testDirectory) || defaultArgs; const testAssertions = require(path.join(testDirectory, "test.js")); const outputPath = path.join(path.resolve(casesPath, "../js/bin"), category.name, testName); const cmd = `${path.resolve(process.cwd(), "bin/webpack.js")}`; const args = testArgs.concat(["--output-path", `${outputPath}`]); const opts = { cwd: path.resolve("./", testDirectory) }; const asyncExists = fs.existsSync(path.join(testDirectory, "async")); const env = { stdout: [], stderr: [], error: [] }; if(asyncExists) { describe(testName, function() { it("should run successfully", function(done) { this.timeout(10000); const child = spawn(process.execPath, [cmd].concat(args), opts); child.on("close", function(code) { env.code = code; }); child.on("error", function(error) { env.error.push(error); }); child.stdout.on("data", (data) => { env.stdout.push(data); }); child.stderr.on("data", (data) => { env.stderr.push(data); }); setTimeout(() => { if(env.code) { done(`Watch didn't run ${env.error}`); } const stdout = convertToArrayOfLines(env.stdout); const stderr = convertToArrayOfLines(env.stderr); testAssertions(stdout, stderr, done); child.kill(); }, 3000); // wait a little to get an output }); }); } else { describe(testName, function() { before(function(done) { this.timeout(20000); const child = spawn(process.execPath, [cmd].concat(args), opts); child.on("close", function(code) { env.code = code; done(); }); child.on("error", function(error) { env.error.push(error); }); child.stdout.on("data", (data) => { env.stdout.push(data); }); child.stderr.on("data", (data) => { env.stderr.push(data); }); }); it("should not cause any errors", function() { should(env.error).be.empty(); }); it("should run successfully", function() { const stdout = convertToArrayOfLines(env.stdout); const stderr = convertToArrayOfLines(env.stderr); testAssertions(env.code, stdout, stderr); }); }); } }); }); }); }); webpack-3.5.6/test/CachePlugin.test.js000066400000000000000000000206011315401342100176070ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const CachePlugin = require("../lib/CachePlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("CachePlugin", () => { let env; beforeEach(() => { env = { compilation: { compiler: {}, warnings: [] } }; }); it("has apply ", () => { (new CachePlugin()).apply.should.be.a.Function(); }); describe("applyMtime", () => { beforeEach(() => env.plugin = new CachePlugin()); it("sets file system accuracy to 1 for granular modification timestamp", () => { env.plugin.applyMtime(1483819067001); env.plugin.FS_ACCURENCY.should.be.exactly(1); }); it("sets file system accuracy to 10 for moderately granular modification timestamp", () => { env.plugin.applyMtime(1483819067004); env.plugin.FS_ACCURENCY.should.be.exactly(10); }); it("sets file system accuracy to 100 for moderately coarse modification timestamp", () => { env.plugin.applyMtime(1483819067040); env.plugin.FS_ACCURENCY.should.be.exactly(100); }); it("sets file system accuracy to 1000 for coarse modification timestamp", () => { env.plugin.applyMtime(1483819067400); env.plugin.FS_ACCURENCY.should.be.exactly(1000); }); }); describe("when applied", () => { describe("for multiple compilers", () => { beforeEach(() => { const plugin = new CachePlugin(); env.compilers = [sinon.spy(), sinon.spy()]; plugin.apply({ compilers: env.compilers }); }); it("calls each compilers apply with the cache plugin context", () => { env.compilers[0].callCount.should.be.exactly(1); env.compilers[0].firstCall.thisValue.should.be.instanceOf(CachePlugin); env.compilers[1].callCount.should.be.exactly(1); env.compilers[1].firstCall.thisValue.should.be.instanceOf(CachePlugin); }); }); describe("for a single compiler", () => { beforeEach(() => { const applyContext = {}; env.eventBindings = applyPluginWithOptions.call(applyContext, CachePlugin, { test: true }); env.plugin = applyContext.plugin; }); it("binds four event handlers", () => env.eventBindings.length.should.be.exactly(4)); it("sets the initial cache", () => env.plugin.cache.test.should.be.true()); describe("compilation handler", () => { it("binds to compilation event", () => env.eventBindings[0].name.should.be.exactly("compilation")); describe("when cachable", () => { describe("and not watching", () => { beforeEach(() => env.eventBindings[0].handler(env.compilation)); it("sets the compilation cache", () => env.compilation.cache.should.deepEqual({ test: true })); }); describe("and watching", () => { beforeEach(() => { env.eventBindings[1].handler(env.compilation, () => {}); env.eventBindings[0].handler(env.compilation); }); it("does not add a compilation warning is added", () => env.compilation.warnings.should.be.empty()); }); }); describe("when not cachable", () => { beforeEach(() => env.compilation.notCacheable = true); describe("and not watching", () => { beforeEach(() => env.eventBindings[0].handler(env.compilation)); it("does not set the cache", () => should(env.compilation.cache).be.undefined()); }); describe("and watching", () => { beforeEach(() => { env.eventBindings[1].handler(env.compilation, () => {}); env.eventBindings[0].handler(env.compilation); }); it("adds a compilation warning", () => { env.compilation.warnings.length.should.be.exactly(1); env.compilation.warnings[0].should.be.Error("CachePlugin - Cache cannot be used because of: true"); }); }); }); }); describe("watch-run handler", () => { beforeEach(() => { env.callback = sinon.spy(); env.eventBindings[1].handler(env.compilation.compiler, env.callback); }); it("binds to watch-run event", () => env.eventBindings[1].name.should.be.exactly("watch-run")); it("sets watching flag", () => env.plugin.watching.should.be.true()); it("calls callback", () => env.callback.callCount.should.be.exactly(1)); }); describe("run handler", () => { beforeEach(() => { env.fsStat = sinon.spy(); env.callback = sinon.spy(); env.compilation.compiler.inputFileSystem = { stat: env.fsStat }; }); it("binds to run event", () => env.eventBindings[2].name.should.be.exactly("run")); describe("Has not previously compiled", () => { beforeEach(() => env.eventBindings[2].handler(env.compilation.compiler, env.callback)); it("does not get any file stats", () => env.fsStat.callCount.should.be.exactly(0)); it("calls the callback", () => { env.callback.callCount.should.be.exactly(1); should(env.callback.firstCall.args[0]).be.undefined(); }); }); describe("Has previously compiled", () => { beforeEach(() => { env.compilation.fileDependencies = ["foo"]; env.compilation.contextDependencies = ["bar"]; env.eventBindings[3].handler(env.compilation, () => {}); env.eventBindings[2].handler(env.compilation.compiler, env.callback); }); it("calls for file stats for file dependencies", () => { env.fsStat.callCount.should.be.exactly(1); env.fsStat.firstCall.args[0].should.be.exactly("foo"); }); describe("file stats callback", () => { beforeEach(() => env.fsStatCallback = env.fsStat.firstCall.args[1]); describe("when error occurs", () => { beforeEach(() => env.fsStatCallback(new Error("Test Error"))); it("calls handler callback with error", () => { env.callback.callCount.should.be.exactly(1); env.callback.firstCall.args[0].should.be.Error("Test Error"); }); }); describe("when ENOENT error occurs", () => { beforeEach(() => env.fsStatCallback({ code: "ENOENT" })); it("calls handler callback without error", () => { env.callback.callCount.should.be.exactly(1); should(env.callback.firstCall.args[0]).be.undefined(); }); }); describe("when stat does not have modified time", () => { beforeEach(() => { sinon.stub(env.plugin, "applyMtime"); env.fsStatCallback(null, {}); }); afterEach(() => env.plugin.applyMtime.restore()); it("does not update file system accuracy", () => env.plugin.applyMtime.callCount.should.be.exactly(0)); it("updates file modified timestamp to infinity", () => env.compilation.compiler.fileTimestamps.should.deepEqual({ foo: Infinity })); it("calls handler callback without error", () => { env.callback.callCount.should.be.exactly(1); should(env.callback.firstCall.args[0]).be.undefined(); }); }); describe("when stat has modified time", () => { beforeEach(() => { sinon.stub(env.plugin, "applyMtime"); env.fsStatCallback(null, { mtime: 1483819067001 }); }); afterEach(() => env.plugin.applyMtime.restore()); it("does not update file system accuracy", () => env.plugin.applyMtime.callCount.should.be.exactly(1)); it("updates file modified timestamp to modified time with accuracy value", () => env.compilation.compiler.fileTimestamps.should.deepEqual({ foo: 1483819069001 })); it("calls handler callback without error", () => { env.callback.callCount.should.be.exactly(1); should(env.callback.firstCall.args[0]).be.undefined(); }); }); }); }); }); describe("after-compile handler", () => { beforeEach(() => { env.compilation.fileDependencies = ["foo"]; env.compilation.contextDependencies = ["bar"]; env.callback = sinon.spy(); env.eventBindings[3].handler(env.compilation, env.callback); }); it("binds to after-compile event", () => env.eventBindings[3].name.should.be.exactly("after-compile")); it("saves copy of compilation file dependecies", () => { env.compilation.compiler.should.deepEqual({ _lastCompilationFileDependencies: ["foo"], _lastCompilationContextDependencies: ["bar"] }); }); it("calls callback", () => env.callback.callCount.should.be.exactly(1)); }); }); }); }); webpack-3.5.6/test/CaseSensitiveModulesWarning.test.js000066400000000000000000000027311315401342100230550ustar00rootroot00000000000000"use strict"; const should = require("should"); 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", () => myCaseSensitiveModulesWarning.name.should.be.exactly("CaseSensitiveModulesWarning")); it("has the a message", () => { myCaseSensitiveModulesWarning.message.should.be.exactly(` 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", () => myCaseSensitiveModulesWarning.origin.should.be.exactly(modules[0])); it('has the a module', () => myCaseSensitiveModulesWarning.module.should.be.exactly(modules[0])); }); webpack-3.5.6/test/Chunk.test.js000066400000000000000000000112441315401342100165000ustar00rootroot00000000000000/* globals describe, it, beforeEach */ "use strict"; const should = require("should"); const sinon = require("sinon"); 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", () => should(ChunkInstance.debugId).be.above(999)); it("returns a string with modules information", () => should(ChunkInstance.toString()).be.exactly("Chunk[]")); it("should have origins based in constructor information", () => should(ChunkInstance.origins[0]).be.eql({ module: "module-test", loc: "loc-test", name: "chunk-test" })); it("should not be the initial instance", () => should(ChunkInstance.isInitial()).be.false()); describe("entry", () => { it("returns an error if get entry", () => should(() => { ChunkInstance.entry; }).throw("Chunk.entry was removed. Use hasRuntime()")); it("returns an error if set an entry", () => should(() => { ChunkInstance.entry = 10; }).throw("Chunk.entry was removed. Use hasRuntime()")); }); describe("initial", () => { it("returns an error if get initial", () => should(() => { ChunkInstance.initial; }).throw("Chunk.initial was removed. Use isInitial()")); it("returns an error if set an initial", () => should(() => { ChunkInstance.initial = 10; }).throw("Chunk.initial was removed. Use isInitial()")); }); describe("hasRuntime", () => { it("returns false", () => should(ChunkInstance.hasRuntime()).be.false()); }); describe("isEmpty", () => { it("should NOT have any module by default", () => should(ChunkInstance.isEmpty()).be.true()); }); describe("size", () => { it("should NOT have any module by default", () => should(ChunkInstance.size({ chunkOverhead: 10, entryChunkMultiplicator: 2 })).be.exactly(10)); }); describe("checkConstraints", () => { it("throws an error", () => should(() => { ChunkInstance.checkConstraints(); }).not.throw(/checkConstraints/)); }); describe("canBeIntegrated", () => { it("returns `false` if other object is initial", () => { const other = { isInitial: () => true }; should(ChunkInstance.canBeIntegrated(other)).be.false(); }); it("returns `true` if other object and chunk instance are NOT initial", () => { const other = { isInitial: () => false }; should(ChunkInstance.canBeIntegrated(other)).be.true(); }); }); describe("removeModule", function() { let module; let removeChunkSpy; beforeEach(function() { removeChunkSpy = sinon.spy(); module = { removeChunk: removeChunkSpy }; }); describe("and the chunk does not contain this module", function() { it("returns false", function() { ChunkInstance.removeModule(module).should.eql(false); }); }); describe("and the chunk does contain this module", function() { beforeEach(function() { ChunkInstance._modules = new Set([module]); }); it("calls module.removeChunk with itself and returns true", function() { ChunkInstance.removeModule(module).should.eql(true); removeChunkSpy.callCount.should.eql(1); removeChunkSpy.args[0][0].should.eql(ChunkInstance); }); }); }); describe("removeChunk", function() { let chunk; let removeParentSpy; beforeEach(function() { removeParentSpy = sinon.spy(); chunk = { removeParent: removeParentSpy }; }); describe("and the chunk does not contain this chunk", function() { it("returns false", function() { ChunkInstance.removeChunk(chunk).should.eql(false); }); }); describe("and the chunk does contain this module", function() { beforeEach(function() { ChunkInstance.chunks = [chunk]; }); it("calls module.removeChunk with itself and returns true", function() { ChunkInstance.removeChunk(chunk).should.eql(true); removeParentSpy.callCount.should.eql(1); removeParentSpy.args[0][0].should.eql(ChunkInstance); }); }); }); describe("removeParent", function() { let chunk; let removeChunkSpy; beforeEach(function() { removeChunkSpy = sinon.spy(); chunk = { removeChunk: removeChunkSpy }; }); describe("and the chunk does not contain this chunk", function() { it("returns false", function() { ChunkInstance.removeParent(chunk).should.eql(false); }); }); describe("and the chunk does contain this module", function() { beforeEach(function() { ChunkInstance.parents = [chunk]; }); it("calls module.removeChunk with itself and returns true", function() { ChunkInstance.removeParent(chunk).should.eql(true); removeChunkSpy.callCount.should.eql(1); removeChunkSpy.args[0][0].should.eql(ChunkInstance); }); }); }); }); webpack-3.5.6/test/Compiler-caching.test.js000066400000000000000000000210571315401342100205770ustar00rootroot00000000000000/* globals describe, it, before, after */ "use strict"; const should = require("should"); const path = require("path"); const fs = require("fs"); const webpack = require("../"); const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter"); describe("Compiler (caching)", function() { this.timeout(15000); function compile(entry, options, callback) { new WebpackOptionsDefaulter().process(options); options.entry = entry; 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: function() { return [].join.call(arguments, "/").replace(/\/+/g, "/"); }, mkdirp: function(path, callback) { logs.mkdirp.push(path); callback(); }, writeFile: function(name, content, callback) { logs.writeFile.push(name, content); files[name] = content.toString("utf-8"); callback(); } }; c.plugin("compilation", (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; should.strictEqual(typeof stats, "object"); stats = stats.toJson({ modules: true, reasons: true }); should.strictEqual(typeof stats, "object"); stats.should.have.property("errors"); Array.isArray(stats.errors).should.be.ok(); if(options.expectErrors) { stats.errors.length.should.be.eql(options.expectErrors); } else { if(stats.errors.length > 0) { stats.errors[0].should.be.type("string"); throw new Error(stats.errors[0]); } } stats.logs = logs; callback(stats, files, compilerIteration++); }); } const postCompileCallbackStack = []; function addAfterCompileCallback(callback) { postCompileCallbackStack.push(callback); } c.plugin("after-compile", (stats, callback) => { if(postCompileCallbackStack.length > 0) { postCompileCallbackStack.shift(arguments); } callback(); }); runCompiler(callback); return { compilerInstance: c, runAgain: runCompiler, addAfterCompileCallback: addAfterCompileCallback }; } const tempFixturePath = path.join(__dirname, "fixtures", "temp-cache-fixture"); const aFilepath = path.join(tempFixturePath, "a.js"); const cFilepath = path.join(tempFixturePath, "c.js"); function cleanup() { function ignoreENOENT(fn) { try { return fn(); } catch(e) { if(e.code !== "ENOENT") { throw e; } } } ignoreENOENT(() => fs.unlinkSync(aFilepath)); ignoreENOENT(() => fs.unlinkSync(cFilepath)); ignoreENOENT(() => fs.rmdirSync(tempFixturePath)); } before(cleanup); after(cleanup); function createTempFixture() { // Remove previous copy if present try { if(fs.statSync(tempFixturePath)) { fs.unlinkSync(aFilepath); fs.unlinkSync(cFilepath); fs.rmdirSync(tempFixturePath); } } catch(e) { if(e.code !== "ENOENT") { throw e; } } // Copy over file since we"ll be modifying some of them fs.mkdirSync(tempFixturePath); fs.createReadStream(path.join(__dirname, "fixtures", "a.js")).pipe(fs.createWriteStream(aFilepath)); fs.createReadStream(path.join(__dirname, "fixtures", "c.js")).pipe(fs.createWriteStream(cFilepath)); return { rootPath: tempFixturePath, aFilepath: aFilepath, cFilepath: cFilepath }; } it("should cache single file (with manual 1s wait) ", (done) => { const options = {}; const tempFixture = createTempFixture(); const helper = compile("./temp-cache-fixture/c", options, (stats, files) => { // Not cached the first time stats.assets[0].name.should.be.exactly("bundle.js"); stats.assets[0].emitted.should.be.exactly(true); helper.runAgain((stats, files, iteration) => { // Cached the second run stats.assets[0].name.should.be.exactly("bundle.js"); stats.assets[0].emitted.should.be.exactly(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 stats.assets[0].name.should.be.exactly("bundle.js"); stats.assets[0].emitted.should.be.exactly(true); done(); }); }, 1100); }); }); }); it("should cache single file (even with no timeout) ", (done) => { const options = {}; const tempFixture = createTempFixture(); const helper = compile("./temp-cache-fixture/c", options, (stats, files) => { // Not cached the first time stats.assets[0].name.should.be.exactly("bundle.js"); stats.assets[0].emitted.should.be.exactly(true); helper.runAgain((stats, files, iteration) => { // Cached the second run stats.assets[0].name.should.be.exactly("bundle.js"); stats.assets[0].emitted.should.be.exactly(false); files["/bundle.js"].should.containEql("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 stats.assets[0].name.should.be.exactly("bundle.js"); stats.assets[0].emitted.should.be.exactly(true); files["/bundle.js"].should.containEql("This is a MODIFIED"); done(); }); }); }); }); it("should only build when modified (with manual 2s wait)", (done) => { const options = {}; const tempFixture = createTempFixture(); const helper = compile("./temp-cache-fixture/c", options, (stats, files) => { // Built the first time stats.modules[0].name.should.containEql("c.js"); stats.modules[0].built.should.be.exactly(true, "c.js should have been built"); stats.modules[1].name.should.containEql("a.js"); stats.modules[1].built.should.be.exactly(true, "a.js should have been built"); setTimeout(() => { helper.runAgain((stats, files, iteration) => { // Not built when cached the second run stats.modules[0].name.should.containEql("c.js"); //stats.modules[0].built.should.be.exactly(false, "c.js should not have built"); stats.modules[1].name.should.containEql("a.js"); //stats.modules[1].built.should.be.exactly(false, "a.js should not have built"); 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 stats.modules[0].name.should.containEql("c.js"); stats.modules[0].built.should.be.exactly(false, "c.js should not have built"); stats.modules[1].name.should.containEql("a.js"); stats.modules[1].built.should.be.exactly(true, "a.js should have been built"); done(); }); }, 2100); }); }, 4100); }); }); it("should build when modified (even with no timeout)", (done) => { const options = {}; const tempFixture = createTempFixture(); const helper = compile("./temp-cache-fixture/c", options, (stats, files) => { // Built the first time stats.modules[0].name.should.containEql("c.js"); stats.modules[0].built.should.be.exactly(true, "c.js should have been built"); stats.modules[1].name.should.containEql("a.js"); stats.modules[1].built.should.be.exactly(true, "a.js should have been built"); helper.runAgain((stats, files, iteration) => { // Not built when cached the second run stats.modules[0].name.should.containEql("c.js"); //stats.modules[0].built.should.be.exactly(false, "c.js should not have built"); stats.modules[1].name.should.containEql("a.js"); //stats.modules[1].built.should.be.exactly(false, "a.js should not have built"); 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 stats.modules[0].name.should.containEql("c.js"); //stats.modules[0].built.should.be.exactly(false, "c.js should not have built"); stats.modules[1].name.should.containEql("a.js"); stats.modules[1].built.should.be.exactly(true, "a.js should have been built"); done(); }); }); }); }); }); webpack-3.5.6/test/Compiler.test.js000066400000000000000000000270111315401342100172010ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const should = require("should"); const path = require("path"); const sinon = require("sinon"); const webpack = require("../"); const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter"); const Compiler = require("../lib/Compiler"); describe("Compiler", () => { function compile(entry, options, callback) { const noOutputPath = !options.output || !options.output.path; new WebpackOptionsDefaulter().process(options); options.entry = entry; options.context = path.join(__dirname, "fixtures"); if(noOutputPath) options.output.path = "/"; options.output.pathinfo = true; const logs = { mkdirp: [], writeFile: [], }; const c = webpack(options); const files = {}; c.outputFileSystem = { join: function() { return [].join.call(arguments, "/").replace(/\/+/g, "/"); }, mkdirp: function(path, callback) { logs.mkdirp.push(path); callback(); }, writeFile: function(name, content, callback) { logs.writeFile.push(name, content); files[name] = content.toString("utf-8"); callback(); } }; c.plugin("compilation", (compilation) => compilation.bail = true); c.run((err, stats) => { if(err) throw err; should.strictEqual(typeof stats, "object"); const compilation = stats.compilation; stats = stats.toJson({ modules: true, reasons: true }); should.strictEqual(typeof stats, "object"); stats.should.have.property("errors"); Array.isArray(stats.errors).should.be.ok(); if(stats.errors.length > 0) { stats.errors[0].should.be.instanceOf(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) => { stats.logs.mkdirp.should.eql([ "/what", "/what/the", ]); done(); }); }); it("should compile a single file", (done) => { compile("./c", {}, (stats, files) => { files.should.have.property("/main.js").have.type("string"); Object.keys(files).should.be.eql(["/main.js"]); const bundle = files["/main.js"]; bundle.should.containEql("function __webpack_require__("); bundle.should.containEql("__webpack_require__(/*! ./a */ 1);"); bundle.should.containEql("./c.js"); bundle.should.containEql("./a.js"); bundle.should.containEql("This is a"); bundle.should.containEql("This is c"); bundle.should.not.containEql("2: function("); bundle.should.not.containEql("window"); bundle.should.not.containEql("jsonp"); bundle.should.not.containEql("fixtures"); done(); }); }); it("should compile a complex file", (done) => { compile("./main1", {}, (stats, files) => { files.should.have.property("/main.js").have.type("string"); Object.keys(files).should.be.eql(["/main.js"]); const bundle = files["/main.js"]; bundle.should.containEql("function __webpack_require__("); bundle.should.containEql("__webpack_require__(/*! ./a */"); bundle.should.containEql("./main1.js"); bundle.should.containEql("./a.js"); bundle.should.containEql("./b.js"); bundle.should.containEql("./node_modules/m1/a.js"); bundle.should.containEql("This is a"); bundle.should.containEql("This is b"); bundle.should.containEql("This is m1/a"); bundle.should.not.containEql("4: function("); bundle.should.not.containEql("window"); bundle.should.not.containEql("jsonp"); bundle.should.not.containEql("fixtures"); done(); }); }); it("should compile a file with transitive dependencies", (done) => { compile("./abc", {}, (stats, files) => { files.should.have.property("/main.js").have.type("string"); Object.keys(files).should.be.eql(["/main.js"]); const bundle = files["/main.js"]; bundle.should.containEql("function __webpack_require__("); bundle.should.containEql("__webpack_require__(/*! ./a */"); bundle.should.containEql("__webpack_require__(/*! ./b */"); bundle.should.containEql("__webpack_require__(/*! ./c */"); bundle.should.containEql("./abc.js"); bundle.should.containEql("./a.js"); bundle.should.containEql("./b.js"); bundle.should.containEql("./c.js"); bundle.should.containEql("This is a"); bundle.should.containEql("This is b"); bundle.should.containEql("This is c"); bundle.should.not.containEql("4: function("); bundle.should.not.containEql("window"); bundle.should.not.containEql("jsonp"); bundle.should.not.containEql("fixtures"); done(); }); }); it("should compile a file with multiple chunks", (done) => { compile("./chunks", {}, (stats, files) => { stats.chunks.length.should.be.eql(2); files.should.have.property("/main.js").have.type("string"); files.should.have.property("/0.js").have.type("string"); Object.keys(files).should.be.eql(["/0.js", "/main.js"]); const bundle = files["/main.js"]; const chunk = files["/0.js"]; bundle.should.containEql("function __webpack_require__("); bundle.should.containEql("__webpack_require__(/*! ./b */"); chunk.should.not.containEql("__webpack_require__(/* ./b */"); bundle.should.containEql("./chunks.js"); chunk.should.containEql("./a.js"); chunk.should.containEql("./b.js"); chunk.should.containEql("This is a"); bundle.should.not.containEql("This is a"); chunk.should.containEql("This is b"); bundle.should.not.containEql("This is b"); bundle.should.not.containEql("4: function("); bundle.should.not.containEql("fixtures"); chunk.should.not.containEql("fixtures"); bundle.should.containEql("webpackJsonp"); chunk.should.containEql("webpackJsonp("); done(); }); }); describe("constructor", () => { let compiler; beforeEach(() => { compiler = webpack({ entry: "./c", context: path.join(__dirname, "fixtures"), output: { path: "/", pathinfo: true, } }); }); describe("parser", () => { describe("apply", () => { it("invokes sets a 'compilation' plugin", (done) => { compiler.plugin = sinon.spy(); compiler.parser.apply(); compiler.plugin.callCount.should.be.exactly(1); 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 = sinon.spy(); compiler.inputFileSystem = { purge: mockPurge, }; compiler.purgeInputFileSystem(); mockPurge.callCount.should.be.exactly(1); done(); }); it("does NOT invoke purge() if !inputFileSystem.purge", (done) => { const mockPurge = sinon.spy(); compiler.inputFileSystem = null; compiler.purgeInputFileSystem(); mockPurge.callCount.should.be.exactly(0); done(); }); }); describe("isChild", () => { it("returns booleanized this.parentCompilation", (done) => { compiler.parentCompilation = "stringyStringString"; const response1 = compiler.isChild(); response1.should.be.exactly(true); compiler.parentCompilation = 123456789; const response2 = compiler.isChild(); response2.should.be.exactly(true); compiler.parentCompilation = { what: "I belong to an object" }; const response3 = compiler.isChild(); response3.should.be.exactly(true); compiler.parentCompilation = ["Array", 123, true, null, [], () => {}]; const response4 = compiler.isChild(); response4.should.be.exactly(true); compiler.parentCompilation = false; const response5 = compiler.isChild(); response5.should.be.exactly(false); compiler.parentCompilation = 0; const response6 = compiler.isChild(); response6.should.be.exactly(false); compiler.parentCompilation = null; const response7 = compiler.isChild(); response7.should.be.exactly(false); compiler.parentCompilation = ""; const response8 = compiler.isChild(); response8.should.be.exactly(false); compiler.parentCompilation = NaN; const response9 = compiler.isChild(); response9.should.be.exactly(false); done(); }); }); describe("createChildCompiler", () => { it("defaults cache.children if none exists yet", (done) => { const mockPlugin = sinon.spy(); class fakePlugin { apply() { mockPlugin(); } } compiler.cache = {}; compiler.createChildCompiler({}, "compiler9000", 0, {}, [new fakePlugin()]); mockPlugin.callCount.should.be.exactly(1); compiler.cache.children.should.match({}); done(); }); it("defaults cache.children[compilerName] if none exists yet", (done) => { compiler.cache = { children: {}, }; compiler.createChildCompiler({}, "compiler9000", 0, {}, null); compiler.cache.children.should.match({ compiler9000: [], }); done(); }); }); }); describe("Watching", () => { let compiler; beforeEach(() => { compiler = webpack({ entry: "./c", context: path.join(__dirname, "fixtures"), output: { path: "/", pathinfo: true, } }); }); describe("static method", () => { it("should have an method, Watching", (done) => { const actual = new Compiler.Watching(compiler, 1000, err => err); actual.running.should.be.exactly(true); actual.constructor.name.should.be.exactly("Watching"); done(); }); }); describe("constructor", () => { it("constructs Watching.watchOptions correctly when passed a number, string, or object for watchOptions", (done) => { const Watching1 = compiler.watch(1000, err => err); const Watching2 = compiler.watch({ aggregateTimeout: 1000 }, err => err); const Watching3 = compiler.watch("I am a string", err => err); Watching1.watchOptions.aggregateTimeout.should.equal(Watching2.watchOptions.aggregateTimeout); Watching3.watchOptions.aggregateTimeout.should.equal(200); done(); }); it("invokes compiler.readRecords", (done) => { compiler.readRecords = sinon.spy(); compiler.watch(1000, err => err); compiler.readRecords.callCount.should.be.exactly(1); done(); }); }); describe("_done", () => { it("invokes this.handler and turns this.running boolean to false when passed an error", (done) => { const mockHandler = sinon.spy(); const Watching1 = compiler.watch(1000, mockHandler); Watching1.running.should.be.exactly(true); Watching1._done(Watching1.handler, false); mockHandler.callCount.should.be.exactly(1); Watching1.running.should.be.exactly(false); done(); }); }); describe("invalidate", () => { it("pauses this.watcher and sets this.watcher to null if this.watcher is true", (done) => { const mockPause = sinon.spy(); const Watching1 = compiler.watch(1000, err => err); Watching1.watcher = { pause: mockPause }; Watching1.invalidate(); mockPause.callCount.should.be.exactly(1); should(Watching1.watcher).be.exactly(null); done(); }); it("sets this.invalid to true if this.running is true, else this.invalid = false", (done) => { const Watching1 = compiler.watch(1000, err => err); Watching1.invalid = false; const response = Watching1.invalidate(); Watching1.invalid.should.be.exactly(true); response.should.be.exactly(false); done(); }); it("invokes this._go() if !this.running", (done) => { const Watching1 = compiler.watch(1000, err => err); Watching1.running = false; Watching1._go = sinon.spy(); Watching1.invalidate(); Watching1._go.callCount.should.be.exactly(1); done(); }); }); }); }); webpack-3.5.6/test/ConfigTestCases.test.js000066400000000000000000000123061315401342100204540ustar00rootroot00000000000000"use strict"; /* globals describe it */ const should = require("should"); const path = require("path"); const fs = require("fs"); const vm = require("vm"); const Test = require("mocha/lib/test"); const checkArrayExpectation = require("./checkArrayExpectation"); const Stats = require("../lib/Stats"); const webpack = require("../lib/webpack"); const prepareOptions = require("../lib/prepareOptions"); describe("ConfigTestCases", () => { const casesPath = path.join(__dirname, "configCases"); let categories = fs.readdirSync(casesPath); 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) => { const suite = describe(testName, () => {}); it(testName + " should compile", function(done) { this.timeout(30000); const testDirectory = path.join(casesPath, category.name, testName); const outputDirectory = path.join(__dirname, "js", "config", category.name, testName); const options = prepareOptions(require(path.join(testDirectory, "webpack.config.js"))); const optionsArr = [].concat(options); optionsArr.forEach((options, idx) => { if(!options.context) options.context = testDirectory; 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"; if(!options.output.chunkFilename) options.output.chunkFilename = "[id].bundle" + idx + ".js"; }); webpack(options, (err, stats) => { if(err) return done(err); const statOptions = Stats.presetToOptions("verbose"); statOptions.colors = false; 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; let exportedTests = 0; function _it(title, fn) { const test = new Test(title, fn); suite.addTest(test); exportedTests++; return test; } const globalContext = { console: console }; 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, window) {" + content + "\n})", globalContext, p); } else { fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it) {" + content + "\n})", p); } const m = { exports: {} }; fn.call(m.exports, _require.bind(null, path.dirname(p)), m, m.exports, path.dirname(p), p, _it, globalContext); return m.exports; } else if(testConfig.modules && module in testConfig.modules) { return testConfig.modules[module]; } else return require(module); } let filesCount = 0; let testConfig = { findBundle: function(i, options) { if(fs.existsSync(path.join(options.output.path, "bundle" + i + ".js"))) { return "./bundle" + i + ".js"; } } }; try { // try to load a test file testConfig = require(path.join(testDirectory, "test.config.js")); } catch(e) {} if(testConfig.noTests) return process.nextTick(done); 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(exportedTests < filesCount) return done(new Error("No tests exported by test case")); process.nextTick(done); }); }); }); }); }); }); webpack-3.5.6/test/ContextDependencyTemplateAsId.test.js000066400000000000000000000104401315401342100233050ustar00rootroot00000000000000"use strict"; const _ = require("lodash"); const should = require("should"); const sinon = require("sinon"); const ContextDependencyTemplateAsId = require("../lib/dependencies/ContextDependencyTemplateAsId"); const requestShortenerMock = { shorten: (request) => `shortened ${request}` }; describe("ContextDependencyTemplateAsId", () => { let env; const applyContextDependencyTemplateAsId = function() { const contextDependencyTemplateAsId = new ContextDependencyTemplateAsId(); const args = [].slice.call(arguments).concat(requestShortenerMock); contextDependencyTemplateAsId.apply.apply(contextDependencyTemplateAsId, args); }; beforeEach(() => { env = { source: { replace: sinon.stub() }, outputOptions: { pathinfo: true }, module: { id: "123", dependencies: [ "myModuleDependency" ] }, baseDependency: { range: [1, 25], request: "myModule" } }; }); it("has apply function", () => { (new ContextDependencyTemplateAsId()).apply.should.be.a.Function(); }); describe("when applied", () => { describe("with module missing depedencies", () => { beforeEach(() => { applyContextDependencyTemplateAsId(env.baseDependency, env.source, env.outputOptions); }); it("replaces source with missing module error", () => { env.source.replace.callCount.should.be.exactly(1); sinon.assert.calledWith(env.source.replace, 1, 24, '!(function webpackMissingModule() { var e = new Error("Cannot find module \\"myModule\\""); e.code = \'MODULE_NOT_FOUND\'; throw e; }())'); }); }); describe("with module which does not have a value range", () => { beforeEach(() => { env.dependency = _.extend(env.baseDependency, { prepend: "prepend value", module: env.module }); }); describe("and path info true", function() { beforeEach(function() { env.outputOptions.pathinfo = true; applyContextDependencyTemplateAsId(env.dependency, env.source, env.outputOptions); }); it("replaces source with webpack require with comment", () => { env.source.replace.callCount.should.be.exactly(1); sinon.assert.calledWith(env.source.replace, 1, 24, '__webpack_require__(/*! shortened myModule */ "123").resolve'); }); }); describe("and path info false", function() { beforeEach(function() { env.outputOptions.pathinfo = false; applyContextDependencyTemplateAsId(env.dependency, env.source, env.outputOptions); }); it("replaces source with webpack require without comment", () => { env.source.replace.callCount.should.be.exactly(1); sinon.assert.calledWith(env.source.replace, 1, 24, '__webpack_require__("123").resolve'); }); }); }); describe("with module which has a value range", () => { describe("with no replacements", () => { beforeEach(() => { const dependency = _.extend(env.baseDependency, { valueRange: [8, 18], prepend: "prepend value", module: env.module }); applyContextDependencyTemplateAsId(dependency, env.source, env.outputOptions); }); it("replaces source with webpack require and wraps value", () => { env.source.replace.callCount.should.be.exactly(2); sinon.assert.calledWith(env.source.replace, 18, 24, ")"); sinon.assert.calledWith(env.source.replace, 1, 7, '__webpack_require__(/*! shortened myModule */ "123").resolve("prepend value"'); }); }); describe("with replacements", () => { beforeEach(() => { const dependency = _.extend(env.baseDependency, { valueRange: [8, 18], replaces: [{ value: "foo", range: [9, 11] }, { value: "bar", range: [13, 15] } ], prepend: "prepend value", module: env.module }); applyContextDependencyTemplateAsId(dependency, env.source, env.outputOptions); }); it("replaces source with webpack require, wraps value and make replacements", () => { env.source.replace.callCount.should.be.exactly(4); sinon.assert.calledWith(env.source.replace, 9, 10, "foo"); sinon.assert.calledWith(env.source.replace, 13, 14, "bar"); sinon.assert.calledWith(env.source.replace, 18, 24, ")"); sinon.assert.calledWith(env.source.replace, 1, 7, '__webpack_require__(/*! shortened myModule */ "123").resolve("prepend value"'); }); }); }); }); }); webpack-3.5.6/test/ContextReplacementPlugin.test.js000066400000000000000000000161751315401342100224230ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const ContextReplacementPlugin = require("../lib/ContextReplacementPlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); const PluginEnvironment = require("./helpers/PluginEnvironment"); describe("ContextReplacementPlugin", () => { it("has apply function", () => (new ContextReplacementPlugin()).apply.should.be.a.Function()); it("should consume resourceRegExp as regular expression", () => { let instance = new ContextReplacementPlugin(/selector/, "mock", "mock", "mock"); should(instance.resourceRegExp instanceof RegExp).be.exactly(true); }); it("should consume newContentResource as function", () => { let instance = new ContextReplacementPlugin(/selector/, () => {}, "mock", "mock"); should(instance.newContentCallback).be.a.Function(); }); it("should consume newContentResource as not an string or function", () => { let instance = new ContextReplacementPlugin(/selector/, 42, "newContentRecursive", "newContentRegExp"); should(instance.resourceRegExp instanceof RegExp).be.exactly(true); should(instance.newContentResource).be.exactly(undefined); should(instance.newContentRecursive).be.exactly(undefined); should(instance.newContentRegExp).be.exactly(42); }); it("should consume newContentResource as an object", () => { let instance = new ContextReplacementPlugin(/selector/, "newResource", { test: "obj" }, /selector/); should(instance.resourceRegExp instanceof RegExp).be.exactly(true); should(instance.newContentResource).be.exactly("newResource"); should(instance.newContentRecursive).be.exactly(undefined); should(instance.newContentRegExp).be.exactly(undefined); should(instance.newContentCreateContextMap).be.a.Function(); let x = (nothing, obj) => { should(obj.test).be.exactly("obj") }; let spy = sinon.spy(x); instance.newContentCreateContextMap(undefined, spy); should(spy.called).be.exactly(true) }); it("should consume newContentResource as an object", () => { let instance = new ContextReplacementPlugin(/selector/, "newResource", () => {}, /selector/); should(instance.resourceRegExp instanceof RegExp).be.exactly(true); should(instance.newContentResource).be.exactly("newResource"); should(instance.newContentRecursive).be.exactly(undefined); should(instance.newContentRegExp).be.exactly(undefined); should(instance.newContentCreateContextMap).be.a.Function(); }); describe("when applied", () => { describe("when before resolve is called", () => { it("default call", () => { let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/); let x = (nothing, result) => { should(result.request).be.exactly('./folder') should(result.dependencies[0].critical).be.exactly(false) should(result.recursive).be.exactly(true) should(result.regExp instanceof RegExp).be.exactly(true) }; let spy = sinon.spy(x); obj.beforeResolve.handler({ request: "selector", dependencies: [{ critical: true }] }, spy) should(spy.called).be.exactly(true) }); it("default call with newContentCallback as a function", () => { let obj = buildPluginWithParams(/selector/, (result) => { should(result.request).be.exactly('selector') should(result.dependencies[0].critical).be.exactly(false) should(result.recursive).be.exactly(undefined) should(result.regExp).be.exactly(undefined) }, true, /filter/); let x = (nothing, result) => { should(result.request).be.exactly('selector') should(result.dependencies[0].critical).be.exactly(false) should(result.recursive).be.exactly(undefined) should(result.regExp).be.exactly(undefined) }; let spy = sinon.spy(x); obj.beforeResolve.handler({ request: "selector", dependencies: [{ critical: false }] }, spy) should(spy.called).be.exactly(true) }); it("call when result is false", () => { let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/); let x = (nothing, result) => { should(result).be.Undefined(); }; let spy = sinon.spy(x); obj.beforeResolve.handler(false, spy); should(spy.called).be.exactly(true) }); }); describe("when after resolve is called", () => { it("default call where regex is correct", () => { let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/); let x = (nothing, result) => { result.resource.should.containEql('selector') result.resource.should.containEql('folder') }; let spy = sinon.spy(x); obj.afterResolve.handler({ resource: "selector", dependencies: [{ critical: true }] }, spy); should(spy.called).be.exactly(true) }); it("default call where regex is incorrect", () => { let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/); let x = (nothing, result) => { result.resource.should.containEql('importwontwork') }; let spy = sinon.spy(x); obj.afterResolve.handler({ resource: "importwontwork", dependencies: [{ critical: true }] }, spy); should(spy.called).be.exactly(true) }); it("default call where regex is correct", () => { let obj = buildPluginWithParams(/selector/, (result) => { //noop }, true, /filter/); let x = (nothing, result) => { result.resource.should.equal('selector') }; let spy = sinon.spy(x); obj.afterResolve.handler({ resource: "selector", dependencies: [{ critical: true }] }, spy); should(spy.called).be.exactly(true) }); it("default call where regex is correct and using function as newContent Resource", () => { let obj = buildPluginWithParams(/selector/, (result) => { result.resource = "imadifferentselector" }, true, /filter/); let x = (nothing, result) => { result.resource.should.containEql('selector') result.resource.should.containEql('imadifferentselector') }; let spy = sinon.spy(x); obj.afterResolve.handler({ resource: "selector", dependencies: [{ critical: true }] }, spy); should(spy.called).be.exactly(true) }); }) }); }); let buildPluginWithParams = (resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) => { let instance = new ContextReplacementPlugin(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp); let pluginEnvironment = new PluginEnvironment(); instance.apply(pluginEnvironment.getEnvironmentStub()); let contextModuleFactory = pluginEnvironment.getEventBindings()[0]; pluginEnvironment.getEventBindings().length.should.be.exactly(1) let contextModuleFactoryPluginEnv = new PluginEnvironment(); contextModuleFactory.handler(contextModuleFactoryPluginEnv.getEnvironmentStub()); let contextModuleFactoryEventBindings = contextModuleFactoryPluginEnv.getEventBindings(); contextModuleFactoryPluginEnv.getEventBindings().length.should.be.exactly(2); let beforeResolve = contextModuleFactoryEventBindings[0]; let afterResolve = contextModuleFactoryEventBindings[1]; return { contextModuleFactory, beforeResolve, afterResolve } }; webpack-3.5.6/test/DependenciesBlockVariable.test.js000066400000000000000000000043721315401342100224430ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const DependenciesBlockVariable = require("../lib/DependenciesBlockVariable"); describe("DependenciesBlockVariable", () => { let DependenciesBlockVariableInstance, dependencyMock, sandbox; before(() => { sandbox = sinon.sandbox.create(); dependencyMock = { constructor: { name: "DependencyMock" }, disconnect: sandbox.spy(), updateHash: sandbox.spy() }; DependenciesBlockVariableInstance = new DependenciesBlockVariable( "dependencies-name", "expression", [dependencyMock]); }); afterEach(() => sandbox.restore()); describe("hasDependencies", () => it("returns `true` if has dependencies", () => should(DependenciesBlockVariableInstance.hasDependencies()).be.true())); describe("disconnect", () => it("trigger dependencies disconnection", () => { DependenciesBlockVariableInstance.disconnect(); should(dependencyMock.disconnect.calledOnce).be.true(); })); describe("updateHash", () => { let hash; before(() => { hash = { update: sandbox.spy() }; DependenciesBlockVariableInstance.updateHash(hash); }); it("should update hash dependencies with name", () => should(hash.update.calledWith("dependencies-name")).be.true()); it("should update hash dependencies with expression", () => should(hash.update.calledWith("expression")).be.true()); it("should update hash inside dependencies", () => should(dependencyMock.updateHash.calledOnce).be.true()); }); describe("expressionSource", () => { let dependencyTemplates, applyMock; before(() => applyMock = sandbox.spy()); it("aplies information inside dependency templates", () => { dependencyTemplates = { get: function() { return { apply: applyMock }; } }; DependenciesBlockVariableInstance.expressionSource( dependencyTemplates, {}, {} ); should(applyMock.calledOnce).be.true(); }); it("aplies information inside dependency templates", () => { dependencyTemplates = { get: function() { return false; } }; should(() => { DependenciesBlockVariableInstance.expressionSource( dependencyTemplates, {}, {} ); }).throw("No template for dependency: DependencyMock"); }); }); }); webpack-3.5.6/test/Errors.test.js000066400000000000000000000134461315401342100167120ustar00rootroot00000000000000"use strict"; /*globals describe it */ const should = require("should"); const path = require("path"); const webpack = require("../lib/webpack"); const base = path.join(__dirname, "fixtures", "errors"); describe("Errors", () => { function customOutputFilesystem(c) { const files = {}; c.outputFileSystem = { join: path.join.bind(path), mkdirp: function(path, callback) { callback(); }, writeFile: function(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; should.strictEqual(typeof stats, "object"); stats = stats.toJson({ errorDetails: false }); should.strictEqual(typeof stats, "object"); stats.should.have.property("errors"); stats.should.have.property("warnings"); Array.isArray(stats.errors).should.be.ok(); // eslint-disable-line no-unused-expressions Array.isArray(stats.warnings).should.be.ok(); // eslint-disable-line no-unused-expressions callback(stats.errors, stats.warnings); }); } it("should throw an error if file doesn't exist", (done) => { getErrors({ entry: "./missingFile" }, (errors, warnings) => { errors.length.should.be.eql(2); warnings.length.should.be.eql(0); errors.sort(); let lines = errors[0].split("\n"); lines[0].should.match(/missingFile.js/); lines[1].should.match(/^Module not found/); lines[1].should.match(/\.\/dir\/missing2/); lines[2].should.match(/missingFile.js 12:9/); lines = errors[1].split("\n"); lines[0].should.match(/missingFile.js/); lines[1].should.match(/^Module not found/); lines[1].should.match(/\.\/missing/); lines[2].should.match(/missingFile.js 4:0/); done(); }); }); it("should report require.extensions as unsupported", (done) => { getErrors({ entry: "./require.extensions" }, (errors, warnings) => { errors.length.should.be.eql(0); warnings.length.should.be.eql(1); const lines = warnings[0].split("\n"); lines[0].should.match(/require.extensions\.js/); lines[1].should.match(/require.extensions is not supported by webpack/); done(); }); }); it("should warn about case-sensitive module names", (done) => { getErrors({ entry: "./case-sensitive" }, (errors, warnings) => { if(errors.length === 0) { warnings.length.should.be.eql(1); const lines = warnings[0].split("\n"); lines[4].should.match(/FILE\.js/); lines[5].should.match(/Used by/); lines[6].should.match(/case-sensitive/); lines[7].should.match(/file\.js/); lines[8].should.match(/Used by/); lines[9].should.match(/case-sensitive/); } else { errors.length.should.be.eql(1); warnings.length.should.be.eql(0); } done(); }); }); it("should warn about NoErrorsPlugin being deprecated in favor of NoEmitOnErrorsPlugin", (done) => { getErrors({ entry: "./no-errors-deprecate", plugins: [ new webpack.NoErrorsPlugin() ] }, (errors, warnings) => { warnings.length.should.be.eql(1); const lines = warnings[0].split("\n"); lines[0].should.match(/webpack/); lines[0].should.match(/NoErrorsPlugin/); lines[0].should.match(/deprecated/); lines[1].should.match(/NoEmitOnErrorsPlugin/); lines[1].should.match(/instead/); done(); }); }); it("should not warn if the NoEmitOnErrorsPlugin is used over the NoErrorsPlugin", (done) => { getErrors({ entry: "./no-errors-deprecate", plugins: [ new webpack.NoEmitOnErrorsPlugin() ] }, (errors, warnings) => { errors.length.should.be.eql(0); warnings.length.should.be.eql(0); done(); }); }); it("should not not emit if NoEmitOnErrorsPlugin is used and there is an error", (done) => { getErrors({ entry: "./missingFile", plugins: [ new webpack.NoEmitOnErrorsPlugin() ] }, (errors, warnings) => { errors.length.should.be.eql(2); warnings.length.should.be.eql(0); errors.sort(); let lines = errors[0].split("\n"); lines[0].should.match(/missingFile.js/); lines[1].should.match(/^Module not found/); lines[1].should.match(/\.\/dir\/missing2/); lines[2].should.match(/missingFile.js 12:9/); lines = errors[1].split("\n"); lines[0].should.match(/missingFile.js/); lines[1].should.match(/^Module not found/); lines[1].should.match(/\.\/missing/); lines[2].should.match(/missingFile.js 4:0/); done(); }); }); it("should throw an error when using incorrect CommonsChunkPlugin configuration", (done) => { getErrors({ entry: { a: "./entry-point", b: "./entry-point", c: "./entry-point" }, output: { filename: "[name].js" }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: "a", filename: "a.js", minChunks: Infinity }), new webpack.optimize.CommonsChunkPlugin({ name: "b", filename: "b.js", minChunks: Infinity }) ] }, (errors, warnings) => { errors.length.should.be.eql(1); warnings.length.should.be.eql(0); const lines = errors[0].split("\n"); lines[0].should.match(/CommonsChunkPlugin/); lines[0].should.match(/non-entry/); done(); }); }); it("should throw an error when trying to use [chunkhash] when it's invalid", (done) => { getErrors({ entry: { a: "./entry-point", b: "./entry-point", c: "./entry-point" }, output: { filename: "[chunkhash].js" }, plugins: [ new webpack.HotModuleReplacementPlugin() ] }, (errors, warnings) => { errors.length.should.be.eql(3); warnings.length.should.be.eql(0); errors.forEach((error) => { const lines = error.split("\n"); lines[0].should.match(/chunk (a|b|c)/); lines[2].should.match(/\[chunkhash\].js/); lines[2].should.match(/use \[hash\] instead/); }); done(); }); }); }); webpack-3.5.6/test/Examples.test.js000066400000000000000000000026471315401342100172150ustar00rootroot00000000000000"use strict"; /* globals describe it */ require("should"); 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) => { it("should compile " + path.relative(basePath, examplePath), function(done) { this.timeout(20000); 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, "js"); options.output.publicPath = "js/"; if(!options.output.filename) options.output.filename = "output.js"; if(!options.entry) options.entry = "./example.js"; } 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(); }); }); }); }); webpack-3.5.6/test/ExternalModule.test.js000066400000000000000000000227431315401342100203660ustar00rootroot00000000000000/* globals describe, it, beforeEach */ "use strict"; require("should"); const sinon = require("sinon"); const ExternalModule = require("../lib/ExternalModule"); const OriginalSource = require("webpack-sources").OriginalSource; const RawSource = require("webpack-sources").RawSource; describe("ExternalModule", function() { let externalModule; let request; let type; beforeEach(function() { request = "some/request"; type = "some-type"; externalModule = new ExternalModule( request, type, `${type} ${request}` ); }); describe("#identifier", function() { it("returns an identifier for this module", function() { const expected = `external "${request}"`; externalModule.identifier().should.eql(expected); }); }); describe("#readableIdentifier", function() { it("returns an identifier for this module", function() { const expected = `external "${request}"`; externalModule.identifier().should.eql(expected); }); }); describe("#needRebuild", function() { it("always returns false", function() { externalModule.needRebuild().should.eql(false); }); }); describe("#size", function() { it("always returns 42", function() { externalModule.size().should.eql(42); }); }); describe("#source", function() { it("calls getSource with the result of getSourceString", function() { // set up const expectedString = "something expected stringy"; const expectedSource = "something expected sourcy"; externalModule.getSource = sinon.stub().returns(expectedSource); externalModule.getSourceString = sinon.stub().returns(expectedString); // invoke const result = externalModule.source(); // check externalModule.getSource.callCount.should.eql(1); externalModule.getSourceString.callCount.should.eql(1); externalModule.getSource.args[0][0].should.eql(expectedString); result.should.eql(expectedSource); }); }); describe("#getSource", function() { describe("given it should use source maps", function() { beforeEach(function() { externalModule.useSourceMap = true; }); it("returns an instance of OriginalSource", function() { // set up const someSourceString = "some source string"; // invoke const result = externalModule.getSource(someSourceString); // check result.should.be.instanceOf(OriginalSource); }); }); describe("given it does not use source maps", function() { beforeEach(function() { externalModule.useSourceMap = false; }); it("returns an instance of RawSource", function() { // set up const someSourceString = "some source string"; // invoke const result = externalModule.getSource(someSourceString); // check result.should.be.instanceOf(RawSource); }); }); }); describe("#getSourceForGlobalVariableExternal", function() { describe("given an array as variable name in the global namespace", function() { it("use the array as lookup in the global object", function() { // set up const type = "window"; const varName = ["foo", "bar"]; const expected = "(function() { module.exports = window[\"foo\"][\"bar\"]; }());"; // invoke const result = externalModule.getSourceForGlobalVariableExternal(varName, type); // check result.should.eql(expected); }); }); describe("given an single variable name", function() { it("look it up in the global namespace", function() { // set up const type = "window"; const varName = "foo"; const expected = "(function() { module.exports = window[\"foo\"]; }());"; // invoke const result = externalModule.getSourceForGlobalVariableExternal(varName, type); // check result.should.eql(expected); }); }); }); describe("#getSourceForCommonJsExternal", function() { describe("given an array as names in the global namespace", function() { it("use the first to require a module and the rest as lookup on the required module", function() { // set up const varName = ["module", "look", "up"]; const expected = "module.exports = require(module)[\"look\"][\"up\"];"; // invoke const result = externalModule.getSourceForCommonJsExternal(varName, type); // check result.should.eql(expected); }); }); describe("given an single variable name", function() { it("require a module with that name", function() { // set up const type = "window"; const varName = "foo"; const expected = "module.exports = require(\"foo\");"; // invoke const result = externalModule.getSourceForCommonJsExternal(varName, type); // check result.should.eql(expected); }); }); }); describe("#checkExternalVariable", function() { it("creates a check that fails if a variable does not exist", function() { // set up const variableToCheck = "foo"; const request = "bar"; const expected = `if(typeof foo === 'undefined') {var e = new Error(\"Cannot find module \\\"bar\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e;} `; // invoke const result = externalModule.checkExternalVariable(variableToCheck, request); // check result.should.eql(expected); }); }); describe("#getSourceForAmdOrUmdExternal", function() { it("looks up a global variable as specified by the id", function() { // set up const id = "someId"; const optional = false; const expected = "module.exports = __WEBPACK_EXTERNAL_MODULE_someId__;"; // invoke const result = externalModule.getSourceForAmdOrUmdExternal(id, optional, request); // check result.should.eql(expected); }); describe("given an optinal check is set", function() { it("ads a check for the existance of the variable before looking it up", function() { // set up const id = "someId"; const optional = true; const expected = `if(typeof __WEBPACK_EXTERNAL_MODULE_someId__ === 'undefined') {var e = new Error("Cannot find module \\"some/request\\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = __WEBPACK_EXTERNAL_MODULE_someId__;`; // invoke const result = externalModule.getSourceForAmdOrUmdExternal(id, optional, request); // check result.should.eql(expected); }); }); }); describe("#getSourceForDefaultCase", function() { it("returns the given request as lookup", function() { // set up const optional = false; const expected = "module.exports = some/request;"; // invoke const result = externalModule.getSourceForDefaultCase(optional, request); // check result.should.eql(expected); }); describe("given an optinal check is requested", function() { it("checks for the existance of the request setting it", function() { // set up const optional = true; const expected = `if(typeof some/request === 'undefined') {var e = new Error("Cannot find module \\"some/request\\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = some/request;`; // invoke const result = externalModule.getSourceForDefaultCase(optional, request); // check result.should.eql(expected); }); }); }); describe("#getSourceString", function() { let globalExternalStub; let globalCommonJsStub; let globalAmdOrUmdStub; let defaultExternalStub; beforeEach(function() { globalExternalStub = externalModule.getSourceForGlobalVariableExternal = sinon.stub(); globalCommonJsStub = externalModule.getSourceForCommonJsExternal = sinon.stub(); globalAmdOrUmdStub = externalModule.getSourceForAmdOrUmdExternal = sinon.stub(); defaultExternalStub = externalModule.getSourceForDefaultCase = sinon.stub(); }); describe("with type being 'this', 'window' or 'global'", function() { it("deletgates to #getSourceForGlobalVariableExternal", function() { ["this", "window", "global"].forEach((type, i) => { // set up externalModule.type = type; // invoke externalModule.getSourceString(); // check globalExternalStub.callCount.should.eql(i + 1); globalCommonJsStub.callCount.should.eql(0); globalAmdOrUmdStub.callCount.should.eql(0); defaultExternalStub.callCount.should.eql(0); }); }); }); describe("with type being 'commonjs' or 'commonjs2'", function() { it("deletgates to #getSourceForCommonJsExternal", function() { ["commonjs", "commonjs2"].forEach((type, i) => { // set up externalModule.type = type; // invoke externalModule.getSourceString(); // check globalExternalStub.callCount.should.eql(0); globalCommonJsStub.callCount.should.eql(i + 1); globalAmdOrUmdStub.callCount.should.eql(0); defaultExternalStub.callCount.should.eql(0); }); }); }); describe("with type being 'amd', 'umd' or 'umd2'", function() { it("deletgates to #getSourceForAmdOrUmdExternal", function() { ["amd", "umd", "umd2"].forEach((type, i) => { // set up externalModule.type = type; // invoke externalModule.getSourceString(); // check globalExternalStub.callCount.should.eql(0); globalCommonJsStub.callCount.should.eql(0); globalAmdOrUmdStub.callCount.should.eql(i + 1); defaultExternalStub.callCount.should.eql(0); }); }); }); describe("with type being non of the above", function() { it("deletgates to #getSourceForGlobalVariableExternal", function() { ["foo", "bar", undefined].forEach((type, i) => { // set up externalModule.type = type; // invoke externalModule.getSourceString(); // check globalExternalStub.callCount.should.eql(0); globalCommonJsStub.callCount.should.eql(0); globalAmdOrUmdStub.callCount.should.eql(0); defaultExternalStub.callCount.should.eql(i + 1); }); }); }); }); }); webpack-3.5.6/test/HarmonyExportImportedSpecifierDependency.test.js000066400000000000000000000011001315401342100255720ustar00rootroot00000000000000/* globals describe, it, beforeEach */ "use strict"; const should = require("should"); 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(); should(instance.getHashValue(undefined)).be.eql(""); should(instance.getHashValue(null)).be.eql(""); }); }); }); webpack-3.5.6/test/HarmonyModulesHelpers.test.js000066400000000000000000000122271315401342100217230ustar00rootroot00000000000000/* globals describe, it, beforeEach */ "use strict"; const should = require("should"); const HarmonyModulesHelpers = require("../lib/dependencies/HarmonyModulesHelpers"); describe("HarmonyModulesHelpers", () => { describe("getModuleVar", () => { it("returns a module var without special characters", () => { should(HarmonyModulesHelpers.getModuleVar({}, 'w*thspeci@lcharact#rs')).be.eql("__WEBPACK_IMPORTED_MODULE_0_w_thspeci_lcharact_rs__"); }); it("returns a module var without double underscore", () => { should(HarmonyModulesHelpers.getModuleVar({}, 'without__double__underscore')).be.eql("__WEBPACK_IMPORTED_MODULE_0_without_double_underscore__"); }); it("returns a module var without spaces", () => { should(HarmonyModulesHelpers.getModuleVar({}, ' without spaces')).be.eql("__WEBPACK_IMPORTED_MODULE_0__without_spaces__"); }); describe("when has harmonyModules information", () => { let request, state, harmonyModuleVarInformation; before(() => { request = 'requested module'; state = { harmonyModules: ['sample test', request] }; harmonyModuleVarInformation = HarmonyModulesHelpers.getModuleVar(state, request); }); it("returns a module based on request position in state harmonyModules array", () => { should(harmonyModuleVarInformation).be.containEql(1); }); it("returns a module based on harmonyModules information", () => { should(harmonyModuleVarInformation).be.eql("__WEBPACK_IMPORTED_MODULE_1_requested_module__"); }); }); }); describe("getNewModuleVar", () => { it("returns module var based on `getModuleVar` method", () => { const request = 'sample test'; const state = { harmonyModules: [] }; should(HarmonyModulesHelpers.getNewModuleVar(state, request)).be.eql('__WEBPACK_IMPORTED_MODULE_0_sample_test__'); }); it("returns null if has request information inside state harmonyModules", () => { const request = 'sample test'; const state = { harmonyModules: [request] }; should(HarmonyModulesHelpers.getNewModuleVar(state, request)).be.eql(null); }); }); describe("checkModuleVar", () => { it("returns null if has current dependency and module dependency are different", () => { should(HarmonyModulesHelpers.checkModuleVar({ harmonyModules: ['sample test'] }, 'other sample test')).be.eql(null); }); it("returns null if has NOT request information inside state harmonyModules", () => { should(HarmonyModulesHelpers.checkModuleVar({ harmonyModules: [] }, 'sample test')).be.eql(null); }); it("returns module var based on `getModuleVar` method", () => { const request = 'sample test'; const state = { harmonyModules: [] }; should(HarmonyModulesHelpers.getNewModuleVar(state, request)).be.eql('__WEBPACK_IMPORTED_MODULE_0_sample_test__'); }); }); describe("isActive", () => { it("returns `true` if module has NOT dependencies", () => { const currentDependency = { describeHarmonyExport: () => { return { exportedName: '', precedence: 1 }; } }; const module = { dependencies: [] }; should(HarmonyModulesHelpers.isActive(module, currentDependency)).be.eql(true); }); it("returns `false` if module currentDependency has precedence greater than module dependency", () => { const currentDependency = { describeHarmonyExport: () => { return { exportedName: 'first dependency', precedence: 2 }; } }; const module = { dependencies: [{ describeHarmonyExport: () => { return { exportedName: 'first dependency', precedence: 1 }; } }] }; should(HarmonyModulesHelpers.isActive(module, currentDependency)).be.eql(false); }); describe("getActiveExports", () => { it("returns an empty array with modules has no dependency", () => { const currentDependency = { describeHarmonyExport: () => {} }; const module = { dependencies: [] }; should(HarmonyModulesHelpers.getActiveExports(module, currentDependency)).be.eql([]); }); it("returns an empty array if the precedence of current dependency is less than module dependency", () => { const currentDependency = { describeHarmonyExport: () => { return { exportedName: 'first dependency', precedence: 1 }; } }; const module = { dependencies: [{ describeHarmonyExport: () => { return { exportedName: 'first dependency', precedence: 2 }; } }] }; should(HarmonyModulesHelpers.getActiveExports(module, currentDependency)).be.eql([]); }); it("returns an array with modules if currentDependency has precedence greater than module dependency", () => { const currentDependency = { describeHarmonyExport: () => { return { exportedName: 'first dependency', precedence: 2 }; } }; const module = { dependencies: [{ describeHarmonyExport: () => { return { exportedName: 'first dependency', precedence: 1 }; } }] }; should(HarmonyModulesHelpers.getActiveExports(module, currentDependency)).be.eql(['first dependency']); }); }); }); }); webpack-3.5.6/test/HotModuleReplacementPlugin.test.js000066400000000000000000000051061315401342100226670ustar00rootroot00000000000000"use strict"; const should = require("should"); const path = require("path"); const fs = require("fs"); const webpack = require("../"); describe("HotModuleReplacementPlugin", function() { this.timeout(10000); it("should not have circular hashes but equal if unmodified", (done) => { const entryFile = path.join(__dirname, "js", "entry.js"); const statsFile1 = path.join(__dirname, "js", "HotModuleReplacementPlugin.test.stats1.txt"); const statsFile2 = path.join(__dirname, "js", "HotModuleReplacementPlugin.test.stats2.txt"); const recordsFile = path.join(__dirname, "js", "records.json"); try { fs.mkdirSync(path.join(__dirname, "js")); } catch(e) {} try { fs.unlinkSync(recordsFile); } catch(e) {} const compiler = webpack({ cache: false, entry: entryFile, recordsPath: recordsFile, output: { path: path.join(__dirname, "js") }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.optimize.OccurrenceOrderPlugin() ] }); 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()); lastHash1.should.be.eql(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()); lastHash2.should.not.be.eql(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()); currentHash1.should.not.be.eql(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; stats.toJson().hash.should.be.eql(currentHash2); currentHash2.should.not.be.eql(lastHash2); currentHash1.should.not.be.eql(currentHash2); lastHash1.should.not.be.eql(lastHash2); done(); }); }); }); }); }); }); }); }); webpack-3.5.6/test/HotTestCases.test.js000066400000000000000000000107251315401342100200040ustar00rootroot00000000000000"use strict"; const should = require("should"); const path = require("path"); const fs = require("fs"); const vm = require("vm"); const Test = require("mocha/lib/test"); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const checkArrayExpectation = require("./checkArrayExpectation"); 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) => { const suite = describe(testName, function() { this.timeout(10000); }); 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 = { options: { updateIndex: 0 } }; const configPath = path.join(testDirectory, "webpack.config.js"); let options = {}; if(fs.existsSync(configPath)) options = require(configPath); 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({ test: /\.js$/, loader: path.join(__dirname, "hotCases", "fake-update-loader.js"), enforce: "pre" }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }); 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), new ExtractTextPlugin("bundle.css") ); 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; let exportedTests = 0; function _it(title, fn) { const test = new Test(title, fn); suite.addTest(test); exportedTests++; return test; } function _next(callback) { fakeUpdateLoaderOptions.options.updateIndex++; compiler.run((err, stats) => { if(err) return done(err); const jsonStats = stats.toJson({ errorDetails: true }); if(checkArrayExpectation(testDirectory, jsonStats, "error", "errors" + fakeUpdateLoaderOptions.options.updateIndex, "Error", done)) return; if(checkArrayExpectation(testDirectory, jsonStats, "warning", "warnings" + fakeUpdateLoaderOptions.options.updateIndex, "Warning", done)) return; if(callback) callback(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, NEXT, STATS) {" + fs.readFileSync(p, "utf-8") + "\n})", p); const m = { exports: {} }; fn.call(m.exports, _require, m, m.exports, outputDirectory, p, _it, _next, jsonStats); return m.exports; } else return require(module); } _require("./bundle.js"); if(exportedTests < 1) return done(new Error("No tests exported by test case")); process.nextTick(done); }); }); }); }); }); }); webpack-3.5.6/test/HotUpdateChunkTemplate.test.js000066400000000000000000000036761315401342100220240ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const HotUpdateChunkTemplate = require("../lib/HotUpdateChunkTemplate"); describe("HotUpdateChunkTemplate", () => { let env; beforeEach(() => { env = { myHotUpdateChunkTemplate: new HotUpdateChunkTemplate({}) }; }); describe("render", () => { beforeEach(() => { env.renderContext = { renderChunkModules: sinon.spy(), applyPluginsWaterfall: sinon.spy() }; const renderArguments = [ "id", ["module1", "module2"], ["module3", "module4"], {}, "moduleTemplate", ["template1"] ]; env.myHotUpdateChunkTemplate.render.apply(env.renderContext, renderArguments); env.pluginsCall = env.renderContext.applyPluginsWaterfall; }); it("renders chunk modules", () => { env.renderContext.renderChunkModules.callCount.should.be.exactly(1); }); it("applies modules plugins", () => { env.pluginsCall.callCount.should.be.exactly(2); env.pluginsCall.firstCall.args[0].should.be.exactly("modules"); }); it("applies render plugins", () => { env.pluginsCall.callCount.should.be.exactly(2); env.pluginsCall.secondCall.args[0].should.be.exactly("render"); }); }); describe("updateHash", () => { beforeEach(() => { env.hash = { update: sinon.spy() }; env.updateHashContext = { applyPlugins: sinon.spy() }; env.myHotUpdateChunkTemplate.updateHash.call(env.updateHashContext, env.hash); }); it("updates hash", () => { env.hash.update.callCount.should.be.exactly(2); env.hash.update.firstCall.args[0].should.be.exactly("HotUpdateChunkTemplate"); env.hash.update.secondCall.args[0].should.be.exactly("1"); }); it("applies hash plugin", () => { env.updateHashContext.applyPlugins.callCount.should.be.exactly(1); env.updateHashContext.applyPlugins.firstCall.args[0].should.be.exactly("hash"); env.updateHashContext.applyPlugins.firstCall.args[1].should.be.exactly(env.hash); }); }); }); webpack-3.5.6/test/Integration.test.js000066400000000000000000000041671315401342100177210ustar00rootroot00000000000000"use strict"; const should = require("should"); const path = require("path"); const webpack = require("../lib/webpack"); describe("Integration", function() { this.timeout(5000); it("should compile library1", (done) => { webpack({ 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; stats.hasErrors().should.be.not.ok(); stats.hasWarnings().should.be.not.ok(); done(); }); }); it("should compile library2", (done) => { webpack({ 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 }, resolve: { // cannot resolve should outside the outermost node_modules // so it is injected here alias: { should: require.resolve("should") } }, 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.plugin("normal-module-factory", (nmf) => { nmf.plugin("after-resolve", (data, callback) => { data.resource = data.resource.replace(/extra\.js/, "extra2.js"); setTimeout(() => callback(null, data), 50); }); }); } ] }, (err, stats) => { if(err) throw err; stats.hasErrors().should.be.not.ok(); stats.hasWarnings().should.be.not.ok(); done(); }); }); }); webpack-3.5.6/test/JsonpExportMainTemplatePlugin.test.js000066400000000000000000000055351315401342100234110ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const TemplatePluginEnvironment = require("./helpers/TemplatePluginEnvironment"); const ConcatSource = require("webpack-sources").ConcatSource; const JsonpExportMainTemplatePlugin = require("../lib/JsonpExportMainTemplatePlugin"); describe("JsonpExportMainTemplatePlugin", () => { let env; const applyTemplatePluginWithOptions = function(Plugin, name) { const plugin = new Plugin(name); const templatePluginEnvironment = new TemplatePluginEnvironment(); const environment = templatePluginEnvironment.getEnvironmentStub(); environment.mainTemplate.applyPluginsWaterfall = () => "templateName"; plugin.apply(environment); return templatePluginEnvironment; }; beforeEach(() => env = {}); it("has apply function", () => (new JsonpExportMainTemplatePlugin()).apply.should.be.a.Function()); describe("when applied", () => { beforeEach(() => env.templatePlugin = applyTemplatePluginWithOptions(JsonpExportMainTemplatePlugin, "foo")); describe("event handlers", () => { beforeEach(() => env.eventBindings = env.templatePlugin.getEventBindings()); it("binds one handlers", () => env.eventBindings.length.should.be.exactly(1)); describe("render-with-entry handler", () => { beforeEach(() => env.eventBinding = env.eventBindings[0]); it("binds to render-with-entry event", () => env.eventBinding.name.should.be.exactly("render-with-entry")); it("creates source wrapper calling JSONP global callback", () => { const source = env.eventBinding.handler("moduleSource()", env.chunk, "bar"); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("templateName(moduleSource());"); }); }); }); describe("main template event handlers", () => { beforeEach(() => env.mainTemplateBindings = env.templatePlugin.getMainTemplateBindings()); it("binds two handlers", () => env.mainTemplateBindings.length.should.be.exactly(2)); describe("global-hash-paths handler", () => { beforeEach(() => env.mainTemplateBinding = env.mainTemplateBindings[0]); it("binds to global-hash-paths event", () => env.mainTemplateBinding.name.should.be.exactly("global-hash-paths")); it("adds name to path array", () => env.mainTemplateBinding.handler([]).should.deepEqual(["foo"])); }); describe("hash handler", () => { beforeEach(() => env.mainTemplateBinding = env.mainTemplateBindings[1]); it("binds to hash event", () => env.mainTemplateBinding.name.should.be.exactly("hash")); it("updates hash", () => { const hash = { update: sinon.spy() }; env.mainTemplateBinding.handler(hash); hash.update.callCount.should.be.exactly(2); hash.update.firstCall.args[0].should.be.exactly("jsonp export"); hash.update.secondCall.args[0].should.be.exactly("foo"); }); }); }); }); }); webpack-3.5.6/test/JsonpHotUpdateChunkTemplatePlugin.test.js000066400000000000000000000036741315401342100242130ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const ConcatSource = require("webpack-sources").ConcatSource; const JsonpHotUpdateChunkTemplatePlugin = require("../lib/JsonpHotUpdateChunkTemplatePlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("JsonpHotUpdateChunkTemplatePlugin", () => { let handlerContext; beforeEach(() => handlerContext = { outputOptions: { hotUpdateFunction: "Foo", library: "Bar" } }); it("has apply function", () => (new JsonpHotUpdateChunkTemplatePlugin()).apply.should.be.a.Function()); describe("when applied", () => { let eventBindings, eventBinding; beforeEach(() => eventBindings = applyPluginWithOptions(JsonpHotUpdateChunkTemplatePlugin)); it("binds two event handlers", () => eventBindings.length.should.be.exactly(2)); describe("render handler", () => { beforeEach(() => eventBinding = eventBindings[0]); it("binds to render event", () => eventBinding.name.should.be.exactly("render")); it("creates source wrapper with export", () => { const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("Foo(100,moduleSource())"); }); }); describe("hash handler", () => { let hashMock; beforeEach(() => { eventBinding = eventBindings[1]; hashMock = { update: sinon.spy() }; }); it("binds to hash event", () => eventBinding.name.should.be.exactly("hash")); it("updates hash object", () => { eventBinding.handler.call(handlerContext, hashMock); hashMock.update.callCount.should.be.exactly(4); sinon.assert.calledWith(hashMock.update, "JsonpHotUpdateChunkTemplatePlugin"); sinon.assert.calledWith(hashMock.update, "3"); sinon.assert.calledWith(hashMock.update, "Foo"); sinon.assert.calledWith(hashMock.update, "Bar"); }); }); }); }); webpack-3.5.6/test/LibraryTemplatePlugin.test.js000066400000000000000000000331351315401342100217120ustar00rootroot00000000000000var should = require("should"); var sinon = require("sinon"); var LibraryTemplatePlugin = require("../lib/LibraryTemplatePlugin"); var applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("LibraryTemplatePlugin", function() { var env; beforeEach(function() { env = { compilation: sinon.spy() }; }); it("has apply function", function() { (new LibraryTemplatePlugin()).apply.should.be.a.Function(); }); describe("when applied", function() { beforeEach(function() { env.eventBindings = applyPluginWithOptions(LibraryTemplatePlugin); }); it("binds two event handlers", function() { env.eventBindings.length.should.be.exactly(1); }); describe("this-compilation handler", function() { beforeEach(function() { env.eventBinding = env.eventBindings[0]; }); describe("event handler", function() { it("binds to this-compilation event", function() { env.eventBinding.name.should.be.exactly("this-compilation"); }); }); describe("when target is unknown", function() { beforeEach(function() { var unknownTarget = "unknownTarget"; env.eventBindings = applyPluginWithOptions(LibraryTemplatePlugin, "foo", unknownTarget, "bar", "baz"); env.eventBinding = env.eventBindings[0]; }); it("throws an error", function() { should(function() { env.eventBinding.handler(env.compilation); }).throw("unknownTarget is not a valid Library target"); }); }); describe("name is a string", function() { [{ type: "var", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("var foo"); should(compilationContext.copyObject).be.undefined(); } }, { type: "assign", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("foo"); should(compilationContext.copyObject).be.undefined(); } }, { type: "this", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('this["foo"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "window", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('window["foo"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "global", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('global["foo"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "commonjs", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('exports["foo"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "commonjs2", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("module.exports"); should(compilationContext.copyObject).be.undefined(); } }, { type: "commonjs-module", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("module.exports"); should(compilationContext.copyObject).be.undefined(); } }, { type: "amd", assertion: function(compilationContext) { compilationContext.name.should.be.exactly("foo"); } }, { type: "umd", assertion: function(compilationContext) { compilationContext.name.should.be.exactly("foo"); compilationContext.optionalAmdExternalAsGlobal.should.be.false(); compilationContext.namedDefine.should.be.exactly("bar"); compilationContext.auxiliaryComment.should.be.exactly("baz"); } }, { type: "umd2", assertion: function(compilationContext) { compilationContext.name.should.be.exactly("foo"); compilationContext.optionalAmdExternalAsGlobal.should.be.true(); compilationContext.namedDefine.should.be.exactly("bar"); compilationContext.auxiliaryComment.should.be.exactly("baz"); } }, { type: "jsonp", assertion: function(compilationContext) { compilationContext.name.should.be.exactly("foo"); } } ].forEach(function(targetTypeAndAssertion) { var type = targetTypeAndAssertion.type; describe("when target is " + type, function() { beforeEach(function() { env.eventBindings = applyPluginWithOptions(LibraryTemplatePlugin, "foo", type, "bar", "baz"); env.eventBinding = env.eventBindings[0]; env.eventBinding.handler(env.compilation); }); it("compilation callback is called", function() { env.compilation.callCount.should.be.exactly(1); }); it("compilation callback context is set up", function() { var compilationContext = env.compilation.firstCall.thisValue; targetTypeAndAssertion.assertion(compilationContext); }); }); }); }); describe("name is an array of strings", function() { [{ type: "var", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('var foo = foo || {}; foo["bar"] = foo["bar"] || {}; foo["bar"]["baz"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "assign", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('foo = typeof foo === "object" ? foo : {}; foo["bar"] = foo["bar"] || {}; foo["bar"]["baz"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "this", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('this["foo"] = this["foo"] || {}; this["foo"]["bar"] = this["foo"]["bar"] || {}; this["foo"]["bar"]["baz"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "window", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('window["foo"] = window["foo"] || {}; window["foo"]["bar"] = window["foo"]["bar"] || {}; window["foo"]["bar"]["baz"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "global", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('global["foo"] = global["foo"] || {}; global["foo"]["bar"] = global["foo"]["bar"] || {}; global["foo"]["bar"]["baz"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "commonjs", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly('exports["foo"] = exports["foo"] || {}; exports["foo"]["bar"] = exports["foo"]["bar"] || {}; exports["foo"]["bar"]["baz"]'); should(compilationContext.copyObject).be.undefined(); } }, { type: "commonjs2", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("module.exports"); should(compilationContext.copyObject).be.undefined(); } }, { type: "commonjs-module", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("module.exports"); should(compilationContext.copyObject).be.undefined(); } }, { type: "amd", assertion: function(compilationContext) { compilationContext.name.should.deepEqual(["foo", "bar", "baz"]); } }, { type: "umd", assertion: function(compilationContext) { compilationContext.name.should.deepEqual(["foo", "bar", "baz"]); compilationContext.optionalAmdExternalAsGlobal.should.be.false(); compilationContext.namedDefine.should.be.exactly("bar"); compilationContext.auxiliaryComment.should.be.exactly("baz"); } }, { type: "umd2", assertion: function(compilationContext) { compilationContext.name.should.deepEqual(["foo", "bar", "baz"]); compilationContext.optionalAmdExternalAsGlobal.should.be.true(); compilationContext.namedDefine.should.be.exactly("bar"); compilationContext.auxiliaryComment.should.be.exactly("baz"); } }, { type: "jsonp", assertion: function(compilationContext) { compilationContext.name.should.deepEqual(["foo", "bar", "baz"]); } } ].forEach(function(targetTypeAndAssertion) { var type = targetTypeAndAssertion.type; describe("when target is " + type, function() { beforeEach(function() { env.eventBindings = applyPluginWithOptions(LibraryTemplatePlugin, ["foo", "bar", "baz"], type, "bar", "baz"); env.eventBinding = env.eventBindings[0]; env.eventBinding.handler(env.compilation); }); it("compilation callback is called", function() { env.compilation.callCount.should.be.exactly(1); }); it("compilation callback context is set up", function() { var compilationContext = env.compilation.firstCall.thisValue; targetTypeAndAssertion.assertion(compilationContext); }); }); }); }); describe("name not provided", function() { [{ type: "this", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("this"); should(compilationContext.copyObject).be.true(); } }, { type: "window", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("window"); should(compilationContext.copyObject).be.true(); } }, { type: "global", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("global"); should(compilationContext.copyObject).be.true(); } }, { type: "commonjs", assertion: function(compilationContext) { compilationContext.varExpression.should.be.exactly("exports"); should(compilationContext.copyObject).be.true(); } } ].forEach(function(targetTypeAndAssertion) { var type = targetTypeAndAssertion.type; describe("when target is " + type, function() { beforeEach(function() { env.eventBindings = applyPluginWithOptions(LibraryTemplatePlugin, undefined, type, "bar", "baz"); env.eventBinding = env.eventBindings[0]; env.eventBinding.handler(env.compilation); }); it("compilation callback is called", function() { env.compilation.callCount.should.be.exactly(1); }); it("compilation callback context is set up", function() { var compilationContext = env.compilation.firstCall.thisValue; targetTypeAndAssertion.assertion(compilationContext); }); }); }); }); describe("name is an object of names per target", function() { [{ type: "umd", namedDefine: true, assertion: function(compilationContext) { compilationContext.name.should.be.exactly("barRoot"); compilationContext.names.should.deepEqual({ root: "barRoot", amd: "bar-amd" }); compilationContext.optionalAmdExternalAsGlobal.should.be.false(); compilationContext.namedDefine.should.be.exactly(true); compilationContext.auxiliaryComment.should.be.exactly("baz"); } }, { type: "umd", namedDefine: false, assertion: function(compilationContext) { compilationContext.name.should.be.exactly("barRoot"); compilationContext.names.should.deepEqual({ root: "barRoot", amd: "bar-amd" }); compilationContext.optionalAmdExternalAsGlobal.should.be.false(); compilationContext.namedDefine.should.be.exactly(false); compilationContext.auxiliaryComment.should.be.exactly("baz"); } }, { type: "umd2", namedDefine: true, assertion: function(compilationContext) { compilationContext.name.should.be.exactly("barRoot"); compilationContext.names.should.deepEqual({ root: "barRoot", amd: "bar-amd" }); compilationContext.optionalAmdExternalAsGlobal.should.be.true(); compilationContext.namedDefine.should.be.exactly(true); compilationContext.auxiliaryComment.should.be.exactly("baz"); } }, { type: "umd2", namedDefine: false, assertion: function(compilationContext) { compilationContext.name.should.be.exactly("barRoot"); compilationContext.names.should.deepEqual({ root: "barRoot", amd: "bar-amd" }); compilationContext.optionalAmdExternalAsGlobal.should.be.true(); compilationContext.namedDefine.should.be.exactly(false); compilationContext.auxiliaryComment.should.be.exactly("baz"); } } ].forEach(function(targetTypeAndAssertion) { var type = targetTypeAndAssertion.type; var namedDefine = targetTypeAndAssertion.namedDefine; describe("when target is " + type, function() { beforeEach(function() { env.eventBindings = applyPluginWithOptions(LibraryTemplatePlugin, { root: "barRoot", amd: "bar-amd" }, type, namedDefine, "baz"); env.eventBinding = env.eventBindings[0]; env.eventBinding.handler(env.compilation); }); it("compilation callback is called", function() { env.compilation.callCount.should.be.exactly(1); }); it("compilation callback context is set up", function() { var compilationContext = env.compilation.firstCall.thisValue; targetTypeAndAssertion.assertion(compilationContext); }); }); }); }); }); }); }); webpack-3.5.6/test/LocalModulesHelpers.test.js000066400000000000000000000024111315401342100213320ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const should = require("should"); 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"] }; should(LocalModulesHelpers.addLocalModule(state, "local_module_sample")).be.an.instanceOf(Object).and.have.properties({ module: "module_sample", name: "local_module_sample", idx: 2, used: false }); should(state.localModules.length).be.eql(3); }); }); describe("getLocalModule", () => { it("returns `null` if names information doesn't match", () => { const state = { module: "module_sample", localModules: [{ name: "first" }, { name: "second" }] }; should(LocalModulesHelpers.getLocalModule(state, "local_module_sample")).be.eql(null); }); it("returns local module informtion", () => { const state = { module: "module_sample", localModules: [{ name: "first" }, { name: "second" }] }; should(LocalModulesHelpers.getLocalModule(state, "first")).be.eql({ name: "first" }); }); }); }); webpack-3.5.6/test/ModuleDependencyError.test.js000066400000000000000000000022731315401342100216700ustar00rootroot00000000000000"use strict"; const path = require("path"); const should = require("should"); const sinon = require("sinon"); const ModuleDependencyError = require("../lib/ModuleDependencyError"); describe("ModuleDependencyError", () => { let env; beforeEach(() => env = {}); it("is a function", () => ModuleDependencyError.should.be.a.Function()); describe("when new error created", () => { beforeEach(() => { env.error = new Error("Error Message"); env.moduleDependencyError = new ModuleDependencyError("myModule", env.error, "Location"); }); it("is an error", () => env.moduleDependencyError.should.be.an.Error()); it("has a name property", () => env.moduleDependencyError.name.should.be.exactly("ModuleDependencyError")); it("has a message property", () => env.moduleDependencyError.message.should.be.exactly("Location Error Message")); it("has a details property", () => env.moduleDependencyError.details.should.containEql(path.join("test", "ModuleDependencyError.test.js:"))); it("has an origin property", () => env.moduleDependencyError.origin.should.be.exactly("myModule")); it("has an error property", () => env.moduleDependencyError.error.should.be.exactly(env.error)); }); }); webpack-3.5.6/test/ModuleReason.test.js000066400000000000000000000045321315401342100200270ustar00rootroot00000000000000"use strict"; const Module = require("../lib/Module"); const Chunk = require("../lib/Chunk"); const Dependency = require("../lib/Dependency"); const ModuleReason = require("../lib/ModuleReason"); const should = require("should"); 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", () => should(myModuleReason.hasChunk(myChunk)).be.false()); it("returns true when chunk is present", () => { myModuleReason.module.addChunk(myChunk); should(myModuleReason.hasChunk(myChunk)).be.true(); }); }); describe("rewriteChunks", () => { it("if old chunk is present, it is replaced with new chunks", () => { myModuleReason.module.addChunk(myChunk); myModuleReason.rewriteChunks(myChunk, [myChunk2]); should(myModuleReason.hasChunk(myChunk)).be.false(); should(myModuleReason.hasChunk(myChunk2)).be.true(); }); it("if old chunk is not present, new chunks are not added", () => { myModuleReason.rewriteChunks(myChunk, [myChunk2]); should(myModuleReason.hasChunk(myChunk)).be.false(); should(myModuleReason.hasChunk(myChunk2)).be.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]); should(myModuleReason.hasChunk(myChunk)).be.true(); should(myModuleReason.hasChunk(myChunk2)).be.false(); }); }); describe(".chunks", () => { it("is null if no rewrites happen first", () => { should(myModuleReason.chunks).be.Null(); }); it("is null if only invalid rewrites happen first", () => { myModuleReason.rewriteChunks(myChunk, [myChunk2]); should(myModuleReason.chunks).be.Null(); }); it("is an array of chunks if a valid rewrite happens", () => { myModuleReason.module.addChunk(myChunk); myModuleReason.rewriteChunks(myChunk, [myChunk2]); should(myModuleReason.chunks).be.eql([myChunk2]); }); }); }); webpack-3.5.6/test/MultiCompiler.test.js000066400000000000000000000360651315401342100202250ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const MultiCompiler = require("../lib/MultiCompiler"); function CompilerEnvironment() { const pluginEvents = []; const runCallbacks = []; const watchCallbacks = []; this.getCompilerStub = function() { return { plugin: function(name, handler) { pluginEvents.push({ name, handler }); }, run: function(callback) { runCallbacks.push({ callback }); }, watch: function(options, callback) { watchCallbacks.push({ options, callback }); return this.name; } }; }; this.getPluginEventBindings = () => pluginEvents; this.getRunCallbacks = () => runCallbacks; this.getWatchCallbacks = () => watchCallbacks; } const createCompiler = function(overrides) { const compilerEnvironment = new CompilerEnvironment(); return Object.assign({ outputPath: "/" }, compilerEnvironment.getCompilerStub(), overrides); }; const setupTwoCompilerEnvironment = function(env, compiler1Values, compiler2Values) { const compilerEnvironment1 = new CompilerEnvironment(); const compilerEnvironment2 = new CompilerEnvironment(); const compilers = [ Object.assign({ name: "compiler1" }, (compiler1Values || {}), compilerEnvironment1.getCompilerStub()), Object.assign({ name: "compiler2" }, (compiler2Values || {}), compilerEnvironment2.getCompilerStub()) ]; env.myMultiCompiler = new MultiCompiler(compilers); env.compiler1EventBindings = compilerEnvironment1.getPluginEventBindings(); env.compiler2EventBindings = compilerEnvironment2.getPluginEventBindings(); env.compiler1WatchCallbacks = compilerEnvironment1.getWatchCallbacks(); env.compiler2WatchCallbacks = compilerEnvironment2.getWatchCallbacks(); env.compiler1RunCallbacks = compilerEnvironment1.getRunCallbacks(); env.compiler2RunCallbacks = compilerEnvironment2.getRunCallbacks(); }; describe("MultiCompiler", () => { let env; beforeEach(() => env = {}); describe("constructor", () => { describe("when provided an array of compilers", () => { beforeEach(() => { env.compilers = [createCompiler(), createCompiler()]; env.myMultiCompiler = new MultiCompiler(env.compilers); }); it("sets the compilers property to the array", () => env.myMultiCompiler.compilers.should.be.exactly(env.compilers)); }); describe("when provided a compiler mapping", () => { beforeEach(() => { const compilers = { compiler1: createCompiler(), compiler2: createCompiler() }; env.myMultiCompiler = new MultiCompiler(compilers); }); it("sets the compilers property to an array of compilers", () => { env.myMultiCompiler.compilers.should.deepEqual([ Object.assign({ name: "compiler1" }, createCompiler()), Object.assign({ name: "compiler2" }, createCompiler()) ]); }); }); describe("defined properties", () => { describe("outputFileSystem", () => { beforeEach(() => { env.compilers = [createCompiler(), createCompiler()]; env.myMultiCompiler = new MultiCompiler(env.compilers); }); it("throws an error when reading the value", () => { should(() => { env.myMultiCompiler.outputFileSystem; }).throw("Cannot read outputFileSystem of a MultiCompiler"); }); it("updates all compilers when setting the value", () => { env.myMultiCompiler.outputFileSystem = "foo"; env.compilers[0].outputFileSystem.should.be.exactly("foo"); env.compilers[1].outputFileSystem.should.be.exactly("foo"); }); }); describe("inputFileSystem", () => { beforeEach(() => { env.compilers = [createCompiler(), createCompiler()]; env.myMultiCompiler = new MultiCompiler(env.compilers); }); it("throws an error when reading the value", () => { should(() => { env.myMultiCompiler.inputFileSystem; }).throw("Cannot read inputFileSystem of a MultiCompiler"); }); it("updates all compilers when setting the value", () => { env.myMultiCompiler.inputFileSystem = "foo"; env.compilers[0].inputFileSystem.should.be.exactly("foo"); env.compilers[1].inputFileSystem.should.be.exactly("foo"); }); }); describe("outputPath", () => { describe("when common path cannot be found and output path is absolute", () => { beforeEach(() => { env.compilers = [ createCompiler({ outputPath: "/foo/bar" }), createCompiler({ outputPath: "quux" }) ]; env.myMultiCompiler = new MultiCompiler(env.compilers); }); it("returns the root path", () => env.myMultiCompiler.outputPath.should.be.exactly("/")); }); describe("when common path cannot be found and output path is relative", () => { beforeEach(() => { env.compilers = [ createCompiler({ outputPath: "foo/bar/baz" }), createCompiler({ outputPath: "quux" }) ]; env.myMultiCompiler = new MultiCompiler(env.compilers); }); it("returns the first segment of relative path", () => env.myMultiCompiler.outputPath.should.be.exactly("foo")); }); describe("when common path can be found and output path is absolute", () => { beforeEach(() => { env.compilers = [ createCompiler({ outputPath: "/foo" }), createCompiler({ outputPath: "/foo/bar/baz" }) ]; env.myMultiCompiler = new MultiCompiler(env.compilers); }); it("returns the shared path", () => env.myMultiCompiler.outputPath.should.be.exactly("/foo")); }); describe("when common path can be found and output path is relative", () => { beforeEach(() => { env.compilers = [ createCompiler({ outputPath: "foo" }), createCompiler({ outputPath: "foo/bar/baz" }) ]; env.myMultiCompiler = new MultiCompiler(env.compilers); }); it("returns the shared path", () => env.myMultiCompiler.outputPath.should.be.exactly("foo")); }); }); }); describe("compiler events", () => { beforeEach(() => setupTwoCompilerEnvironment(env)); it("binds two event handler", () => { env.compiler1EventBindings.length.should.be.exactly(2); env.compiler2EventBindings.length.should.be.exactly(2); }); describe("done handler", () => { beforeEach(() => { env.doneEventBinding1 = env.compiler1EventBindings[0]; env.doneEventBinding2 = env.compiler2EventBindings[0]; }); it("binds to done event", () => env.doneEventBinding1.name.should.be.exactly("done")); describe("when called for first compiler", () => { beforeEach(() => { env.mockDonePlugin = sinon.spy(); env.myMultiCompiler.plugin("done", env.mockDonePlugin); env.doneEventBinding1.handler({ hash: "foo" }); }); it("does not call the done plugin when not all compilers are finished", () => env.mockDonePlugin.callCount.should.be.exactly(0)); describe("and called for second compiler", () => { beforeEach(() => env.doneEventBinding2.handler({ hash: "bar" })); it("calls the done plugin", () => env.mockDonePlugin.callCount.should.be.exactly(1)); }); }); }); describe("invalid handler", () => { beforeEach(() => env.invalidEventBinding = env.compiler1EventBindings[1]); it("binds to invalid event", () => env.invalidEventBinding.name.should.be.exactly("invalid")); describe("when called", () => { beforeEach(() => { env.mockInvalidPlugin = sinon.spy(); env.myMultiCompiler.plugin("invalid", env.mockInvalidPlugin); env.invalidEventBinding.handler(); }); it("calls the invalid plugin", () => env.mockInvalidPlugin.callCount.should.be.exactly(1)); }); }); }); }); describe("watch", () => { describe("without compiler dependencies", () => { beforeEach(() => { setupTwoCompilerEnvironment(env); env.callback = sinon.spy(); env.options = [{ testWatchOptions: true }, { testWatchOptions2: true }]; env.result = env.myMultiCompiler.watch(env.options, env.callback); }); it("returns a multi-watching object", () => { const result = JSON.stringify(env.result); result.should.be.exactly('{"watchings":["compiler1","compiler2"],"compiler":{"_plugins":{},"compilers":[{"name":"compiler1"},{"name":"compiler2"}]}}'); }); it("calls watch on each compiler with original options", () => { env.compiler1WatchCallbacks.length.should.be.exactly(1); env.compiler1WatchCallbacks[0].options.should.be.exactly(env.options[0]); env.compiler2WatchCallbacks.length.should.be.exactly(1); env.compiler2WatchCallbacks[0].options.should.be.exactly(env.options[1]); }); it("calls the callback when all compilers watch", () => { env.compiler1WatchCallbacks[0].callback(null, { hash: "foo" }); env.callback.callCount.should.be.exactly(0); env.compiler2WatchCallbacks[0].callback(null, { hash: "bar" }); env.callback.callCount.should.be.exactly(1); }); describe("on first run", () => { describe("callback called with no compiler errors", () => { beforeEach(() => env.compiler1WatchCallbacks[0].callback(new Error("Test error"))); it("has failure parameters", () => { env.callback.callCount.should.be.exactly(1); env.callback.getCall(0).args[0].should.be.Error(); should(env.callback.getCall(0).args[1]).be.undefined(); }); }); describe("callback called with no compiler errors", () => { beforeEach(() => env.compiler1WatchCallbacks[0].callback(null, { hash: "foo" })); it("does not call the callback", () => env.callback.callCount.should.be.exactly(0)); }); }); describe("on subsequent runs", () => { describe("callback called with compiler errors", () => { beforeEach(() => { env.compiler1WatchCallbacks[0].callback(null, { hash: "foo" }); env.compiler2WatchCallbacks[0].callback(new Error("Test error")); }); it("has failure parameters", () => { env.callback.callCount.should.be.exactly(1); env.callback.getCall(0).args[0].should.be.Error(); should(env.callback.getCall(0).args[1]).be.undefined(); }); }); describe("callback called with no compiler errors", () => { beforeEach(() => { env.compiler1WatchCallbacks[0].callback(null, { hash: "foo" }); env.compiler2WatchCallbacks[0].callback(null, { hash: "bar" }); }); it("has success parameters", () => { env.callback.callCount.should.be.exactly(1); should(env.callback.getCall(0).args[0]).be.Null(); const stats = JSON.stringify(env.callback.getCall(0).args[1]); stats.should.be.exactly('{"stats":[{"hash":"foo"},{"hash":"bar"}],"hash":"foobar"}'); }); }); }); }); describe("with compiler dependencies", () => { beforeEach(() => { setupTwoCompilerEnvironment(env, { name: "compiler1", dependencies: ["compiler2"] }, { name: "compiler2" }); env.callback = sinon.spy(); env.options = [{ testWatchOptions: true }, { testWatchOptions2: true }]; env.result = env.myMultiCompiler.watch(env.options, env.callback); }); it("calls run on each compiler in dependency order", () => { env.compiler1WatchCallbacks.length.should.be.exactly(0); env.compiler2WatchCallbacks.length.should.be.exactly(1); env.compiler2WatchCallbacks[0].options.should.be.exactly(env.options[1]); env.compiler2WatchCallbacks[0].callback(null, { hash: "bar" }); env.compiler1WatchCallbacks.length.should.be.exactly(1); env.compiler1WatchCallbacks[0].options.should.be.exactly(env.options[0]); }); it("calls the callback when all compilers run in dependency order", () => { env.compiler2WatchCallbacks[0].callback(null, { hash: "bar" }); env.callback.callCount.should.be.exactly(0); env.compiler1WatchCallbacks[0].callback(null, { hash: "foo" }); env.callback.callCount.should.be.exactly(1); }); }); }); describe("run", () => { describe("without compiler dependencies", () => { beforeEach(() => { setupTwoCompilerEnvironment(env); env.callback = sinon.spy(); env.myMultiCompiler.run(env.callback); }); it("calls run on each compiler", () => { env.compiler1RunCallbacks.length.should.be.exactly(1); env.compiler2RunCallbacks.length.should.be.exactly(1); }); it("calls the callback when all compilers run", () => { env.compiler1RunCallbacks[0].callback(null, { hash: "foo" }); env.callback.callCount.should.be.exactly(0); env.compiler2RunCallbacks[0].callback(null, { hash: "bar" }); env.callback.callCount.should.be.exactly(1); }); describe("callback called with no compiler errors", () => { beforeEach(() => { env.compiler1RunCallbacks[0].callback(null, { hash: "foo" }); env.compiler2RunCallbacks[0].callback(null, { hash: "bar" }); }); it("has success parameters", () => { env.callback.callCount.should.be.exactly(1); should(env.callback.getCall(0).args[0]).be.Null(); const stats = JSON.stringify(env.callback.getCall(0).args[1]); stats.should.be.exactly('{"stats":[{"hash":"foo"},{"hash":"bar"}],"hash":"foobar"}'); }); }); describe("callback called with compiler errors", () => { beforeEach(() => { env.compiler1RunCallbacks[0].callback(null, { hash: "foo" }); env.compiler2RunCallbacks[0].callback(new Error("Test error")); }); it("has failure parameters", () => { env.callback.callCount.should.be.exactly(1); env.callback.getCall(0).args[0].should.be.Error(); should(env.callback.getCall(0).args[1]).be.undefined(); }); }); }); describe("with compiler dependencies", () => { beforeEach(() => { setupTwoCompilerEnvironment(env, { name: "compiler1", dependencies: ["compiler2"] }, { name: "compiler2" }); env.callback = sinon.spy(); env.myMultiCompiler.run(env.callback); }); it("calls run on each compiler in dependency order", () => { env.compiler1RunCallbacks.length.should.be.exactly(0); env.compiler2RunCallbacks.length.should.be.exactly(1); env.compiler2RunCallbacks[0].callback(null, { hash: "bar" }); env.compiler1RunCallbacks.length.should.be.exactly(1); }); it("calls the callback when all compilers run in dependency order", () => { env.compiler2RunCallbacks[0].callback(null, { hash: "bar" }); env.callback.callCount.should.be.exactly(0); env.compiler1RunCallbacks[0].callback(null, { hash: "foo" }); env.callback.callCount.should.be.exactly(1); }); }); }); describe("purgeInputFileSystem", () => { beforeEach(() => { env.compilers = [ Object.assign({ inputFileSystem: { purge: sinon.spy() } }, createCompiler()), createCompiler() ]; env.myMultiCompiler = new MultiCompiler(env.compilers); env.myMultiCompiler.purgeInputFileSystem(); }); it("calls the compilers purge if available", () => { const purgeSpy = env.compilers[0].inputFileSystem.purge; purgeSpy.callCount.should.be.exactly(1); }); }); }); webpack-3.5.6/test/MultiStats.test.js000066400000000000000000000125301315401342100175400ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const packageJSON = require("../package.json"); const MultiStats = require("../lib/MultiStats"); const createStat = overides => { return Object.assign({ hash: "foo", compilation: { name: "bar" }, hasErrors: () => false, hasWarnings: () => false, toJson: () => Object.assign({ hash: "foo", version: "version", warnings: [], errors: [] }, overides) }, overides); }; 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", () => myMultiStats.hash.should.be.exactly("abc123xyz890")); }); describe("hasErrors", () => { describe("when both have errors", () => { beforeEach(() => { stats = [ createStat({ hasErrors: () => true }), createStat({ hasErrors: () => true }) ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => myMultiStats.hasErrors().should.be.exactly(true)); }); describe("when one has an error", () => { beforeEach(() => { stats = [ createStat({ hasErrors: () => true }), createStat() ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => myMultiStats.hasErrors().should.be.exactly(true)); }); describe("when none have errors", () => { beforeEach(() => { stats = [ createStat(), createStat() ]; myMultiStats = new MultiStats(stats); }); it("returns false", () => myMultiStats.hasErrors().should.be.exactly(false)); }); }); describe("hasWarnings", () => { describe("when both have warnings", () => { beforeEach(() => { stats = [ createStat({ hasWarnings: () => true }), createStat({ hasWarnings: () => true }) ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => myMultiStats.hasWarnings().should.be.exactly(true)); }); describe("when one has a warning", () => { beforeEach(() => { stats = [ createStat({ hasWarnings: () => true }), createStat() ]; myMultiStats = new MultiStats(stats); }); it("returns true", () => myMultiStats.hasWarnings().should.be.exactly(true)); }); describe("when none have warnings", () => { beforeEach(() => { stats = [ createStat(), createStat() ]; myMultiStats = new MultiStats(stats); }); it("returns false", () => myMultiStats.hasWarnings().should.be.exactly(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 }); result.should.deepEqual({ 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); result.should.deepEqual({ 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", () => { result.should.be.exactly( "Hash: abc123xyz890\n" + "Version: webpack 1.2.3\n" + "Child abc123-compilation:\n" + " Hash: abc123\n" + "Child xyz890-compilation:\n" + " Hash: xyz890" ); }); }); }); webpack-3.5.6/test/MultiWatching.test.js000066400000000000000000000027111315401342100202060ustar00rootroot00000000000000"use strict"; const Tapable = require("tapable"); const should = require("should"); const sinon = require("sinon"); const MultiWatching = require("../lib/MultiWatching"); const createWatching = function() { return { invalidate: sinon.spy(), close: sinon.spy() }; }; const createCompiler = () => { const compiler = { _plugins: {} }; Tapable.mixin(compiler); return compiler; }; describe("MultiWatching", () => { let watchings, compiler, myMultiWatching; beforeEach(() => { watchings = [createWatching(), createWatching()]; compiler = createCompiler(); myMultiWatching = new MultiWatching(watchings, compiler); }); describe("invalidate", () => { beforeEach(() => myMultiWatching.invalidate()); it("invalidates each watching", () => { watchings[0].invalidate.callCount.should.be.exactly(1); watchings[1].invalidate.callCount.should.be.exactly(1); }); }); describe("close", () => { let callback; const callClosedFinishedCallback = (watching) => watching.close.getCall(0).args[0](); beforeEach(() => { callback = sinon.spy(); myMultiWatching.close(callback); }); it("closes each watching", () => { watchings[0].close.callCount.should.be.exactly(1); watchings[1].close.callCount.should.be.exactly(1); }); it("calls callback after each watching has closed", () => { callClosedFinishedCallback(watchings[0]); callClosedFinishedCallback(watchings[1]); callback.callCount.should.be.exactly(1); }); }); }); webpack-3.5.6/test/NodeHotUpdateChunkTemplatePlugin.test.js000066400000000000000000000037361315401342100240060ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const ConcatSource = require("webpack-sources").ConcatSource; const NodeHotUpdateChunkTemplatePlugin = require("../lib/node/NodeHotUpdateChunkTemplatePlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("NodeHotUpdateChunkTemplatePlugin", () => { let handlerContext; beforeEach(() => { handlerContext = { outputOptions: { hotUpdateFunction: "Foo", library: "Bar" } }; }); it("has apply function", () => (new NodeHotUpdateChunkTemplatePlugin()).apply.should.be.a.Function()); describe("when applied", () => { let eventBindings, eventBinding; beforeEach(() => eventBindings = applyPluginWithOptions(NodeHotUpdateChunkTemplatePlugin)); it("binds two event handlers", () => eventBindings.length.should.be.exactly(2)); describe("render handler", () => { beforeEach(() => eventBinding = eventBindings[0]); it("binds to render event", () => eventBinding.name.should.be.exactly("render")); it("creates source wrapper with export", () => { const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("exports.id = 100;\nexports.modules = moduleSource();"); }); }); describe("hash handler", () => { let hashMock; beforeEach(() => { eventBinding = eventBindings[1]; hashMock = { update: sinon.spy() }; }); it("binds to hash event", () => eventBinding.name.should.be.exactly("hash")); it("updates hash object", () => { eventBinding.handler.call(handlerContext, hashMock); hashMock.update.callCount.should.be.exactly(4); sinon.assert.calledWith(hashMock.update, "NodeHotUpdateChunkTemplatePlugin"); sinon.assert.calledWith(hashMock.update, "3"); sinon.assert.calledWith(hashMock.update, "Foo"); sinon.assert.calledWith(hashMock.update, "Bar"); }); }); }); }); webpack-3.5.6/test/NodeTemplatePlugin.test.js000066400000000000000000000040361315401342100211710ustar00rootroot00000000000000/* global describe, it */ "use strict"; const should = require("should"); const path = require("path"); const webpack = require("../lib/webpack"); describe("NodeTemplatePlugin", () => { it("should compile and run a simple module", (done) => { webpack({ context: path.join(__dirname, "fixtures", "nodetest"), target: "node", output: { path: path.join(__dirname, "js"), filename: "result.js", chunkFilename: "[hash].result.[id].js", library: "abc", libraryTarget: "commonjs", }, entry: "./entry", plugins: [ new webpack.optimize.UglifyJsPlugin() ] }, (err, stats) => { if(err) return err; stats.hasErrors().should.be.not.ok(); stats.hasWarnings().should.be.not.ok(); const result = require("./js/result").abc; result.nextTick.should.be.equal(process.nextTick); result.fs.should.be.equal(require("fs")); result.loadChunk(456, (chunk) => { chunk.should.be.eql(123); result.loadChunk(567, (chunk) => { chunk.should.be.eql({ a: 1 }); done(); }); }); }); }); it("should compile and run a simple module in single mode", (done) => { webpack({ context: path.join(__dirname, "fixtures", "nodetest"), target: "node", output: { path: path.join(__dirname, "js"), filename: "result2.js", chunkFilename: "[hash].result2.[id].js", library: "def", libraryTarget: "umd", auxiliaryComment: "test" }, entry: "./entry", plugins: [ new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }), new webpack.optimize.UglifyJsPlugin() ] }, (err, stats) => { if(err) return err; stats.hasErrors().should.be.not.ok(); const result = require("./js/result2"); result.nextTick.should.be.equal(process.nextTick); result.fs.should.be.equal(require("fs")); const sameTick = true; result.loadChunk(456, (chunk) => { chunk.should.be.eql(123); sameTick.should.be.eql(true); result.loadChunk(567, (chunk) => { chunk.should.be.eql({ a: 1 }); done(); }); }); }); }); }); webpack-3.5.6/test/NodeWatchFileSystem.test.js000066400000000000000000000175171315401342100213220ustar00rootroot00000000000000/* globals describe it */ var should = require("should"); var NodeWatchFileSystem = require("../lib/node/NodeWatchFileSystem"); describe("NodeWatchFileSystem", function() { it('should throw if \'files\' argument is not an array', function() { should(function() { new NodeWatchFileSystem().watch(undefined) }).throw("Invalid arguments: 'files'"); }); it('should throw if \'dirs\' argument is not an array', function() { should(function() { new NodeWatchFileSystem().watch([], undefined) }).throw("Invalid arguments: 'dirs'"); }); it('should throw if \'missing\' argument is not an array', function() { should(function() { new NodeWatchFileSystem().watch([], [], undefined) }).throw("Invalid arguments: 'missing'"); }); it('should throw if \'starttime\' argument is missing', function() { should(function() { new NodeWatchFileSystem().watch([], [], [], '42', {}, function() {}) }).throw("Invalid arguments: 'startTime'"); }); it('should throw if \'callback\' argument is missing', function() { should(function() { new NodeWatchFileSystem().watch([], [], [], 42, {}, undefined) }).throw("Invalid arguments: 'callback'"); }); it('should throw if \'options\' argument is invalid', function() { should(function() { new NodeWatchFileSystem().watch([], [], [], 42, 'options', function() {}) }).throw("Invalid arguments: 'options'"); }); it('should throw if \'callbackUndelayed\' argument is invalid', function() { should(function() { new NodeWatchFileSystem().watch([], [], [], 42, {}, function() {}, 'undefined') }).throw("Invalid arguments: 'callbackUndelayed'"); }); if(process.env.NO_WATCH_TESTS) { it("long running tests excluded"); return; } var path = require("path"); var fs = require("fs"); var fixtures = path.join(__dirname, "fixtures"); var fileDirect = path.join(fixtures, "watched-file.txt"); var fileSubdir = path.join(fixtures, "subdir", "watched-file.txt"); this.timeout(10000); it("should register a file change (change delayed)", function(done) { var startTime = new Date().getTime(); var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([fileDirect], [], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */ ) { if(err) throw err; filesModified.should.be.eql([fileDirect]); dirsModified.should.be.eql([]); Object.assign({}, fileTimestamps).should.have.property(fileDirect).have.type("number"); watcher.close(); done(); }); setTimeout(function() { fs.writeFile(fileDirect, "", function() {}); }, 500); }); it("should register a file change (watch delayed)", function(done) { var startTime = new Date().getTime(); setTimeout(function() { var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([fileDirect], [], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */ ) { if(err) throw err; filesModified.should.be.eql([fileDirect]); dirsModified.should.be.eql([]); Object.assign({}, fileTimestamps).should.have.property(fileDirect).have.type("number"); watcher.close(); done(); }); }, 500); fs.writeFile(fileDirect, "", function() {}); }); it("should register a context change (change delayed)", function(done) { var startTime = new Date().getTime(); var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) { if(err) throw err; filesModified.should.be.eql([]); dirsModified.should.be.eql([fixtures]); Object.assign({}, dirTimestamps).should.have.property(fixtures).have.type("number"); watcher.close(); done(); }); setTimeout(function() { fs.writeFile(fileDirect, "", function() {}); }, 500); }); it("should register a context change (watch delayed)", function(done) { var startTime = new Date().getTime(); setTimeout(function() { var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) { if(err) throw err; filesModified.should.be.eql([]); dirsModified.should.be.eql([fixtures]); Object.assign({}, dirTimestamps).should.have.property(fixtures).have.type("number"); watcher.close(); done(); }); }, 500); fs.writeFile(fileDirect, "", function() {}); }); it("should register a context change (change delayed, subdirectory)", function(done) { var startTime = new Date().getTime(); var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) { if(err) throw err; filesModified.should.be.eql([]); dirsModified.should.be.eql([fixtures]); Object.assign({}, dirTimestamps).should.have.property(fixtures).have.type("number"); watcher.close(); done(); }); setTimeout(function() { fs.writeFile(fileSubdir, "", function() {}); }, 500); }); it("should register a context change (watch delayed, subdirectory)", function(done) { var startTime = new Date().getTime(); setTimeout(function() { var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) { if(err) throw err; filesModified.should.be.eql([]); dirsModified.should.be.eql([fixtures]); Object.assign({}, dirTimestamps).should.have.property(fixtures).have.type("number"); watcher.close(); done(); }); }, 500); fs.writeFile(fileSubdir, "", function() {}); }); it("should allow to combine all", function(done) { var startTime = new Date().getTime(); setTimeout(function() { var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([fileDirect, fileSubdir], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) { if(err) throw err; filesModified.should.be.eql([fileSubdir, fileDirect]); dirsModified.should.be.eql([fixtures]); Object.assign({}, fileTimestamps).should.have.property(fileDirect).have.type("number"); Object.assign({}, fileTimestamps).should.have.property(fileSubdir).have.type("number"); Object.assign({}, dirTimestamps).should.have.property(fixtures).have.type("number"); watcher.close(); done(); }); }, 500); fs.writeFile(fileDirect, "", function() {}); fs.writeFile(fileSubdir, "", function() {}); }); it("should sum up multiple changes", function(done) { var startTime = new Date().getTime(); var wfs = new NodeWatchFileSystem(); var watcher = wfs.watch([fileDirect, fileSubdir], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) { if(err) throw err; filesModified.should.be.eql([fileSubdir, fileDirect]); dirsModified.should.be.eql([fixtures]); Object.assign({}, fileTimestamps).should.have.property(fileDirect).have.type("number"); Object.assign({}, fileTimestamps).should.have.property(fileSubdir).have.type("number"); Object.assign({}, dirTimestamps).should.have.property(fixtures).have.type("number"); watcher.close(); done(); }); setTimeout(function() { fs.writeFile(fileDirect, "", function() {}); setTimeout(function() { fs.writeFile(fileDirect, "", function() {}); setTimeout(function() { fs.writeFile(fileDirect, "", function() {}); setTimeout(function() { fs.writeFile(fileSubdir, "", function() {}); }, 500); }, 500); }, 500); }, 500); }); }); webpack-3.5.6/test/NormalModule.test.js000066400000000000000000000324401315401342100200270ustar00rootroot00000000000000/* globals describe, it, beforeEach, afterEach */ "use strict"; require("should"); const sinon = require("sinon"); 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", function() { let normalModule; let request; let userRequest; let rawRequest; let loaders; let resource; let parser; beforeEach(function() { request = "some/request"; userRequest = "some/userRequest"; rawRequest = "some/rawRequest"; loaders = []; resource = "some/resource"; parser = { parse() {} }; normalModule = new NormalModule( request, userRequest, rawRequest, loaders, resource, parser ); }); describe("#identifier", function() { it("returns an identifier for this module", function() { normalModule.identifier().should.eql(request); }); it("returns an identifier from toString", function() { normalModule.debugId = 1000; normalModule.toString().should.eql("Module[1000]"); normalModule.id = 1; normalModule.toString().should.eql("Module[1]"); }); }); describe("#readableIdentifier", function() { it("calls the given requestShortener with the user request", function() { const spy = sinon.spy(); normalModule.readableIdentifier({ shorten: spy }); spy.callCount.should.eql(1); spy.args[0][0].should.eql(userRequest); }); }); describe("#libIdent", function() { it("contextifies the userRequest of the module", function() { normalModule.libIdent({ context: "some/context" }).should.eql("../userRequest"); }); describe("given a userRequest containing loaders", function() { beforeEach(function() { userRequest = "some/userRequest!some/other/userRequest!some/thing/is/off/here"; normalModule = new NormalModule( request, userRequest, rawRequest, loaders, resource, parser ); }); it("contextifies every path in the userRequest", function() { normalModule.libIdent({ context: "some/context" }).should.eql("../userRequest!../other/userRequest!../thing/is/off/here"); }); }); describe("given a userRequest containing query parameters", function() { it("ignores paths in query parameters", function() { userRequest = "some/context/loader?query=foo\\bar&otherPath=testpath/other"; normalModule = new NormalModule( request, userRequest, rawRequest, loaders, resource, parser ); normalModule.libIdent({ context: "some/context", }).should.eql("./loader?query=foo\\bar&otherPath=testpath/other"); }); }); }); describe("#nameForCondition", function() { it("return the resource", function() { normalModule.nameForCondition().should.eql(resource); }); describe("given a resource containing a ?-sign", function() { const baseResource = "some/resource"; beforeEach(function() { resource = baseResource + "?some=query"; normalModule = new NormalModule( request, userRequest, rawRequest, loaders, resource, parser ); }); it("return only the part before the ?-sign", function() { normalModule.nameForCondition().should.eql(baseResource); }); }); }); describe("#createSourceForAsset", function() { let name; let content; let sourceMap; beforeEach(function() { name = "some name"; content = "some content"; sourceMap = "some sourcemap"; }); describe("given no sourcemap", function() { it("returns a RawSource", function() { normalModule.createSourceForAsset(name, content).should.be.instanceOf(RawSource); }); }); describe("given a string as the sourcemap", function() { it("returns a OriginalSource", function() { normalModule.createSourceForAsset(name, content, sourceMap).should.be.instanceOf(OriginalSource); }); }); describe("given a some other kind of sourcemap", function() { beforeEach(function() { sourceMap = () => {}; }); it("returns a SourceMapSource", function() { normalModule.createSourceForAsset(name, content, sourceMap).should.be.instanceOf(SourceMapSource); }); }); }); describe("#source", function() { describe("without the module having any source", function() { beforeEach(function() { normalModule._source = null; }); it("returns a Source containing an Error", function() { normalModule.source().should.be.instanceOf(RawSource); normalModule.source().source().should.eql("throw new Error('No source available');"); }); }); }); describe("#originalSource", function() { let expectedSource = "some source"; beforeEach(function() { normalModule._source = new RawSource(expectedSource); }); it("returns an original Source", function() { normalModule.originalSource().should.eql(normalModule._source); }); }); describe("#updateHashWithSource", function() { let hashSpy; let hash; beforeEach(function() { hashSpy = sinon.spy(); hash = { update: hashSpy }; }); describe("without the module having any source", function() { beforeEach(function() { normalModule._source = null; }); it("calls hash function with \"null\"", function() { normalModule.updateHashWithSource(hash); hashSpy.callCount.should.eql(1); hashSpy.args[0][0].should.eql("null"); }); }); describe("without the module having source", function() { let expectedSource = "some source"; beforeEach(function() { normalModule._source = new RawSource(expectedSource); }); it("calls hash function with \"source\" and then the actual source of the module", function() { normalModule.updateHashWithSource(hash); hashSpy.callCount.should.eql(2); hashSpy.args[0][0].should.eql("source"); hashSpy.args[1][0].should.eql(expectedSource); }); }); }); describe("#hasDependencies", function() { it("returns true if has dependencies", function() { normalModule.addDependency(new NullDependency()); normalModule.hasDependencies().should.eql(true); }); it("returns false if has dependencies", function() { normalModule.hasDependencies().should.eql(false); }); }); describe("#needRebuild", function() { let fileTimestamps; let contextTimestamps; let fileDependencies; let contextDependencies; let fileA; let fileB; function setDeps( fileDependencies, contextDependencies) { normalModule.fileDependencies = fileDependencies; normalModule.contextDependencies = contextDependencies; } beforeEach(function() { fileA = "fileA"; fileB = "fileB"; fileDependencies = [fileA, fileB]; contextDependencies = [fileA, fileB]; fileTimestamps = { [fileA]: 1, [fileB]: 1, }; contextTimestamps = { [fileA]: 1, [fileB]: 1, }; normalModule.buildTimestamp = 2; setDeps(fileDependencies, contextDependencies); }); describe("given all timestamps are older than the buildTimestamp", function() { it("returns false", function() { normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(false); }); }); describe("given a file timestamp is newer than the buildTimestamp", function() { beforeEach(function() { fileTimestamps[fileA] = 3; }); it("returns true", function() { normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true); }); }); describe("given a no file timestamp exists", function() { beforeEach(function() { fileTimestamps = {}; }); it("returns true", function() { normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true); }); }); describe("given a context timestamp is newer than the buildTimestamp", function() { beforeEach(function() { contextTimestamps[fileA] = 3; }); it("returns true", function() { normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true); }); }); describe("given a no context timestamp exists", function() { beforeEach(function() { contextTimestamps = {}; }); it("returns true", function() { normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true); }); }); }); describe("#splitVariablesInUniqueNamedChunks", function() { let variables; beforeEach(function() { variables = [{ name: "foo" }, { name: "bar" }, { name: "baz" }, { name: "some" }, { name: "more" }]; }); describe("given an empty array of vars", function() { it("returns an empty array", function() { normalModule.splitVariablesInUniqueNamedChunks([]).should.eql([ [] ]); }); }); describe("given an array of distrinct variables", function() { it("returns an array containing an array containing the variables", function() { normalModule.splitVariablesInUniqueNamedChunks(variables).should.eql([variables]); }); }); describe("given an array with duplicate variables", function() { it("returns several arrays each containing only distinct variable names", function() { normalModule.splitVariablesInUniqueNamedChunks(variables.concat(variables)).should.eql([variables, variables]); }); describe("and a duplicate as the last variable", function() { it("returns correctly split distinct arrays", function() { normalModule.splitVariablesInUniqueNamedChunks(variables.concat(variables).concat(variables[0])).should.eql([variables, variables, [variables[0]]]); }); }); }); }); describe("#applyNoParseRule", function() { let rule; let content; describe("given a string as rule", function() { beforeEach(function() { rule = "some-rule"; }); describe("and the content starting with the string specified in rule", function() { beforeEach(function() { content = rule + "some-content"; }); it("returns true", function() { normalModule.shouldPreventParsing(rule, content).should.eql(true); }); }); describe("and the content does not start with the string specified in rule", function() { beforeEach(function() { content = "some-content"; }); it("returns false", function() { normalModule.shouldPreventParsing(rule, content).should.eql(false); }); }); }); describe("given a regex as rule", function() { beforeEach(function() { rule = /some-rule/; }); describe("and the content matches the rule", function() { beforeEach(function() { content = rule + "some-content"; }); it("returns true", function() { normalModule.shouldPreventParsing(rule, content).should.eql(true); }); }); describe("and the content does not match the rule", function() { beforeEach(function() { content = "some-content"; }); it("returns false", function() { normalModule.shouldPreventParsing(rule, content).should.eql(false); }); }); }); }); describe("#shouldPreventParsing", function() { let applyNoParseRuleSpy; beforeEach(function() { applyNoParseRuleSpy = sinon.stub(); normalModule.applyNoParseRule = applyNoParseRuleSpy; }); describe("given no noParseRule", function() { it("returns false", function() { normalModule.shouldPreventParsing().should.eql(false); applyNoParseRuleSpy.callCount.should.eql(0); }); }); describe("given a noParseRule", function() { let returnValOfSpy; beforeEach(function() { returnValOfSpy = true; applyNoParseRuleSpy.returns(returnValOfSpy); }); describe("that is a string", function() { it("calls and returns whatever applyNoParseRule returns", function() { normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy); applyNoParseRuleSpy.callCount.should.eql(1); }); }); describe("that is a regex", function() { it("calls and returns whatever applyNoParseRule returns", function() { normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy); applyNoParseRuleSpy.callCount.should.eql(1); }); }); describe("that is an array", function() { describe("of strings and or regexs", function() { let someRules; beforeEach(function() { someRules = [ "some rule", /some rule1/, "some rule2", ]; }); describe("and none of them match", function() { beforeEach(function() { returnValOfSpy = false; applyNoParseRuleSpy.returns(returnValOfSpy); }); it("returns false", function() { normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy); applyNoParseRuleSpy.callCount.should.eql(3); }); }); describe("and the first of them matches", function() { beforeEach(function() { returnValOfSpy = true; applyNoParseRuleSpy.returns(returnValOfSpy); }); it("returns true", function() { normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy); applyNoParseRuleSpy.callCount.should.eql(1); }); }); describe("and the last of them matches", function() { beforeEach(function() { returnValOfSpy = true; applyNoParseRuleSpy.onCall(0).returns(false); applyNoParseRuleSpy.onCall(1).returns(false); applyNoParseRuleSpy.onCall(2).returns(true); }); it("returns true", function() { normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy); applyNoParseRuleSpy.callCount.should.eql(3); }); }); }); }); }); }); }); webpack-3.5.6/test/NullDependency.test.js000066400000000000000000000022301315401342100203340ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const NullDependency = require("../lib/dependencies/NullDependency"); describe("NullDependency", () => { let env; beforeEach(() => env = {}); it("is a function", () => NullDependency.should.be.a.Function()); describe("when created", () => { beforeEach(() => env.nullDependency = new NullDependency()); it("has a null type", () => env.nullDependency.type.should.be.exactly("null")); it("is not an equal resource", () => env.nullDependency.isEqualResource().should.be.False()); it("has update hash function", () => env.nullDependency.updateHash.should.be.Function()); it("does not update hash", () => { const hash = { update: sinon.stub() }; env.nullDependency.updateHash(hash); hash.update.called.should.be.false(); }); }); describe("Template", () => { it("is a function", () => NullDependency.Template.should.be.a.Function()); describe("when created", () => { beforeEach(() => env.nullDependencyTemplate = new NullDependency.Template()); it("has apply function", () => env.nullDependencyTemplate.apply.should.be.Function()); }); }); }); webpack-3.5.6/test/Parser.test.js000066400000000000000000000271471315401342100166750ustar00rootroot00000000000000"use strict"; const should = require("should"); const Parser = require("../lib/Parser"); const BasicEvaluatedExpression = require("../lib/BasicEvaluatedExpression"); describe("Parser", () => { 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; }, {} ], "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"] } ], }; 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.plugin("can-rename abc", (expr) => true); testParser.plugin("can-rename ijk", (expr) => true); testParser.plugin("call abc", (expr) => { if(!testParser.state.abc) testParser.state.abc = []; testParser.state.abc.push(testParser.parseString(expr.arguments[0])); return true; }); testParser.plugin("call cde.abc", (expr) => { if(!testParser.state.cdeabc) testParser.state.cdeabc = []; testParser.state.cdeabc.push(testParser.parseString(expr.arguments[0])); return true; }); testParser.plugin("call cde.ddd.abc", (expr) => { if(!testParser.state.cdedddabc) testParser.state.cdedddabc = []; testParser.state.cdedddabc.push(testParser.parseString(expr.arguments[0])); return true; }); testParser.plugin("expression fgh", (expr) => { if(!testParser.state.fgh) testParser.state.fgh = []; testParser.state.fgh.push(testParser.scope.definitions.join(" ")); return true; }); testParser.plugin("expression fgh.sub", (expr) => { if(!testParser.state.fghsub) testParser.state.fghsub = []; testParser.state.fghsub.push(testParser.scope.inTry ? "try" : "notry"); return true; }); testParser.plugin("expression ijk.sub", (expr) => { if(!testParser.state.ijksub) testParser.state.ijksub = []; testParser.state.ijksub.push("test"); return true; }); testParser.plugin("expression memberExpr", (expr) => { if(!testParser.state.expressions) testParser.state.expressions = []; testParser.state.expressions.push(expr.name); return true; }); const actual = testParser.parse(source); should.strictEqual(typeof actual, "object"); actual.should.be.eql(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.plugin("program", (ast, comments) => { if(!testParser.state.comments) testParser.state.comments = comments; return true; }); const actual = testParser.parse(source); should.strictEqual(typeof actual, "object"); should.strictEqual(typeof actual.comments, "object"); actual.comments.forEach((element, index) => { should.strictEqual(typeof element.type, "string"); should.strictEqual(typeof element.value, "string"); element.type.should.be.eql(state[index].type); element.value.should.be.eql(state[index].value); }); }); describe("expression evaluation", () => { function evaluateInParser(source) { const parser = new Parser(); parser.plugin("call test", (expr) => { parser.state.result = parser.evaluateExpression(expr.arguments[0]); }); parser.plugin("evaluate Identifier aString", (expr) => new BasicEvaluatedExpression().setString("aString").setRange(expr.range)); parser.plugin("evaluate Identifier b.Number", (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", "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]": "", "'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.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); evalExprToString(evalExpr).should.be.eql(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 }" }; const parser = new Parser(); Object.keys(cases).forEach((name) => { const expr = cases[name]; it(name, () => { const actual = parser.parse(expr); should.strictEqual(typeof actual, "object"); }); }); }); describe("should parse await", () => { const cases = { "require": [ "async function x() { await require('y'); }", { param: "y" } ], "System.import": [ "async function x() { const y = await System.import('z'); }", { param: "z" } ] }; const parser = new Parser(); parser.plugin("call require", (expr) => { const param = parser.evaluateExpression(expr.arguments[0]); parser.state.param = param.string; }); parser.plugin("call System.import", (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]); actual.should.be.eql(cases[name][1]); }); }); }); }); }); webpack-3.5.6/test/README.md000066400000000000000000000103531315401342100153730ustar00rootroot00000000000000# 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 * Clone repo * install and link deps * `yarn install && yarn link && yarn link webpack` * `yarn test` * To run an individual suite: (recommended during development for easier isolated diffs) Example: `$(npm bin)/mocha --grep ConfigTestCases` ## Test suite overview We use MochaJS for our tests. For more information on Mocha you can visit their [homepage](https://mochajs.org/)! ### 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 (`Stats.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 the following happens: * Checks for `expected.txt` file containing expected results. * If the `expected.txt` doesn't match what is output, then an `actual.txt` stats output file will be created and the test will fail. (A typical workflow for stats cases is to fail the test and copy the results from `actual.txt` to `expected.txt`.) * If the actual output matches `expected.txt`, the tests passes and you are free to submit that PR with pride!!! ## 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-3.5.6/test/RawModule.test.js000066400000000000000000000050161315401342100173270ustar00rootroot00000000000000"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 should = require("should"); const path = require("path"); const crypto = require("crypto"); describe("RawModule", () => { let myRawModule; before(() => { const source = "sourceStr attribute"; const identifier = "identifierStr attribute"; const readableIdentifier = "readableIdentifierStr attribute"; myRawModule = new RawModule(source, identifier, readableIdentifier); }); describe("identifier", () => { it("returns value for identifierStr attribute", () => should(myRawModule.identifier()).be.exactly("identifierStr attribute")); }); describe("size", () => { it("returns value for sourceStr attribute\"s length property", () => { const sourceStrLength = myRawModule.sourceStr.length; should(myRawModule.size()).be.exactly(sourceStrLength); }); }); describe("readableIdentifier", () => { it("returns result of calling provided requestShortener\"s shorten method " + "on readableIdentifierStr attribute", () => { const requestShortener = new RequestShortener(path.resolve()); should.exist(myRawModule.readableIdentifier(requestShortener)); } ); }); describe("needRebuild", () => { it("returns false", () => should(myRawModule.needRebuild()).be.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; myRawModule.source().should.match(originalSource); } ); it("returns a new RawSource instance with sourceStr attribute provided " + "as constructor argument if useSourceMap is falsey", () => { const rawSource = new RawSource(myRawModule.sourceStr); myRawModule.useSourceMap = false; myRawModule.source().should.match(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\"")); hashFoo.should.not.equal(hashBar); }); }); }); webpack-3.5.6/test/RecordIdsPlugin.test.js000066400000000000000000000021331315401342100204620ustar00rootroot00000000000000/* globals describe, before, it */ "use strict"; const should = require("should"); const path = require("path"); const webpack = require("../lib/webpack"); const identifierUtils = require("../lib/util/identifier"); describe("RecordIdsPlugin", () => { let compiler; before(() => { compiler = webpack({ entry: "./nodetest/entry", context: path.join(__dirname, "fixtures"), output: { path: path.join(__dirname, "nodetest", "js"), filename: "result1.js" } }); compiler.plugin("compilation", (compilation, callback) => { compilation.plugin("should-record", () => true); }); }); it("should cache identifiers", (done) => { compiler.compile((err, compilation) => { if(err) done(err); let pass = true; for(let i = 0; i < compilation.modules.length; i++) { try { should.exist(compilation.modules[i].portableId); compilation.modules[i].portableId.should.equal(identifierUtils.makePathsRelative(compiler.context, compilation.modules[i].identifier())); } catch(e) { done(e); pass = false; break; } } if(pass) done(); }); }); }); webpack-3.5.6/test/RequireJsStuffPlugin.test.js000066400000000000000000000146451315401342100215400ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const RequireJsStuffPlugin = require("../lib/RequireJsStuffPlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); const PluginEnvironment = require("./helpers/PluginEnvironment"); describe("RequireJsStuffPlugin", () => { it("has apply function", () => (new RequireJsStuffPlugin()).apply.should.be.a.Function()); describe("when applied", () => { let eventBindings; let eventBinding; beforeEach(() => eventBindings = applyPluginWithOptions(RequireJsStuffPlugin)); it("binds one event handler", () => eventBindings.length.should.be.exactly(1)); describe("compilation handler", () => { beforeEach(() => eventBinding = eventBindings[0]); it("binds to compilation event", () => eventBinding.name.should.be.exactly("compilation")); describe("when called", () => { let pluginEnvironment; let compilationEventBindings; let compilation; beforeEach(() => { pluginEnvironment = new PluginEnvironment(); compilation = { dependencyFactories: { set: sinon.spy() }, dependencyTemplates: { set: sinon.spy() } }; const params = { normalModuleFactory: pluginEnvironment.getEnvironmentStub() }; eventBinding.handler(compilation, params); compilationEventBindings = pluginEnvironment.getEventBindings(); }); it("sets the dependency factory", () => compilation.dependencyFactories.set.callCount.should.be.exactly(1)); it("sets the dependency template", () => compilation.dependencyTemplates.set.callCount.should.be.exactly(1)); it("binds one event handler", () => compilationEventBindings.length.should.be.exactly(1)); describe("parser handler", () => { let parser; let parserEventBindings; let compilationEventBinding; beforeEach(() => { compilationEventBinding = compilationEventBindings[0]; pluginEnvironment = new PluginEnvironment(); parser = pluginEnvironment.getEnvironmentStub(); }); it("binds to parser event", () => compilationEventBinding.name.should.be.exactly("parser")); describe("when called with parser options of requirejs as false", () => { beforeEach(() => { compilationEventBinding.handler(parser, { requireJs: false }); parserEventBindings = pluginEnvironment.getEventBindings(); }); it("binds no event handlers", () => parserEventBindings.length.should.be.exactly(0)); }); describe("when called with empty parser options", () => { let parserEventBinding; let parserEventContext; let expressionMock; beforeEach(() => { parserEventContext = { state: { current: { addDependency: sinon.spy() } } }; expressionMock = { range: 10, loc: 5 }; compilationEventBinding.handler(parser, {}); parserEventBindings = pluginEnvironment.getEventBindings(); }); it("binds four event handlers", () => parserEventBindings.length.should.be.exactly(4)); describe("'call require.config' handler", () => { beforeEach(() => parserEventBinding = parserEventBindings[0]); it("binds to 'call require.config' event", () => parserEventBinding.name.should.be.exactly("call require.config")); describe("when called", () => { beforeEach(() => parserEventBinding.handler.call(parserEventContext, expressionMock)); it("adds dependency to current state", () => { const addDependencySpy = parserEventContext.state.current.addDependency; const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]); addDependencySpy.callCount.should.be.exactly(1); addedDependency.should.be.exactly('{"module":null,"expression":"undefined","range":10,"loc":5}'); }); }); }); describe("'call requirejs.config' handler", () => { beforeEach(() => parserEventBinding = parserEventBindings[1]); it("binds to 'call requirejs.config' event", () => parserEventBinding.name.should.be.exactly("call requirejs.config")); describe("when called", () => { beforeEach(() => parserEventBinding.handler.call(parserEventContext, expressionMock)); it("adds dependency to current state", () => { const addDependencySpy = parserEventContext.state.current.addDependency; const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]); addDependencySpy.callCount.should.be.exactly(1); addedDependency.should.be.exactly('{"module":null,"expression":"undefined","range":10,"loc":5}'); }); }); }); describe("'expression require.version' handler", () => { beforeEach(() => parserEventBinding = parserEventBindings[2]); it("binds to 'expression require.version' event", () => parserEventBinding.name.should.be.exactly("expression require.version")); describe("when called", () => { beforeEach(() => parserEventBinding.handler.call(parserEventContext, expressionMock)); it("adds dependency to current state", () => { const addDependencySpy = parserEventContext.state.current.addDependency; const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]); addDependencySpy.callCount.should.be.exactly(1); addedDependency.should.be.exactly('{"module":null,"expression":"\\"0.0.0\\"","range":10,"loc":5}'); }); }); }); describe("'expression requirejs.onError' handler", () => { beforeEach(() => parserEventBinding = parserEventBindings[3]); it("binds to 'expression requirejs.onError' event", () => parserEventBinding.name.should.be.exactly("expression requirejs.onError")); describe("when called", () => { beforeEach(() => parserEventBinding.handler.call(parserEventContext, expressionMock)); it("adds dependency to current state", () => { const addDependencySpy = parserEventContext.state.current.addDependency; const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]); addDependencySpy.callCount.should.be.exactly(1); addedDependency.should.be.exactly('{"module":null,"expression":"__webpack_require__.oe","range":10,"loc":5}'); }); }); }); }); }); }); }); }); }); webpack-3.5.6/test/RuleSet.test.js000066400000000000000000000231301315401342100170100ustar00rootroot00000000000000"use strict"; const should = require("should"); 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([]); (loader.rules).should.eql([]); }); it("should create RuleSet and match with empty array", () => { const loader = new RuleSet([]); (match(loader, "something")).should.eql([]); }); it("should not match with loaders array", () => { const loader = new RuleSet([{ test: /\.css$/, loader: "css" }]); (match(loader, "something")).should.eql([]); }); it("should match with regex", () => { const loader = new RuleSet([{ test: /\.css$/, loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should match with string", () => { const loader = new RuleSet([{ test: "style.css", loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should match with function", () => { const loader = new RuleSet([{ test: function(str) { return str === "style.css"; }, loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should throw if invalid test", () => { should.throws(() => { const loader = new RuleSet([{ test: { invalid: "test" }, loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }, /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" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should accept multiple test array that not all match", () => { const loader = new RuleSet([{ test: [ /style.css/, /something.css/ ], loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should not match if include does not match", () => { const loader = new RuleSet([{ test: /\.css$/, include: /output.css/, loader: "css" }]); (match(loader, "style.css")).should.eql([]); }); it("should match if include matches", () => { const loader = new RuleSet([{ test: /\.css$/, include: /style.css/, loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should not match if exclude matches", () => { const loader = new RuleSet([{ test: /\.css$/, exclude: /style.css/, loader: "css" }]); (match(loader, "style.css")).should.eql([]); }); it("should match if exclude does not match", () => { const loader = new RuleSet([{ test: /\.css$/, exclude: /output.css/, loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should work if a loader is applied to all files", () => { const loader = new RuleSet([{ loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); (match(loader, "scripts.js")).should.eql(["css"]); }); it("should work with using loader as string", () => { const loader = new RuleSet([{ test: /\.css$/, loader: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should work with using loader as array", () => { const loader = new RuleSet([{ test: /\.css$/, loader: ["css"] }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should work with using loaders as string", () => { const loader = new RuleSet([{ test: /\.css$/, loaders: "css" }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should work with using loaders as array", () => { const loader = new RuleSet([{ test: /\.css$/, loaders: ["css"] }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should throw if using loaders with non-string or array", () => { should.throws(function() { const loader = new RuleSet([{ test: /\.css$/, loaders: { someObj: true } }]); (match(loader, "style.css")).should.eql(["css"]); }, /No loader specified/); }); it("should work with using loader with inline query", () => { const loader = new RuleSet([{ test: /\.css$/, loader: "css?modules=1" }]); (match(loader, "style.css")).should.eql(["css?modules=1"]); }); it("should work with using loader with string query", () => { const loader = new RuleSet([{ test: /\.css$/, loader: "css", query: "modules=1" }]); (match(loader, "style.css")).should.eql(["css?modules=1"]); }); it("should work with using loader with object query", () => { const loader = new RuleSet([{ test: /\.css$/, loader: "css", query: { modules: 1 } }]); (match(loader, "style.css")).should.eql(["css?{\"modules\":1}"]); }); it("should work with using array loaders with basic object notation", () => { const loader = new RuleSet([{ test: /\.css$/, loaders: [{ loader: "css" }] }]); (match(loader, "style.css")).should.eql(["css"]); }); it("should throw if using array loaders with object notation without specifying a loader", () => { should.throws(() => { const loader = new RuleSet([{ test: /\.css$/, loaders: [{ stuff: 1 }] }]); match(loader, "style.css"); }, /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" }] }]); (match(loader, "style.css")).should.eql(["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" }] }]); (match(loader, "style.css")).should.eql(["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" }]); (match(loader, "style.css")).should.eql(["style?filesize=1000", "css?modules=1"]); }); it("should throw if using array loaders with a single legacy", () => { should.throws(() => { const loader = new RuleSet([{ test: /\.css$/, loaders: ["style-loader", "css-loader"], query: "modules=1" }]); (match(loader, "style.css")).should.eql(["css"]); }, /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"] }]); (match(loader, "style.css")).should.eql(["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" }; }, ] }]); (match(loader, "style.css")).should.eql(["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" }; }, ] }]); (match(loader, "style.css")).should.eql(["style-loader", "css-loader"]); }); it("should work when using an array of functions returning either a loader obejct or loader name string", () => { const loader = new RuleSet([{ test: /\.css$/, use: [ function(data) { return "style-loader" }, function(data) { return { loader: "css-loader" }; }, ] }]); (match(loader, "style.css")).should.eql(["style-loader", "css-loader"]); }); it("should throw if using array loaders with invalid type", () => { should.throws(() => { const loader = new RuleSet([{ test: /\.css$/, loaders: ["style-loader", "css-loader", 5], }]); (match(loader, "style.css")).should.eql(["css"]); }, /No loader specified/); }); describe("when exclude array holds an undefined item", () => { function errorHasContext(err) { if(/Expected condition but got falsy value/.test(err) && /test/.test(err) && /include/.test(err) && /exclude/.test(err) && /node_modules/.test(err) && /undefined/.test(err)) { return true; } } it("should throw with context", () => { should.throws(() => { const loader = new RuleSet([{ test: /\.css$/, loader: "css", include: [ "src", ], exclude: [ "node_modules", undefined, ], }]); (match(loader, "style.css")).should.eql(["css"]); }, errorHasContext); }); it("in resource should throw with context", () => { should.throws(() => { const loader = new RuleSet([{ resource: { test: /\.css$/, include: [ "src", ], exclude: [ "node_modules", undefined, ], }, }]); (match(loader, "style.css")).should.eql(["css"]); }, errorHasContext); }); it("in issuer should throw with context", () => { should.throws(() => { const loader = new RuleSet([{ issuer: { test: /\.css$/, include: [ "src", ], exclude: [ "node_modules", undefined, ], }, }]); (match(loader, "style.css")).should.eql(["css"]); }, errorHasContext); }); }); }); webpack-3.5.6/test/SortableSet.test.js000066400000000000000000000015431315401342100176600ustar00rootroot00000000000000/* 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], () => {}); Array.from(sortableSet).should.eql([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(); Array.from(sortableSet).should.eql([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); Array.from(sortableSet).should.eql([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]); }); }); webpack-3.5.6/test/SourceMapDevToolModuleOptionsPlugin.test.js000066400000000000000000000063361315401342100245320ustar00rootroot00000000000000"use strict"; const should = require("should"); const SourceMapDevToolModuleOptionsPlugin = require("../lib/SourceMapDevToolModuleOptionsPlugin"); const applyPluginWithOptions = require('./helpers/applyPluginWithOptions'); describe("SourceMapDevToolModuleOptionsPlugin", () => { it("has apply function", () => (new SourceMapDevToolModuleOptionsPlugin()).apply.should.be.a.Function()); 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", () => eventBindings.length.should.be.exactly(0)); }); describe("with module true", () => { beforeEach(() => eventBindings = applyPluginWithOptions(SourceMapDevToolModuleOptionsPlugin, { module: true, lineToLine: false })); it("binds one event handler", () => eventBindings.length.should.be.exactly(1)); describe("event handler", () => { it("binds to build-module event", () => eventBindings[0].name.should.be.exactly("build-module")); it("sets source map flag", () => { const module = {}; eventBindings[0].handler(module); module.should.deepEqual({ useSourceMap: true }); }); }); }); describe("with line-to-line true", () => { beforeEach(() => eventBindings = applyPluginWithOptions(SourceMapDevToolModuleOptionsPlugin, { module: false, lineToLine: true })); it("binds one event handler", () => eventBindings.length.should.be.exactly(1)); describe("event handler", () => { it("binds to build-module event", () => eventBindings[0].name.should.be.exactly("build-module")); it("sets line-to-line flag", () => { const module = {}; eventBindings[0].handler(module); module.should.deepEqual({ lineToLine: true }); }); }); }); describe("with line-to-line object", () => { beforeEach(() => eventBindings = applyPluginWithOptions(SourceMapDevToolModuleOptionsPlugin, { module: false, lineToLine: {} })); it("binds one event handler", () => eventBindings.length.should.be.exactly(1)); describe("event handler", () => { it("binds to build-module event", () => eventBindings[0].name.should.be.exactly("build-module")); describe("when module has no resource", () => { it("makes no changes", () => { const module = {}; eventBindings[0].handler(module); module.should.deepEqual({}); }); }); describe("when module has a resource", () => { it("sets line-to-line flag", () => { const module = { resource: "foo" }; eventBindings[0].handler(module); module.should.deepEqual({ 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); module.should.deepEqual({ lineToLine: true, resource: "foo?bar" }); }); }); }); }); }); }); webpack-3.5.6/test/Stats.test.js000066400000000000000000000131611315401342100165260ustar00rootroot00000000000000/*globals describe it */ "use strict"; require("should"); const path = require("path"); const fs = require("fs"); const webpack = require("../lib/webpack"); 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")) ); const Stats = require("../lib/Stats"); describe("Stats", () => { tests.forEach(testName => { it("should print correct stats for " + testName, (done) => { let options = { 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); }); 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.apply(new webpack.optimize.OccurrenceOrderPlugin()); }); c.run((err, stats) => { if(err) return done(err); if(/error$/.test(testName)) { stats.hasErrors().should.be.equal(true); } else if(stats.hasErrors()) { done(new Error(stats.toJson().errors.join("\n\n"))); } let toStringOptions = { colors: false }; let hasColorSetting = false; if(typeof options.stats !== "undefined") { toStringOptions = options.stats; hasColorSetting = typeof options.stats.colors !== "undefined"; } if(Array.isArray(options) && !toStringOptions.children) { toStringOptions.children = options.map(o => o.stats); } let actual = stats.toString(toStringOptions); (typeof actual).should.be.eql("string"); if(!hasColorSetting) { actual = actual .replace(/\u001b\[[0-9;]*m/g, "") .replace(/[0-9]+(\s?ms)/g, "X$1"); } 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"); } actual = actual .replace(/\r\n?/g, "\n") .replace(/[\t ]*Version:.+\n/g, "") .replace(path.join(base, testName), "Xdir/" + testName) .replace(/ dependencies:Xms/g, ""); const expected = fs.readFileSync(path.join(base, testName, "expected.txt"), "utf-8").replace(/\r/g, ""); if(actual !== expected) { fs.writeFileSync(path.join(base, testName, "actual.txt"), actual, "utf-8"); } else if(fs.existsSync(path.join(base, testName, "actual.txt"))) { fs.unlinkSync(path.join(base, testName, "actual.txt")); } actual.should.be.eql(expected); done(); }); }); }); describe("Error Handling", () => { describe("does have", () => { it("hasErrors", () => { const mockStats = new Stats({ errors: ["firstError"], hash: "1234" }); mockStats.hasErrors().should.be.ok(); }); it("hasWarnings", () => { const mockStats = new Stats({ warnings: ["firstError"], hash: "1234" }); mockStats.hasWarnings().should.be.ok(); }); }); describe("does not have", () => { it("hasErrors", () => { const mockStats = new Stats({ errors: [], hash: "1234" }); mockStats.hasErrors().should.not.be.ok(); }); it("hasWarnings", () => { const mockStats = new Stats({ warnings: [], hash: "1234" }); mockStats.hasWarnings().should.not.be.ok(); }); }); it("formatError handles string errors", () => { const mockStats = new Stats({ errors: ["firstError"], warnings: [], assets: [], entrypoints: {}, chunks: [], modules: [], children: [], hash: "1234", mainTemplate: { getPublicPath: () => "path" } }); const obj = mockStats.toJson(); obj.errors[0].should.be.equal("firstError"); }); }); describe("Presets", () => { describe("presetToOptions", () => { it("returns correct object with 'Normal'", () => { Stats.presetToOptions("Normal").should.eql({}); }); it("truthy values behave as 'normal'", () => { const normalOpts = Stats.presetToOptions("normal"); Stats.presetToOptions("pizza").should.eql(normalOpts); Stats.presetToOptions(true).should.eql(normalOpts); Stats.presetToOptions(1).should.eql(normalOpts); Stats.presetToOptions("verbose").should.not.eql(normalOpts); Stats.presetToOptions(false).should.not.eql(normalOpts); }); it("returns correct object with 'none'", () => { Stats.presetToOptions("none").should.eql({ all: false }); }); it("falsy values behave as 'none'", () => { const noneOpts = Stats.presetToOptions("none"); Stats.presetToOptions("").should.eql(noneOpts); Stats.presetToOptions(null).should.eql(noneOpts); Stats.presetToOptions().should.eql(noneOpts); Stats.presetToOptions(0).should.eql(noneOpts); Stats.presetToOptions(false).should.eql(noneOpts); }); }); }); }); webpack-3.5.6/test/Template.test.js000066400000000000000000000014021315401342100171760ustar00rootroot00000000000000"use strict"; const should = require("should"); const Template = require("../lib/Template"); describe("Template", () => { it("should generate valid identifiers", () => Template.toIdentifier("0abc-def9").should.equal("_abc_def9")); it("should generate valid number identifiers", () => { const items = []; let item; for(let i = 0; i < 80; i += 1) { item = Template.numberToIdentifer(i); if(item === "") { throw new Error("empty number identifier"); } else if(items.indexOf(item) > -1) { throw new Error("duplicate number identifier"); } else { items.push(item); } } }); it("should generate sanitized path identifiers", () => { Template.toPath("path/to-sdfas/sadfome$$.js").should.equal("path-to-sdfas-sadfome$$-js"); }); }); webpack-3.5.6/test/TestCases.test.js000066400000000000000000000135721315401342100173340ustar00rootroot00000000000000/* global describe, it*/ "use strict"; require("should"); const path = require("path"); const fs = require("fs"); const vm = require("vm"); const Test = require("mocha/lib/test"); const checkArrayExpectation = require("./checkArrayExpectation"); const Stats = require("../lib/Stats"); const webpack = require("../lib/webpack"); describe("TestCases", () => { 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) }; }); [{ name: "normal" }, { name: "concat", plugins: [ new webpack.optimize.ModuleConcatenationPlugin() ] }, { name: "hot", plugins: [ new webpack.HotModuleReplacementPlugin() ] }, { name: "hot-multi-step", plugins: [ new webpack.HotModuleReplacementPlugin({ multiStep: true }) ] }, { name: "devtool-eval", devtool: "eval" }, { name: "devtool-eval-named-modules", devtool: "eval", plugins: [ new webpack.NamedModulesPlugin() ] }, { name: "devtool-eval-source-map", devtool: "#eval-source-map" }, { name: "devtool-inline-source-map", devtool: "inline-source-map" }, { name: "devtool-source-map", devtool: "#@source-map" }, { name: "devtool-cheap-inline-source-map", devtool: "cheap-inline-source-map" }, { name: "devtool-cheap-eval-source-map", devtool: "cheap-eval-source-map" }, { name: "devtool-cheap-eval-module-source-map", devtool: "cheap-eval-module-source-map" }, { name: "devtool-cheap-source-map", devtool: "cheap-source-map" }, { name: "minimized", minimize: true, plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: false }) ] }, { name: "minimized-source-map", devtool: "eval-cheap-module-source-map", minimize: true, plugins: [ new webpack.optimize.UglifyJsPlugin() ] }, { name: "minimized-hashed-modules", minimize: true, plugins: [ new webpack.optimize.UglifyJsPlugin(), new webpack.HashedModuleIdsPlugin() ] }, { name: "all-combined", devtool: "#@source-map", minimize: true, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.optimize.UglifyJsPlugin(), new webpack.NamedModulesPlugin(), new webpack.NamedChunksPlugin() ] }].forEach((config) => { describe(config.name, () => { categories.forEach((category) => { describe(category.name, function() { this.timeout(30000); 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) => { const suite = describe(testName, () => {}); it(testName + " should compile", (done) => { 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, 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: [".webpack.js", ".web.js", ".js", ".json"] }, 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: { loaders: [{ test: /\.coffee$/, loader: "coffee-loader" }, { test: /\.jade$/, loader: "jade-loader" }] }, plugins: (config.plugins || []).concat(function() { this.plugin("compilation", (compilation) => { ["optimize", "optimize-modules-basic", "optimize-chunks-basic", "after-optimize-tree", "after-optimize-assets"].forEach((hook) => { compilation.plugin(hook, () => compilation.checkConstraints()); }); }); }) }; webpack(options, (err, stats) => { if(err) return done(err); const statOptions = Stats.presetToOptions("verbose"); statOptions.colors = false; 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; let exportedTest = 0; function _it(title, fn) { const test = new Test(title, fn); suite.addTest(test); exportedTest++; return test; } function _require(module) { if(module.substr(0, 2) === "./") { const p = path.join(outputDirectory, module); const fn = vm.runInThisContext("(function(require, module, exports, __dirname, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p); const m = { exports: {} }; fn.call(m.exports, _require, m, m.exports, outputDirectory, _it); return m.exports; } else return require(module); } _require("./bundle.js"); if(exportedTest === 0) return done(new Error("No tests exported by test case")); done(); }); }); }); }); }); }); }); }); webpack-3.5.6/test/Validation.test.js000066400000000000000000000152661315401342100175320ustar00rootroot00000000000000/* globals describe, it */ "use strict"; require("should"); const webpack = require("../lib/webpack"); const WebpackOptionsValidationError = require("../lib/WebpackOptionsValidationError"); 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 configuration", config: {}, message: [ " - configuration misses the property 'entry'.", " object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function", " The entry point(s) of the compilation." ] }, { name: "empty entry string", config: { entry: "" }, message: [ " - configuration.entry should be one of these:", " object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function", " The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an object.", " * configuration.entry should not be empty.", " * configuration.entry should be an array:", " [non-empty string]", " * configuration.entry should be an instance of function", " function returning an entry object or a promise.." ] }, { name: "empty entry bundle array", config: { entry: { "bundle": [] } }, message: [ " - configuration.entry should be one of these:", " object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function", " The entry point(s) of the compilation.", " Details:", " * configuration.entry['bundle'] should be a string.", " * configuration.entry['bundle'] should not be empty.", " * configuration.entry['bundle'] should be one of these:", " non-empty string | [non-empty string]", " * configuration.entry should be a string.", " * configuration.entry should be an array:", " [non-empty string]", " * configuration.entry should be an instance of function", " function returning an entry object or a promise.." ] }, { name: "invalid instanceof", config: { entry: "a", module: { wrappedContextRegExp: 1337 } }, message: [ " - configuration.module.wrappedContextRegExp should be an instance of RegExp.", ] }, { name: "multiple errors", config: { entry: [/a/], output: { filename: /a/ } }, message: [ " - configuration.entry should be one of these:", " object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function", " The entry point(s) of the compilation.", " Details:", " * configuration.entry should be an object.", " * configuration.entry should be a string.", " * configuration.entry[0] should be a string.", " * configuration.entry should be an instance of function", " function returning an entry object or a promise..", " - configuration.output.filename should be a string." ] }, { name: "multiple configurations", config: [{ entry: [/a/], }, { entry: "a", output: { filename: /a/ } }], message: [ " - configuration[0].entry should be one of these:", " object { : non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function", " The entry point(s) of the compilation.", " Details:", " * configuration[0].entry should be an object.", " * configuration[0].entry should be a string.", " * configuration[0].entry[0] should be a string.", " * configuration[0].entry should be an instance of function", " function returning an entry object or a promise..", " - configuration[1].output.filename should be a string." ] }, { name: "deep error", config: { entry: "a", module: { rules: [{ oneOf: [{ test: "/a", paser: { amd: false } }] }] } }, message: [ " - configuration.module.rules[0].oneOf[0] has an unknown property 'paser'. These properties are valid:", " object { enforce?, exclude?, include?, issuer?, loader?, loaders?, oneOf?, options?, parser?, query?, resource?, resourceQuery?, compiler?, rules?, test?, use? }" ] }, { 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?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, " + "recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }", " For typos: please correct them.", " For loader options: webpack 2 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: "relative path", config: { entry: "foo.js", output: { filename: "/bar" } }, message: [ " - 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." ] }, { name: "absolute path", config: { entry: "foo.js", output: { filename: "bar" }, context: "baz" }, message: [ " - configuration.context: The provided value \"baz\" is not an absolute path!", ] }]; testCases.forEach((testCase) => { it("should fail validation for " + testCase.name, () => { try { webpack(testCase.config); } catch(e) { if(!(e instanceof WebpackOptionsValidationError)) throw e; e.message.should.startWith("Invalid configuration object."); e.message.split("\n").slice(1).should.be.eql(testCase.message); return; } throw new Error("Validation didn't fail"); }); }); }); webpack-3.5.6/test/WatchDetection.test.js000066400000000000000000000053341315401342100203400ustar00rootroot00000000000000"use strict"; /*globals describe it before after */ const should = require("should"); const path = require("path"); const fs = require("fs"); const MemoryFs = require("memory-fs"); const webpack = require("../"); describe("WatchDetection", () => { for(let changeTimeout = 0; changeTimeout < 100; changeTimeout += 10) { createTestCase(changeTimeout); } for(let changeTimeout = 100; changeTimeout <= 2000; changeTimeout += 100) { createTestCase(changeTimeout); } function createTestCase(changeTimeout) { describe("time between changes " + changeTimeout + "ms", function() { this.timeout(10000); 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"); before(() => { try { fs.mkdirSync(fixturePath); } catch(e) {} fs.writeFileSync(filePath, "require('./file2')", "utf-8"); fs.writeFileSync(file2Path, "original", "utf-8"); }); after((done) => { setTimeout(() => { try { fs.unlinkSync(filePath); } catch(e) {} try { fs.unlinkSync(file2Path); } catch(e) {} try { fs.rmdirSync(fixturePath); } catch(e) {} done(); }, 100); // cool down a bit }); it("should build the bundle correctly", (done) => { const compiler = webpack({ entry: loaderPath + "!" + filePath, output: { path: "/", filename: "bundle.js" } }); const memfs = compiler.outputFileSystem = new MemoryFs(); let onChange; compiler.plugin("done", () => { 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) step4(); }; fs.writeFile(file2Path, "correct", "utf-8", handleError); } function step4() { onChange = null; watcher.close(() => { setTimeout(done, 1000); }); } function handleError(err) { if(err) done(err); } }); }); } }); webpack-3.5.6/test/WatchTestCases.test.js000066400000000000000000000147711315401342100203250ustar00rootroot00000000000000"use strict"; const should = require("should"); const path = require("path"); const fs = require("fs"); const vm = require("vm"); const Test = require("mocha/lib/test"); const checkArrayExpectation = require("./checkArrayExpectation"); const Stats = require("../lib/Stats"); const webpack = require("../lib/webpack"); function copyDiff(src, dest) { 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); } else { var content = fs.readFileSync(srcFile); if(/^DELETE\s*$/.test(content.toString("utf-8"))) fs.unlinkSync(destFile); else fs.writeFileSync(destFile, content); } }); } 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); } }); } describe("WatchTestCases", () => { 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).sort() }; }); before(() => { 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) => { before(() => { 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) => { return { name: name, suite: describe(name, () => {}) }; }); before(() => remove(tempDirectory)); it("should compile", function(done) { this.timeout(45000); 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.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 run = runs[runIdx]; let lastHash = ""; copyDiff(path.join(testDirectory, run.name), tempDirectory); const compiler = webpack(options); const watching = compiler.watch({ aggregateTimeout: 1000 }, (err, stats) => { if(err) return done(err); if(!stats) return done(new Error("No stats reported from Compiler")); if(stats.hash === lastHash) return; lastHash = stats.hash; if(run.done) return done(new Error("Compilation changed but no change was issued " + lastHash + " != " + stats.hash + " (run " + runIdx + ")")); run.done = true; if(err) return done(err); const statOptions = Stats.presetToOptions("verbose"); statOptions.colors = false; 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", done)) return; if(checkArrayExpectation(path.join(testDirectory, run.name), jsonStats, "warning", "Warning", done)) return; let exportedTests = 0; function _it(title, fn) { const test = new Test(title, fn); run.suite.addTest(test); exportedTests++; return test; } 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"); } fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it, WATCH_STEP, STATS_JSON, STATE) {" + content + "\n})", p); const m = { exports: {} }; fn.call(m.exports, _require.bind(null, path.dirname(p)), m, m.exports, path.dirname(p), p, _it, run.name, jsonStats, state); return module.exports; } else if(testConfig.modules && module in testConfig.modules) { return testConfig.modules[module]; } else return require(module); } let testConfig = {}; try { // try to load a test file testConfig = require(path.join(testDirectory, "test.config.js")); } catch(e) {} if(testConfig.noTests) return process.nextTick(done); _require(outputDirectory, "./bundle.js"); if(exportedTests < 1) return done(new Error("No tests exported by test case")); runIdx++; if(runIdx < runs.length) { run = runs[runIdx]; setTimeout(() => { copyDiff(path.join(testDirectory, run.name), tempDirectory); }, 1500); } else { watching.close(); process.nextTick(done); } }); }); }); }); }); }); }); webpack-3.5.6/test/WatcherEvents.test.js000066400000000000000000000027441315401342100202170ustar00rootroot00000000000000"use strict"; /*globals describe it before after */ const path = require("path"); const should = require("should"); 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", function() { this.timeout(10000); it("should emit 'watch-close' when using single-compiler mode and the compiler is not running", function(done) { let called = false; const compiler = createSingleCompiler(); const watcher = compiler.watch({}, (err, stats) => { called.should.be.exactly(true); done(err); }); compiler.plugin("watch-close", () => { called = true; }); compiler.plugin("done", () => { watcher.close(); }); }); it("should emit 'watch-close' when using multi-compiler mode and the compiler is not running", function(done) { let called = false; const compiler = createMultiCompiler(); const watcher = compiler.watch({}, (err, stats) => { called.should.be.exactly(true); done(err); }); compiler.plugin("watch-close", () => { called = true; }); compiler.plugin("done", () => { watcher.close(); }); }); }); webpack-3.5.6/test/WebEnvironmentPlugin.test.js000066400000000000000000000013151315401342100215470ustar00rootroot00000000000000"use strict"; const should = require("should"); const WebEnvironmentPlugin = require("../lib/web/WebEnvironmentPlugin"); describe("WebEnvironmentPlugin", () => { let WebEnvironmentPluginInstance; before(() => WebEnvironmentPluginInstance = new WebEnvironmentPlugin("inputFileSystem", "outputFileSystem")); describe("apply", () => { let compileSpy; before(() => { compileSpy = { outputFileSystem: "otherOutputFileSystem" }; WebEnvironmentPluginInstance.apply(compileSpy); }); it("should set compiler.outputFileSystem information with the same as setted in WebEnvironmentPlugin", () => should(compileSpy.outputFileSystem).be.eql(WebEnvironmentPluginInstance.outputFileSystem)); }); }); webpack-3.5.6/test/WebWorkerChunkTemplatePlugin.test.js000066400000000000000000000047011315401342100232030ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const ConcatSource = require("webpack-sources").ConcatSource; const WebWorkerChunkTemplatePlugin = require("../lib/webworker/WebWorkerChunkTemplatePlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("WebWorkerChunkTemplatePlugin", () => { let handlerContext; beforeEach(() => { handlerContext = { outputOptions: { chunkCallbackName: "Foo", library: "Bar" } }; }); it("has apply function", () => { (new WebWorkerChunkTemplatePlugin()).apply.should.be.a.Function(); }); describe("when applied", () => { let eventBindings, eventBinding; beforeEach(() => { eventBindings = applyPluginWithOptions(WebWorkerChunkTemplatePlugin); }); it("binds two event handlers", () => { eventBindings.length.should.be.exactly(2); }); describe("render handler", () => { beforeEach(() => { eventBinding = eventBindings[0]; }); it("binds to render event", () => { eventBinding.name.should.be.exactly("render"); }); describe("with chunk call back name set", () => { it("creates source wrapper with function name", () => { const source = eventBinding.handler.call(handlerContext, "modules()", { ids: 100, }); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("Foo(100,modules())"); }); }); describe("without chunk call back name set", () => { it("creates source wrapper with library name", () => { delete handlerContext.outputOptions.chunkCallbackName; const source = eventBinding.handler.call(handlerContext, "modules()", { ids: 100, }); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("webpackChunkBar(100,modules())"); }); }); }); describe("hash handler", () => { var hashMock; beforeEach(() => { eventBinding = eventBindings[1]; hashMock = { update: sinon.spy() }; }); it("binds to hash event", () => { eventBinding.name.should.be.exactly("hash"); }); it("updates hash object", () => { eventBinding.handler.call(handlerContext, hashMock); hashMock.update.callCount.should.be.exactly(4); sinon.assert.calledWith(hashMock.update, "webworker"); sinon.assert.calledWith(hashMock.update, "3"); sinon.assert.calledWith(hashMock.update, "Foo"); sinon.assert.calledWith(hashMock.update, "Bar"); }); }); }); }); webpack-3.5.6/test/WebWorkerHotUpdateChunkTemplatePlugin.test.js000066400000000000000000000047441315401342100250300ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const ConcatSource = require("webpack-sources").ConcatSource; const WebWorkerHotUpdateChunkTemplatePlugin = require("../lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("WebWorkerHotUpdateChunkTemplatePlugin", () => { let handlerContext; beforeEach(() => { handlerContext = { outputOptions: { hotUpdateFunction: "Foo", library: "Bar" } }; }); it("has apply function", () => (new WebWorkerHotUpdateChunkTemplatePlugin()).apply.should.be.a.Function()); describe("when applied", () => { let eventBindings, eventBinding; beforeEach(() => eventBindings = applyPluginWithOptions(WebWorkerHotUpdateChunkTemplatePlugin)); it("binds two event handlers", () => eventBindings.length.should.be.exactly(2)); describe("render handler", () => { beforeEach(() => eventBinding = eventBindings[0]); it("binds to render event", () => eventBinding.name.should.be.exactly("render")); describe("with hot update function name set", () => { it("creates source wrapper with function name", () => { const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("Foo(100,moduleSource())"); }); }); describe("without hot update function name set", () => { it("creates source wrapper with library name", () => { delete handlerContext.outputOptions.hotUpdateFunction; const source = eventBinding.handler.call(handlerContext, "moduleSource()", [], [], {}, 100); source.should.be.instanceof(ConcatSource); source.source().should.be.exactly("webpackHotUpdateBar(100,moduleSource())"); }); }); }); describe("hash handler", () => { let hashMock; beforeEach(() => { eventBinding = eventBindings[1]; hashMock = { update: sinon.spy() }; }); it("binds to hash event", () => { eventBinding.name.should.be.exactly("hash"); }); it("updates hash object", () => { eventBinding.handler.call(handlerContext, hashMock); hashMock.update.callCount.should.be.exactly(4); sinon.assert.calledWith(hashMock.update, "WebWorkerHotUpdateChunkTemplatePlugin"); sinon.assert.calledWith(hashMock.update, "3"); sinon.assert.calledWith(hashMock.update, "Foo"); sinon.assert.calledWith(hashMock.update, "Bar"); }); }); }); }); webpack-3.5.6/test/WebWorkerMainTemplatePlugin.test.js000066400000000000000000000171171315401342100230240ustar00rootroot00000000000000"use strict"; const should = require("should"); const sinon = require("sinon"); const WebWorkerMainTemplatePlugin = require("../lib/webworker/WebWorkerMainTemplatePlugin"); const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); describe("WebWorkerMainTemplatePlugin", function() { let env; beforeEach(() => { env = {}; }); it("has apply function", function() { (new WebWorkerMainTemplatePlugin()).apply.should.be.a.Function(); }); describe("when applied", function() { beforeEach(function() { env.eventBindings = applyPluginWithOptions(WebWorkerMainTemplatePlugin); env.handlerContext = { requireFn: 'requireFn', indent: (value) => typeof value === 'string' ? value : value.join("\n"), asString: (values) => values.join("\n"), renderCurrentHashCode: (value) => value, outputOptions: { chunkFilename: 'chunkFilename' }, applyPluginsWaterfall: (moduleName, fileName, data) => { return `"${moduleName}${data.hash}${data.hashWithLength()}${data.chunk && data.chunk.id || ''}"`; }, renderAddModule: () => 'renderAddModuleSource();', }; }); it("binds five event handlers", function() { env.eventBindings.length.should.be.exactly(5); }); describe("local-vars handler", function() { beforeEach(() => { env.eventBinding = env.eventBindings[0]; }); it("binds to local-vars event", () => { env.eventBinding.name.should.be.exactly("local-vars"); }); describe("when no chunks are provided", () => { beforeEach(() => { const chunk = { ids: [], chunks: [] }; env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); }); it("returns the original source", () => { env.source.should.be.exactly("moduleSource()") }); }); describe("when chunks are provided", () => { beforeEach(() => { const chunk = { ids: [1, 2, 3], chunks: [ 'foo', 'bar', 'baz' ] }; env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123'); }); it("returns the original source with installed mapping", () => { env.source.should.be.exactly(` moduleSource() // object to store loaded chunks // "1" means "already loaded" var installedChunks = { 1: 1, 2: 1, 3: 1 }; `.trim()) }); }); }); describe("require-ensure handler", () => { beforeEach(() => { env.eventBinding = env.eventBindings[1]; }); it("binds to require-ensure event", () => { env.eventBinding.name.should.be.exactly("require-ensure"); }); describe("when called", () => { beforeEach(() => { const chunk = {}; env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123'); }); it("creates import scripts call and promise resolve", () => { env.source.should.be.exactly(` return new Promise(function(resolve) { // "1" is the signal for "already loaded" if(!installedChunks[chunkId]) { importScripts("asset-path" + abc123 + "" + abc123 + "" + chunkId + ""); } resolve(); }); `.trim()) }); }); }); describe("bootstrap handler", () => { beforeEach(() => { env.eventBinding = env.eventBindings[2]; }); it("binds to bootstrap event", () => { env.eventBinding.name.should.be.exactly("bootstrap"); }); describe("when no chunks are provided", () => { beforeEach(() => { const chunk = { ids: [], chunks: [] }; env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); }); it("returns the original source", () => { env.source.should.be.exactly("moduleSource()") }); }); describe("when chunks are provided", () => { beforeEach(() => { const chunk = { ids: [1, 2, 3], chunks: [ 'foo', 'bar', 'baz' ] }; env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); }); it("returns the original source with chunk callback", () => { env.source.should.be.exactly(` moduleSource() this["webpackChunk"] = function webpackChunkCallback(chunkIds, moreModules) { for(var moduleId in moreModules) { renderAddModuleSource(); } while(chunkIds.length) installedChunks[chunkIds.pop()] = 1; }; `.trim()) }); }); }); describe("hot-bootstrap handler", () => { beforeEach(() => { env.eventBinding = env.eventBindings[3]; }); it("binds to hot-bootstrap event", () => { env.eventBinding.name.should.be.exactly("hot-bootstrap"); }); describe("when called", () => { beforeEach(() => { const chunk = {}; env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123'); }); it("returns the original source with hot update callback", () => { env.source.should.be.exactly(` moduleSource() var parentHotUpdateCallback = this["webpackHotUpdate"]; this["webpackHotUpdate"] = function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars hotAddUpdateChunk(chunkId, moreModules); if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } ; function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars importScripts(requireFn.p + "asset-path" + abc123 + "" + abc123 + "" + chunkId + ""); } function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars 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 = requireFn.p + "asset-path" + abc123 + "" + abc123 + ""; 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); } }; }); } function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars delete installedChunks[chunkId]; } `.trim()) }); }); }); describe("hash handler", () => { beforeEach(() => { env.eventBinding = env.eventBindings[4]; env.handlerContext = { outputOptions: { publicPath: "Alpha", filename: "Bravo", chunkFilename: "Charlie", chunkCallbackName: "Delta", library: "Echo" } }; env.hashMock = { update: sinon.spy() }; env.eventBinding.handler.call(env.handlerContext, env.hashMock); }); it("binds to hash event", () => { env.eventBinding.name.should.be.exactly("hash"); }); it("updates hash object", () => { env.hashMock.update.callCount.should.be.exactly(7); sinon.assert.calledWith(env.hashMock.update, "webworker"); sinon.assert.calledWith(env.hashMock.update, "3"); sinon.assert.calledWith(env.hashMock.update, "Alpha"); sinon.assert.calledWith(env.hashMock.update, "Bravo"); sinon.assert.calledWith(env.hashMock.update, "Charlie"); sinon.assert.calledWith(env.hashMock.update, "Delta"); sinon.assert.calledWith(env.hashMock.update, "Echo"); }); }); }); }); webpack-3.5.6/test/WebpackError.test.js000066400000000000000000000014101315401342100200100ustar00rootroot00000000000000"use strict"; const util = require("util"); const should = require("should"); 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", function() { const errorStr = util.inspect(new CustomError("Message")); const errorArr = errorStr.split("\n"); errorArr[0].should.equal("CustomError: CustomMessage"); errorArr[1].should.containEql("WebpackError.test.js"); errorArr[errorArr.length - 1].should.equal("CustomDetails"); }); }); webpack-3.5.6/test/WebpackMissingModule.test.js000066400000000000000000000023571315401342100215110ustar00rootroot00000000000000/* globals describe, it */ "use strict"; const should = require("should"); 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"); should(errorMessage).be.eql("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"); should(errorMessage).be.eql("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"); should(errorMessage).be.eql("!(function webpackMissingModule() { var e = new Error(\"Cannot find module \\\"mock message\\\"\"); e.code = 'MODULE_NOT_FOUND'; throw e; }())"); }); }); }); webpack-3.5.6/test/benchmarkCases/000077500000000000000000000000001315401342100170235ustar00rootroot00000000000000webpack-3.5.6/test/benchmarkCases/large-ast/000077500000000000000000000000001315401342100207025ustar00rootroot00000000000000webpack-3.5.6/test/benchmarkCases/large-ast/index.js000066400000000000000000000010221315401342100223420ustar00rootroot00000000000000import "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-3.5.6/test/benchmarkCases/large-ast/index2.js000066400000000000000000000003701315401342100224310ustar00rootroot00000000000000import "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-3.5.6/test/benchmarkCases/large-ast/webpack.config.js000066400000000000000000000000661315401342100241220ustar00rootroot00000000000000module.exports = { entry: ["./index", "./index2"] }; webpack-3.5.6/test/benchmarkCases/libraries/000077500000000000000000000000001315401342100207775ustar00rootroot00000000000000webpack-3.5.6/test/benchmarkCases/libraries/webpack.config.js000066400000000000000000000000771315401342100242210ustar00rootroot00000000000000module.exports = { entry: ["react", "react-dom", "lodash"] }; webpack-3.5.6/test/benchmarkCases/many-chunks/000077500000000000000000000000001315401342100212605ustar00rootroot00000000000000webpack-3.5.6/test/benchmarkCases/many-chunks/a.js000066400000000000000000000005361315401342100220420ustar00rootroot00000000000000import("./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-3.5.6/test/benchmarkCases/many-chunks/b.js000066400000000000000000000003351315401342100220400ustar00rootroot00000000000000import("./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-3.5.6/test/benchmarkCases/many-chunks/c.js000066400000000000000000000000131315401342100220320ustar00rootroot00000000000000// content webpack-3.5.6/test/benchmarkCases/many-chunks/index.js000066400000000000000000000002521315401342100227240ustar00rootroot00000000000000import("./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-3.5.6/test/benchmarkCases/many-chunks/webpack.config.js000066400000000000000000000000501315401342100244710ustar00rootroot00000000000000module.exports = { entry: "./index" }; webpack-3.5.6/test/benchmarkCases/many-modules-source-map/000077500000000000000000000000001315401342100235065ustar00rootroot00000000000000webpack-3.5.6/test/benchmarkCases/many-modules-source-map/a.js000066400000000000000000000005501315401342100242640ustar00rootroot00000000000000require("./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-3.5.6/test/benchmarkCases/many-modules-source-map/b.js000066400000000000000000000006271315401342100242720ustar00rootroot00000000000000require("./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-3.5.6/test/benchmarkCases/many-modules-source-map/c.js000066400000000000000000000000131315401342100242600ustar00rootroot00000000000000// content webpack-3.5.6/test/benchmarkCases/many-modules-source-map/index.js000066400000000000000000000002401315401342100251470ustar00rootroot00000000000000import "./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-3.5.6/test/benchmarkCases/many-modules-source-map/webpack.config.js000066400000000000000000000001221315401342100267170ustar00rootroot00000000000000module.exports = { entry: "./index", devtool: "eval-cheap-module-source-map" }; webpack-3.5.6/test/benchmarkCases/many-modules/000077500000000000000000000000001315401342100214355ustar00rootroot00000000000000webpack-3.5.6/test/benchmarkCases/many-modules/a.js000066400000000000000000000005501315401342100222130ustar00rootroot00000000000000require("./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-3.5.6/test/benchmarkCases/many-modules/b.js000066400000000000000000000006271315401342100222210ustar00rootroot00000000000000require("./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-3.5.6/test/benchmarkCases/many-modules/c.js000066400000000000000000000000131315401342100222070ustar00rootroot00000000000000// content webpack-3.5.6/test/benchmarkCases/many-modules/index.js000066400000000000000000000002401315401342100230760ustar00rootroot00000000000000import "./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-3.5.6/test/benchmarkCases/many-modules/webpack.config.js000066400000000000000000000000501315401342100246460ustar00rootroot00000000000000module.exports = { entry: "./index" }; webpack-3.5.6/test/binCases/000077500000000000000000000000001315401342100156415ustar00rootroot00000000000000webpack-3.5.6/test/binCases/config-name/000077500000000000000000000000001315401342100200245ustar00rootroot00000000000000webpack-3.5.6/test/binCases/config-name/found-many/000077500000000000000000000000001315401342100221015ustar00rootroot00000000000000webpack-3.5.6/test/binCases/config-name/found-many/index.js000066400000000000000000000000301315401342100235370ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/config-name/found-many/index2.js000066400000000000000000000000301315401342100236210ustar00rootroot00000000000000module.exports = "bar"; webpack-3.5.6/test/binCases/config-name/found-many/index3.js000066400000000000000000000000001315401342100236170ustar00rootroot00000000000000webpack-3.5.6/test/binCases/config-name/found-many/test.js000066400000000000000000000003771315401342100234250ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[7].should.containEql("./index2.js"); stdout[13].should.containEql("./index3.js"); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/config-name/found-many/test.opts000066400000000000000000000002051315401342100237640ustar00rootroot00000000000000--config ./webpack.config.js --config-name bar --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node webpack-3.5.6/test/binCases/config-name/found-many/webpack.config.js000066400000000000000000000003751315401342100253240ustar00rootroot00000000000000var path = require("path"); module.exports = [ { name: "foo", entry: path.resolve(__dirname, "./index") }, { name: "bar", entry: path.resolve(__dirname, "./index2") }, { name: "bar", entry: path.resolve(__dirname, "./index3.js") } ]; webpack-3.5.6/test/binCases/config-name/found-one/000077500000000000000000000000001315401342100217165ustar00rootroot00000000000000webpack-3.5.6/test/binCases/config-name/found-one/index.js000066400000000000000000000000301315401342100233540ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/config-name/found-one/index2.js000066400000000000000000000000301315401342100234360ustar00rootroot00000000000000module.exports = "bar"; webpack-3.5.6/test/binCases/config-name/found-one/test.js000066400000000000000000000003211315401342100232270ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[5].should.containEql("./index2.js"); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/config-name/found-one/test.opts000066400000000000000000000002051315401342100236010ustar00rootroot00000000000000--config ./webpack.config.js --config-name bar --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node webpack-3.5.6/test/binCases/config-name/found-one/webpack.config.js000066400000000000000000000002671315401342100251410ustar00rootroot00000000000000var path = require("path"); module.exports = [ { name: "foo", entry: path.resolve(__dirname, "./index") }, { name: "bar", entry: path.resolve(__dirname, "./index2") } ]; webpack-3.5.6/test/binCases/config-name/not-found/000077500000000000000000000000001315401342100217355ustar00rootroot00000000000000webpack-3.5.6/test/binCases/config-name/not-found/test.js000066400000000000000000000003261315401342100232530ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.not.eql(0); stdout.should.be.empty(); stderr[0].should.containEql("Configuration with name 'foo' was not found."); }; webpack-3.5.6/test/binCases/config-name/not-found/test.opts000066400000000000000000000000571315401342100236250ustar00rootroot00000000000000--config ./webpack.config.js --config-name foo webpack-3.5.6/test/binCases/config-name/not-found/webpack.config.js000066400000000000000000000000451315401342100251520ustar00rootroot00000000000000module.exports = [{ name: "bar" }]; webpack-3.5.6/test/binCases/configFile/000077500000000000000000000000001315401342100177065ustar00rootroot00000000000000webpack-3.5.6/test/binCases/configFile/profile/000077500000000000000000000000001315401342100213465ustar00rootroot00000000000000webpack-3.5.6/test/binCases/configFile/profile/bar.js000066400000000000000000000000241315401342100224440ustar00rootroot00000000000000console.log('bar'); webpack-3.5.6/test/binCases/configFile/profile/foo.js000066400000000000000000000000471315401342100224700ustar00rootroot00000000000000require('./bar'); console.log('foo'); webpack-3.5.6/test/binCases/configFile/profile/index.js000066400000000000000000000000351315401342100230110ustar00rootroot00000000000000const foo = require('./foo');webpack-3.5.6/test/binCases/configFile/profile/test.js000066400000000000000000000004431315401342100226640ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[6].should.containEql("factory:"); stdout[8].should.containEql("factory:"); stdout[10].should.containEql("factory:"); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/configFile/profile/webpack.config.js000066400000000000000000000001561315401342100245660ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: path.resolve(__dirname, "./index"), profile: true }; webpack-3.5.6/test/binCases/entry/000077500000000000000000000000001315401342100170025ustar00rootroot00000000000000webpack-3.5.6/test/binCases/entry/multi-file/000077500000000000000000000000001315401342100210515ustar00rootroot00000000000000webpack-3.5.6/test/binCases/entry/multi-file/a.js000066400000000000000000000000311315401342100216210ustar00rootroot00000000000000module.exports = "fileA";webpack-3.5.6/test/binCases/entry/multi-file/index.js000066400000000000000000000000311315401342100225100ustar00rootroot00000000000000module.exports = "index";webpack-3.5.6/test/binCases/entry/multi-file/test.js000066400000000000000000000005671315401342100223760ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[4].should.containEql("null.js"); stdout[5].should.match(/multi.*index\.js.*a\.js/); // should have multi-file entry stdout[6].should.match(/index\.js.*\{0\}/); stdout[7].should.match(/a\.js.*\{0\}/); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/entry/multi-file/test.opts000066400000000000000000000002251315401342100227360ustar00rootroot00000000000000--entry ./index.js --entry ./a.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node webpack-3.5.6/test/binCases/entry/multi-file/webpack.config.js000066400000000000000000000000251315401342100242640ustar00rootroot00000000000000module.exports = {}; webpack-3.5.6/test/binCases/entry/named-entry/000077500000000000000000000000001315401342100212255ustar00rootroot00000000000000webpack-3.5.6/test/binCases/entry/named-entry/a.js000066400000000000000000000000311315401342100217750ustar00rootroot00000000000000module.exports = "fileA";webpack-3.5.6/test/binCases/entry/named-entry/index.js000066400000000000000000000000311315401342100226640ustar00rootroot00000000000000module.exports = "index";webpack-3.5.6/test/binCases/entry/named-entry/test.js000066400000000000000000000005621315401342100225450ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[4].should.containEql("null.js"); stdout[5].should.containEql("foo.js"); // named entry from --entry foo=./a.js stdout[6].should.match(/a\.js.*\{1\}/); stdout[7].should.match(/index\.js.*\{0\}/); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/entry/named-entry/test.opts000066400000000000000000000002311315401342100231070ustar00rootroot00000000000000--entry foo=./a.js --entry ./index.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node webpack-3.5.6/test/binCases/entry/named-entry/webpack.config.js000066400000000000000000000000251315401342100244400ustar00rootroot00000000000000module.exports = {}; webpack-3.5.6/test/binCases/entry/non-hyphenated-args/000077500000000000000000000000001315401342100226555ustar00rootroot00000000000000webpack-3.5.6/test/binCases/entry/non-hyphenated-args/a.js000066400000000000000000000000311315401342100234250ustar00rootroot00000000000000module.exports = "fileA";webpack-3.5.6/test/binCases/entry/non-hyphenated-args/index.js000066400000000000000000000000311315401342100243140ustar00rootroot00000000000000module.exports = "index";webpack-3.5.6/test/binCases/entry/non-hyphenated-args/test.js000066400000000000000000000007021315401342100241710ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[4].should.containEql("null.js"); stdout[5].should.containEql("main.js"); // non-hyphenated arg ./a.js should create chunk "main" stdout[6].should.match(/index\.js.*\{0\}/); // index.js should be in chunk 0 stdout[7].should.match(/a\.js.*\{1\}/); // a.js should be in chunk 1 stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/entry/non-hyphenated-args/test.opts000066400000000000000000000002151315401342100245410ustar00rootroot00000000000000./a.js --entry ./index.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node webpack-3.5.6/test/binCases/entry/non-hyphenated-args/webpack.config.js000066400000000000000000000000251315401342100260700ustar00rootroot00000000000000module.exports = {}; webpack-3.5.6/test/binCases/errors/000077500000000000000000000000001315401342100171555ustar00rootroot00000000000000webpack-3.5.6/test/binCases/errors/parse/000077500000000000000000000000001315401342100202675ustar00rootroot00000000000000webpack-3.5.6/test/binCases/errors/parse/index.js000066400000000000000000000000021315401342100217240ustar00rootroot00000000000000} webpack-3.5.6/test/binCases/errors/parse/test.js000066400000000000000000000010301315401342100215760ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.eql(2); stdout[0].should.containEql("Hash: "); stdout[1].should.containEql("Version: "); stdout[2].should.containEql("Time: "); stdout[5].should.containEql("./index.js"); stdout[5].should.containEql("[built]"); stdout[5].should.containEql("[failed]"); stdout[5].should.containEql("[1 error]"); stdout[7].should.containEql("ERROR in ./index.js"); stdout[8].should.containEql("Module parse failed:"); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/errors/parse/webpack.config.js000066400000000000000000000000751315401342100235070ustar00rootroot00000000000000module.exports = { context: __dirname, entry: "./index" }; webpack-3.5.6/test/binCases/help/000077500000000000000000000000001315401342100165715ustar00rootroot00000000000000webpack-3.5.6/test/binCases/help/help-output/000077500000000000000000000000001315401342100210575ustar00rootroot00000000000000webpack-3.5.6/test/binCases/help/help-output/test.js000066400000000000000000000011521315401342100223730ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[0].should.startWith("webpack"); stdout.should.containEql("Config options:"); stdout.should.containEql("Basic options:"); stdout.should.containEql("Module options:"); stdout.should.containEql("Output options:"); stdout.should.containEql("Advanced options:"); stdout.should.containEql("Resolving options:"); stdout.should.containEql("Optimizing options:"); stdout.should.containEql("Stats options:"); stdout.should.containEql("Options:"); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/help/help-output/test.opts000066400000000000000000000000071315401342100227420ustar00rootroot00000000000000--help webpack-3.5.6/test/binCases/module/000077500000000000000000000000001315401342100171265ustar00rootroot00000000000000webpack-3.5.6/test/binCases/module/module-bind/000077500000000000000000000000001315401342100213255ustar00rootroot00000000000000webpack-3.5.6/test/binCases/module/module-bind/file.post000066400000000000000000000000051315401342100231460ustar00rootroot00000000000000post webpack-3.5.6/test/binCases/module/module-bind/file.pre000066400000000000000000000000041315401342100227460ustar00rootroot00000000000000pre webpack-3.5.6/test/binCases/module/module-bind/index.js000066400000000000000000000001341315401342100227700ustar00rootroot00000000000000var pre = require('./file.pre'); var post = require('./file.post'); module.exports = "foo"; webpack-3.5.6/test/binCases/module/module-bind/post-loader.js000066400000000000000000000001641315401342100241150ustar00rootroot00000000000000module.exports = function(source) { console.log("post-loaded " + source.replace(/\r?\n/g, "")); return source; }; webpack-3.5.6/test/binCases/module/module-bind/pre-loader.js000066400000000000000000000001631315401342100237150ustar00rootroot00000000000000module.exports = function(source) { console.log("pre-loaded " + source.replace(/\r?\n/g, "")); return source; }; webpack-3.5.6/test/binCases/module/module-bind/test.js000066400000000000000000000003771315401342100226510ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout.should.containEql("pre-loaded pre"); stdout.should.containEql("post-loaded post"); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/module/module-bind/test.opts000066400000000000000000000003171315401342100232140ustar00rootroot00000000000000--entry ./index.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node --module-bind-pre pre=./pre-loader --module-bind-post post=./post-loader webpack-3.5.6/test/binCases/module/module-bind/webpack.config.js000066400000000000000000000001371315401342100245440ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: path.resolve(__dirname, "./index"), }; webpack-3.5.6/test/binCases/plugins/000077500000000000000000000000001315401342100173225ustar00rootroot00000000000000webpack-3.5.6/test/binCases/plugins/uglifyjsplugin-empty-args/000077500000000000000000000000001315401342100244635ustar00rootroot00000000000000webpack-3.5.6/test/binCases/plugins/uglifyjsplugin-empty-args/index.js000066400000000000000000000000301315401342100261210ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/plugins/uglifyjsplugin-empty-args/test.js000066400000000000000000000003611315401342100260000ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.exactly(0); stdout.should.be.ok(); stdout[4].should.containEql("bytes"); // without uglifyjs it's multiple kBs stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/plugins/uglifyjsplugin-empty-args/test.opts000066400000000000000000000002631315401342100263520ustar00rootroot00000000000000--entry ./index.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node --plugin webpack/lib/optimize/UglifyJsPlugin webpack-3.5.6/test/binCases/plugins/uglifyjsplugin-empty-args/webpack.config.js000066400000000000000000000001371315401342100277020ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: path.resolve(__dirname, "./index"), }; webpack-3.5.6/test/binCases/stats/000077500000000000000000000000001315401342100167775ustar00rootroot00000000000000webpack-3.5.6/test/binCases/stats/custom-preset/000077500000000000000000000000001315401342100216115ustar00rootroot00000000000000webpack-3.5.6/test/binCases/stats/custom-preset/index.js000066400000000000000000000000301315401342100232470ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/stats/custom-preset/test.js000066400000000000000000000002421315401342100231240ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { stderr.should.be.empty(); code.should.be.eql(0); stdout.should.be.empty(); }; webpack-3.5.6/test/binCases/stats/custom-preset/test.opts000066400000000000000000000001701315401342100234750ustar00rootroot00000000000000--entry ./index.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node --display none webpack-3.5.6/test/binCases/stats/multi-config/000077500000000000000000000000001315401342100213745ustar00rootroot00000000000000webpack-3.5.6/test/binCases/stats/multi-config/index.js000066400000000000000000000000301315401342100230320ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/stats/multi-config/index2.js000066400000000000000000000000301315401342100231140ustar00rootroot00000000000000module.exports = "bar"; webpack-3.5.6/test/binCases/stats/multi-config/test.js000066400000000000000000000002361315401342100227120ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.eql(0); stdout.should.be.ok(); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/stats/multi-config/webpack.config.js000066400000000000000000000003111315401342100246050ustar00rootroot00000000000000var path = require("path"); module.exports = [ { entry: path.resolve(__dirname, "./index"), stats: "errors-only" }, { entry: path.resolve(__dirname, "./index2"), stats: "errors-only" } ]; webpack-3.5.6/test/binCases/stats/none/000077500000000000000000000000001315401342100177365ustar00rootroot00000000000000webpack-3.5.6/test/binCases/stats/none/index.js000066400000000000000000000000301315401342100213740ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/stats/none/test.js000066400000000000000000000002421315401342100212510ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.eql(0); stdout.should.be.empty(); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/stats/none/webpack.config.js000066400000000000000000000001561315401342100231560ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: path.resolve(__dirname, "./index"), stats: "none" }; webpack-3.5.6/test/binCases/stats/single-config/000077500000000000000000000000001315401342100215235ustar00rootroot00000000000000webpack-3.5.6/test/binCases/stats/single-config/index.js000066400000000000000000000000301315401342100231610ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/stats/single-config/test.js000066400000000000000000000010311315401342100230330ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(code, stdout, stderr) { code.should.be.eql(0); stdout.should.be.ok(); stdout[0].should.containEql("Hash: "); stdout[1].should.containEql("Version: "); stdout[2].should.containEql("Time: "); stdout[4].should.containEql("\u001b[1m\u001b[32mnull.js\u001b[39m\u001b[22m"); stdout[5].should.containEql("chunk"); stdout[6].should.not.containEql("./index.js"); stdout[6].should.not.containEql("[built]"); stdout[6].should.containEql("1 module"); stderr.should.be.empty(); }; webpack-3.5.6/test/binCases/stats/single-config/webpack.config.js000066400000000000000000000002541315401342100247420ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: path.resolve(__dirname, "./index"), stats: { assets: true, colors: true, chunks: true, maxModules: 0 } }; webpack-3.5.6/test/binCases/test.opts000066400000000000000000000002061315401342100175250ustar00rootroot00000000000000--entry ./index.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node webpack-3.5.6/test/binCases/watch/000077500000000000000000000000001315401342100167475ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/multi-config-watch-opt/000077500000000000000000000000001315401342100232505ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/multi-config-watch-opt/async000066400000000000000000000000001315401342100242760ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/multi-config-watch-opt/index.js000066400000000000000000000000301315401342100247060ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/watch/multi-config-watch-opt/index2.js000066400000000000000000000000301315401342100247700ustar00rootroot00000000000000module.exports = "bar"; webpack-3.5.6/test/binCases/watch/multi-config-watch-opt/test.js000066400000000000000000000003641315401342100245700ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(stdout, stderr, done) { stdout.should.be.ok(); stdout[0].should.containEql(""); stdout[1].should.containEql("Webpack is watching the files…"); stderr.should.be.empty(); done(); }; webpack-3.5.6/test/binCases/watch/multi-config-watch-opt/test.opts000066400000000000000000000002161315401342100251350ustar00rootroot00000000000000--entry ./index.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node --watch webpack-3.5.6/test/binCases/watch/multi-config-watch-opt/webpack.config.js000066400000000000000000000002311315401342100264620ustar00rootroot00000000000000var path = require("path"); module.exports = [ { entry: path.resolve(__dirname, "./index") }, { entry: path.resolve(__dirname, "./index2") } ]; webpack-3.5.6/test/binCases/watch/multi-config/000077500000000000000000000000001315401342100213445ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/multi-config/async000066400000000000000000000000001315401342100223720ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/multi-config/index.js000066400000000000000000000000301315401342100230020ustar00rootroot00000000000000module.exports = "foo"; webpack-3.5.6/test/binCases/watch/multi-config/index2.js000066400000000000000000000000301315401342100230640ustar00rootroot00000000000000module.exports = "bar"; webpack-3.5.6/test/binCases/watch/multi-config/test.js000066400000000000000000000003641315401342100226640ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(stdout, stderr, done) { stdout.should.be.ok(); stdout[0].should.containEql(""); stdout[1].should.containEql("Webpack is watching the files…"); stderr.should.be.empty(); done(); }; webpack-3.5.6/test/binCases/watch/multi-config/webpack.config.js000066400000000000000000000002501315401342100245570ustar00rootroot00000000000000var path = require("path"); module.exports = [ { entry: path.resolve(__dirname, "./index"), watch: true }, { entry: path.resolve(__dirname, "./index2") } ]; webpack-3.5.6/test/binCases/watch/single-config-watch-opt/000077500000000000000000000000001315401342100233775ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/single-config-watch-opt/async000066400000000000000000000000001315401342100244250ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/single-config-watch-opt/test.js000066400000000000000000000003641315401342100247170ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(stdout, stderr, done) { stdout.should.be.ok(); stdout[0].should.containEql(""); stdout[1].should.containEql("Webpack is watching the files…"); stderr.should.be.empty(); done(); }; webpack-3.5.6/test/binCases/watch/single-config-watch-opt/test.opts000066400000000000000000000002161315401342100252640ustar00rootroot00000000000000--entry ./index.js --config ./webpack.config.js --output-filename [name].js --output-chunk-filename [id].chunk.js --target async-node --watch webpack-3.5.6/test/binCases/watch/single-config-watch-opt/webpack.config.js000066400000000000000000000001361315401342100266150ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: path.resolve(__dirname, "./index") }; webpack-3.5.6/test/binCases/watch/single-config/000077500000000000000000000000001315401342100214735ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/single-config/async000066400000000000000000000000001315401342100225210ustar00rootroot00000000000000webpack-3.5.6/test/binCases/watch/single-config/test.js000066400000000000000000000003641315401342100230130ustar00rootroot00000000000000"use strict"; module.exports = function testAssertions(stdout, stderr, done) { stdout.should.be.ok(); stdout[0].should.containEql(""); stdout[1].should.containEql("Webpack is watching the files…"); stderr.should.be.empty(); done(); }; webpack-3.5.6/test/binCases/watch/single-config/webpack.config.js000066400000000000000000000001541315401342100247110ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: path.resolve(__dirname, "./index"), watch: true }; webpack-3.5.6/test/browsertest/000077500000000000000000000000001315401342100164755ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/build.js000066400000000000000000000051151315401342100201340ustar00rootroot00000000000000/* 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-3.5.6/test/browsertest/img/000077500000000000000000000000001315401342100172515ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/img/fail.png000066400000000000000000000002761315401342100206770ustar00rootroot00000000000000PNG  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 resolve: # cannot resolve should outside the outermost node_modules # so it is injected here alias: should: require.resolve "should" plugins: [ new webpack.optimize.LimitChunkCountPlugin maxChunks: 3 new webpack.optimize.CommonsChunkPlugin name: "common" filename: "library2.commons.js" 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-3.5.6/test/browsertest/middlewareTest.js000066400000000000000000000023071315401342100220120ustar00rootroot00000000000000var 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.optimize.UglifyJsPlugin(), 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-3.5.6/test/browsertest/mocha.css000066400000000000000000000056621315401342100203070ustar00rootroot00000000000000@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-3.5.6/test/browsertest/mocha.js000066400000000000000000002763461315401342100201440ustar00rootroot00000000000000;(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(); } }; /** * Outut 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 , numerOfLines = 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-3.5.6/test/browsertest/node_modules/000077500000000000000000000000001315401342100211525ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/extra.loader.js000066400000000000000000000001361315401342100241000ustar00rootroot00000000000000module.exports = function(string) { this.cacheable(); return string + " with post loader"; }webpack-3.5.6/test/browsertest/node_modules/library1/000077500000000000000000000000001315401342100226775ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library1/index.js000066400000000000000000000015731315401342100243520ustar00rootroot00000000000000// Single File library var loadTimelibrary1 = typeof window.library1 === "undefined" describe("library1", function() { it("should load library1 only once", function() { loadTimelibrary1.should.be.ok; }); it("should load a component", function() { require("./lib/component").should.be.eql("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) { sameTick.should.be.eql(true); require("submodule1").should.be.eql("submodule1"); require("submodule2").should.be.eql("submodule2"); require("submodule3")().should.be.eql("submodule3"); require.ensure([], function(require) { sameTick.should.be.eql(true); done(); }); }); setImmediate(function() { sameTick = false; }); }); }); module.exports = true;webpack-3.5.6/test/browsertest/node_modules/library1/lib/000077500000000000000000000000001315401342100234455ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library1/lib/comp.js000066400000000000000000000000421315401342100247350ustar00rootroot00000000000000module.exports = "lib1 component";webpack-3.5.6/test/browsertest/node_modules/library1/lib/component.js000066400000000000000000000000461315401342100260050ustar00rootroot00000000000000module.exports = require("./comp.js");webpack-3.5.6/test/browsertest/node_modules/library1/node_modules/000077500000000000000000000000001315401342100253545ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library1/node_modules/submodule1/000077500000000000000000000000001315401342100274345ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library1/node_modules/submodule1/index.js000066400000000000000000000000361315401342100311000ustar00rootroot00000000000000module.exports = "submodule1";webpack-3.5.6/test/browsertest/node_modules/library1/node_modules/submodule2/000077500000000000000000000000001315401342100274355ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library1/node_modules/submodule2/index.js000066400000000000000000000000721315401342100311010ustar00rootroot00000000000000module.exports = (function() { return "submodule2"; }());webpack-3.5.6/test/browsertest/node_modules/library2/000077500000000000000000000000001315401342100227005ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library2/lib/000077500000000000000000000000001315401342100234465ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library2/lib/common.js000066400000000000000000000003621315401342100252750ustar00rootroot00000000000000var should = require("should"); var typeofLibrary2 = typeof library2; describe("library2", function() { it("should run before main", function() { typeofLibrary2.should.be.eql("undefined"); }); }); exports.library2common = { ok2: true };webpack-3.5.6/test/browsertest/node_modules/library2/lib/extra.js000066400000000000000000000000361315401342100251260ustar00rootroot00000000000000module.exports = "Lib2 extra";webpack-3.5.6/test/browsertest/node_modules/library2/lib/extra2.js000066400000000000000000000000371315401342100252110ustar00rootroot00000000000000module.exports = "Lib2 extra2";webpack-3.5.6/test/browsertest/node_modules/library2/lib/main.js000066400000000000000000000062761315401342100247430ustar00rootroot00000000000000// Chunked File library var should = require("should"); var library2commonValue = library2common; describe("library2", function() { var tickExtra, tickEmpty, tickMerged; var extraValue, testValue; before(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() { library2commonValue.should.be.eql({ok2: true}); }); it("should load stuff with require.ensure asynchron", function() { should.strictEqual(tickExtra, false); }); it("should load not include stuff from parent, remove empty chunks and apply a post loader", function() { should.strictEqual(tickEmpty, true); extraValue.should.be.eql("Lib2 extra2 with post loader"); }); it("should merge chunks if maxChunks specified", function() { should.strictEqual(tickEmpty, true); testValue.should.be.eql("test module"); }); it("should load require.amd from options", function() { require.amd.should.have.property("fromOptions").be.eql(true); }); it("should run empty AMD require", function(done) { var emptyRequire = false; require([], function() { emptyRequire = true; }); Promise.resolve().then(function() {}).then(function() {}).then(function() { emptyRequire.should.be.eql(true); done(); }); }); it("should provide free variables", function() { s3().should.be.eql("submodule3"); }); it("should define values", function() { (CONST_UNDEFINED === undefined).should.be.eql(true); (CONST_NULL === null).should.be.eql(true); CONST_TRUE.should.be.eql(true); CONST_FALSE.should.be.eql(false); (CONST_FUNCTION()).should.be.eql("ok"); (CONST_NUMBER).should.be.eql(123); CONST_NUMBER_EXPR.should.be.eql(123); (typeof CONST_TYPEOF).should.be.eql("typeof"); var o = CONST_OBJECT; (CONST_OBJECT.A).should.be.eql(1); CONST_OBJECT.B.should.be.eql("B"); CONST_OBJECT.C().should.be.eql("C"); o.A.should.be.eql(1); o.B.should.be.eql("B"); o.C().should.be.eql("C"); (function(o) { o.A.should.be.eql(1); o.B.should.be.eql("B"); o.C().should.be.eql("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 linewebpack-3.5.6/test/browsertest/node_modules/library2/lib/test.js000066400000000000000000000000371315401342100247630ustar00rootroot00000000000000module.exports = "test module";webpack-3.5.6/test/browsertest/node_modules/library2/node_modules/000077500000000000000000000000001315401342100253555ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library2/node_modules/submodule1/000077500000000000000000000000001315401342100274355ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library2/node_modules/submodule1/index.js000066400000000000000000000000361315401342100311010ustar00rootroot00000000000000module.exports = "submodule1";webpack-3.5.6/test/browsertest/node_modules/library2/node_modules/submodule2/000077500000000000000000000000001315401342100274365ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library2/node_modules/submodule2/index.js000066400000000000000000000000721315401342100311020ustar00rootroot00000000000000module.exports = (function() { return "submodule2"; }());webpack-3.5.6/test/browsertest/node_modules/library2/node_modules/submodule3/000077500000000000000000000000001315401342100274375ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/library2/node_modules/submodule3/index.js000066400000000000000000000000661315401342100311060ustar00rootroot00000000000000module.exports = function() { return "submodule3"; };webpack-3.5.6/test/browsertest/node_modules/library2/package.json000066400000000000000000000000321315401342100251610ustar00rootroot00000000000000{ "main": "lib/main.js" }webpack-3.5.6/test/browsertest/node_modules/library2b.js000066400000000000000000000001561315401342100234020ustar00rootroot00000000000000describe("library2b", function() { it("should load this library", function() { true.should.be.ok; }); }); webpack-3.5.6/test/browsertest/node_modules/subcontent/000077500000000000000000000000001315401342100233365ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/subcontent/index.js000066400000000000000000000000311315401342100247750ustar00rootroot00000000000000module.exports = "error";webpack-3.5.6/test/browsertest/node_modules/subcontent/test.jade000066400000000000000000000000101315401342100251310ustar00rootroot00000000000000xyz: abcwebpack-3.5.6/test/browsertest/node_modules/subcontent2/000077500000000000000000000000001315401342100234205ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/subcontent2/file.js000066400000000000000000000000331315401342100246710ustar00rootroot00000000000000module.exports = "orginal";webpack-3.5.6/test/browsertest/node_modules/submodule3/000077500000000000000000000000001315401342100232345ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/node_modules/submodule3/index.js000066400000000000000000000000661315401342100247030ustar00rootroot00000000000000module.exports = function() { return "submodule3"; };webpack-3.5.6/test/browsertest/package.json000066400000000000000000000000671315401342100207660ustar00rootroot00000000000000{ "name": "node-webkit-tests", "main": "tests.html" }webpack-3.5.6/test/browsertest/tests.html000066400000000000000000000020431315401342100205240ustar00rootroot00000000000000 Mocha
    • styling

      • style!css loader

      • style!less loader

      • file loader:

    webpack-3.5.6/test/browsertest/web_modules/000077500000000000000000000000001315401342100210025ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/web_modules/subcontent/000077500000000000000000000000001315401342100231665ustar00rootroot00000000000000webpack-3.5.6/test/browsertest/web_modules/subcontent/index.js000066400000000000000000000000341315401342100246300ustar00rootroot00000000000000module.exports = "replaced";webpack-3.5.6/test/browsertest/webpack.config.js000066400000000000000000000004311315401342100217110ustar00rootroot00000000000000module.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-3.5.6/test/cases/000077500000000000000000000000001315401342100152105ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/000077500000000000000000000000001315401342100165035ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/context-weak/000077500000000000000000000000001315401342100211145ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/context-weak/dir/000077500000000000000000000000001315401342100216725ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/context-weak/dir/four.js000066400000000000000000000000241315401342100231770ustar00rootroot00000000000000module.exports = 4; webpack-3.5.6/test/cases/chunks/context-weak/index.js000066400000000000000000000014351315401342100225640ustar00rootroot00000000000000it("should not bundle context requires with asyncMode === 'weak'", function() { var contextRequire = require.context(".", false, /two/, "weak"); (function() { contextRequire("./two") }).should.throw(/not available/); }); it("should find module with asyncMode === 'weak' when required elsewhere", function() { var contextRequire = require.context(".", false, /.+/, "weak"); contextRequire("./three").should.be.eql(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"); contextRequire("./dir/four").should.be.eql(4); require("./dir/four"); // in a real app would be served as a separate chunk }); webpack-3.5.6/test/cases/chunks/context-weak/three.js000066400000000000000000000000241315401342100225550ustar00rootroot00000000000000module.exports = 3; webpack-3.5.6/test/cases/chunks/context-weak/two.js000066400000000000000000000000241315401342100222570ustar00rootroot00000000000000module.exports = 2; webpack-3.5.6/test/cases/chunks/context/000077500000000000000000000000001315401342100201675ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/context/index.js000066400000000000000000000004311315401342100216320ustar00rootroot00000000000000it("should also work in a chunk", function(done) { require.ensure([], function(require) { var contextRequire = require.context(".", false, /two/); contextRequire("./two").should.be.eql(2); var tw = "tw"; require("." + "/" + tw + "o").should.be.eql(2); done(); }); }); webpack-3.5.6/test/cases/chunks/context/two.js000066400000000000000000000000231315401342100213310ustar00rootroot00000000000000module.exports = 2;webpack-3.5.6/test/cases/chunks/import-context/000077500000000000000000000000001315401342100214775ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/import-context/dir/000077500000000000000000000000001315401342100222555ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/import-context/dir/one.js000066400000000000000000000000241315401342100233700ustar00rootroot00000000000000module.exports = 1; webpack-3.5.6/test/cases/chunks/import-context/dir/three.js000066400000000000000000000000241315401342100237160ustar00rootroot00000000000000module.exports = 3; webpack-3.5.6/test/cases/chunks/import-context/dir/two.js000066400000000000000000000000241315401342100234200ustar00rootroot00000000000000module.exports = 2; webpack-3.5.6/test/cases/chunks/import-context/dir2/000077500000000000000000000000001315401342100223375ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/import-context/dir2/one.js000066400000000000000000000000241315401342100234520ustar00rootroot00000000000000module.exports = 1; webpack-3.5.6/test/cases/chunks/import-context/dir2/three.js000066400000000000000000000000241315401342100240000ustar00rootroot00000000000000module.exports = 3; webpack-3.5.6/test/cases/chunks/import-context/dir2/two.js000066400000000000000000000000241315401342100235020ustar00rootroot00000000000000module.exports = 2; webpack-3.5.6/test/cases/chunks/import-context/index.js000066400000000000000000000020411315401342100231410ustar00rootroot00000000000000function testCase(load, done) { load("two", 2, function() { var sync = true; load("one", 1, function() { sync.should.be.eql(false); load("three", 3, function() { var sync = true; load("two", 2, function() { sync.should.be.eql(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) { result.should.be.eql(expected); callback(); }).catch(function(err) { done(err); }); } testCase(load, done); }); it("should be able to use expressions in System.import", function(done) { function load(name, expected, callback) { System.import("./dir2/" + name).then(function(result) { result.should.be.eql(expected); callback(); }).catch(function(err) { done(err); }); } testCase(load, done); }); webpack-3.5.6/test/cases/chunks/import/000077500000000000000000000000001315401342100200155ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/import/index.js000066400000000000000000000005471315401342100214700ustar00rootroot00000000000000it("should be able to use import", function(done) { import("./two").then(function(two) { two.should.be.eql(2); done(); }).catch(function(err) { done(err); }); }); it("should be able to use System.import", function(done) { System.import("./two").then(function(two) { two.should.be.eql(2); done(); }).catch(function(err) { done(err); }); }); webpack-3.5.6/test/cases/chunks/import/two.js000066400000000000000000000000231315401342100211570ustar00rootroot00000000000000module.exports = 2;webpack-3.5.6/test/cases/chunks/inline-options/000077500000000000000000000000001315401342100214525ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir1/000077500000000000000000000000001315401342100223115ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir1/a.js000066400000000000000000000000241315401342100230630ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir1/b.js000066400000000000000000000000241315401342100230640ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir1/c.js000066400000000000000000000000241315401342100230650ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir1/d.js000066400000000000000000000000241315401342100230660ustar00rootroot00000000000000export default "d"; webpack-3.5.6/test/cases/chunks/inline-options/dir10/000077500000000000000000000000001315401342100223715ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir10/a.js000066400000000000000000000000241315401342100231430ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir11/000077500000000000000000000000001315401342100223725ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir11/a.js000066400000000000000000000000241315401342100231440ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir2/000077500000000000000000000000001315401342100223125ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir2/a.js000066400000000000000000000000241315401342100230640ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir2/b.js000066400000000000000000000000241315401342100230650ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir2/c.js000066400000000000000000000000241315401342100230660ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir2/d.js000066400000000000000000000000241315401342100230670ustar00rootroot00000000000000export default "d"; webpack-3.5.6/test/cases/chunks/inline-options/dir3/000077500000000000000000000000001315401342100223135ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir3/a.js000066400000000000000000000000241315401342100230650ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir3/b.js000066400000000000000000000000241315401342100230660ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir3/c.js000066400000000000000000000000241315401342100230670ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir3/d.js000066400000000000000000000000241315401342100230700ustar00rootroot00000000000000export default "d"; webpack-3.5.6/test/cases/chunks/inline-options/dir4/000077500000000000000000000000001315401342100223145ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir4/a.js000066400000000000000000000000241315401342100230660ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir4/b.js000066400000000000000000000000241315401342100230670ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir4/c.js000066400000000000000000000000241315401342100230700ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir4/d.js000066400000000000000000000000241315401342100230710ustar00rootroot00000000000000export default "d"; webpack-3.5.6/test/cases/chunks/inline-options/dir5/000077500000000000000000000000001315401342100223155ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir5/a.js000066400000000000000000000000241315401342100230670ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir5/b.js000066400000000000000000000000241315401342100230700ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir5/c.js000066400000000000000000000000241315401342100230710ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir5/d.js000066400000000000000000000000241315401342100230720ustar00rootroot00000000000000export default "d"; webpack-3.5.6/test/cases/chunks/inline-options/dir6/000077500000000000000000000000001315401342100223165ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir6/a.js000066400000000000000000000000241315401342100230700ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir6/b.js000066400000000000000000000000241315401342100230710ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir6/c.js000066400000000000000000000000241315401342100230720ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir6/d.js000066400000000000000000000000241315401342100230730ustar00rootroot00000000000000export default "d"; webpack-3.5.6/test/cases/chunks/inline-options/dir7/000077500000000000000000000000001315401342100223175ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir7/a.js000066400000000000000000000000241315401342100230710ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir7/b.js000066400000000000000000000000241315401342100230720ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir7/c.js000066400000000000000000000000241315401342100230730ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir7/d.js000066400000000000000000000000241315401342100230740ustar00rootroot00000000000000export default "d"; webpack-3.5.6/test/cases/chunks/inline-options/dir8/000077500000000000000000000000001315401342100223205ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir8/a.js000066400000000000000000000000241315401342100230720ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir8/b.js000066400000000000000000000000241315401342100230730ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir8/c.js000066400000000000000000000000241315401342100230740ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/dir9/000077500000000000000000000000001315401342100223215ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/inline-options/dir9/a.js000066400000000000000000000000241315401342100230730ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/chunks/inline-options/dir9/b.js000066400000000000000000000000241315401342100230740ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/chunks/inline-options/dir9/c.js000066400000000000000000000000241315401342100230750ustar00rootroot00000000000000export default "c"; webpack-3.5.6/test/cases/chunks/inline-options/index.js000066400000000000000000000075551315401342100231330ustar00rootroot00000000000000it("should be able to use eager mode", function(done) { function load(name) { return import(/* webpackMode: "eager" */ "./dir1/" + name); } testChunkLoading(load, true, true, done); }); it("should be able to use lazy-once mode", function(done) { function load(name) { return import(/* webpackMode: "lazy-once" */ "./dir2/" + name); } testChunkLoading(load, false, true, done); }); it("should be able to use lazy-once mode with name", function(done) { function load(name) { return import(/* webpackMode: "lazy-once", webpackChunkName: "name-lazy-once" */ "./dir3/" + name); } testChunkLoading(load, false, true, done); }); it("should be able to use lazy mode", function(done) { function load(name) { return import(/* webpackMode: "lazy" */ "./dir4/" + name); } testChunkLoading(load, false, false, done); }); it("should be able to use lazy mode with name", function(done) { function load(name) { return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy" */ "./dir5/" + name); } testChunkLoading(load, false, false, done); }); it("should be able to use lazy mode with name and placeholder", function(done) { function load(name) { return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy-[request]" */ "./dir6/" + name); } testChunkLoading(load, false, false, done); }); it("should be able to combine chunks by name", function(done) { 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"); } } testChunkLoading(load, false, true, done); }); it("should be able to use weak mode", function(done) { function load(name) { return import(/* webpackMode: "weak" */ "./dir8/" + name); } require("./dir8/a") // chunks served manually by the user require("./dir8/b") require("./dir8/c") testChunkLoading(load, true, true, done); }); it("should be able to use weak mode (without context)", function(done) { 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") testChunkLoading(load, true, true, done); }); it("should not find module when mode is weak and chunk not served elsewhere", function(done) { var name = "a"; import(/* webpackMode: "weak" */ "./dir10/" + name) .catch(function(e) { e.should.match(/not available/); done(); }) }); it("should not find module when mode is weak and chunk not served elsewhere (without context)", function(done) { import(/* webpackMode: "weak" */ "./dir11/a") .catch(function(e) { e.should.match(/not available/); done(); }) }); function testChunkLoading(load, expectedSyncInitial, expectedSyncRequested, done) { var sync = false; var syncInitial = true; Promise.all([load("a"), load("b")]).then(function() { syncInitial.should.be.eql(expectedSyncInitial); sync = true; Promise.all([ load("a").then(function(a) { a.should.be.eql({ default: "a" }); sync.should.be.eql(true); }), load("c").then(function(c) { c.should.be.eql({ default: "c" }); sync.should.be.eql(expectedSyncRequested); }) ]).then(function() { done(); }, done); Promise.resolve().then(function(){}).then(function(){}).then(function(){}).then(function(){ sync = false; }); }).catch(done); Promise.resolve().then(function(){}).then(function(){}).then(function(){}).then(function(){ syncInitial = false; }); } webpack-3.5.6/test/cases/chunks/issue-2443/000077500000000000000000000000001315401342100202255ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/issue-2443/dir/000077500000000000000000000000001315401342100210035ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/issue-2443/dir/one/000077500000000000000000000000001315401342100215645ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/issue-2443/dir/one/file.js000066400000000000000000000000241315401342100230350ustar00rootroot00000000000000module.exports = 1; webpack-3.5.6/test/cases/chunks/issue-2443/dir/three/000077500000000000000000000000001315401342100221125ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/issue-2443/dir/three/file.js000066400000000000000000000000241315401342100233630ustar00rootroot00000000000000module.exports = 3; webpack-3.5.6/test/cases/chunks/issue-2443/dir/two/000077500000000000000000000000001315401342100216145ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/issue-2443/dir/two/file.js000066400000000000000000000000241315401342100230650ustar00rootroot00000000000000module.exports = 2; webpack-3.5.6/test/cases/chunks/issue-2443/index.js000066400000000000000000000007521315401342100216760ustar00rootroot00000000000000it("should be able to use expressions in import (directory)", function(done) { function load(name, expected, callback) { import("./dir/" + name + "/file.js").then(function(result) { result.should.be.eql(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-3.5.6/test/cases/chunks/named-chunks/000077500000000000000000000000001315401342100210605ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/named-chunks/empty.js000066400000000000000000000000001315401342100225420ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/named-chunks/empty2.js000066400000000000000000000000001315401342100226240ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/named-chunks/empty3.js000066400000000000000000000000001315401342100226250ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/named-chunks/empty4.js000066400000000000000000000000001315401342100226260ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/named-chunks/index.js000066400000000000000000000062411315401342100225300ustar00rootroot00000000000000it("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"); sync.should.be.ok(); done(); }, "named-chunk"); } }); it("should handle empty named chunks", function(done) { var sync = false; require.ensure([], function(require) { sync.should.be.ok(); }, "empty-named-chunk"); require.ensure([], function(require) { sync.should.be.ok(); 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"); sync.should.be.ok(); 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) { sync.should.be.ok(); }, function(error) {}, "empty-named-chunk-for-error-callback"); require.ensure([], function(require) { sync.should.be.ok(); 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){ sync.should.be.ok(); if(i++ > 0) done(); }).catch(function(err){ done(err); }); import("./empty?import3-in-chunk2" /* webpackChunkName: "import-named-chunk-2" */).then(function(result){ sync.should.not.be.ok(); 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){ sync.should.be.ok(); if(i++ > 0) done(); }).catch(function(err){ done(err); }); import("./e" + mpty + "4" /* webpackChunkName: "context-named-chunk-2" */).then(function(result){ sync.should.not.be.ok(); if(i++ > 0) done(); }).catch(function(err){ done(err); }); sync = true; Promise.resolve().then(function(){}).then(function(){}).then(function(){ sync = false; }); }); }); webpack-3.5.6/test/cases/chunks/parsing/000077500000000000000000000000001315401342100201465ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/parsing/empty.js000066400000000000000000000000001315401342100216300ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/parsing/index.js000066400000000000000000000021721315401342100216150ustar00rootroot00000000000000var should = require("should"); it("should handle bound function expressions", function(done) { require.ensure([], function(require) { this.should.be.eql({ test: true }); require("./empty?test"); process.nextTick.should.have.type("function"); // check if injection still works require.ensure([], function(require) { this.should.be.eql({ 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() { require("./empty?require.ensure:test").should.be.eql({}); 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() { should.strictEqual(value, "require.include"); value.should.be.eql("require.include"); done(); }); }); webpack-3.5.6/test/cases/chunks/parsing/require.include.js000066400000000000000000000000431315401342100235770ustar00rootroot00000000000000module.exports = "require.include";webpack-3.5.6/test/cases/chunks/runtime/000077500000000000000000000000001315401342100201665ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/runtime/a.js000066400000000000000000000000251315401342100207410ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/chunks/runtime/acircular.js000066400000000000000000000001211315401342100224630ustar00rootroot00000000000000require.ensure(["./acircular2"], function(require) { require("./acircular2"); })webpack-3.5.6/test/cases/chunks/runtime/acircular2.js000066400000000000000000000001171315401342100225520ustar00rootroot00000000000000require.ensure(["./acircular"], function(require) { require("./acircular"); })webpack-3.5.6/test/cases/chunks/runtime/b.js000066400000000000000000000000401315401342100207370ustar00rootroot00000000000000module.exports = require("./a");webpack-3.5.6/test/cases/chunks/runtime/duplicate.js000066400000000000000000000001221315401342100224710ustar00rootroot00000000000000require.ensure(["./a"], function(require) { require("./a").should.be.eql("a"); })webpack-3.5.6/test/cases/chunks/runtime/duplicate2.js000066400000000000000000000001221315401342100225530ustar00rootroot00000000000000require.ensure(["./b"], function(require) { require("./b").should.be.eql("a"); })webpack-3.5.6/test/cases/chunks/runtime/empty.js000066400000000000000000000000001315401342100216500ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/runtime/index.js000066400000000000000000000021721315401342100216350ustar00rootroot00000000000000/* 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 { asyncFlag.should.be.eql(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 { sync.should.be.eql(true); done(); } catch(e) { done(e); } }); Promise.resolve().then(function() {}).then(function() {}).then(function() { sync = false; }); } }); webpack-3.5.6/test/cases/chunks/var-inject-error-handler/000077500000000000000000000000001315401342100233075ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/var-inject-error-handler/empty.js000066400000000000000000000000001315401342100247710ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/var-inject-error-handler/index.js000066400000000000000000000003531315401342100247550ustar00rootroot00000000000000it("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-3.5.6/test/cases/chunks/weak-dependencies-context/000077500000000000000000000000001315401342100235405ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies-context/a.js000066400000000000000000000000001315401342100243040ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies-context/b.js000066400000000000000000000000001315401342100243050ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies-context/c.js000066400000000000000000000000001315401342100243060ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies-context/index.js000066400000000000000000000012041315401342100252020ustar00rootroot00000000000000it("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"); resolveWeakA.should.exist; resolveWeakB.should.exist; resolveWeakC.should.exist; a.should.be.eql(false); b.should.be.eql(false); c.should.be.eql(true); }); webpack-3.5.6/test/cases/chunks/weak-dependencies/000077500000000000000000000000001315401342100220565ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies/a.js000066400000000000000000000000001315401342100226220ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies/b.js000066400000000000000000000000001315401342100226230ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies/c.js000066400000000000000000000000001315401342100226240ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies/d.js000066400000000000000000000000001315401342100226250ustar00rootroot00000000000000webpack-3.5.6/test/cases/chunks/weak-dependencies/index.js000066400000000000000000000006751315401342100235330ustar00rootroot00000000000000it("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"); a.should.be.eql(false); b.should.be.eql(true); c.should.be.eql(false); d.should.be.eql(true); });webpack-3.5.6/test/cases/compile/000077500000000000000000000000001315401342100166405ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/deduplication-bundle-loader/000077500000000000000000000000001315401342100241775ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/deduplication-bundle-loader/a/000077500000000000000000000000001315401342100244175ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/deduplication-bundle-loader/a/file.js000066400000000000000000000000251315401342100256710ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/compile/deduplication-bundle-loader/b/000077500000000000000000000000001315401342100244205ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/deduplication-bundle-loader/b/file.js000066400000000000000000000000251315401342100256720ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/cases/compile/deduplication-bundle-loader/index.js000066400000000000000000000005631315401342100256500ustar00rootroot00000000000000it("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"); (typeof a).should.be.eql("function"); (typeof b).should.be.eql("function"); a(function(ra) { ra.should.be.eql("a"); b(function(rb) { rb.should.be.eql("b"); done(); }) }); }); webpack-3.5.6/test/cases/compile/deduplication/000077500000000000000000000000001315401342100214645ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/deduplication/d.js000066400000000000000000000000251315401342100222420ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/test/cases/compile/deduplication/dedupe1/000077500000000000000000000000001315401342100230135ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/deduplication/dedupe1/dupdep.js000066400000000000000000000000321315401342100246250ustar00rootroot00000000000000module.exports = "edupe1";webpack-3.5.6/test/cases/compile/deduplication/dedupe1/index.js000066400000000000000000000001371315401342100244610ustar00rootroot00000000000000module.exports = require("../d") + require("./dupdep"); var ep = "ep"; require("./dupd" + ep); webpack-3.5.6/test/cases/compile/deduplication/dedupe2/000077500000000000000000000000001315401342100230145ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/deduplication/dedupe2/dupdep.js000066400000000000000000000000321315401342100246260ustar00rootroot00000000000000module.exports = "edupe2";webpack-3.5.6/test/cases/compile/deduplication/dedupe2/index.js000066400000000000000000000001371315401342100244620ustar00rootroot00000000000000module.exports = require("../d") + require("./dupdep"); var ep = "ep"; require("./dupd" + ep); webpack-3.5.6/test/cases/compile/deduplication/index.js000066400000000000000000000003541315401342100231330ustar00rootroot00000000000000it("should load a duplicate module with different dependencies correctly", function() { var dedupe1 = require("./dedupe1"); var dedupe2 = require("./dedupe2"); dedupe1.should.be.eql("dedupe1"); dedupe2.should.be.eql("dedupe2"); }); webpack-3.5.6/test/cases/compile/error-hide-stack/000077500000000000000000000000001315401342100220035ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/error-hide-stack/errors.js000066400000000000000000000000761315401342100236600ustar00rootroot00000000000000module.exports = [ [/Module build failed: Message\nStack/] ];webpack-3.5.6/test/cases/compile/error-hide-stack/index.js000066400000000000000000000001611315401342100234460ustar00rootroot00000000000000it("should hide stack in details", function() { (function f() { require("./loader!"); }).should.throw(); }); webpack-3.5.6/test/cases/compile/error-hide-stack/loader.js000066400000000000000000000001721315401342100236070ustar00rootroot00000000000000module.exports = function() { var err = new Error("Message"); err.stack = "Stack"; err.hideStack = true; throw err; };webpack-3.5.6/test/cases/compile/issue2221/000077500000000000000000000000001315401342100202775ustar00rootroot00000000000000webpack-3.5.6/test/cases/compile/issue2221/exportvar.js000066400000000000000000000000271315401342100226660ustar00rootroot00000000000000export var foo = "bar" webpack-3.5.6/test/cases/compile/issue2221/index.js000066400000000000000000000001571315401342100217470ustar00rootroot00000000000000it("should compile non-immutable exports with missing semicolons", function(){ require("./exportvar"); }); webpack-3.5.6/test/cases/concord/000077500000000000000000000000001315401342100166375ustar00rootroot00000000000000webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/000077500000000000000000000000001315401342100243555ustar00rootroot00000000000000webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/index.js000066400000000000000000000005721315401342100260260ustar00rootroot00000000000000it("should resolve the alias in package.json", function() { require("app/file").default.should.be.eql("file"); }); it("should resolve the alias and extensions in package.json", function() { require("app/file2").default.should.be.eql("correct file2"); }); it("should resolve the alias in package.json", function() { require("thing").default.should.be.eql("the thing"); }); webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/modules/000077500000000000000000000000001315401342100260255ustar00rootroot00000000000000webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/modules/app/000077500000000000000000000000001315401342100266055ustar00rootroot00000000000000webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/modules/app/file.js000066400000000000000000000000271315401342100300610ustar00rootroot00000000000000export default "file"; webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/modules/app/file2.js000066400000000000000000000000361315401342100301430ustar00rootroot00000000000000export default "wrong file2"; webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/modules/app/file2.my-js000066400000000000000000000000401315401342100305610ustar00rootroot00000000000000export default "correct file2"; webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/package.json000066400000000000000000000002171315401342100266430ustar00rootroot00000000000000{ "concord": { "modules": { "app/**": "./modules/app/**", "thing": "./the-thing" }, "extensions": [ ".my-js", ".js" ] } }webpack-3.5.6/test/cases/concord/inner-modules-and-extensions/the-thing.js000066400000000000000000000000331315401342100265760ustar00rootroot00000000000000export default "the thing";webpack-3.5.6/test/cases/context/000077500000000000000000000000001315401342100166745ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/ignore-hidden-files/000077500000000000000000000000001315401342100225105ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/ignore-hidden-files/folder/000077500000000000000000000000001315401342100237635ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/ignore-hidden-files/folder/.file.js000066400000000000000000000000301315401342100253070ustar00rootroot00000000000000module.exports = "fail";webpack-3.5.6/test/cases/context/ignore-hidden-files/index.js000066400000000000000000000002151315401342100241530ustar00rootroot00000000000000it("should ignore hidden files", function() { (function() { var name = "./file.js"; require("./folder/" + name); }).should.throw(); });webpack-3.5.6/test/cases/context/issue-1769/000077500000000000000000000000001315401342100204305ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-1769/folder/000077500000000000000000000000001315401342100217035ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-1769/folder/0.js000066400000000000000000000000001315401342100223660ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-1769/index.js000066400000000000000000000003751315401342100221020ustar00rootroot00000000000000it("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) { err.should.be.instanceof(Error); done(); }); }); webpack-3.5.6/test/cases/context/issue-3873/000077500000000000000000000000001315401342100204265ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-3873/index.js000066400000000000000000000002421315401342100220710ustar00rootroot00000000000000function get(name) { return require("./" + name); } it("should automatically infer the index.js file", function() { get("module").should.be.eql("module"); }); webpack-3.5.6/test/cases/context/issue-3873/module/000077500000000000000000000000001315401342100217135ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-3873/module/index.js000066400000000000000000000000331315401342100233540ustar00rootroot00000000000000module.exports = "module"; webpack-3.5.6/test/cases/context/issue-524/000077500000000000000000000000001315401342100203345ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-524/index.js000066400000000000000000000013021315401342100217750ustar00rootroot00000000000000it("should support an empty context", function() { var c = require.context(".", true, /^nothing$/); (typeof c.id).should.be.oneOf(["number", "string"]); (function() { c.resolve(""); }).should.throw(); (function() { c(""); }).should.throw(); c.keys().should.be.eql([]); }); // This would be a useful testcase, but it requires an (really) empty directory. // **but** you cannot commit empty directories into git /*it("should support an empty context (empty dir)", function() { var c = require.context("./empty", true, /^nothing$/); c.id.should.be.type("number"); (function() { c.resolve(""); }).should.throw(); (function() { c(""); }).should.throw(); c.keys().should.be.eql([]); });*/ webpack-3.5.6/test/cases/context/issue-801/000077500000000000000000000000001315401342100203325ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-801/folder/000077500000000000000000000000001315401342100216055ustar00rootroot00000000000000webpack-3.5.6/test/cases/context/issue-801/folder/file.js000066400000000000000000000005771315401342100230730ustar00rootroot00000000000000module.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-3.5.6/test/cases/context/issue-801/index.js000066400000000000000000000006411315401342100220000ustar00rootroot00000000000000it("should emit valid code for dynamic require string with expr", function() { var test = require("./folder/file"); test("file").should.be.eql({ a: false, b: false, c: true, d: true }); test("file.js").should.be.eql({ a: false, b: false, c: false, d: true }); test("./file").should.be.eql({ a: true, b: true, c: false, d: false }); test("./file.js").should.be.eql({ a: false, b: false, c: false, d: false }); });webpack-3.5.6/test/cases/errors/000077500000000000000000000000001315401342100165245ustar00rootroot00000000000000webpack-3.5.6/test/cases/errors/case-sensistive/000077500000000000000000000000001315401342100216315ustar00rootroot00000000000000webpack-3.5.6/test/cases/errors/case-sensistive/a.js000066400000000000000000000000001315401342100223750ustar00rootroot00000000000000webpack-3.5.6/test/cases/errors/case-sensistive/b/000077500000000000000000000000001315401342100220525ustar00rootroot00000000000000webpack-3.5.6/test/cases/errors/case-sensistive/b/file.js000066400000000000000000000000001315401342100233150ustar00rootroot00000000000000webpack-3.5.6/test/cases/errors/case-sensistive/index.js000066400000000000000000000003671315401342100233040ustar00rootroot00000000000000it("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"); a.should.not.be.equal(A); b.should.not.be.equal(B); }); webpack-3.5.6/test/cases/errors/case-sensistive/test.filter.js000066400000000000000000000002331315401342100244300ustar00rootroot00000000000000var fs = require("fs"); var path = require("path"); module.exports = function(config) { return fs.existsSync(path.join(__dirname, "TEST.FILTER.JS")); }; webpack-3.5.6/test/cases/errors/case-sensistive/warnings.js000066400000000000000000000004211315401342100240140ustar00rootroot00000000000000module.exports = [ [/There are multiple modules with names that only differ in casing/, /case-sensistive.A\.js/, /case-sensistive.a\.js/], [/There are multiple modules with names that only differ in casing/, /case-sensistive.B.file\.js/, /case-sensistive.b.file\.js/] ]; webpack-3.5.6/test/cases/errors/loader-error-warning/000077500000000000000000000000001315401342100225645ustar00rootroot00000000000000webpack-3.5.6/test/cases/errors/loader-error-warning/a.js000066400000000000000000000000001315401342100233300ustar00rootroot00000000000000webpack-3.5.6/test/cases/errors/loader-error-warning/error-loader.js000066400000000000000000000001351315401342100255160ustar00rootroot00000000000000module.exports = function(source) { this.emitError(this.query.substr(1)); return source; } webpack-3.5.6/test/cases/errors/loader-error-warning/errors.js000066400000000000000000000003051315401342100244340ustar00rootroot00000000000000module.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-3.5.6/test/cases/errors/loader-error-warning/index.js000066400000000000000000000002611315401342100242300ustar00rootroot00000000000000it("should emit the correct errors and warnings", function() { require("./error-loader?abc!./a"); require("./error-loader?def!./a"); require("./warning-loader?xyz!./a"); }); webpack-3.5.6/test/cases/errors/loader-error-warning/warning-loader.js000066400000000000000000000001371315401342100260340ustar00rootroot00000000000000module.exports = function(source) { this.emitWarning(this.query.substr(1)); return source; } webpack-3.5.6/test/cases/errors/loader-error-warning/warnings.js000066400000000000000000000001571315401342100247550ustar00rootroot00000000000000module.exports = [ [ /xyz/, /Emitted value instead of an instance of Error/, /warning-loader\.js/ ] ]; webpack-3.5.6/test/cases/loaders/000077500000000000000000000000001315401342100166415ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/_css/000077500000000000000000000000001315401342100175705ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/_css/folder/000077500000000000000000000000001315401342100210435ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/_css/folder/stylesheet-import1.css000066400000000000000000000002471315401342100253420ustar00rootroot00000000000000@import url(~resources-module/stylesheet-import2.css) print, screen; @import url(stylesheet-import3.css) print and screen; .rule-import1 { background: lightgreen; } webpack-3.5.6/test/cases/loaders/_css/folder/stylesheet-import3.css000066400000000000000000000000561315401342100253420ustar00rootroot00000000000000.rule-import2 { background: red !important; }webpack-3.5.6/test/cases/loaders/_css/generateCss.js000066400000000000000000000003341315401342100223710ustar00rootroot00000000000000var 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-3.5.6/test/cases/loaders/_css/node_modules/000077500000000000000000000000001315401342100222455ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/_css/node_modules/resources-module/000077500000000000000000000000001315401342100255425ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/_css/node_modules/resources-module/import2.less000066400000000000000000000000571315401342100300300ustar00rootroot00000000000000.less-rule-import2 { background: lightgreen; }webpack-3.5.6/test/cases/loaders/_css/node_modules/resources-module/stylesheet-import2.css000066400000000000000000000000521315401342100320340ustar00rootroot00000000000000.rule-import2 { background: lightgreen; }webpack-3.5.6/test/cases/loaders/_css/stylesheet.css000066400000000000000000000001261315401342100224720ustar00rootroot00000000000000@import url(folder/stylesheet-import1.css); .rule-direct { background: lightgreen; }webpack-3.5.6/test/cases/loaders/_resources/000077500000000000000000000000001315401342100210125ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/_resources/abc.txt000066400000000000000000000000031315401342100222710ustar00rootroot00000000000000abcwebpack-3.5.6/test/cases/loaders/_resources/included.jade000066400000000000000000000000131315401342100234200ustar00rootroot00000000000000h1 includedwebpack-3.5.6/test/cases/loaders/_resources/parent.jade000066400000000000000000000000421315401342100231240ustar00rootroot00000000000000p block content include included webpack-3.5.6/test/cases/loaders/_resources/script.coffee000066400000000000000000000001251315401342100234650ustar00rootroot00000000000000condition = true obj = text: "coffee test" module.exports = obj.text if condition?webpack-3.5.6/test/cases/loaders/_resources/template.jade000066400000000000000000000001251315401342100234500ustar00rootroot00000000000000extends parent block content = typeof abc === "undefined" ? "self" + self.abc : abcwebpack-3.5.6/test/cases/loaders/async/000077500000000000000000000000001315401342100177565ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/async/a.js000066400000000000000000000000251315401342100205310ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/loaders/async/index.js000066400000000000000000000016161315401342100214270ustar00rootroot00000000000000it("should allow combinations of async and sync loaders", function() { require("./loaders/syncloader!./a").should.be.eql("a"); require("./loaders/asyncloader!./a").should.be.eql("a"); require("./loaders/syncloader!./loaders/syncloader!./a").should.be.eql("a"); require("./loaders/syncloader!./loaders/asyncloader!./a").should.be.eql("a"); require("./loaders/asyncloader!./loaders/syncloader!./a").should.be.eql("a"); require("./loaders/asyncloader!./loaders/asyncloader!./a").should.be.eql("a"); require("./loaders/asyncloader!./loaders/asyncloader!./loaders/asyncloader!./a").should.be.eql("a"); require("./loaders/asyncloader!./loaders/syncloader!./loaders/asyncloader!./a").should.be.eql("a"); require("./loaders/syncloader!./loaders/asyncloader!./loaders/syncloader!./a").should.be.eql("a"); require("./loaders/syncloader!./loaders/syncloader!./loaders/syncloader!./a").should.be.eql("a"); }); webpack-3.5.6/test/cases/loaders/async/loaders/000077500000000000000000000000001315401342100214075ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/async/loaders/asyncloader.js000066400000000000000000000004321315401342100242500ustar00rootroot00000000000000module.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-3.5.6/test/cases/loaders/async/loaders/syncloader.js000066400000000000000000000000701315401342100241050ustar00rootroot00000000000000module.exports = function(content) { return content; };webpack-3.5.6/test/cases/loaders/coffee-loader/000077500000000000000000000000001315401342100213345ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/coffee-loader/index.js000066400000000000000000000007731315401342100230100ustar00rootroot00000000000000it("should handle the coffee loader correctly", function() { require("!coffee-loader!../_resources/script.coffee").should.be.eql("coffee test"); require("../_resources/script.coffee").should.be.eql("coffee test"); }); it("should handle literate coffee script correctly", function() { require("!coffee-loader?literate!./script.coffee.md").should.be.eql("literate coffee test"); }); it("should generate valid code with cheap-source-map", function() { require("!coffee-loader!./module-only.coffee"); }); webpack-3.5.6/test/cases/loaders/coffee-loader/module-only.coffee000066400000000000000000000000061315401342100247450ustar00rootroot00000000000000modulewebpack-3.5.6/test/cases/loaders/coffee-loader/script.coffee.md000066400000000000000000000003521315401342100244100ustar00rootroot00000000000000# 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-3.5.6/test/cases/loaders/context/000077500000000000000000000000001315401342100203255ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/context/index.js000066400000000000000000000003701315401342100217720ustar00rootroot00000000000000it("should be able to use a context with a loader", function() { var abc = "abc", scr = "script.coffee"; require("../_resources/" + scr).should.be.eql("coffee test"); require("raw-loader!../_resources/" + abc + ".txt").should.be.eql("abc"); }); webpack-3.5.6/test/cases/loaders/css-loader/000077500000000000000000000000001315401342100206755ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/css-loader/index.js000066400000000000000000000005571315401342100223510ustar00rootroot00000000000000it("should handle the css loader correctly", function() { (require("!css-loader!../_css/stylesheet.css") + "").indexOf(".rule-direct").should.not.be.eql(-1); (require("!css-loader!../_css/stylesheet.css") + "").indexOf(".rule-import1").should.not.be.eql(-1); (require("!css-loader!../_css/stylesheet.css") + "").indexOf(".rule-import2").should.not.be.eql(-1); }); webpack-3.5.6/test/cases/loaders/issue-2299/000077500000000000000000000000001315401342100203745ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/issue-2299/a.json000066400000000000000000000001431315401342100215050ustar00rootroot00000000000000{ "imports": [ "./subdir_1/b.json", "./subdir_2/c.json" ], "a": true } webpack-3.5.6/test/cases/loaders/issue-2299/index.js000066400000000000000000000003131315401342100220360ustar00rootroot00000000000000it("should be able to use loadModule multiple times within a loader, on files in different directories", function() { require('!./loader/index.js!./a.json').should.have.properties(['a', 'b', 'c']); }); webpack-3.5.6/test/cases/loaders/issue-2299/loader/000077500000000000000000000000001315401342100216425ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/issue-2299/loader/index.js000066400000000000000000000012261315401342100233100ustar00rootroot00000000000000var asyncLib = require("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, this.exec(source, url)); }.bind(this)); }.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-3.5.6/test/cases/loaders/issue-2299/subdir_1/000077500000000000000000000000001315401342100221045ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/issue-2299/subdir_1/b.json000066400000000000000000000000221315401342100232120ustar00rootroot00000000000000{ "b": true } webpack-3.5.6/test/cases/loaders/issue-2299/subdir_2/000077500000000000000000000000001315401342100221055ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/issue-2299/subdir_2/c.json000066400000000000000000000000221315401342100232140ustar00rootroot00000000000000{ "c": true } webpack-3.5.6/test/cases/loaders/jade-loader/000077500000000000000000000000001315401342100210105ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/jade-loader/index.js000066400000000000000000000004351315401342100224570ustar00rootroot00000000000000it("should handle the jade loader correctly", function() { require("!jade-loader?self!../_resources/template.jade")({abc: "abc"}).should.be.eql("

    selfabc

    included

    "); require("../_resources/template.jade")({abc: "abc"}).should.be.eql("

    abc

    included

    "); }); webpack-3.5.6/test/cases/loaders/json-loader/000077500000000000000000000000001315401342100210565ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/json-loader/index.js000066400000000000000000000016341315401342100225270ustar00rootroot00000000000000var should = require("should"); it("should be able to load JSON files without loader", function() { var someJson = require("./some.json"); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); }); it("should also work when the json extension is omitted", function() { var someJson = require("./some"); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); }); it("should still be possible to manually apply the json-loader for compatibility reasons", function() { var someJson = require("json-loader!./some.json"); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); }); it("should still be possible to use a custom loader", function() { var someJson = JSON.parse(require("raw-loader!./some.json")); someJson.should.have.property("it", "works"); someJson.should.have.property("number", 42); }); webpack-3.5.6/test/cases/loaders/json-loader/some.json000066400000000000000000000000441315401342100227120ustar00rootroot00000000000000{ "it": "works", "number": 42 } webpack-3.5.6/test/cases/loaders/less-loader/000077500000000000000000000000001315401342100210535ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/less-loader/index.js000066400000000000000000000006461315401342100225260ustar00rootroot00000000000000it("should handle the less loader (piped with raw loader) correctly", function() { require("!raw-loader!less-loader!./less/stylesheet.less").indexOf(".less-rule-direct").should.not.be.eql(-1); require("!raw-loader!less-loader!./less/stylesheet.less").indexOf(".less-rule-import1").should.not.be.eql(-1); require("!raw-loader!less-loader!./less/stylesheet.less").indexOf(".less-rule-import2").should.not.be.eql(-1); }); webpack-3.5.6/test/cases/loaders/less-loader/less/000077500000000000000000000000001315401342100220215ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/less-loader/less/folder/000077500000000000000000000000001315401342100232745ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/less-loader/less/folder/import1.less000066400000000000000000000001751315401342100255620ustar00rootroot00000000000000@import "~resources-module/import2.less"; .less-rule-import1 { background: lightgreen; background-image: url("url.js"); } webpack-3.5.6/test/cases/loaders/less-loader/less/folder/url.js000066400000000000000000000000001315401342100244220ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/less-loader/less/stylesheet.less000066400000000000000000000001111315401342100250730ustar00rootroot00000000000000@import "folder/import1"; .less-rule-direct { background: lightgreen; }webpack-3.5.6/test/cases/loaders/less-loader/node_modules/000077500000000000000000000000001315401342100235305ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/less-loader/node_modules/resources-module/000077500000000000000000000000001315401342100270255ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/less-loader/node_modules/resources-module/import2.less000066400000000000000000000000571315401342100313130ustar00rootroot00000000000000.less-rule-import2 { background: lightgreen; }webpack-3.5.6/test/cases/loaders/less-loader/node_modules/resources-module/stylesheet-import2.css000066400000000000000000000000521315401342100333170ustar00rootroot00000000000000.rule-import2 { background: lightgreen; }webpack-3.5.6/test/cases/loaders/module-description-file/000077500000000000000000000000001315401342100233645ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/module-description-file/index.js000066400000000000000000000012761315401342100250370ustar00rootroot00000000000000it("should run a loader from package.json", function() { require("testloader!../_resources/abc.txt").should.be.eql("abcwebpack"); require("testloader/lib/loader2!../_resources/abc.txt").should.be.eql("abcweb"); require("testloader/lib/loader3!../_resources/abc.txt").should.be.eql("abcloader"); require("testloader/lib/loader-indirect!../_resources/abc.txt").should.be.eql("abcwebpack"); }); it("should run a loader from .webpack-loader.js extension", function() { require("testloader/lib/loader!../_resources/abc.txt").should.be.eql("abcwebpack"); }); it("should be able to pipe loaders", function() { require("testloader!./reverseloader!../_resources/abc.txt").should.be.eql("cbawebpack"); }); webpack-3.5.6/test/cases/loaders/module-description-file/node_modules/000077500000000000000000000000001315401342100260415ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/module-description-file/node_modules/testloader/000077500000000000000000000000001315401342100302075ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/module-description-file/node_modules/testloader/lib/000077500000000000000000000000001315401342100307555ustar00rootroot00000000000000loader-indirect.js000066400000000000000000000000671315401342100343040ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/module-description-file/node_modules/testloader/libmodule.exports = require("./loader.webpack-loader.js");webpack-3.5.6/test/cases/loaders/module-description-file/node_modules/testloader/lib/loader.js000066400000000000000000000002011315401342100325520ustar00rootroot00000000000000module.exports = function(content) { var content = contents[0]; callback(null, "module.exports=" + JSON.stringify(content)); } loader.webpack-loader.js000066400000000000000000000001461315401342100353620ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/module-description-file/node_modules/testloader/libmodule.exports = function(content) { return "module.exports=" + JSON.stringify(content+"webpack"); } loader2.web-loader.js000066400000000000000000000001601315401342100346010ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/module-description-file/node_modules/testloader/libmodule.exports = function(content) { this.callback(null, "module.exports=" + JSON.stringify(content+"web")); } loader3.loader.js000066400000000000000000000002141315401342100340270ustar00rootroot00000000000000webpack-3.5.6/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-3.5.6/test/cases/loaders/module-description-file/node_modules/testloader/package.json000066400000000000000000000001131315401342100324700ustar00rootroot00000000000000{ "name": "testloader", "webpackLoader": "lib/loader.webpack-loader.js" }webpack-3.5.6/test/cases/loaders/module-description-file/reverseloader.js000066400000000000000000000001251315401342100265620ustar00rootroot00000000000000module.exports = function(content) { return content.split("").reverse().join(""); } webpack-3.5.6/test/cases/loaders/query/000077500000000000000000000000001315401342100200065ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/query/a.js000066400000000000000000000000251315401342100205610ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/loaders/query/context-query-test/000077500000000000000000000000001315401342100236125ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/query/context-query-test/test.js000066400000000000000000000000141315401342100251220ustar00rootroot00000000000000test contentwebpack-3.5.6/test/cases/loaders/query/index.js000066400000000000000000000026461315401342100214630ustar00rootroot00000000000000it("should pass query to loader", function() { var result = require("./loaders/queryloader?query!./a?resourcequery"); result.should.be.eql({ 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"); result.should.be.eql({ resourceQuery: "?resourcequery", query: "?query", prev: null }); }); it("should pass query to loader without resource", function() { var result = require("./loaders/queryloader?query!"); result.should.be.eql({ query: "?query", prev: null }); }); it("should pass query to multiple loaders", function() { var result = require("./loaders/queryloader?query1!./loaders/queryloader?query2!./a?resourcequery"); result.should.have.type("object"); result.should.have.property("resourceQuery").be.eql("?resourcequery"); result.should.have.property("query").be.eql("?query1"); result.should.have.property("prev").be.eql("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); result.should.be.eql({ resourceQuery: "", query: "?query", prev: "test content" }); }); webpack-3.5.6/test/cases/loaders/query/loaders/000077500000000000000000000000001315401342100214375ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/query/loaders/queryloader.js000066400000000000000000000002451315401342100243320ustar00rootroot00000000000000module.exports = function(content) { return "module.exports = " + JSON.stringify({ resourceQuery: this.resourceQuery, query: this.query, prev: content }); } webpack-3.5.6/test/cases/loaders/raw-loader/000077500000000000000000000000001315401342100206765ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/raw-loader/index.js000066400000000000000000000002011315401342100223340ustar00rootroot00000000000000it("should handle the raw loader correctly", function() { require("raw-loader!../_resources/abc.txt").should.be.eql("abc"); }); webpack-3.5.6/test/cases/loaders/val-loader/000077500000000000000000000000001315401342100206675ustar00rootroot00000000000000webpack-3.5.6/test/cases/loaders/val-loader/index.js000066400000000000000000000006301315401342100223330ustar00rootroot00000000000000it("should handle the val loader (piped with css loader) correctly", function() { (require("!css-loader!val-loader!../_css/generateCss") + "").indexOf("generated").should.not.be.eql(-1); (require("!css-loader!val-loader!../_css/generateCss") + "").indexOf(".rule-import2").should.not.be.eql(-1); (require("!raw-loader!val-loader!../_css/generateCss") + "").indexOf("generated").should.not.be.eql(-1); }); webpack-3.5.6/test/cases/nonce/000077500000000000000000000000001315401342100163125ustar00rootroot00000000000000webpack-3.5.6/test/cases/nonce/set-nonce/000077500000000000000000000000001315401342100202055ustar00rootroot00000000000000webpack-3.5.6/test/cases/nonce/set-nonce/empty.js000066400000000000000000000000001315401342100216670ustar00rootroot00000000000000webpack-3.5.6/test/cases/nonce/set-nonce/index.js000066400000000000000000000016461315401342100216610ustar00rootroot00000000000000it("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"]'); script.getAttribute('nonce').should.be.eql('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"]'); script.hasAttribute('nonce').should.be.eql(false); } __webpack_nonce__ = undefined; done(); });webpack-3.5.6/test/cases/optimize/000077500000000000000000000000001315401342100170505ustar00rootroot00000000000000webpack-3.5.6/test/cases/optimize/tree-shaking-commonjs/000077500000000000000000000000001315401342100232545ustar00rootroot00000000000000webpack-3.5.6/test/cases/optimize/tree-shaking-commonjs/a.js000066400000000000000000000000311315401342100240240ustar00rootroot00000000000000export {test} from "./b";webpack-3.5.6/test/cases/optimize/tree-shaking-commonjs/b.js000066400000000000000000000000401315401342100240250ustar00rootroot00000000000000module.exports = require("./c");webpack-3.5.6/test/cases/optimize/tree-shaking-commonjs/c.js000066400000000000000000000000241315401342100240300ustar00rootroot00000000000000export * from "./d";webpack-3.5.6/test/cases/optimize/tree-shaking-commonjs/d.js000066400000000000000000000000401315401342100240270ustar00rootroot00000000000000module.exports = require("./e");webpack-3.5.6/test/cases/optimize/tree-shaking-commonjs/e.js000066400000000000000000000000261315401342100240340ustar00rootroot00000000000000export var test = 123;webpack-3.5.6/test/cases/optimize/tree-shaking-commonjs/index.js000066400000000000000000000001671315401342100247250ustar00rootroot00000000000000import { test } from "./a"; it("should correctly tree shake star exports", function() { test.should.be.eql(123); }); webpack-3.5.6/test/cases/optimize/tree-shaking-star/000077500000000000000000000000001315401342100224005ustar00rootroot00000000000000webpack-3.5.6/test/cases/optimize/tree-shaking-star/a.js000066400000000000000000000000241315401342100231520ustar00rootroot00000000000000export * from "./b";webpack-3.5.6/test/cases/optimize/tree-shaking-star/b.js000066400000000000000000000000241315401342100231530ustar00rootroot00000000000000export * from "./c";webpack-3.5.6/test/cases/optimize/tree-shaking-star/c.js000066400000000000000000000000241315401342100231540ustar00rootroot00000000000000export * from "./d";webpack-3.5.6/test/cases/optimize/tree-shaking-star/d.js000066400000000000000000000000261315401342100231570ustar00rootroot00000000000000export var test = 123;webpack-3.5.6/test/cases/optimize/tree-shaking-star/index.js000066400000000000000000000003351315401342100240460ustar00rootroot00000000000000import { test } from "./a"; import { func1, func3 } from "./x"; it("should correctly tree shake star exports", function() { test.should.be.eql(123); func1().should.be.eql("func1"); func3().should.be.eql("func3"); }); webpack-3.5.6/test/cases/optimize/tree-shaking-star/x.js000066400000000000000000000000541315401342100232040ustar00rootroot00000000000000export * from "./x1"; export * from "./x2"; webpack-3.5.6/test/cases/optimize/tree-shaking-star/x1.js000066400000000000000000000001301315401342100232600ustar00rootroot00000000000000export function func1() { return "func1"; } export function func2() { return "func2"; } webpack-3.5.6/test/cases/optimize/tree-shaking-star/x2.js000066400000000000000000000001301315401342100232610ustar00rootroot00000000000000export function func3() { return "func3"; } export function func4() { return "func4"; } webpack-3.5.6/test/cases/optimize/tree-shaking-star2/000077500000000000000000000000001315401342100224625ustar00rootroot00000000000000webpack-3.5.6/test/cases/optimize/tree-shaking-star2/a.js000066400000000000000000000000261315401342100232360ustar00rootroot00000000000000export * from "./aa"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/aa.js000066400000000000000000000000261315401342100233770ustar00rootroot00000000000000export var aa = "aa"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/b.js000066400000000000000000000000251315401342100232360ustar00rootroot00000000000000export * from "./bb";webpack-3.5.6/test/cases/optimize/tree-shaking-star2/bb.js000066400000000000000000000000261315401342100234010ustar00rootroot00000000000000export var bb = "bb"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/c.js000066400000000000000000000000241315401342100232360ustar00rootroot00000000000000export var c = "c"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/d.js000066400000000000000000000000211315401342100232340ustar00rootroot00000000000000exports.d = "d"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/index.js000066400000000000000000000004411315401342100241260ustar00rootroot00000000000000import { aa } from "./root"; import { aa as aa2, d } from "./root3"; var root6 = require("./root6"); it("should correctly tree shake star exports", function() { aa.should.be.eql("aa"); aa2.should.be.eql("aa"); d.should.be.eql("d"); root6.should.be.eql({ aa: "aa", c: "c" }); }); webpack-3.5.6/test/cases/optimize/tree-shaking-star2/root.js000066400000000000000000000000771315401342100240070ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/root2.js000066400000000000000000000001241315401342100240620ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; export * from "./d"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/root3.js000066400000000000000000000000311315401342100240600ustar00rootroot00000000000000export * from "./root2"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/root4.js000066400000000000000000000000521315401342100240640ustar00rootroot00000000000000export * from "./a"; export * from "./c"; webpack-3.5.6/test/cases/optimize/tree-shaking-star2/root5.js000066400000000000000000000000441315401342100240660ustar00rootroot00000000000000module.exports = require("./root4");webpack-3.5.6/test/cases/optimize/tree-shaking-star2/root6.js000066400000000000000000000000311315401342100240630ustar00rootroot00000000000000export * from "./root5"; webpack-3.5.6/test/cases/parsing/000077500000000000000000000000001315401342100166535ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/bom/000077500000000000000000000000001315401342100174305ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/bom/bomfile.css000066400000000000000000000000231315401342100215520ustar00rootroot00000000000000body{color:#abc}webpack-3.5.6/test/cases/parsing/bom/bomfile.js000066400000000000000000000000311315401342100213750ustar00rootroot00000000000000module.exports = "ok";webpack-3.5.6/test/cases/parsing/bom/index.js000066400000000000000000000004201315401342100210710ustar00rootroot00000000000000it("should load a utf-8 file with BOM", function() { var result = require("./bomfile"); result.should.be.eql("ok"); }); it("should load a css file with BOM", function() { var css = require("!css-loader!./bomfile.css") + ""; css.should.be.eql("body{color:#abc}"); }); webpack-3.5.6/test/cases/parsing/bom/typeof.js000066400000000000000000000000401315401342100212660ustar00rootroot00000000000000module.exports = typeof require;webpack-3.5.6/test/cases/parsing/browserify/000077500000000000000000000000001315401342100210465ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/browserify/index.js000066400000000000000000000026471315401342100225240ustar00rootroot00000000000000it("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 { require("./file").should.be.eql("ok"); done(); }); }); it("should parse a string in require.ensure with arrow function array expression", function(done) { require.ensure("./file", require => (require("./file").should.be.eql("ok"), done())); }); webpack-3.5.6/test/cases/parsing/chunks/test.filter.js000066400000000000000000000002161315401342100227460ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-3.5.6/test/cases/parsing/class/000077500000000000000000000000001315401342100177605ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/class/a.js000066400000000000000000000000271315401342100205350ustar00rootroot00000000000000module.exports = "ok"; webpack-3.5.6/test/cases/parsing/class/index.js000066400000000000000000000002611315401342100214240ustar00rootroot00000000000000import X, { A, B } from "./module"; it("should parse classes", function() { new X().a.should.be.eql("ok"); new A().a.should.be.eql("ok"); new B().a.should.be.eql("ok"); }); webpack-3.5.6/test/cases/parsing/class/module.js000066400000000000000000000003361315401342100216050ustar00rootroot00000000000000class A { constructor() { this.a = require("./a"); } } const B = class { constructor() { this.a = require("./a"); } }; export default class { constructor() { this.a = require("./a"); } }; export { A, B }; webpack-3.5.6/test/cases/parsing/class/test.filter.js000066400000000000000000000002161315401342100225600ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-3.5.6/test/cases/parsing/context/000077500000000000000000000000001315401342100203375ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/context/index.js000066400000000000000000000034011315401342100220020ustar00rootroot00000000000000it("should be able to load a file with the require.context method", function() { require.context("./templates")("./tmpl").should.be.eql("test template"); (require.context("./././templates"))("./tmpl").should.be.eql("test template"); (require.context("././templates/.")("./tmpl")).should.be.eql("test template"); require . context ( "." + "/." + "/" + "templ" + "ates" ) ( "./subdir/tmpl.js" ).should.be.eql("subdir test template"); require.context("./templates", true, /./)("xyz").should.be.eql("xyz"); }); it("should automatically create contexts", function() { var template = "tmpl", templateFull = "./tmpl.js"; var mp = "mp", tmp = "tmp", mpl = "mpl"; require("./templates/" + template).should.be.eql("test template"); require("./templates/" + tmp + "l").should.be.eql("test template"); require("./templates/t" + mpl).should.be.eql("test template"); require("./templates/t" + mp + "l").should.be.eql("test template"); }); it("should be able to require.resolve with automatical context", function() { var template = "tmpl"; require.resolve("./templates/" + template).should.be.eql(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"; renamedRequire("./templates/" + template).should.be.eql("test template"); }); it("should compile an empty context", function() { var x = ""; (function() { require("./templates/notExisting" + x); }).toString().should.not.match(/require/); }); it("should execute an empty context", function() { var context; (function() { context = require.context("./templates/", true, /^\.\/notExisting/); }).should.not.throw(); (function() { context(""); }).should.throw(); });webpack-3.5.6/test/cases/parsing/context/templates/000077500000000000000000000000001315401342100223355ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/context/templates/dump-file.txt000066400000000000000000000000761315401342100247630ustar00rootroot00000000000000This is a file! with some content it should break webpack :)webpack-3.5.6/test/cases/parsing/context/templates/node_modules/000077500000000000000000000000001315401342100250125ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/context/templates/node_modules/xyz.js000066400000000000000000000000271315401342100262010ustar00rootroot00000000000000module.exports = "xyz";webpack-3.5.6/test/cases/parsing/context/templates/subdir/000077500000000000000000000000001315401342100236255ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/context/templates/subdir/tmpl.js000066400000000000000000000000501315401342100251320ustar00rootroot00000000000000module.exports = "subdir test template";webpack-3.5.6/test/cases/parsing/context/templates/templateLoader.js000066400000000000000000000000721315401342100256340ustar00rootroot00000000000000module.exports = function(name) { return require(name); }webpack-3.5.6/test/cases/parsing/context/templates/templateLoaderIndirect.js000066400000000000000000000003251315401342100273170ustar00rootroot00000000000000module.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-3.5.6/test/cases/parsing/context/templates/tmpl.js000066400000000000000000000000411315401342100236420ustar00rootroot00000000000000module.exports = "test template";webpack-3.5.6/test/cases/parsing/context/warnings.js000066400000000000000000000003771315401342100225340ustar00rootroot00000000000000module.exports = [ [/Module parse failed/, /dump-file\.txt/, /templates \^\\\.\\\/\.\*\$/], [/Critical dependency/, /templateLoader\.js/], [/Critical dependency/, /templateLoaderIndirect\.js/], [/Critical dependency/, /templateLoaderIndirect\.js/], ];webpack-3.5.6/test/cases/parsing/es6.nominimize/000077500000000000000000000000001315401342100215255ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/es6.nominimize/a.js000066400000000000000000000000261315401342100223010ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/cases/parsing/es6.nominimize/array.js000066400000000000000000000000341315401342100231760ustar00rootroot00000000000000module.exports = [1, 2, 3]; webpack-3.5.6/test/cases/parsing/es6.nominimize/async.js000066400000000000000000000000321315401342100231730ustar00rootroot00000000000000module.exports = "async"; webpack-3.5.6/test/cases/parsing/es6.nominimize/b.js000066400000000000000000000000261315401342100223020ustar00rootroot00000000000000module.exports = "b"; webpack-3.5.6/test/cases/parsing/es6.nominimize/c.js000066400000000000000000000000261315401342100223030ustar00rootroot00000000000000module.exports = "c"; webpack-3.5.6/test/cases/parsing/es6.nominimize/index.js000066400000000000000000000025011315401342100231700ustar00rootroot00000000000000"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(); x.a.should.be.eql("a"); x.func().should.be.eql("b"); x.c().should.be.eql("c"); }); it("should parse spread operator"/*, function() { [0, ...require("./array")].should.be.eql([0, 1, 2, 3]); ({z: 0, ...require("./object")}).should.be.eql({z: 0, a: 1, b: 2, c: 3}); }*/); it("should parse arrow function", function() { (() => require("./a"))().should.be.eql("a"); (() => { return require("./a"); })().should.be.eql("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`; x.should.be.eql("abc"); y.should.be.eql("b"); }) it("should parse generators and yield", function() { function* gen() { yield require("./a"); yield require("./b"); } var x = gen(); x.next().value.should.be.eql("a"); x.next().value.should.be.eql("b"); x.next().done.should.be.eql(true); }) webpack-3.5.6/test/cases/parsing/es6.nominimize/object.js000066400000000000000000000000451315401342100233300ustar00rootroot00000000000000module.exports = {a: 1, b: 2, c: 3}; webpack-3.5.6/test/cases/parsing/es6.nominimize/test.filter.js000066400000000000000000000002161315401342100243250ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-3.5.6/test/cases/parsing/evaluate/000077500000000000000000000000001315401342100204615ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/evaluate/a.js000066400000000000000000000000251315401342100212340ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/parsing/evaluate/index.js000066400000000000000000000011741315401342100221310ustar00rootroot00000000000000it("should evaluate null", function() { var y = null ? require("fail") : require("./a"); if(null) require("fail"); }); if("shouldn't evaluate expression", function() { var value = ""; var x = (value + "") ? "fail" : "ok"; x.should.be.eql("ok"); }); it("should short-circut 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); result.should.be.eql("?resourceQuery"); }); webpack-3.5.6/test/cases/parsing/evaluate/resourceQuery/000077500000000000000000000000001315401342100233365ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/evaluate/resourceQuery/index.js000066400000000000000000000001671315401342100250070ustar00rootroot00000000000000module.exports = require((__resourceQuery.substr(1) + "/resourceQuery/returnRQ?XXXQuery").replace(/XXX/g, "resource"));webpack-3.5.6/test/cases/parsing/evaluate/resourceQuery/returnRQ.js000066400000000000000000000000411315401342100254510ustar00rootroot00000000000000module.exports = __resourceQuery;webpack-3.5.6/test/cases/parsing/extract-amd/000077500000000000000000000000001315401342100210645ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/extract-amd/a.js000066400000000000000000000000251315401342100216370ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/parsing/extract-amd/c.js000066400000000000000000000000251315401342100216410ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/cases/parsing/extract-amd/circular.js000066400000000000000000000000731315401342100232260ustar00rootroot00000000000000module.exports = 1; module.exports = require("./circular");webpack-3.5.6/test/cases/parsing/extract-amd/constructor.js000066400000000000000000000000711315401342100240050ustar00rootroot00000000000000module.exports = function(value) { this.value = value; }webpack-3.5.6/test/cases/parsing/extract-amd/d.js000066400000000000000000000000251315401342100216420ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/test/cases/parsing/extract-amd/index.js000066400000000000000000000147531315401342100225430ustar00rootroot00000000000000var should = require("should"); it("should parse fancy function calls", function() { ("function"==typeof define && define.amd ? define : function(e,t){return t()} )(["./constructor"], function(c) { return new c(1324); }); module.exports.should.have.property("value").be.eql(1324); (("function"==typeof define && define.amd ? define : function(e,t){return t()} )(["./constructor"], function(c) { return new c(4231); })); module.exports.should.have.property("value").be.eql(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) { (typeof require).should.be.eql("function"); (typeof module).should.be.eql("object"); (typeof exports).should.be.eql("object"); (typeof require("./constructor")).should.be.eql("function"); (typeof constructor).should.be.eql("function"); a.should.be.eql("a"); }); define("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), function(require, module, exports, constructor, a) { (typeof require).should.be.eql("function"); (typeof module).should.be.eql("object"); (typeof exports).should.be.eql("object"); (typeof require("./constructor")).should.be.eql("function"); (typeof constructor).should.be.eql("function"); a.should.be.eql("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) { circular.should.be.eql(1); circular2.should.be.eql(1); testTemplate.should.be.eql("b"); done(); }); }); it("should be able to use require.js-style define", function(done) { define("name", ["./circular"], function(circular) { circular.should.be.eql(1); done(); }); }); it("should be able to use require.js-style define, optional dependancies, not exist", function(done) { define("name", ["./optional"], function(optional) { should(optional.b).not.exist; done(); }); }); it("should be able to use require.js-style define, special string", function(done) { define(["require"], function(require) { require("./circular").should.be.eql(1); done(); }); }); it("should be able to use require.js-style define, without name", function(done) { true && define(["./circular"], function(circular) { circular.should.be.eql(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); module.exports.should.be.equal(obj); module.exports = null; define("blaaa", obj); module.exports.should.be.equal(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) { (typeof require).should.be.eql("function"); exports.should.be.equal(_test_exports); module.should.be.equal(_test_module); require("./circular").should.be.eql(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) { c.should.be.eql(1); done(); } }); it("should create a chunk for require.js require", function(done) { var sameTick = true; require(["./c"], function(c) { sameTick.should.be.eql(false); c.should.be.eql("c"); require("./d").should.be.eql("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) { a.should.be.eql(123); (typeof require).should.be.eql("function"); require("./a").should.be.eql("a"); done(); }.bind(null, 123)); }); it("should parse a bound function expression 2", function(done) { define("name", function(a, require, exports, module) { a.should.be.eql(123); (typeof require).should.be.eql("function"); require("./a").should.be.eql("a"); done(); }.bind(null, 123)); }); it("should parse a bound function expression 3", function(done) { define(["./a"], function(number, a) { number.should.be.eql(123); a.should.be.eql("a"); done(); }.bind(null, 123)); }); it("should parse a bound function expression 4", function(done) { define("name", ["./a"], function(number, a) { number.should.be.eql(123); a.should.be.eql("a"); done(); }.bind(null, 123)); }); it("should not fail issue #138 second", function() { (function(define, global) { 'use strict'; define(function (require) { (typeof require).should.be.eql("function"); require("./a").should.be.eql("a"); return "#138 2."; }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }, this); module.exports.should.be.eql("#138 2."); }); it("should parse an define with empty array and object", function() { var obj = {ok: 95476}; define([], obj); module.exports.should.be.eql(obj); }); it("should parse an define with object", function() { var obj = {ok: 76243}; define(obj); module.exports.should.be.eql(obj); }); webpack-3.5.6/test/cases/parsing/extract-amd/optional.js000066400000000000000000000002061315401342100232450ustar00rootroot00000000000000module.exports = 2; try { module.exports.a = require("./a"); } catch (e) {}; try { module.exports.b = require("./b"); } catch (e) {}; webpack-3.5.6/test/cases/parsing/extract-amd/templates/000077500000000000000000000000001315401342100230625ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/extract-amd/templates/a.js000066400000000000000000000000251315401342100236350ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/parsing/extract-amd/templates/b.js000066400000000000000000000000251315401342100236360ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/cases/parsing/extract-amd/templates/c.js000066400000000000000000000000251315401342100236370ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/cases/parsing/extract-amd/warnings.js000066400000000000000000000001171315401342100232510ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/b' /, /b\.js/] ]; webpack-3.5.6/test/cases/parsing/extract-require/000077500000000000000000000000001315401342100217775ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/extract-require/constructor.js000066400000000000000000000000711315401342100247200ustar00rootroot00000000000000module.exports = function(value) { this.value = value; }webpack-3.5.6/test/cases/parsing/extract-require/errors.js000066400000000000000000000001561315401342100236530ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /, /extract-require\/index.js/] ];webpack-3.5.6/test/cases/parsing/extract-require/folder/000077500000000000000000000000001315401342100232525ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/extract-require/folder/file1.js000066400000000000000000000000311315401342100246020ustar00rootroot00000000000000module.exports = "file1";webpack-3.5.6/test/cases/parsing/extract-require/folder/file2.js000066400000000000000000000000311315401342100246030ustar00rootroot00000000000000module.exports = "file2";webpack-3.5.6/test/cases/parsing/extract-require/folder/file3.js000066400000000000000000000000311315401342100246040ustar00rootroot00000000000000module.exports = "file3";webpack-3.5.6/test/cases/parsing/extract-require/index.js000066400000000000000000000024241315401342100234460ustar00rootroot00000000000000var should = require("should"); function testCase(number) { require(number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule").should.be.eql("file" + number); require( number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule" ).should.be.eql("file" + number); } it("should parse complex require calls", function() { should.strictEqual(new(require("./constructor"))(1234).value, 1234, "Parse require in new(...) should work"); should.strictEqual(new ( require ( "./constructor" ) ) ( 1234 ) .value, 1234, "Parse require in new(...) should work, with spaces"); }); it("should let the user hide the require function", function() { (function(require) { return require; }(1234)).should.be.eql(1234); function testFunc(abc, require) { return require; } testFunc(333, 678).should.be.eql(678); (function() { var require = 123; require.should.be.eql(123); }()); (function() { function require() { return 123; }; require("error").should.be.eql(123); }()); (function() { var module = 1233; module.should.be.eql(1233); }()); }); it("should not create a context for the ?: operator", function() { testCase(1); testCase(2); testCase(3); }); webpack-3.5.6/test/cases/parsing/filename/000077500000000000000000000000001315401342100204335ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/filename/index.js000066400000000000000000000004331315401342100221000ustar00rootroot00000000000000it("should be a string (__filename)", function() { __filename.should.be.type("string"); var f = __filename; f.should.be.type("string"); }); it("should be a string (__dirname)", function() { __dirname.should.be.type("string"); var d = __dirname; d.should.be.type("string"); });webpack-3.5.6/test/cases/parsing/harmony-commonjs-mix/000077500000000000000000000000001315401342100227465ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-commonjs-mix/index.js000066400000000000000000000002401315401342100244070ustar00rootroot00000000000000it("should result in a warning when using module.exports in harmony module", function() { var x = require("./module1"); x.should.be.eql({default: 1234}); }); webpack-3.5.6/test/cases/parsing/harmony-commonjs-mix/module.js000066400000000000000000000000221315401342100245630ustar00rootroot00000000000000export default 1; webpack-3.5.6/test/cases/parsing/harmony-commonjs-mix/module1.js000066400000000000000000000006341315401342100246550ustar00rootroot00000000000000import "./module"; (function() { module.exports = 1; }).should.throw(); (typeof module.exports).should.be.eql("undefined"); (typeof define).should.be.eql("undefined"); (function() { define(function() {}) }).should.throw(/define is not defined/); export default 1234; if(eval("typeof exports !== \"undefined\"")) { // exports is node.js exports and not webpacks Object.keys(exports).should.be.eql([]); } webpack-3.5.6/test/cases/parsing/harmony-commonjs/000077500000000000000000000000001315401342100221535ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-commonjs/a.js000066400000000000000000000000611315401342100227260ustar00rootroot00000000000000export default function test() { return "OK"; } webpack-3.5.6/test/cases/parsing/harmony-commonjs/b.js000066400000000000000000000000531315401342100227300ustar00rootroot00000000000000export * from "./c"; export * from "./c2"; webpack-3.5.6/test/cases/parsing/harmony-commonjs/c.js000066400000000000000000000000251315401342100227300ustar00rootroot00000000000000export * from "./d"; webpack-3.5.6/test/cases/parsing/harmony-commonjs/c2.js000066400000000000000000000000241315401342100230110ustar00rootroot00000000000000export var x = "x"; webpack-3.5.6/test/cases/parsing/harmony-commonjs/d.js000066400000000000000000000000211315401342100227250ustar00rootroot00000000000000exports.y = "y"; webpack-3.5.6/test/cases/parsing/harmony-commonjs/e.js000066400000000000000000000000421315401342100227310ustar00rootroot00000000000000exports.a = "a"; exports.b = "b"; webpack-3.5.6/test/cases/parsing/harmony-commonjs/index.js000066400000000000000000000016541315401342100236260ustar00rootroot00000000000000import { x, y } from "./b"; it("should pass when required by CommonJS module", function () { var test1 = require('./a').default; test1().should.be.eql("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 __esMoudule 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)(); test2.should.be.eql("OK"); }); it("should double reexport from non-harmony modules correctly", function() { y.should.be.eql("y"); x.should.be.eql("x"); }); import { a, b } from "./reexport" it("should be possible to reexport a module with unknown exports", function() { a.should.be.eql("a"); b.should.be.eql("b"); }); webpack-3.5.6/test/cases/parsing/harmony-commonjs/reexport.js000066400000000000000000000000431315401342100243560ustar00rootroot00000000000000export * from "./e"; import "./e"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/000077500000000000000000000000001315401342100236175ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/1.js000066400000000000000000000000511315401342100243110ustar00rootroot00000000000000export var x = "1"; export * from "./a"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/2.js000066400000000000000000000000511315401342100243120ustar00rootroot00000000000000export * from "./a"; export var x = "1"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/3.js000066400000000000000000000000521315401342100243140ustar00rootroot00000000000000export * from "./a"; export * from "./b"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/4.js000066400000000000000000000000521315401342100243150ustar00rootroot00000000000000export * from "./b"; export * from "./a"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/5.js000066400000000000000000000000521315401342100243160ustar00rootroot00000000000000export * from "./c"; export * from "./d"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/6.js000066400000000000000000000001241315401342100243170ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; export * from "./d"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/7.js000066400000000000000000000001241315401342100243200ustar00rootroot00000000000000export * from "./d"; export * from "./b"; export * from "./c"; export * from "./a"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/a.js000066400000000000000000000000241315401342100243710ustar00rootroot00000000000000export var x = "a"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/b.js000066400000000000000000000000241315401342100243720ustar00rootroot00000000000000export var x = "b"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/c.js000066400000000000000000000000211315401342100243700ustar00rootroot00000000000000exports.x = "c"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/d.js000066400000000000000000000000211315401342100243710ustar00rootroot00000000000000exports.x = "d"; webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/index.js000066400000000000000000000016551315401342100252730ustar00rootroot00000000000000import { 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() { x1.should.be.eql("1"); x2.should.be.eql("1"); x3.should.be.eql("a"); x4.should.be.eql("b"); x5.should.be.eql("c"); x6.should.be.eql("a"); x7.should.be.eql("d"); }); it("should not overwrite when using star export (unknown exports)", function() { y1.should.be.eql("1"); y2.should.be.eql("1"); y3.should.be.eql("a"); y4.should.be.eql("b"); y5.should.be.eql("c"); y6.should.be.eql("a"); y7.should.be.eql("d"); }); webpack-3.5.6/test/cases/parsing/harmony-duplicate-export/reexport.js000066400000000000000000000000251315401342100260220ustar00rootroot00000000000000export * from "./a"; webpack-3.5.6/test/cases/parsing/harmony-edge-cases/000077500000000000000000000000001315401342100223265ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-edge-cases/a.js000066400000000000000000000001171315401342100231030ustar00rootroot00000000000000export default function test() { return "ok"; } var a = test(); export { a };webpack-3.5.6/test/cases/parsing/harmony-edge-cases/b.js000066400000000000000000000001171315401342100231040ustar00rootroot00000000000000export default function test() { return "ok"; } var b = test(); export { b };webpack-3.5.6/test/cases/parsing/harmony-edge-cases/c.js000066400000000000000000000000241315401342100231020ustar00rootroot00000000000000export var c = "ok";webpack-3.5.6/test/cases/parsing/harmony-edge-cases/d.js000066400000000000000000000000251315401342100231040ustar00rootroot00000000000000export default "ok"; webpack-3.5.6/test/cases/parsing/harmony-edge-cases/fake-reexport.js000066400000000000000000000001011315401342100254300ustar00rootroot00000000000000import { c } from "./c"; import d from "./d"; export { c, d }; webpack-3.5.6/test/cases/parsing/harmony-edge-cases/index.js000066400000000000000000000004271315401342100237760ustar00rootroot00000000000000import { a } from "./a"; import x, { b } from "./b"; import { c, d } from "./fake-reexport"; it("should be able to use exported function", function() { a.should.be.eql("ok"); b.should.be.eql("ok"); x().should.be.eql("ok"); c.should.be.eql("ok"); d.should.be.eql("ok"); }); webpack-3.5.6/test/cases/parsing/harmony-export-hoist/000077500000000000000000000000001315401342100227735ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-export-hoist/bar.js000066400000000000000000000001171315401342100240740ustar00rootroot00000000000000import { foo, foo2 } from "./foo"; export default { foo: foo, foo2: foo2 }; webpack-3.5.6/test/cases/parsing/harmony-export-hoist/foo.js000066400000000000000000000002311315401342100241100ustar00rootroot00000000000000import {bar} from "./bar"; export function foo() { return "ok"; } function foo2() { return "ok"; } export { foo2 } export { default } from "./bar"; webpack-3.5.6/test/cases/parsing/harmony-export-hoist/index.js000066400000000000000000000004171315401342100244420ustar00rootroot00000000000000"use strict"; it("should hoist exports", function() { var result = require("./foo").default; (typeof result.foo).should.have.eql("function"); (typeof result.foo2).should.have.eql("function"); result.foo().should.be.eql("ok"); result.foo2().should.be.eql("ok"); }); webpack-3.5.6/test/cases/parsing/harmony-export-precedence/000077500000000000000000000000001315401342100237425ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-export-precedence/a.js000066400000000000000000000002011315401342100245110ustar00rootroot00000000000000export function a() { return "a1"; } export { b } from "./b"; export * from "./c"; export { d } from "./b"; export var e = "e1"; webpack-3.5.6/test/cases/parsing/harmony-export-precedence/b.js000066400000000000000000000001511315401342100245160ustar00rootroot00000000000000export var a = "a2"; export var b = "b2"; export var c = "c2"; export var d = "d2"; export var e = "e2"; webpack-3.5.6/test/cases/parsing/harmony-export-precedence/c.js000066400000000000000000000002031315401342100245150ustar00rootroot00000000000000export var a = "a3"; export var b = "b3"; export var c = "c3"; export var e = "e3"; export var f = "f3"; export default "default"; webpack-3.5.6/test/cases/parsing/harmony-export-precedence/d.js000066400000000000000000000000321315401342100245160ustar00rootroot00000000000000export default "default"; webpack-3.5.6/test/cases/parsing/harmony-export-precedence/index.js000066400000000000000000000007441315401342100254140ustar00rootroot00000000000000import { a, b, c, d, e } from "./a"; import defaultImport from "./a"; it("should prefer local exports", function() { a().should.be.eql("a1"); e.should.be.eql("e1"); }); it("should prefer indirect exports over star exports", function() { b.should.be.eql("b2"); d.should.be.eql("d2"); }); it("should use star exports", function() { c.should.be.eql("c3"); }); it("should not export default via star export", function() { (typeof defaultImport).should.be.eql("undefined"); }); webpack-3.5.6/test/cases/parsing/harmony-export-precedence/warnings.js000066400000000000000000000001441315401342100261270ustar00rootroot00000000000000module.exports = [ [/export 'default' \(imported as 'defaultImport'\) was not found in '.\/a'/] ]; webpack-3.5.6/test/cases/parsing/harmony-import-export-order/000077500000000000000000000000001315401342100242705ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-import-export-order/a.js000066400000000000000000000001011315401342100250360ustar00rootroot00000000000000import { add } from "./tracker"; add("a"); export var ax = "ax"; webpack-3.5.6/test/cases/parsing/harmony-import-export-order/b.js000066400000000000000000000001311315401342100250420ustar00rootroot00000000000000import { ax } from "./c"; import { add } from "./tracker"; add("b"); export var bx = ax; webpack-3.5.6/test/cases/parsing/harmony-import-export-order/c.js000066400000000000000000000002041315401342100250440ustar00rootroot00000000000000export * from "./a"; export * from "./b"; import { bx } from "./b"; export { bx as cx } import { add } from "./tracker"; add("c"); webpack-3.5.6/test/cases/parsing/harmony-import-export-order/index.js000066400000000000000000000005311315401342100257340ustar00rootroot00000000000000it("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"); tracker.list.should.be.eql(["a", "b", "c"]); c.ax.should.be.eql("ax"); c.bx.should.be.eql("ax"); c.cx.should.be.eql("ax"); }); webpack-3.5.6/test/cases/parsing/harmony-import-export-order/tracker.js000066400000000000000000000001041315401342100262540ustar00rootroot00000000000000export var list = []; export function add(str) { list.push(str); } webpack-3.5.6/test/cases/parsing/harmony-import-targets/000077500000000000000000000000001315401342100233075ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-import-targets/index.js000066400000000000000000000011521315401342100247530ustar00rootroot00000000000000import {x, f} from "./x"; it("should import into object literal", function() { ({ x: x }).should.be.eql({x: 1}); var obj = { x: x }; obj.should.be.eql({x: 1}); }); function func(z) { return z; } it("should import into function argument", function() { func(x).should.be.eql(1); f(x).should.be.eql(1); func({x:x}).should.be.eql({x:1}); f({x:x}).should.be.eql({x:1}); var y = f(x); y.should.be.eql(1); y = function() { return x; }; y().should.be.eql(1); }); it("should import into array literal", function() { ([x, f(2)]).should.be.eql([1, 2]); ([{ value: x }]).should.be.eql([{ value: x }]); }); webpack-3.5.6/test/cases/parsing/harmony-import-targets/x.js000066400000000000000000000000651315401342100241150ustar00rootroot00000000000000export var x = 1; export function f(x) { return x; }webpack-3.5.6/test/cases/parsing/harmony-info/000077500000000000000000000000001315401342100212615ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-info/commonjs.js000066400000000000000000000000001315401342100234320ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-info/index.js000066400000000000000000000002541315401342100227270ustar00rootroot00000000000000import 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-3.5.6/test/cases/parsing/harmony-info/module.js000066400000000000000000000001141315401342100231000ustar00rootroot00000000000000function b() {} export { b } export var c = 123; export function d() {} webpack-3.5.6/test/cases/parsing/harmony-info/warnings.js000066400000000000000000000003231315401342100234450ustar00rootroot00000000000000module.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-3.5.6/test/cases/parsing/harmony-injecting-order/000077500000000000000000000000001315401342100234115ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-injecting-order/file.js000066400000000000000000000000751315401342100246700ustar00rootroot00000000000000export function f() { return __webpack_amd_options__; }; webpack-3.5.6/test/cases/parsing/harmony-injecting-order/index.js000066400000000000000000000001521315401342100250540ustar00rootroot00000000000000it("should inject variables before exporting", function() { require("./file").f().should.be.eql({}); }); webpack-3.5.6/test/cases/parsing/harmony-spec/000077500000000000000000000000001315401342100212605ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-spec/eval.js000066400000000000000000000001051315401342100225410ustar00rootroot00000000000000export var value = 0; export function evalInModule(x) { eval(x); }; webpack-3.5.6/test/cases/parsing/harmony-spec/export-cycle-a.js000066400000000000000000000001731315401342100244530ustar00rootroot00000000000000function fun() { return true; }; import { callFun } from "./export-cycle-b"; export default callFun(); export { fun }; webpack-3.5.6/test/cases/parsing/harmony-spec/export-cycle-b.js000066400000000000000000000001261315401342100244520ustar00rootroot00000000000000import { fun } from "./export-cycle-a"; export function callFun() { return fun(); } webpack-3.5.6/test/cases/parsing/harmony-spec/index.js000066400000000000000000000020321315401342100227220ustar00rootroot00000000000000import { 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() { value.should.be.eql(0); add(2); value.should.be.eql(2); }); it("should establish live binding of values with transpiled es5 module", function() { value2.should.be.eql(0); add2(5); value2.should.be.eql(5); }); it("should allow to use eval with exports", function() { valueEval.should.be.eql(0); evalInModule("value = 5"); valueEval.should.be.eql(5); }); it("should execute modules in the correct order", function() { getLog().should.be.eql(["a", "b", "c"]); }); it("should bind exports before the module executes", function() { cycleValue.should.be.eql(true); }); it("should allow to import live variables from itself", function() { data.should.be.eql([undefined, 1, 2]); }); import { value as valueEval, evalInModule } from "./eval"; webpack-3.5.6/test/cases/parsing/harmony-spec/live-es5.js000066400000000000000000000001461315401342100232500ustar00rootroot00000000000000exports.__esModule = true; exports.value = 0; exports.add = function add(x) { exports.value += x; }; webpack-3.5.6/test/cases/parsing/harmony-spec/live.js000066400000000000000000000000771315401342100225610ustar00rootroot00000000000000export var value = 0; export function add(x) { value += x; }; webpack-3.5.6/test/cases/parsing/harmony-spec/order-a.js000066400000000000000000000000611315401342100231440ustar00rootroot00000000000000import { log } from "./order-tracker"; log("a"); webpack-3.5.6/test/cases/parsing/harmony-spec/order-b.js000066400000000000000000000000611315401342100231450ustar00rootroot00000000000000import { log } from "./order-tracker"; log("b"); webpack-3.5.6/test/cases/parsing/harmony-spec/order-c.js000066400000000000000000000001311315401342100231440ustar00rootroot00000000000000import { log } from "./order-tracker"; import "./order-a"; log("c"); import "./order-b"; webpack-3.5.6/test/cases/parsing/harmony-spec/order-tracker.js000066400000000000000000000001461315401342100243630ustar00rootroot00000000000000var data = []; export function log(x) { data.push(x); }; export function getLog() { return data; }; webpack-3.5.6/test/cases/parsing/harmony-spec/self-cycle.js000066400000000000000000000002071315401342100236430ustar00rootroot00000000000000import { 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-3.5.6/test/cases/parsing/harmony-this/000077500000000000000000000000001315401342100212755ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony-this/abc.js000066400000000000000000000002651315401342100223630ustar00rootroot00000000000000function returnThis() { if(typeof this === "undefined") return "undefined"; return this; } var a = returnThis; var b = returnThis; export { a, b } export default returnThis; webpack-3.5.6/test/cases/parsing/harmony-this/index.js000066400000000000000000000011061315401342100227400ustar00rootroot00000000000000"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 d().should.be.eql("undefined"); x a().should.be.eql("undefined"); x B().should.be.eql("undefined"); }); import C2, { C } from "./new"; import * as New from "./new"; it("should be possible to use new correctly", function() { x new C().should.match({ok: true}); x new C2().should.match({ok: true}); x new New.C().should.match({ok: true}); }); webpack-3.5.6/test/cases/parsing/harmony-this/new.js000066400000000000000000000001411315401342100224200ustar00rootroot00000000000000function C() { this.ok = this.pok; } C.prototype.pok = true; export default C; export { C }; webpack-3.5.6/test/cases/parsing/harmony/000077500000000000000000000000001315401342100203305ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony/index.js000066400000000000000000000057771315401342100220150ustar00rootroot00000000000000import {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() { defaultExport.should.be.eql("def"); }); it("should import an identifier from a module", function() { a.should.be.eql("a"); B.should.be.eql("b"); }); it("should import a whole module", function() { abc.a.should.be.eql("a"); abc.b.should.be.eql("b"); abc.c.should.be.eql("c"); abc.d.c.should.be.eql("c"); abc.e.should.be.eql("c"); var copy = (function(a) { return a; }(abc)); copy.a.should.be.eql("a"); copy.b.should.be.eql("b"); copy.c.should.be.eql("c"); copy.d.c.should.be.eql("c"); copy.e.should.be.eql("c"); (typeof abc).should.be.eql("object"); }); it("should export functions", function() { fn.should.have.type("function"); fn().should.be.eql("fn"); (fn === fn).should.be.eql(true); }); it("should multiple variables with one statement", function() { one.should.be.eql("one"); two.should.be.eql("two"); }); it("should still be able to use exported stuff", function() { test1.should.be.eql("fn"); test2.should.be.eql("two"); }); it("should reexport a module", function() { rea.should.be.eql("a"); reb.should.be.eql("b"); rec.should.be.eql("c"); reo.should.be.eql("one"); retwo.should.be.eql("two"); rea2.should.be.eql("a"); }); it("should support circular dependencies", function() { threeIsOdd.should.be.eql(true); even(4).should.be.eql(true); }); it("should support export specifier", function() { specA.should.be.eql(1); specB.should.be.eql(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 Thing.should.have.type("function"); x Thing().should.be.eql("thing"); x Other.should.be.eql("other"); Thing2.should.have.type("function"); new Thing2().value.should.be.eql("thing"); Other2.should.be.eql("other"); Thing3().should.be.eql("thing"); }); it("should be able to import commonjs with star import", function() { var copyOfCommonjs = commonjs; commonjs().should.be.eql("thing"); commonjs.Other.should.be.eql("other"); copyOfCommonjs().should.be.eql("thing"); copyOfCommonjs.Other.should.be.eql("other"); var copyOfCommonjsTrans = commonjsTrans; new commonjsTrans.default().value.should.be.eql("thing"); commonjsTrans.Other.should.be.eql("other"); new copyOfCommonjsTrans.default().value.should.be.eql("thing"); copyOfCommonjsTrans.Other.should.be.eql("other"); }); webpack-3.5.6/test/cases/parsing/harmony/node_modules/000077500000000000000000000000001315401342100230055ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/harmony/node_modules/abc.js000066400000000000000000000002461315401342100240720ustar00rootroot00000000000000export 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-3.5.6/test/cases/parsing/harmony/node_modules/abc_c.js000066400000000000000000000000241315401342100243660ustar00rootroot00000000000000export var c = "c"; webpack-3.5.6/test/cases/parsing/harmony/node_modules/circularEven.js000066400000000000000000000002051315401342100257620ustar00rootroot00000000000000import { odd } from "circularOdd"; export default odd(3); export function even(n) { if(n == 0) return true; return odd(n - 1); } webpack-3.5.6/test/cases/parsing/harmony/node_modules/circularOdd.js000066400000000000000000000001601315401342100255730ustar00rootroot00000000000000import { even } from "circularEven"; export function odd(n) { if(n == 0) return false; return even(n - 1); } webpack-3.5.6/test/cases/parsing/harmony/node_modules/commonjs-trans.js000066400000000000000000000001651315401342100263170ustar00rootroot00000000000000exports.__esModule = true; exports.default = function Thing() { this.value = "thing"; }; exports.Other = "other"; webpack-3.5.6/test/cases/parsing/harmony/node_modules/commonjs.js000066400000000000000000000001271315401342100251700ustar00rootroot00000000000000module.exports = function Thing() { return "thing"; } module.exports.Other = "other";webpack-3.5.6/test/cases/parsing/harmony/node_modules/def.js000066400000000000000000000000251315401342100240760ustar00rootroot00000000000000export default "def";webpack-3.5.6/test/cases/parsing/harmony/node_modules/exportKinds.js000066400000000000000000000001761315401342100256610ustar00rootroot00000000000000export function fn() { return "fn"; } export var one = "one", two = "two"; export var test1 = fn(); export var test2 = two; webpack-3.5.6/test/cases/parsing/harmony/node_modules/exports-specifier.js000066400000000000000000000000631315401342100270150ustar00rootroot00000000000000var specA = 1, b = 2; export { specA, b as specB } webpack-3.5.6/test/cases/parsing/harmony/node_modules/reexport.js000066400000000000000000000001541315401342100252130ustar00rootroot00000000000000export * from "abc"; export { one as o, two } from "exportKinds"; export { default as def } from "commonjs";webpack-3.5.6/test/cases/parsing/harmony/node_modules/reexport2.js000066400000000000000000000000421315401342100252710ustar00rootroot00000000000000"use strict"; export * from "abc";webpack-3.5.6/test/cases/parsing/harmony/node_modules/unused.js000066400000000000000000000001511315401342100246430ustar00rootroot00000000000000export var a = "a"; var b = "b"; export {b as d}; export {c as e} from "./abc_c"; export * from "./abc"; webpack-3.5.6/test/cases/parsing/hot-api/000077500000000000000000000000001315401342100202145ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/hot-api/a.js000066400000000000000000000000251315401342100207670ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/parsing/hot-api/b.js000066400000000000000000000000251315401342100207700ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/cases/parsing/hot-api/index.js000066400000000000000000000005411315401342100216610ustar00rootroot00000000000000if(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-3.5.6/test/cases/parsing/hot-error-handler/000077500000000000000000000000001315401342100222075ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/hot-error-handler/index.js000066400000000000000000000002061315401342100236520ustar00rootroot00000000000000it("should parse a self accept with error handler", function() { if(module.hot) { module.hot.accept(function(err) { }); } });webpack-3.5.6/test/cases/parsing/hot-hash/000077500000000000000000000000001315401342100203665ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/hot-hash/index.js000066400000000000000000000003741315401342100220370ustar00rootroot00000000000000if(module.hot) { it("should have __webpack_hash__", function() { (typeof __webpack_hash__).should.be.type("string"); __webpack_hash__.should.match(/^[0-9a-f]{20}$/); }); } else { it("should have __webpack_hash__ (disabled)", function() { }); } webpack-3.5.6/test/cases/parsing/inject-free-vars/000077500000000000000000000000001315401342100220175ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/inject-free-vars/fail.js000066400000000000000000000000301315401342100232610ustar00rootroot00000000000000throw new Error("Fail");webpack-3.5.6/test/cases/parsing/inject-free-vars/index.js000066400000000000000000000010051315401342100234600ustar00rootroot00000000000000it("should inject the module object into a chunk (AMD1)", function(done) { require([], function() { module.webpackPolyfill.should.be.eql(1); done(); }); }); it("should inject the module object into a chunk (AMD2)", function() { require([module.webpackPolyfill ? "./x1" : "./fail"]); module.webpackPolyfill.should.be.eql(1); }); it("should inject the module object into a chunk (ensure)", function(done) { require.ensure([], function(require) { module.webpackPolyfill.should.be.eql(1); done(); }); }); webpack-3.5.6/test/cases/parsing/inject-free-vars/x1.js000066400000000000000000000000001315401342100226730ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-1044/000077500000000000000000000000001315401342100203715ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-1044/index.js000066400000000000000000000002171315401342100220360ustar00rootroot00000000000000it("should not crash on missing spaces", function() { (function() { return"function"==typeof define&&define.amd?"hello":"world"; })(); }); webpack-3.5.6/test/cases/parsing/issue-1600/000077500000000000000000000000001315401342100203675ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-1600/file.js000066400000000000000000000000721315401342100216430ustar00rootroot00000000000000// module.js export default(function () { return 1; }); webpack-3.5.6/test/cases/parsing/issue-1600/index.js000066400000000000000000000001421315401342100220310ustar00rootroot00000000000000import fn from './file'; it("should compile correctly", function() { fn().should.be.eql(1); }); webpack-3.5.6/test/cases/parsing/issue-2006/000077500000000000000000000000001315401342100203705ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2006/errors.js000066400000000000000000000000531315401342100222400ustar00rootroot00000000000000module.exports = [ [/Empty dependency/] ];webpack-3.5.6/test/cases/parsing/issue-2006/index.js000066400000000000000000000001041315401342100220300ustar00rootroot00000000000000it("should compile", function() {}); if(/./.test("")) require(""); webpack-3.5.6/test/cases/parsing/issue-2019/000077500000000000000000000000001315401342100203745ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2019/file.js000066400000000000000000000001251315401342100216470ustar00rootroot00000000000000var CONSTANT = "const"; var def = "default"; export default def; export { CONSTANT };webpack-3.5.6/test/cases/parsing/issue-2019/index.js000066400000000000000000000002571315401342100220450ustar00rootroot00000000000000it("should not fail on default export before export", function() { require("./file").default.should.be.eql("default"); require("./file").CONSTANT.should.be.eql("const"); });webpack-3.5.6/test/cases/parsing/issue-2050/000077500000000000000000000000001315401342100203675ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2050/a.js000066400000000000000000000000341315401342100211420ustar00rootroot00000000000000var xa = "a"; export { xa };webpack-3.5.6/test/cases/parsing/issue-2050/b.js000066400000000000000000000000341315401342100211430ustar00rootroot00000000000000var xb = "b"; export { xb };webpack-3.5.6/test/cases/parsing/issue-2050/c.js000066400000000000000000000000341315401342100211440ustar00rootroot00000000000000var xc = "c"; export { xc };webpack-3.5.6/test/cases/parsing/issue-2050/d.js000066400000000000000000000000361315401342100211470ustar00rootroot00000000000000var xd = "d"; exports.xd = xd;webpack-3.5.6/test/cases/parsing/issue-2050/index.js000066400000000000000000000002111315401342100220260ustar00rootroot00000000000000it("should support multiple reexports", function() { require("./x").should.be.eql({ xa: "a", xb: "b", xc: "c", xd: "d" }); }); webpack-3.5.6/test/cases/parsing/issue-2050/module.js000066400000000000000000000001231315401342100222060ustar00rootroot00000000000000export * from "./a"; export * from "./b"; export * from "./c"; export * from "./d";webpack-3.5.6/test/cases/parsing/issue-2050/x.js000066400000000000000000000001261315401342100211730ustar00rootroot00000000000000import { xa, xb, xc, xd } from "./module"; export { xa, xb, xc as xc, xd as xd } webpack-3.5.6/test/cases/parsing/issue-2084/000077500000000000000000000000001315401342100203765ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2084/file.js000066400000000000000000000000311315401342100216450ustar00rootroot00000000000000module.exports = "file"; webpack-3.5.6/test/cases/parsing/issue-2084/index.js000066400000000000000000000043061315401342100220460ustar00rootroot00000000000000function 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 { require("./file").should.be.eql("file"); this.should.be.eql({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 { require("./file").should.be.eql("file"); load.should.be.eql("load"); this.should.be.eql({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 { require("./file").should.be.eql("file"); this.should.be.eql({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 { require("./file").should.be.eql("file"); load.should.be.eql("load"); this.should.be.eql({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 { require("./file").should.be.eql("file"); this.should.be.eql({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 { require("./file").should.be.eql("file"); this.should.be.eql({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 { require("./file").should.be.eql("file"); this.should.be.eql({ok: true}); done(); } catch(e) { done(e); } }.bind(this)); }); }); webpack-3.5.6/test/cases/parsing/issue-2084/load.js000066400000000000000000000000311315401342100216450ustar00rootroot00000000000000module.exports = "load"; webpack-3.5.6/test/cases/parsing/issue-2349/000077500000000000000000000000001315401342100204025ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2349/a.js000066400000000000000000000001031315401342100211520ustar00rootroot00000000000000export var x = 1 // named export export default 0 // default exportwebpack-3.5.6/test/cases/parsing/issue-2349/index.js000066400000000000000000000002151315401342100220450ustar00rootroot00000000000000import {x} from './a' // named imported cases an errors it("should be able to import a named export", function() { x.should.be.eql(1); }); webpack-3.5.6/test/cases/parsing/issue-2522/000077500000000000000000000000001315401342100203735ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2522/index.js000066400000000000000000000004321315401342100220370ustar00rootroot00000000000000import { 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 }; o.should.be.eql({ a: 123, aa: 123, b: 456, c: { a: 123, default: 456 } }); })webpack-3.5.6/test/cases/parsing/issue-2522/module.js000066400000000000000000000000471315401342100222170ustar00rootroot00000000000000export var a = 123; export default 456;webpack-3.5.6/test/cases/parsing/issue-2522/test.filter.js000066400000000000000000000002161315401342100231730ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-3.5.6/test/cases/parsing/issue-2523/000077500000000000000000000000001315401342100203745ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2523/index.js000066400000000000000000000003601315401342100220400ustar00rootroot00000000000000import A from "./module"; import { B } from "./module"; import { c } from "./module"; it("should allow to export a class", function() { (typeof A).should.be.eql("function"); (typeof B).should.be.eql("function"); c.should.be.eql("c"); })webpack-3.5.6/test/cases/parsing/issue-2523/module.js000066400000000000000000000001021315401342100222100ustar00rootroot00000000000000export default class A {} export class B {} export const c = 'c';webpack-3.5.6/test/cases/parsing/issue-2523/test.filter.js000066400000000000000000000002161315401342100231740ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-3.5.6/test/cases/parsing/issue-2528-2/000077500000000000000000000000001315401342100205405ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2528-2/index.js000066400000000000000000000000501315401342100222000ustar00rootroot00000000000000foo(); import { foo } from './module'; webpack-3.5.6/test/cases/parsing/issue-2528-2/module.js000066400000000000000000000000741315401342100223640ustar00rootroot00000000000000export function foo() { it("should run", function() {}); } webpack-3.5.6/test/cases/parsing/issue-2528/000077500000000000000000000000001315401342100204015ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2528/helperA.js000066400000000000000000000000531315401342100223150ustar00rootroot00000000000000module.exports = function(a) { return a; } webpack-3.5.6/test/cases/parsing/issue-2528/helperB.js000066400000000000000000000000701315401342100223150ustar00rootroot00000000000000module.exports = { mark: function(a) { return a(); } } webpack-3.5.6/test/cases/parsing/issue-2528/helperC.js000066400000000000000000000003121315401342100223150ustar00rootroot00000000000000module.exports = { wrap: function(fn) { return function() { var context = { prev: 0, next: 0, stop: function() { this.next = "end"; } }; while(context.next !== "end") fn(context); } } } webpack-3.5.6/test/cases/parsing/issue-2528/index.js000066400000000000000000000022271315401342100220510ustar00rootroot00000000000000import { 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(); count.should.be.eql(org + 1); exportedAsync(); count.should.be.eql(org + 2); }); webpack-3.5.6/test/cases/parsing/issue-2528/module.js000066400000000000000000000001071315401342100222220ustar00rootroot00000000000000export function foo() { count++; return; } export var count = 0; webpack-3.5.6/test/cases/parsing/issue-2570/000077500000000000000000000000001315401342100203765ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2570/fn.js000066400000000000000000000000771315401342100213430ustar00rootroot00000000000000export default function() { return [].slice.call(arguments); } webpack-3.5.6/test/cases/parsing/issue-2570/index.js000066400000000000000000000004601315401342100220430ustar00rootroot00000000000000import 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)); a.should.be.eql([1]); b.should.be.eql([2]); c.should.be.eql([3, 4]); d.should.be.eql([5, 6]); }); webpack-3.5.6/test/cases/parsing/issue-2600/000077500000000000000000000000001315401342100203705ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2600/errors.js000066400000000000000000000000621315401342100222400ustar00rootroot00000000000000module.exports = [ [/Can't resolve 'missing'/] ];webpack-3.5.6/test/cases/parsing/issue-2600/index.js000066400000000000000000000001151315401342100220320ustar00rootroot00000000000000if(Math.sin(1) > 1000) import("missing"); it("should run", function() {}); webpack-3.5.6/test/cases/parsing/issue-2618/000077500000000000000000000000001315401342100204015ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2618/index.js000066400000000000000000000004431315401342100220470ustar00rootroot00000000000000import defaultValue, { value, value2, value3, value4 } from "./module"; it("should be possible to redefine Object in a module", function() { value.should.be.eql(123); value2.should.be.eql(123); value3.should.be.eql(123); value4.should.be.eql(123); defaultValue.should.be.eql(123); }); webpack-3.5.6/test/cases/parsing/issue-2618/module.js000066400000000000000000000002541315401342100222250ustar00rootroot00000000000000var Object = 123; export const value = Object; export var value2 = Object; export default Object; export * from "./module2"; export { value3 as value4 } from "./module2"; webpack-3.5.6/test/cases/parsing/issue-2618/module2.js000066400000000000000000000000311315401342100223000ustar00rootroot00000000000000export var value3 = 123; webpack-3.5.6/test/cases/parsing/issue-2618/test.filter.js000066400000000000000000000002161315401342100232010ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-3.5.6/test/cases/parsing/issue-2622/000077500000000000000000000000001315401342100203745ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2622/index.js000066400000000000000000000005241315401342100220420ustar00rootroot00000000000000import { 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() { func().should.be.eql(["a", "b"]); func2().should.be.eql(["a", "b"]); func(1).should.be.eql([1, "b"]); func2(2).should.be.eql([2, "b"]); }); webpack-3.5.6/test/cases/parsing/issue-2622/module.js000066400000000000000000000000501315401342100222120ustar00rootroot00000000000000export var a = "a"; export var b = "b"; webpack-3.5.6/test/cases/parsing/issue-2622/test.filter.js000066400000000000000000000002461315401342100231770ustar00rootroot00000000000000var supportsDefaultArgs = require("../../../helpers/supportsDefaultArgs"); module.exports = function(config) { return !config.minimize && supportsDefaultArgs(); }; webpack-3.5.6/test/cases/parsing/issue-2641/000077500000000000000000000000001315401342100203755ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2641/errors.js000066400000000000000000000001221315401342100222420ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /] ]; webpack-3.5.6/test/cases/parsing/issue-2641/file.js000066400000000000000000000000501315401342100216450ustar00rootroot00000000000000define(function() { return "file"; }); webpack-3.5.6/test/cases/parsing/issue-2641/index.js000066400000000000000000000024321315401342100220430ustar00rootroot00000000000000it("should require existing module with supplied error callback", function(done) { require(['./file'], function(file){ file.should.be.eql("file"); done(); }, function(error) {}); }); it("should call error callback on missing module", function(done) { require(['./file', './missingModule'], function(file){}, function(error) { error.should.be.instanceOf(Error); error.message.should.be.eql('Cannot find module "./missingModule"'); done(); }); }); it("should call error callback on missing module in context", function(done) { (function(module) { require(['./' + module], function(file){}, function(error) { error.should.be.instanceOf(Error); error.message.should.be.eql("Cannot find module './missingModule'."); done(); }); })('missingModule'); }); it("should call error callback on exception thrown in loading module", function(done) { require(['./throwing'], function(){}, function(error) { error.should.be.instanceOf(Error); error.message.should.be.eql('message'); done(); }); }); it("should not call error callback on exception thrown in require callback", function(done) { require(['./throwing'], function() { throw new Error('message'); }, function(error) { error.should.be.instanceOf(Error); error.message.should.be.eql('message'); done(); }); }); webpack-3.5.6/test/cases/parsing/issue-2641/throwing.js000066400000000000000000000000651315401342100225750ustar00rootroot00000000000000define(function() { throw new Error('message'); }); webpack-3.5.6/test/cases/parsing/issue-2895/000077500000000000000000000000001315401342100204105ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2895/a.js000066400000000000000000000000521315401342100211630ustar00rootroot00000000000000export const a = { x: 1 }, b = { x: 2 } webpack-3.5.6/test/cases/parsing/issue-2895/index.js000066400000000000000000000002261315401342100220550ustar00rootroot00000000000000import { a, b } from "./a"; it("should export a const value without semicolon", function() { a.should.be.eql({x: 1}); b.should.be.eql({x: 2}); }); webpack-3.5.6/test/cases/parsing/issue-2895/test.filter.js000066400000000000000000000002511315401342100232070ustar00rootroot00000000000000var supportsBlockScoping = require("../../../helpers/supportsBlockScoping"); module.exports = function(config) { return !config.minimize && supportsBlockScoping(); }; webpack-3.5.6/test/cases/parsing/issue-2942/000077500000000000000000000000001315401342100204015ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-2942/index.js000066400000000000000000000007151315401342100220510ustar00rootroot00000000000000it("should polyfill System", function() { if (typeof System === "object" && typeof System.register === "function") { require("fail"); } (typeof System).should.be.eql("object"); (typeof System.register).should.be.eql("undefined"); (typeof System.get).should.be.eql("undefined"); (typeof System.set).should.be.eql("undefined"); (typeof System.anyNewItem).should.be.eql("undefined"); var x = System.anyNewItem; (typeof x).should.be.eql("undefined"); }) webpack-3.5.6/test/cases/parsing/issue-2942/warnings.js000066400000000000000000000002421315401342100225650ustar00rootroot00000000000000module.exports = [ [/System.get is not supported by webpack/], [/System.register is not supported by webpack/], [/System.set is not supported by webpack/], ]; webpack-3.5.6/test/cases/parsing/issue-3116/000077500000000000000000000000001315401342100203735ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-3116/file.js000066400000000000000000000000621315401342100216460ustar00rootroot00000000000000export default "default"; export var abc = "abc"; webpack-3.5.6/test/cases/parsing/issue-3116/file2.js000066400000000000000000000000621315401342100217300ustar00rootroot00000000000000export default "default"; export var abc = "abc"; webpack-3.5.6/test/cases/parsing/issue-3116/index.js000066400000000000000000000006511315401342100220420ustar00rootroot00000000000000import * as file from "./file"; import * as file2 from "./file2"; it("should translate indexed access to harmony import correctly", function() { file["default"].should.be.eql("default"); file["abc"].should.be.eql("abc"); }); it("should translate dynamic indexed access to harmony import correctly", function() { var fault = "fault"; file2["de" + fault].should.be.eql("default"); file2["abc"].should.be.eql("abc"); }); webpack-3.5.6/test/cases/parsing/issue-3238/000077500000000000000000000000001315401342100204005ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-3238/index.js000066400000000000000000000001761315401342100220510ustar00rootroot00000000000000it("supports empty element in destructuring", function() { const second = ([, x]) => x; second([1, 2]).should.eql(2); }); webpack-3.5.6/test/cases/parsing/issue-3238/test.filter.js000066400000000000000000000003041315401342100231760ustar00rootroot00000000000000var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); module.exports = function(config) { return !config.minimize && supportsIteratorDestructuring(); }; webpack-3.5.6/test/cases/parsing/issue-3252/000077500000000000000000000000001315401342100203745ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-3252/a.js000066400000000000000000000002561315401342100211550ustar00rootroot00000000000000export class V6Engine { toString() { return 'V6'; } } export class V8Engine { toString() { return 'V8'; } } export function getVersion() { return '1.0'; } webpack-3.5.6/test/cases/parsing/issue-3252/index.js000066400000000000000000000003311315401342100220360ustar00rootroot00000000000000import * as E from './a'; function fooBar({some, bar = E.V6Engine}) { return new bar().toString(); } it("supports default argument assignment in import", function () { fooBar({some:"test"}).should.eql('V6'); }); webpack-3.5.6/test/cases/parsing/issue-3252/test.filter.js000066400000000000000000000002671315401342100232020ustar00rootroot00000000000000var supportsDefaultAssignment = require("../../../helpers/supportDefaultAssignment"); module.exports = function(config) { return !config.minimize && supportsDefaultAssignment(); }; webpack-3.5.6/test/cases/parsing/issue-3273/000077500000000000000000000000001315401342100203775ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-3273/file.js000066400000000000000000000000321315401342100216470ustar00rootroot00000000000000export var test = "test"; webpack-3.5.6/test/cases/parsing/issue-3273/index.js000066400000000000000000000016401315401342100220450ustar00rootroot00000000000000import { test } from "./file"; it("should hide import by local var", function() { var test = "ok"; test.should.be.eql("ok"); }); it("should hide import by object pattern", function() { var { test } = { test: "ok" }; test.should.be.eql("ok"); }); it("should hide import by array pattern", function() { var [test] = ["ok"]; test.should.be.eql("ok"); }); it("should hide import by array pattern (nested)", function() { var [[test]] = [["ok"]]; test.should.be.eql("ok"); }); it("should hide import by pattern in function", function() { (function({test}) { test.should.be.eql("ok"); }({ test: "ok" })); }); it("should allow import in default (incorrect)", function() { var { other = test, test } = { test: "ok" }; test.should.be.eql("ok"); (typeof other).should.be.eql("undefined"); }); it("should allow import in default", function() { var { other = test } = { test: "ok" }; other.should.be.eql("test"); }); webpack-3.5.6/test/cases/parsing/issue-3273/test.filter.js000066400000000000000000000004631315401342100232030ustar00rootroot00000000000000var supportsDefaultAssignment = require("../../../helpers/supportDefaultAssignment"); var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); module.exports = function(config) { return !config.minimize && supportsDefaultAssignment() && supportsObjectDestructuring(); }; webpack-3.5.6/test/cases/parsing/issue-345/000077500000000000000000000000001315401342100203145ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-345/abc/000077500000000000000000000000001315401342100210415ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-345/abc/abcTest.js000066400000000000000000000000261315401342100227620ustar00rootroot00000000000000module.exports = "ok";webpack-3.5.6/test/cases/parsing/issue-345/index.js000066400000000000000000000003001315401342100217520ustar00rootroot00000000000000it("should parse multiple expressions in a require", function(done) { var name = "abc"; require(["./" + name + "/" + name + "Test"], function(x) { x.should.be.eql("ok"); done(); }); });webpack-3.5.6/test/cases/parsing/issue-3769/000077500000000000000000000000001315401342100204115ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-3769/a.js000066400000000000000000000000321315401342100211620ustar00rootroot00000000000000export const thing = 123; webpack-3.5.6/test/cases/parsing/issue-3769/b.js000066400000000000000000000000241315401342100211640ustar00rootroot00000000000000export default 123; webpack-3.5.6/test/cases/parsing/issue-3769/c.js000066400000000000000000000000241315401342100211650ustar00rootroot00000000000000export default 123; webpack-3.5.6/test/cases/parsing/issue-3769/cjs.js000066400000000000000000000000571315401342100215300ustar00rootroot00000000000000exports.__esModule = true; exports.test = 123; webpack-3.5.6/test/cases/parsing/issue-3769/d.js000066400000000000000000000000241315401342100211660ustar00rootroot00000000000000export default 123; webpack-3.5.6/test/cases/parsing/issue-3769/imported.js000066400000000000000000000000271315401342100225710ustar00rootroot00000000000000exports.test = "test"; webpack-3.5.6/test/cases/parsing/issue-3769/index.js000066400000000000000000000001451315401342100220560ustar00rootroot00000000000000it("should generate valid code", function() { require("./module").myTest.should.be.eql("test"); }); webpack-3.5.6/test/cases/parsing/issue-3769/module.js000066400000000000000000000013101315401342100222270ustar00rootroot00000000000000import { 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-3.5.6/test/cases/parsing/issue-387/000077500000000000000000000000001315401342100203225ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-387/file.js000066400000000000000000000000261315401342100215750ustar00rootroot00000000000000module.exports = 4321;webpack-3.5.6/test/cases/parsing/issue-387/index.js000066400000000000000000000024031315401342100217660ustar00rootroot00000000000000it("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); } )); module.exports.should.be.eql(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); } )); module.exports.should.be.eql(1234); }); it("should parse cujojs UMD modules with inlinded 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); } )); module.exports.should.be.eql(4321); });webpack-3.5.6/test/cases/parsing/issue-3917/000077500000000000000000000000001315401342100204045ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-3917/index.js000066400000000000000000000005341315401342100220530ustar00rootroot00000000000000it("should be able to compile a module with UMD", function() { var x = require("./module"); x.default.should.be.equal(global); }); it("should not find a free exports", function() { var x = require("./module2"); if(typeof exports !== "undefined") (x.default).should.be.equal(exports); else (x.default).should.be.eql(false); }); export {} webpack-3.5.6/test/cases/parsing/issue-3917/module.js000066400000000000000000000005161315401342100222310ustar00rootroot00000000000000var 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-3.5.6/test/cases/parsing/issue-3917/module2.js000066400000000000000000000001651315401342100223130ustar00rootroot00000000000000var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; export default freeExports; webpack-3.5.6/test/cases/parsing/issue-3964/000077500000000000000000000000001315401342100204065ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-3964/index.js000066400000000000000000000002201315401342100220450ustar00rootroot00000000000000it("should be possible to export default an imported name", function() { var x = require("./module"); x.should.be.eql({ default: 1234 }); }); webpack-3.5.6/test/cases/parsing/issue-3964/module.js000066400000000000000000000000451315401342100222300ustar00rootroot00000000000000import X from "./x" export default X webpack-3.5.6/test/cases/parsing/issue-3964/x.js000066400000000000000000000000251315401342100212100ustar00rootroot00000000000000export default 1234; webpack-3.5.6/test/cases/parsing/issue-4179/000077500000000000000000000000001315401342100204055ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4179/index.js000066400000000000000000000004061315401342100220520ustar00rootroot00000000000000import def from "./module?harmony"; import * as mod from "./module?harmony-start" it("should export a sequence expression correctly", function() { require("./module?cjs").should.be.eql({ default: 2 }); def.should.be.eql(2); mod.default.should.be.eql(2); }); webpack-3.5.6/test/cases/parsing/issue-4179/module.js000066400000000000000000000000271315401342100222270ustar00rootroot00000000000000export default (1, 2); webpack-3.5.6/test/cases/parsing/issue-4357/000077500000000000000000000000001315401342100204035ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4357/a.js000066400000000000000000000000261315401342100211570ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/cases/parsing/issue-4357/b.js000066400000000000000000000000241315401342100211560ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/cases/parsing/issue-4357/index.js000066400000000000000000000006771315401342100220620ustar00rootroot00000000000000import b from "./b"; it("should parse dynamic property names", function() { var o = { [require("./a")]: "a", [b]: "b" }; o.should.be.eql({ 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"}}]; aa.should.be.eql("a"); bb.should.be.eql("b"); cc.should.be.eql("c"); }); webpack-3.5.6/test/cases/parsing/issue-4357/test.filter.js000066400000000000000000000005001315401342100231770ustar00rootroot00000000000000var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); module.exports = function(config) { return !config.minimize && supportsIteratorDestructuring() && supportsObjectDestructuring(); }; webpack-3.5.6/test/cases/parsing/issue-4596/000077500000000000000000000000001315401342100204105ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4596/index.js000066400000000000000000000005761315401342100220650ustar00rootroot00000000000000it("should evaluate require.resolve as truthy value", function() { var id; if(require.resolve) id = require.resolve("./module.js"); (typeof id).should.be.oneOf("number", "string"); }); it("should evaluate require.resolve in ?: expression", function() { var id = require.resolve ? require.resolve("./module.js") : null; (typeof id).should.be.oneOf("number", "string"); }); webpack-3.5.6/test/cases/parsing/issue-4596/module.js000066400000000000000000000000001315401342100222210ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4608-1/000077500000000000000000000000001315401342100205405ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4608-1/index.js000066400000000000000000000040261315401342100222070ustar00rootroot00000000000000it("should find var declaration later in code", function() { (typeof require).should.be.eql("undefined"); var require; }); it("should find var declaration in same statement", function() { var fn = (function() { require("fail"); }), require; require = (function(x) { x.should.be.eql("fail"); }); fn(); }); it("should find a catch block declaration", function() { try { var f = (function(x) { x.should.be.eql("fail"); }); throw f; } catch(require) { require("fail"); } }); it("should find var declaration in control statements", function() { var f = (function(x) { x.should.be.eql("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) { x.should.be.eql("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-3.5.6/test/cases/parsing/issue-4608-2/000077500000000000000000000000001315401342100205415ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4608-2/index.js000066400000000000000000000007741315401342100222160ustar00rootroot00000000000000"use strict"; it("should find var declaration in control statements", function() { var f = (function(x) { x.should.be.eql("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) { x.should.be.eql("fail"); }); (function() { var test = (function() { require("fail"); }); for(let x of ["a"]) { var require = f; } test(); }()); }); webpack-3.5.6/test/cases/parsing/issue-4608-2/test.filter.js000066400000000000000000000002241315401342100233400ustar00rootroot00000000000000var supportsForOf = require("../../../helpers/supportsForOf"); module.exports = function(config) { return !config.minimize && supportsForOf(); }; webpack-3.5.6/test/cases/parsing/issue-4709/000077500000000000000000000000001315401342100204045ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4709/index.js000066400000000000000000000007011315401342100220470ustar00rootroot00000000000000function 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-3.5.6/test/cases/parsing/issue-4870/000077500000000000000000000000001315401342100204035ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-4870/file.js000066400000000000000000000000321315401342100216530ustar00rootroot00000000000000export var test = "test"; webpack-3.5.6/test/cases/parsing/issue-4870/index.js000066400000000000000000000004441315401342100220520ustar00rootroot00000000000000import { test } from "./file"; it("should allow import in array destructing", function() { var other; [other = test] = []; other.should.be.eql("test"); }); it("should allow import in object destructing", function() { var other; ({other = test} = {}); other.should.be.eql("test"); }); webpack-3.5.6/test/cases/parsing/issue-4870/test.filter.js000066400000000000000000000005001315401342100231770ustar00rootroot00000000000000var supportsIteratorDestructuring = require("../../../helpers/supportsIteratorDestructuring"); var supportsObjectDestructuring = require("../../../helpers/supportsObjectDestructuring"); module.exports = function(config) { return !config.minimize && supportsObjectDestructuring() && supportsIteratorDestructuring(); }; webpack-3.5.6/test/cases/parsing/issue-494/000077500000000000000000000000001315401342100203215ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-494/index.js000066400000000000000000000002031315401342100217610ustar00rootroot00000000000000it("should replace a free var in a IIFE", function() { (function(md) { md.should.be.type("function"); }(module.deprecate)); });webpack-3.5.6/test/cases/parsing/issue-551/000077500000000000000000000000001315401342100203135ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-551/index.js000066400000000000000000000012151315401342100217570ustar00rootroot00000000000000var window = {}; it("should be able to set the public path", function() { var originalValue = __webpack_public_path__; global.xyz = "xyz"; __webpack_public_path__ = global.xyz; __webpack_require__.p.should.be.eql("xyz"); delete global.xyz; window.something = "something"; __webpack_public_path__ = window.something; __webpack_require__.p.should.be.eql("something"); delete window.something; __webpack_public_path__ = "abc"; __webpack_require__.p.should.be.eql("abc"); __webpack_public_path__ = func(); __webpack_require__.p.should.be.eql("func"); __webpack_public_path__ = originalValue; function func() { return "func"; } }); webpack-3.5.6/test/cases/parsing/issue-5624/000077500000000000000000000000001315401342100204015ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-5624/index.js000066400000000000000000000002201315401342100220400ustar00rootroot00000000000000import { fn } from "./module"; it("should allow conditionals as callee", function() { var x = (true ? fn : fn)(); x.should.be.eql("ok"); }); webpack-3.5.6/test/cases/parsing/issue-5624/module.js000066400000000000000000000000471315401342100222250ustar00rootroot00000000000000export function fn() { return "ok"; } webpack-3.5.6/test/cases/parsing/issue-627/000077500000000000000000000000001315401342100203175ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-627/dir/000077500000000000000000000000001315401342100210755ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-627/dir/test.js000066400000000000000000000001571315401342100224150ustar00rootroot00000000000000(function() { var expr1 = "a", expr2 = "b"; require(Math.random() < 0.5 ? expr1 : expr2); }).should.throw(); webpack-3.5.6/test/cases/parsing/issue-627/index.js000066400000000000000000000001221315401342100217570ustar00rootroot00000000000000it("should compile expr in ?: operator", function() { require("./dir/test"); }); webpack-3.5.6/test/cases/parsing/issue-627/warnings.js000066400000000000000000000000571315401342100225070ustar00rootroot00000000000000module.exports = [ [/Critical dependency/] ]; webpack-3.5.6/test/cases/parsing/issue-758/000077500000000000000000000000001315401342100203245ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/issue-758/errors.js000066400000000000000000000001221315401342100221710ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /] ]; webpack-3.5.6/test/cases/parsing/issue-758/file.js000066400000000000000000000000501315401342100215740ustar00rootroot00000000000000define(function() { return "file"; }); webpack-3.5.6/test/cases/parsing/issue-758/index.js000066400000000000000000000035061315401342100217750ustar00rootroot00000000000000it("should require existing module with supplied error callback", function(done) { require.ensure(['./file'], function(){ var file = require('./file'); file.should.be.eql("file"); done(); }, function(error) {}); }); it("should call error callback on missing module", function(done) { require.ensure(['./missingModule'], function(){ require('./missingModule'); }, function(error) { error.should.be.instanceOf(Error); error.message.should.be.eql('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) { error.should.be.instanceOf(Error); error.message.should.be.eql("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) { error.should.be.instanceOf(Error); error.message.should.be.eql('message'); done(); }); }); it("should not call error callback on exception thrown in require callback", function(done) { require.ensure(['./throwing'], function() { require('./throwing'); throw new Error('message'); }, function(error) { error.should.be.instanceOf(Error); error.message.should.be.eql('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.reject('fake chunk load error'); }; require.ensure(['./file'], function(){ var file = require('./file'); }, function(error) { error.should.be.eql('fake chunk load error'); done(); }); __webpack_require__.e = temp; }); webpack-3.5.6/test/cases/parsing/issue-758/throwing.js000066400000000000000000000000651315401342100225240ustar00rootroot00000000000000define(function() { throw new Error('message'); }); webpack-3.5.6/test/cases/parsing/javascript/000077500000000000000000000000001315401342100210215ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/javascript/index.js000066400000000000000000000002001315401342100224560ustar00rootroot00000000000000it("should parse sparse arrays", function() { // issue #136 [,null].should.have.length(2); [0,,,0].should.have.length(4); }); webpack-3.5.6/test/cases/parsing/local-modules/000077500000000000000000000000001315401342100214135ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/local-modules/dep.js000066400000000000000000000000271315401342100225200ustar00rootroot00000000000000module.exports = "dep";webpack-3.5.6/test/cases/parsing/local-modules/index.js000066400000000000000000000033011315401342100230550ustar00rootroot00000000000000it("should define and require a local module", function() { module.exports = "not set"; define("my-module", function() { return 1234; }); module.exports.should.be.eql("not set"); define(["my-module"], function(myModule) { myModule.should.be.eql(1234); return 2345; }); module.exports.should.be.eql(2345); require("my-module").should.be.eql(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) { myModule2.should.be.eql(1235); sync = true; }); setImmediate(function() { sync.should.be.eql(true); done(); }); }); it("should define and require a local module with deps", function() { module.exports = "not set"; define("my-module3", ["./dep"], function(dep) { dep.should.be.eql("dep"); return 1234; }); module.exports.should.be.eql("not set"); define("my-module4", ["my-module3", "./dep"], function(myModule, dep) { dep.should.be.eql("dep"); myModule.should.be.eql(1234); return 2345; }); module.exports.should.be.eql("not set"); require("my-module3").should.be.eql(1234); require("my-module4").should.be.eql(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) { myModule3.should.be.eql(1234); myModule4.should.be.eql(2345); return 3456; }); require("my-dir/my-other-dir/my-module5").should.be.eql(3456); }) webpack-3.5.6/test/cases/parsing/renaming/000077500000000000000000000000001315401342100204535ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/renaming/file.js000066400000000000000000000000261315401342100217260ustar00rootroot00000000000000module.exports = "ok";webpack-3.5.6/test/cases/parsing/renaming/index.js000066400000000000000000000052261315401342100221250ustar00rootroot00000000000000it("should be able to rename require by var", function() { var cjsRequire; // just to make it difficult var cjsRequire = require, cjsRequire2 = typeof require !== "undefined" && require; cjsRequire("./file").should.be.eql("ok"); cjsRequire2("./file").should.be.eql("ok"); }); it("should be able to rename require by assign", function() { var cjsRequire, cjsRequire2; (function() { cjsRequire = require; cjsRequire2 = typeof require === "function" && require; cjsRequire("./file").should.be.eql("ok"); cjsRequire2("./file").should.be.eql("ok"); }()); }); it("should be able to rename require by IIFE", function() { (function(cjsRequire) { cjsRequire("./file").should.be.eql("ok"); }(require)); }); it("should be able to rename require by IIFE call", function() { (function(somethingElse, cjsRequire) { cjsRequire("./file").should.be.eql("ok"); somethingElse.should.be.eql(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) { R("./file").should.be.eql("ok"); _require("./file").should.be.eql("ok"); _require2("./file").should.be.eql("ok"); E.should.be.eql(exports); _exports.should.be.eql(exports); _exports2.should.be.eql(exports); M.should.be.eql(module); _module.should.be.eql(module); _module2.should.be.eql(module); }); _define2(["./file"], function(file) { file.should.be.eql("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) { r("./file").should.be.eql("ok"); (typeof require).should.be.eql("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) { R("./file").should.be.eql("ok"); _require("./file").should.be.eql("ok"); E.should.be.eql(exports); _exports.should.be.eql(exports); M.should.be.eql(module); _module.should.be.eql(module); }); }).call(this, typeof exports !== 'undefined' ? exports : null, typeof module !== 'undefined' ? module : null, typeof define !== 'undefined' ? define : null, typeof require !== 'undefined' ? require : null); }); webpack-3.5.6/test/cases/parsing/requirejs/000077500000000000000000000000001315401342100206645ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/requirejs/file.js000066400000000000000000000000001315401342100221270ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/requirejs/index.js000066400000000000000000000007711315401342100223360ustar00rootroot00000000000000it("should ignore require.config", function() { require.config({ }); requirejs.config({ }); }); it("should have a require.version", function() { require.version.should.be.type("string"); }); it("should have a requirejs.onError function", function() { function f(){} requirejs.onError.should.be.type("function"); // has default handler var org = requirejs.onError; requirejs.onError = f; requirejs.onError.should.be.eql(f); requirejs.onError = org; require(["./file.js"], function() {}); }); webpack-3.5.6/test/cases/parsing/resolve-weak-context/000077500000000000000000000000001315401342100227415ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/resolve-weak-context/dir/000077500000000000000000000000001315401342100235175ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/resolve-weak-context/dir/file.js000066400000000000000000000000341315401342100247710ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/cases/parsing/resolve-weak-context/index.js000066400000000000000000000003031315401342100244020ustar00rootroot00000000000000it("should be able to use require.resolveWeak with expression", function() { var expr = "file"; var id = require.resolveWeak("./dir/" + expr); id.should.be.eql(require("./dir/file.js")); }); webpack-3.5.6/test/cases/parsing/strict-mode/000077500000000000000000000000001315401342100211055ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/strict-mode/abc.js000066400000000000000000000000631315401342100221670ustar00rootroot00000000000000export default function() { return typeof this; };webpack-3.5.6/test/cases/parsing/strict-mode/index.js000066400000000000000000000006371315401342100225600ustar00rootroot00000000000000"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; })(); (typeof x).should.be.eql("undefined"); }); it("should import modules in strict mode", function() { a().should.be.eql("undefined"); }); });webpack-3.5.6/test/cases/parsing/template-string/000077500000000000000000000000001315401342100217725ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/template-string/abc/000077500000000000000000000000001315401342100225175ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/template-string/abc/abcTest.js000066400000000000000000000000251315401342100244370ustar00rootroot00000000000000export default "ok"; webpack-3.5.6/test/cases/parsing/template-string/amd.js000066400000000000000000000007241315401342100230740ustar00rootroot00000000000000 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) { result.default.should.eql("ok") if (--pending <= 0) { done() } } }) webpack-3.5.6/test/cases/parsing/template-string/cjs.js000066400000000000000000000022701315401342100231100ustar00rootroot00000000000000 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(`./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++) { imports[i].default.should.eql("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++) { imports[i].default.should.eql("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. require.resolve(`./sync/${name}Test`).should.not.be.undefined(); }) webpack-3.5.6/test/cases/parsing/template-string/index.js000066400000000000000000000010261315401342100234360ustar00rootroot00000000000000var should = require('should') it("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++) { imports[i].default.should.eql("ok"); } }) .then(function () { done(); }, done) }); require("./cjs") require("./amd") webpack-3.5.6/test/cases/parsing/template-string/sync/000077500000000000000000000000001315401342100227465ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/template-string/sync/syncTest.js000066400000000000000000000000271315401342100251170ustar00rootroot00000000000000export default "sync"; webpack-3.5.6/test/cases/parsing/template-string/test.filter.js000066400000000000000000000002621315401342100245730ustar00rootroot00000000000000var supportsTemplateStrings = require("../../../helpers/supportsTemplateStrings"); module.exports = function(config) { return !config.minimize && supportsTemplateStrings(); }; webpack-3.5.6/test/cases/parsing/typeof/000077500000000000000000000000001315401342100201615ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/typeof/errorfile.js000066400000000000000000000000651315401342100225110ustar00rootroot00000000000000))) This results in a syntax error loading this file.webpack-3.5.6/test/cases/parsing/typeof/index.js000066400000000000000000000044231315401342100216310ustar00rootroot00000000000000it("should not create a context for typeof require", function() { require("./typeof").should.be.eql("function"); }); it("should answer typeof require correctly", function() { (typeof require).should.be.eql("function"); }); it("should answer typeof define correctly", function() { (typeof define).should.be.eql("function"); }); it("should answer typeof require.amd correctly", function() { (typeof require.amd).should.be.eql("object"); }); it("should answer typeof define.amd correctly", function() { (typeof define.amd).should.be.eql("object"); }); it("should answer typeof module correctly", function() { (typeof module).should.be.eql("object"); }); it("should answer typeof exports correctly", function() { (typeof exports).should.be.eql("object"); }); it("should answer typeof require.include correctly", function() { (typeof require.include).should.be.eql("function"); }); it("should answer typeof require.ensure correctly", function() { (typeof require.ensure).should.be.eql("function"); }); it("should answer typeof require.resolve correctly", function() { (typeof require.resolve).should.be.eql("function"); }); it("should answer typeof System correctly", function() { (typeof System).should.be.eql("object"); }); it("should answer typeof System.import correctly", function() { (typeof System.import).should.be.eql("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 System.import !== "function") exports = require("fail"); if(typeof require.include !== "function") require.include("fail"); if(typeof require.ensure !== "function") require.ensure(["fail"], function(){}); }); webpack-3.5.6/test/cases/parsing/typeof/typeof.js000066400000000000000000000000401315401342100220170ustar00rootroot00000000000000module.exports = typeof require;webpack-3.5.6/test/cases/parsing/unsupported-amd/000077500000000000000000000000001315401342100220025ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/unsupported-amd/errors.js000066400000000000000000000001571315401342100236570ustar00rootroot00000000000000module.exports = [ [/Cannot statically analyse/, /in line 12/], [/Cannot statically analyse/, /in line 4/] ];webpack-3.5.6/test/cases/parsing/unsupported-amd/index.js000066400000000000000000000005311315401342100234460ustar00rootroot00000000000000it("should fail on unsupported use of AMD require 1", function() { (function() { var abc = ["./a", "./b"]; require(abc, function(a, b) {}); }).should.throw(); }); it("should fail on unsupported use of AMD require 2", function() { (function() { var abc = ["./a", "./b"]; function f(a, b) {} require(abc, f); }).should.throw(); }); webpack-3.5.6/test/cases/parsing/var-hiding/000077500000000000000000000000001315401342100207035ustar00rootroot00000000000000webpack-3.5.6/test/cases/parsing/var-hiding/index.js000066400000000000000000000003521315401342100223500ustar00rootroot00000000000000var fn = function(module) { if (typeof module !== 'number') { throw new Error("module should be a number"); } (typeof module).should.be.eql("number"); }; it("should hide a free var by function argument", function() { fn(1); });webpack-3.5.6/test/cases/resolving/000077500000000000000000000000001315401342100172205ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/000077500000000000000000000000001315401342100217645ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/errors.js000066400000000000000000000004541315401342100236410ustar00rootroot00000000000000module.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-3.5.6/test/cases/resolving/browser-field/index.js000066400000000000000000000030741315401342100234350ustar00rootroot00000000000000it("should replace a module with a module", function() { require("replacing-module1").should.be.eql("new-module"); }); it("should replace a module with a file in a module", function() { require("replacing-module2").should.be.eql("new-module/inner"); }); it("should replace a module with file in the same module", function() { require("replacing-module3").should.be.eql("new-module/inner"); }); it("should replace a module with a file in the current module", function() { require("replacing-module4").should.be.eql("replacing-module4/module"); }); it("should replace a file with another file", function() { require("replacing-file1").should.be.eql("new-file"); }); it("should replace a file with a module", function() { require("replacing-file2").should.be.eql("new-module"); }); it("should replace a file with a file in a module", function() { require("replacing-file3").should.be.eql("new-module/inner"); }); it("should replace a file in a directory with another file", function() { require("replacing-file4").should.be.eql("new-file"); }); it("should ignore recursive module mappings", function() { require("recursive-module").should.be.eql("new-module"); }); it("should use empty modules for ignored modules", function() { require("ignoring-module").module.should.be.eql({}); require("ignoring-module").file.should.be.eql({}); require("ignoring-module").module.should.not.be.equal(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-3.5.6/test/cases/resolving/browser-field/node_modules/000077500000000000000000000000001315401342100244415ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/ignoring-module/000077500000000000000000000000001315401342100275405ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/ignoring-module/file.js000066400000000000000000000000301315401342100310060ustar00rootroot00000000000000throw new Error("Fail");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/ignoring-module/index.js000066400000000000000000000001131315401342100312000ustar00rootroot00000000000000exports.module = require("wrong-module"); exports.file = require("./file");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/ignoring-module/package.json000066400000000000000000000001021315401342100320170ustar00rootroot00000000000000{ "browser": { "wrong-module": false, "./file.js": false } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/new-module/000077500000000000000000000000001315401342100265155ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/new-module/index.js000066400000000000000000000000361315401342100301610ustar00rootroot00000000000000module.exports = "new-module";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/new-module/inner.js000066400000000000000000000000441315401342100301640ustar00rootroot00000000000000module.exports = "new-module/inner";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-file/000077500000000000000000000000001315401342100273655ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-file/a.js000066400000000000000000000000251315401342100301400ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-file/b.js000066400000000000000000000000251315401342100301410ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-file/c.js000066400000000000000000000000251315401342100301420ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-file/d.js000066400000000000000000000000251315401342100301430ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-file/package.json000066400000000000000000000001411315401342100316470ustar00rootroot00000000000000{ "browser": { "a.js": "./a", "./b.js": "./b", "c.js": "./d.js", "./d.js": "./c.js" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-module/000077500000000000000000000000001315401342100277335ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-module/index.js000066400000000000000000000000471315401342100314010ustar00rootroot00000000000000module.exports = require("new-module");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/recursive-module/package.json000066400000000000000000000000611315401342100322160ustar00rootroot00000000000000{ "browser": { "new-module": "new-module" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file1/000077500000000000000000000000001315401342100274035ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file1/file.js000066400000000000000000000000301315401342100306510ustar00rootroot00000000000000module.exports = "file";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file1/index.js000066400000000000000000000000431315401342100310450ustar00rootroot00000000000000module.exports = require("./file");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file1/new-file.js000066400000000000000000000000341315401342100314440ustar00rootroot00000000000000module.exports = "new-file";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file1/package.json000066400000000000000000000000631315401342100316700ustar00rootroot00000000000000{ "browser": { "./file.js": "./new-file.js" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file2/000077500000000000000000000000001315401342100274045ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file2/file.js000066400000000000000000000000301315401342100306520ustar00rootroot00000000000000module.exports = "file";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file2/index.js000066400000000000000000000000431315401342100310460ustar00rootroot00000000000000module.exports = require("./file");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file2/package.json000066400000000000000000000000601315401342100316660ustar00rootroot00000000000000{ "browser": { "./file.js": "new-module" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file3/000077500000000000000000000000001315401342100274055ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file3/file.js000066400000000000000000000000301315401342100306530ustar00rootroot00000000000000module.exports = "file";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file3/index.js000066400000000000000000000000431315401342100310470ustar00rootroot00000000000000module.exports = require("./file");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file3/package.json000066400000000000000000000000661315401342100316750ustar00rootroot00000000000000{ "browser": { "./file.js": "new-module/inner" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file4/000077500000000000000000000000001315401342100274065ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/000077500000000000000000000000001315401342100301645ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/file.js000066400000000000000000000000301315401342100314320ustar00rootroot00000000000000module.exports = "file";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/index.js000066400000000000000000000000431315401342100316260ustar00rootroot00000000000000module.exports = require("./file");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file4/dir/new-file.js000066400000000000000000000000341315401342100322250ustar00rootroot00000000000000module.exports = "new-file";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file4/index.js000066400000000000000000000000421315401342100310470ustar00rootroot00000000000000module.exports = require("./dir");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-file4/package.json000066400000000000000000000000701315401342100316710ustar00rootroot00000000000000{ "browser": { "./dir/file.js": "./dir/new-file" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module1/000077500000000000000000000000001315401342100277515ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module1/index.js000066400000000000000000000000511315401342100314120ustar00rootroot00000000000000module.exports = require("wrong-module");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module1/package.json000066400000000000000000000000631315401342100322360ustar00rootroot00000000000000{ "browser": { "wrong-module": "new-module" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module2/000077500000000000000000000000001315401342100277525ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module2/index.js000066400000000000000000000000511315401342100314130ustar00rootroot00000000000000module.exports = require("wrong-module");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module2/package.json000066400000000000000000000000711315401342100322360ustar00rootroot00000000000000{ "browser": { "wrong-module": "new-module/inner" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module3/000077500000000000000000000000001315401342100277535ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module3/index.js000066400000000000000000000000471315401342100314210ustar00rootroot00000000000000module.exports = require("new-module");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module3/package.json000066400000000000000000000000671315401342100322440ustar00rootroot00000000000000{ "browser": { "new-module": "new-module/inner" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module4/000077500000000000000000000000001315401342100277545ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module4/index.js000066400000000000000000000000511315401342100314150ustar00rootroot00000000000000module.exports = require("wrong-module");webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module4/module.js000066400000000000000000000000541315401342100315760ustar00rootroot00000000000000module.exports = "replacing-module4/module";webpack-3.5.6/test/cases/resolving/browser-field/node_modules/replacing-module4/package.json000066400000000000000000000000641315401342100322420ustar00rootroot00000000000000{ "browser": { "wrong-module": "./module.js" } }webpack-3.5.6/test/cases/resolving/browser-field/node_modules/wrong-module.js000066400000000000000000000000401315401342100274100ustar00rootroot00000000000000module.exports = "wrong-module";webpack-3.5.6/test/cases/resolving/commomjs-local-module/000077500000000000000000000000001315401342100234175ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/commomjs-local-module/index.js000066400000000000000000000012641315401342100250670ustar00rootroot00000000000000var should = require("should"); define("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() { should.strictEqual(require("regular"), "regular-module"); should.strictEqual(require("return-module"), "module is returned"); const overrideExports = require("override-exports"); should(overrideExports).be.a.Object(); should(Object.keys(overrideExports).length).be.exactly(0); }); webpack-3.5.6/test/cases/resolving/context/000077500000000000000000000000001315401342100207045ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/context/index.js000066400000000000000000000007051315401342100223530ustar00rootroot00000000000000it("should resolve loaders relative to require", function() { var index = "index", test = "test"; require("./loaders/queryloader?query!!!!./node_modules/subcontent/" + index + ".js").should.be.eql({ resourceQuery: "", query: "?query", prev: "module.exports = \"error\";" }); require("!./loaders/queryloader?query!./node_modules/subcontent/" + test + ".jade").should.be.eql({ resourceQuery: "", query: "?query", prev: "xyz: abc" }); }); webpack-3.5.6/test/cases/resolving/context/loaders/000077500000000000000000000000001315401342100223355ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/context/loaders/queryloader.js000066400000000000000000000002451315401342100252300ustar00rootroot00000000000000module.exports = function(content) { return "module.exports = " + JSON.stringify({ resourceQuery: this.resourceQuery, query: this.query, prev: content }); } webpack-3.5.6/test/cases/resolving/context/node_modules/000077500000000000000000000000001315401342100233615ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/context/node_modules/subcontent/000077500000000000000000000000001315401342100255455ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/context/node_modules/subcontent/index.js000066400000000000000000000000311315401342100272040ustar00rootroot00000000000000module.exports = "error";webpack-3.5.6/test/cases/resolving/context/node_modules/subcontent/test.jade000066400000000000000000000000101315401342100273400ustar00rootroot00000000000000xyz: abcwebpack-3.5.6/test/cases/resolving/issue-2986/000077500000000000000000000000001315401342100207565ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/issue-2986/errors.js000066400000000000000000000001621315401342100226270ustar00rootroot00000000000000module.exports = [ [/Can't resolve 'any' in/, /BREAKING CHANGE/, /any-loader/], [/Can't resolve 'other' in/] ]; webpack-3.5.6/test/cases/resolving/issue-2986/index.js000066400000000000000000000001451315401342100224230ustar00rootroot00000000000000require.include("any!"); require.include("other!"); it("should have correct errors", function() {}) webpack-3.5.6/test/cases/resolving/issue-2986/node_modules/000077500000000000000000000000001315401342100234335ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/issue-2986/node_modules/any-loader.js000066400000000000000000000000651315401342100260250ustar00rootroot00000000000000module.exports = function(source) { return source; } webpack-3.5.6/test/cases/resolving/query/000077500000000000000000000000001315401342100203655ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/query/empty.js000066400000000000000000000000001315401342100220470ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/query/index.js000066400000000000000000000006101315401342100220270ustar00rootroot00000000000000var should = require("should"); it("should make different modules for query", function() { var a = require("./empty"); var b = require("./empty?1"); var c = require("./empty?2"); should.strictEqual(typeof a, "object"); should.strictEqual(typeof b, "object"); should.strictEqual(typeof c, "object"); a.should.be.not.equal(b); a.should.be.not.equal(c); b.should.be.not.equal(c); }); webpack-3.5.6/test/cases/resolving/single-file-module/000077500000000000000000000000001315401342100227015ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/single-file-module/index.js000066400000000000000000000001611315401342100243440ustar00rootroot00000000000000it("should load single file modules", function() { require("subfilemodule").should.be.eql("subfilemodule"); }); webpack-3.5.6/test/cases/resolving/single-file-module/node_modules/000077500000000000000000000000001315401342100253565ustar00rootroot00000000000000webpack-3.5.6/test/cases/resolving/single-file-module/node_modules/subfilemodule.js000066400000000000000000000000411315401342100305460ustar00rootroot00000000000000module.exports = "subfilemodule";webpack-3.5.6/test/cases/runtime/000077500000000000000000000000001315401342100166735ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/chunk-callback-order/000077500000000000000000000000001315401342100226465ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/chunk-callback-order/a.js000066400000000000000000000000251315401342100234210ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/cases/runtime/chunk-callback-order/b.js000066400000000000000000000000401315401342100234170ustar00rootroot00000000000000module.exports = require("./a");webpack-3.5.6/test/cases/runtime/chunk-callback-order/duplicate.js000066400000000000000000000001221315401342100251510ustar00rootroot00000000000000require.ensure(["./a"], function(require) { require("./a").should.be.eql("a"); })webpack-3.5.6/test/cases/runtime/chunk-callback-order/duplicate2.js000066400000000000000000000001221315401342100252330ustar00rootroot00000000000000require.ensure(["./b"], function(require) { require("./b").should.be.eql("a"); })webpack-3.5.6/test/cases/runtime/chunk-callback-order/index.js000066400000000000000000000005701315401342100243150ustar00rootroot00000000000000it("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); calls.should.be.eql([1,2]); done(); }); }); webpack-3.5.6/test/cases/runtime/circular-dependencies/000077500000000000000000000000001315401342100231235ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/circular-dependencies/circular.js000066400000000000000000000000731315401342100252650ustar00rootroot00000000000000module.exports = 1; module.exports = require("./circular");webpack-3.5.6/test/cases/runtime/circular-dependencies/circular2.js000066400000000000000000000000741315401342100253500ustar00rootroot00000000000000module.exports = 2; module.exports = require("./circular2");webpack-3.5.6/test/cases/runtime/circular-dependencies/index.js000066400000000000000000000001541315401342100245700ustar00rootroot00000000000000it("should load circular dependencies correctly", function() { require("./circular").should.be.eql(1); }); webpack-3.5.6/test/cases/runtime/error-handling/000077500000000000000000000000001315401342100216065ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/error-handling/errors.js000066400000000000000000000001551315401342100234610ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule' /, /error-handling\/index.js/] ];webpack-3.5.6/test/cases/runtime/error-handling/folder/000077500000000000000000000000001315401342100230615ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/error-handling/folder/file1.js000066400000000000000000000000311315401342100244110ustar00rootroot00000000000000module.exports = "file1";webpack-3.5.6/test/cases/runtime/error-handling/folder/file2.js000066400000000000000000000000311315401342100244120ustar00rootroot00000000000000module.exports = "file2";webpack-3.5.6/test/cases/runtime/error-handling/folder/file3.js000066400000000000000000000000311315401342100244130ustar00rootroot00000000000000module.exports = "file3";webpack-3.5.6/test/cases/runtime/error-handling/index.js000066400000000000000000000013331315401342100232530ustar00rootroot00000000000000function testCase(number) { require(number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule").should.be.eql("file" + number); require( number === 1 ? "./folder/file1" : number === 2 ? "./folder/file2" : number === 3 ? "./folder/file3" : "./missingModule" ).should.be.eql("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; } error.should.be.instanceOf(Error); error = null; try { require("./missingModule2"); // direct } catch(e) { error = e; } error.should.be.instanceOf(Error); }); webpack-3.5.6/test/cases/runtime/error-handling/warnings.js000066400000000000000000000001561315401342100237760ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/missingModule2' /, /error-handling\/index.js/] ];webpack-3.5.6/test/cases/runtime/issue-1650/000077500000000000000000000000001315401342100204145ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/issue-1650/file.js000066400000000000000000000000401315401342100216630ustar00rootroot00000000000000__webpack_public_path__ = "ok"; webpack-3.5.6/test/cases/runtime/issue-1650/index.js000066400000000000000000000003141315401342100220570ustar00rootroot00000000000000it("should be able to set the public path globally", function() { var org = __webpack_public_path__; require("./file"); __webpack_public_path__.should.be.eql("ok"); __webpack_public_path__ = org; }); webpack-3.5.6/test/cases/runtime/issue-1788/000077500000000000000000000000001315401342100204305ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/issue-1788/a.js000066400000000000000000000002121315401342100212010ustar00rootroot00000000000000import b from './b'; export default 'a-default'; export { btest } from "./b"; export function atest() { b.should.be.eql("b-default"); } webpack-3.5.6/test/cases/runtime/issue-1788/b.js000066400000000000000000000001551315401342100212100ustar00rootroot00000000000000import a from './a'; export default 'b-default'; export function btest() { a.should.be.eql("a-default"); } webpack-3.5.6/test/cases/runtime/issue-1788/index.js000066400000000000000000000001571315401342100221000ustar00rootroot00000000000000import { atest, btest } from "./a"; it("should have the correct values", function() { atest(); btest(); }); webpack-3.5.6/test/cases/runtime/issue-2391-chunk/000077500000000000000000000000001315401342100215255ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/issue-2391-chunk/file.js000066400000000000000000000000001315401342100227700ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/issue-2391-chunk/index.js000066400000000000000000000002231315401342100231670ustar00rootroot00000000000000it("should have a require.onError function by default", function() { (typeof require.onError).should.be.eql("function"); require(["./file"]); });webpack-3.5.6/test/cases/runtime/issue-2391/000077500000000000000000000000001315401342100204175ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/issue-2391/index.js000066400000000000000000000002461315401342100220660ustar00rootroot00000000000000it("should not have a require.onError function by default", function() { (typeof require.onError).should.be.eql("undefined"); // expected to fail in browsertests });webpack-3.5.6/test/cases/runtime/missing-module-exception/000077500000000000000000000000001315401342100236235ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/missing-module-exception/index.js000066400000000000000000000002161315401342100252670ustar00rootroot00000000000000it("should have correct error code", function() { try { require("./fail"); } catch(e) { e.code.should.be.eql("MODULE_NOT_FOUND"); } });webpack-3.5.6/test/cases/runtime/missing-module-exception/warnings.js000066400000000000000000000001101315401342100260010ustar00rootroot00000000000000module.exports = [ [/Module not found/, /Can't resolve '\.\/fail' /] ];webpack-3.5.6/test/cases/runtime/module-caching/000077500000000000000000000000001315401342100215525ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/module-caching/index.js000066400000000000000000000021421315401342100232160ustar00rootroot00000000000000var should = require("should"); it("should cache modules correctly", function(done) { delete require.cache[require.resolve("./singluar.js")]; require("./singluar.js").value.should.be.eql(1); (require("./singluar.js")).value.should.be.eql(1); require("./sing" + "luar.js").value = 2; require("./singluar.js").value.should.be.eql(2); require.ensure(["./two.js"], function(require) { require("./singluar.js").value.should.be.eql(2); done(); }); }); it("should be able the remove modules from cache with require.cache and require.resolve", function() { var singlarObj = require("./singluar2"); var singlarId = require.resolve("./singluar2"); var singlarIdInConditional = require.resolve(true ? "./singluar2" : "./singluar"); if(typeof singlarId !== "number" && typeof singlarId !== "string") throw new Error("require.resolve should return a number or string"); singlarIdInConditional.should.be.eql(singlarId); (require.cache).should.have.type("object"); (require.cache[singlarId]).should.have.type("object"); delete require.cache[singlarId]; require("./singluar2").should.be.not.equal(singlarObj); }); webpack-3.5.6/test/cases/runtime/module-caching/singluar.js000066400000000000000000000000311315401342100237260ustar00rootroot00000000000000module.exports.value = 1;webpack-3.5.6/test/cases/runtime/module-caching/singluar2.js000066400000000000000000000000001315401342100240040ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/module-caching/two.js000066400000000000000000000000231315401342100227140ustar00rootroot00000000000000module.exports = 2;webpack-3.5.6/test/cases/runtime/require-function/000077500000000000000000000000001315401342100221725ustar00rootroot00000000000000webpack-3.5.6/test/cases/runtime/require-function/fail.js000066400000000000000000000000371315401342100234430ustar00rootroot00000000000000This file should not load! }][{webpack-3.5.6/test/cases/runtime/require-function/index.js000066400000000000000000000003461315401342100236420ustar00rootroot00000000000000it("should have correct properties on the require function", function() { __webpack_require__.c.should.have.type("object"); __webpack_require__.m.should.have.type("object"); __webpack_require__.p.should.have.type("string"); });webpack-3.5.6/test/cases/scope-hoisting/000077500000000000000000000000001315401342100201435ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/async-keyword-5615/000077500000000000000000000000001315401342100233405ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/async-keyword-5615/async.js000066400000000000000000000000321315401342100250060ustar00rootroot00000000000000export default "default"; webpack-3.5.6/test/cases/scope-hoisting/async-keyword-5615/index.js000066400000000000000000000001651315401342100250070ustar00rootroot00000000000000import value from "./async"; it("should have the correct values", function() { value.should.be.eql("default"); }); webpack-3.5.6/test/cases/scope-hoisting/chained-reexport/000077500000000000000000000000001315401342100234045ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/chained-reexport/a.js000066400000000000000000000000341315401342100241570ustar00rootroot00000000000000export var named = "named"; webpack-3.5.6/test/cases/scope-hoisting/chained-reexport/b.js000066400000000000000000000000251315401342100241600ustar00rootroot00000000000000export * from "./a"; webpack-3.5.6/test/cases/scope-hoisting/chained-reexport/c.js000066400000000000000000000000351315401342100241620ustar00rootroot00000000000000export { named } from "./b"; webpack-3.5.6/test/cases/scope-hoisting/chained-reexport/index.js000066400000000000000000000001631315401342100250510ustar00rootroot00000000000000import { named } from "./c"; it("should have the correct values", function() { named.should.be.eql("named"); }); webpack-3.5.6/test/cases/scope-hoisting/circular-external/000077500000000000000000000000001315401342100235675ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/circular-external/a1.js000066400000000000000000000000361315401342100244250ustar00rootroot00000000000000import "./a2"; import "./b1"; webpack-3.5.6/test/cases/scope-hoisting/circular-external/a2.js000066400000000000000000000000121315401342100244200ustar00rootroot00000000000000export {} webpack-3.5.6/test/cases/scope-hoisting/circular-external/b1.js000066400000000000000000000000361315401342100244260ustar00rootroot00000000000000import "./b2"; import "./c1"; webpack-3.5.6/test/cases/scope-hoisting/circular-external/b2.js000066400000000000000000000000121315401342100244210ustar00rootroot00000000000000export {} webpack-3.5.6/test/cases/scope-hoisting/circular-external/c1.js000066400000000000000000000000361315401342100244270ustar00rootroot00000000000000import "./c2"; import "./a1"; webpack-3.5.6/test/cases/scope-hoisting/circular-external/c2.js000066400000000000000000000000121315401342100244220ustar00rootroot00000000000000export {} webpack-3.5.6/test/cases/scope-hoisting/circular-external/index.js000066400000000000000000000002351315401342100252340ustar00rootroot00000000000000it("should compile and run fine", function(done) { Promise.all([ import("./a1"), import("./b1"), import("./c1") ]).then(function() { done(); }); }); webpack-3.5.6/test/cases/scope-hoisting/circular-namespace-object/000077500000000000000000000000001315401342100251455ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/circular-namespace-object/index.js000066400000000000000000000002131315401342100266060ustar00rootroot00000000000000import value from "./module"; it("should have access to namespace object before evaluation", function() { value.should.be.eql("ok"); }); webpack-3.5.6/test/cases/scope-hoisting/circular-namespace-object/module.js000066400000000000000000000001161315401342100267660ustar00rootroot00000000000000export { default } from "./module2" export function func() { return "ok"; } webpack-3.5.6/test/cases/scope-hoisting/circular-namespace-object/module2.js000066400000000000000000000001271315401342100270520ustar00rootroot00000000000000import * as module from "./module"; var f = Object(module).func; export default f(); webpack-3.5.6/test/cases/scope-hoisting/export-namespace/000077500000000000000000000000001315401342100234165ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/export-namespace/index.js000066400000000000000000000004771315401342100250730ustar00rootroot00000000000000import { ns as ns1 } from "./module1"; const ns2 = require("./module2").ns; it("should allow to export a namespace object (concated)", function() { ns1.should.be.eql({ a: "a", b: "b" }); }); it("should allow to export a namespace object (exposed)", function() { ns2.should.be.eql({ a: "a", b: "b" }); }); webpack-3.5.6/test/cases/scope-hoisting/export-namespace/module1.js000066400000000000000000000000541315401342100253210ustar00rootroot00000000000000import * as ns from "./ns1"; export { ns }; webpack-3.5.6/test/cases/scope-hoisting/export-namespace/module2.js000066400000000000000000000000541315401342100253220ustar00rootroot00000000000000import * as ns from "./ns2"; export { ns }; webpack-3.5.6/test/cases/scope-hoisting/export-namespace/ns1.js000066400000000000000000000000501315401342100244500ustar00rootroot00000000000000export var a = "a"; export var b = "b"; webpack-3.5.6/test/cases/scope-hoisting/export-namespace/ns2.js000066400000000000000000000000501315401342100244510ustar00rootroot00000000000000export var a = "a"; export var b = "b"; webpack-3.5.6/test/cases/scope-hoisting/import-order/000077500000000000000000000000001315401342100225665ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/import-order/commonjs.js000066400000000000000000000000741315401342100247520ustar00rootroot00000000000000var track = require("./tracker").track; track("commonjs"); webpack-3.5.6/test/cases/scope-hoisting/import-order/index.js000066400000000000000000000002711315401342100242330ustar00rootroot00000000000000import "./commonjs"; import "./module"; import { log } from "./tracker"; it("should evaluate import in the correct order", function() { log.should.be.eql(["commonjs", "module"]); }); webpack-3.5.6/test/cases/scope-hoisting/import-order/module.js000066400000000000000000000000651315401342100244120ustar00rootroot00000000000000import { track } from "./tracker"; track("module"); webpack-3.5.6/test/cases/scope-hoisting/import-order/tracker.js000066400000000000000000000001071315401342100245550ustar00rootroot00000000000000export var log = []; export function track(name) { log.push(name); } webpack-3.5.6/test/cases/scope-hoisting/indirect-reexport/000077500000000000000000000000001315401342100236125ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/indirect-reexport/a.js000066400000000000000000000000301315401342100243610ustar00rootroot00000000000000export default "named"; webpack-3.5.6/test/cases/scope-hoisting/indirect-reexport/b.js000066400000000000000000000000521315401342100243660ustar00rootroot00000000000000import named from "./a"; export { named } webpack-3.5.6/test/cases/scope-hoisting/indirect-reexport/c.js000066400000000000000000000000561315401342100243730ustar00rootroot00000000000000import { named } from "./b"; export { named } webpack-3.5.6/test/cases/scope-hoisting/indirect-reexport/index.js000066400000000000000000000001601315401342100252540ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { c.named.should.be.eql("named"); }); webpack-3.5.6/test/cases/scope-hoisting/inside-class/000077500000000000000000000000001315401342100225215ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/inside-class/first.js000066400000000000000000000002231315401342100242030ustar00rootroot00000000000000export class Foo { test() { return Foo.value; } } Foo.value = 1; export class Bar { test() { return Bar.value; } } Bar.value = 1; webpack-3.5.6/test/cases/scope-hoisting/inside-class/index.js000066400000000000000000000005311315401342100241650ustar00rootroot00000000000000import { 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(); a.should.be.eql(1); b.should.be.eql(2); new FirstBar().test().should.be.eql(1); new Bar().test().should.be.eql(2); }); webpack-3.5.6/test/cases/scope-hoisting/inside-class/second.js000066400000000000000000000002231315401342100243270ustar00rootroot00000000000000export class Foo { test() { return Foo.value; } } Foo.value = 2; export class Bar { test() { return Bar.value; } } Bar.value = 2; webpack-3.5.6/test/cases/scope-hoisting/inside-class/test.filter.js000066400000000000000000000002161315401342100253210ustar00rootroot00000000000000var supportsES6 = require("../../../helpers/supportsES6"); module.exports = function(config) { return !config.minimize && supportsES6(); }; webpack-3.5.6/test/cases/scope-hoisting/intra-references/000077500000000000000000000000001315401342100233775ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/intra-references/a.js000066400000000000000000000000371315401342100241550ustar00rootroot00000000000000export { default } from "./b"; webpack-3.5.6/test/cases/scope-hoisting/intra-references/b.js000066400000000000000000000000371315401342100241560ustar00rootroot00000000000000export { default } from "./c"; webpack-3.5.6/test/cases/scope-hoisting/intra-references/c.js000066400000000000000000000000251315401342100241540ustar00rootroot00000000000000export default "ok"; webpack-3.5.6/test/cases/scope-hoisting/intra-references/index.js000066400000000000000000000002351315401342100250440ustar00rootroot00000000000000import value from "./a"; it("should have the correct values", function() { value.should.be.eql("ok"); }); // prevent scope hoisting of b require("./b"); webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/000077500000000000000000000000001315401342100233035ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/index.js000066400000000000000000000002551315401342100247520ustar00rootroot00000000000000var testData = require("./src/index.js"); it("should export the correct values", function() { testData.should.be.eql({ icon: { svg: { default: 1 } } }); }) webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/src/000077500000000000000000000000001315401342100240725ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/src/icon/000077500000000000000000000000001315401342100250225ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/src/icon/index.js000066400000000000000000000000631315401342100264660ustar00rootroot00000000000000import * as svg from "./svg"; export { svg }; webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/src/icon/svg/000077500000000000000000000000001315401342100256215ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/src/icon/svg/index.js000066400000000000000000000000221315401342100272600ustar00rootroot00000000000000export default 1; webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/src/icon/svg/svg1.js000066400000000000000000000000271315401342100270360ustar00rootroot00000000000000export const svg1 = 1; webpack-3.5.6/test/cases/scope-hoisting/issue-5020-minimal/src/index.js000066400000000000000000000000651315401342100255400ustar00rootroot00000000000000import * as icon from "./icon"; export { icon } webpack-3.5.6/test/cases/scope-hoisting/issue-5020/000077500000000000000000000000001315401342100216575ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020/index.js000066400000000000000000000005131315401342100233230ustar00rootroot00000000000000var testData = require("./src/index.js"); it("should export the correct values", function() { testData.should.be.eql({ svg5: { svg: { clinical1: { svg1: 1 }, clinical2: { svg2: 2 } } }, svg6: { svg: { test: { svg1: 10 }, clinical2: { svg2: 20 } } } }); }) webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/000077500000000000000000000000001315401342100224465ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon/000077500000000000000000000000001315401342100233765ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon/index.js000066400000000000000000000000631315401342100250420ustar00rootroot00000000000000import * as svg from "./svg"; export { svg }; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon/svg/000077500000000000000000000000001315401342100241755ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon/svg/index.js000066400000000000000000000002511315401342100256400ustar00rootroot00000000000000import { svg1 } from "./svg1"; import { svg2 } from "./svg2"; const clinical1 = { svg1 }; const clinical2 = { svg2 }; export { clinical1, clinical2 }; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon/svg/svg1.js000066400000000000000000000000271315401342100254120ustar00rootroot00000000000000export const svg1 = 1; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon/svg/svg2.js000066400000000000000000000000271315401342100254130ustar00rootroot00000000000000export const svg2 = 2; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon1/000077500000000000000000000000001315401342100234575ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon1/index.js000066400000000000000000000000631315401342100251230ustar00rootroot00000000000000import * as svg from "./svg"; export { svg }; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon1/svg/000077500000000000000000000000001315401342100242565ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon1/svg/index.js000066400000000000000000000002371315401342100257250ustar00rootroot00000000000000import { svg1 } from "./svg1"; import { svg2 } from "./svg2"; const test = { svg1 }; const clinical2 = { svg2 }; export { test, clinical2 }; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon1/svg/svg1.js000066400000000000000000000000301315401342100254650ustar00rootroot00000000000000export const svg1 = 10; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/icon1/svg/svg2.js000066400000000000000000000000301315401342100254660ustar00rootroot00000000000000export const svg2 = 20; webpack-3.5.6/test/cases/scope-hoisting/issue-5020/src/index.js000066400000000000000000000001401315401342100241060ustar00rootroot00000000000000import * as svg5 from "./icon"; import * as svg6 from "./icon1"; export { svg5, svg6 } webpack-3.5.6/test/cases/scope-hoisting/issue-5096/000077500000000000000000000000001315401342100216745ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5096/b.js000066400000000000000000000000641315401342100224530ustar00rootroot00000000000000import { a } from './index'; export const b = a(); webpack-3.5.6/test/cases/scope-hoisting/issue-5096/index.js000066400000000000000000000003061315401342100233400ustar00rootroot00000000000000import { b } from './b'; export function a() { return "a"; }; // Inject a variable if(Math.random() < -1) console.log(module); it("should compile fine", function() { b.should.be.eql("a"); }); webpack-3.5.6/test/cases/scope-hoisting/issue-5314/000077500000000000000000000000001315401342100216655ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5314/index.js000066400000000000000000000002541315401342100233330ustar00rootroot00000000000000import a from "./module"; var obj = {}; it("should allow access to the default export of the root module", function() { a().should.be.eql(obj); }); export default obj; webpack-3.5.6/test/cases/scope-hoisting/issue-5314/module.js000066400000000000000000000001021315401342100235010ustar00rootroot00000000000000import b from "./index"; export default function() { return b; }; webpack-3.5.6/test/cases/scope-hoisting/issue-5443/000077500000000000000000000000001315401342100216705ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5443/index.js000066400000000000000000000002401315401342100233310ustar00rootroot00000000000000import { module } from "./reexport"; it("should have the correct values", function() { module.should.be.eql({ default: "default", named: "named" }); }); webpack-3.5.6/test/cases/scope-hoisting/issue-5443/module.js000066400000000000000000000000661315401342100235150ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-3.5.6/test/cases/scope-hoisting/issue-5443/reexport.js000066400000000000000000000000701315401342100240730ustar00rootroot00000000000000import * as module from "./module" export { module } webpack-3.5.6/test/cases/scope-hoisting/issue-5481/000077500000000000000000000000001315401342100216725ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/issue-5481/cjs.js000066400000000000000000000000271315401342100230060ustar00rootroot00000000000000module.exports = "ok"; webpack-3.5.6/test/cases/scope-hoisting/issue-5481/index.js000066400000000000000000000002021315401342100233310ustar00rootroot00000000000000import value from "./module"; it("should not cause name conflicts", function() { (typeof value).should.be.eql("undefined"); }); webpack-3.5.6/test/cases/scope-hoisting/issue-5481/module.js000066400000000000000000000001061315401342100235120ustar00rootroot00000000000000import a from "./cjs"; var cjs_default; export default cjs_default; webpack-3.5.6/test/cases/scope-hoisting/name-conflicts/000077500000000000000000000000001315401342100230455ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/name-conflicts/index.js000066400000000000000000000006511315401342100245140ustar00rootroot00000000000000import 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() { value1.should.be.eql("a"); value2.should.be.eql("a"); value3.should.be.eql("a"); value4.should.be.eql("a"); value5.should.be.eql("a"); value6.should.be.eql("a"); }); webpack-3.5.6/test/cases/scope-hoisting/name-conflicts/module.js000066400000000000000000000000241315401342100246640ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/cases/scope-hoisting/reexport-cjs/000077500000000000000000000000001315401342100225705ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/reexport-cjs/a.js000066400000000000000000000000311315401342100233400ustar00rootroot00000000000000exports.named = "named"; webpack-3.5.6/test/cases/scope-hoisting/reexport-cjs/b.js000066400000000000000000000000351315401342100233450ustar00rootroot00000000000000export { named } from "./a"; webpack-3.5.6/test/cases/scope-hoisting/reexport-cjs/c.js000066400000000000000000000000351315401342100233460ustar00rootroot00000000000000export { named } from "./b"; webpack-3.5.6/test/cases/scope-hoisting/reexport-cjs/index.js000066400000000000000000000001631315401342100242350ustar00rootroot00000000000000import { named } from "./c"; it("should have the correct values", function() { named.should.be.eql("named"); }); webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-cjs/000077500000000000000000000000001315401342100242355ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-cjs/a.js000066400000000000000000000000311315401342100250050ustar00rootroot00000000000000exports.named = "named"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-cjs/b.js000066400000000000000000000000351315401342100250120ustar00rootroot00000000000000export { named } from "./a"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-cjs/c.js000066400000000000000000000000351315401342100250130ustar00rootroot00000000000000export { named } from "./b"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-cjs/index.js000066400000000000000000000001601315401342100256770ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { c.named.should.be.eql("named"); }); webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-default-cjs/000077500000000000000000000000001315401342100256575ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-default-cjs/a.js000066400000000000000000000000341315401342100264320ustar00rootroot00000000000000module.exports = "default"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-default-cjs/b.js000066400000000000000000000000371315401342100264360ustar00rootroot00000000000000export { default } from "./a"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-default-cjs/c.js000066400000000000000000000000371315401342100264370ustar00rootroot00000000000000export { default } from "./b"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-default-cjs/index.js000066400000000000000000000001641315401342100273250ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { c.default.should.be.eql("default"); }); webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-harmony/000077500000000000000000000000001315401342100251335ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-harmony/a.js000066400000000000000000000000341315401342100257060ustar00rootroot00000000000000export var named = "named"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-harmony/b.js000066400000000000000000000000251315401342100257070ustar00rootroot00000000000000export * from "./a"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-harmony/c.js000066400000000000000000000000351315401342100257110ustar00rootroot00000000000000export { named } from "./b"; webpack-3.5.6/test/cases/scope-hoisting/reexport-exposed-harmony/index.js000066400000000000000000000001601315401342100265750ustar00rootroot00000000000000var c = require("./c"); it("should have the correct values", function() { c.named.should.be.eql("named"); }); webpack-3.5.6/test/cases/scope-hoisting/renaming-4967/000077500000000000000000000000001315401342100223525ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/renaming-4967/file1.js000066400000000000000000000001741315401342100237120ustar00rootroot00000000000000export function a() { return "ok"; } export function test() { function file1_js_a() { return "fail"; } return a(); } webpack-3.5.6/test/cases/scope-hoisting/renaming-4967/index.js000066400000000000000000000003261315401342100240200ustar00rootroot00000000000000it("should check existing variables when renaming", function() { require("./module").d.x().should.be.eql("ok"); require("./module").c.a().should.be.eql("ok"); require("./module").test().should.be.eql("ok"); }); webpack-3.5.6/test/cases/scope-hoisting/renaming-4967/module.js000066400000000000000000000003451315401342100241770ustar00rootroot00000000000000import { 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-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/000077500000000000000000000000001315401342100243265ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/file1.js000066400000000000000000000000331315401342100256600ustar00rootroot00000000000000export var test = "test1"; webpack-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/file2.js000066400000000000000000000000541315401342100256640ustar00rootroot00000000000000var [ test ] = [ "test2" ]; export { test } webpack-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/file3.js000066400000000000000000000000621315401342100256640ustar00rootroot00000000000000var { test } = { test: "test3" }; export { test } webpack-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/file4.js000066400000000000000000000000761315401342100256720ustar00rootroot00000000000000var {o:[{ test }]} = {o:[{ test: "test4" }]}; export { test } webpack-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/index.js000066400000000000000000000006651315401342100260020ustar00rootroot00000000000000import m from "./module"; it("should apply shorthand properties correctly when renaming", function() { m.should.be.eql({ 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-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/module.js000066400000000000000000000006571315401342100261610ustar00rootroot00000000000000import { 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-3.5.6/test/cases/scope-hoisting/renaming-shorthand-5027/test.filter.js000066400000000000000000000010071315401342100271250ustar00rootroot00000000000000var 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-3.5.6/test/cases/scope-hoisting/require-root-5604/000077500000000000000000000000001315401342100231745ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/require-root-5604/index.js000066400000000000000000000003601315401342100246400ustar00rootroot00000000000000import value, { self as moduleSelf } from "./module"; export var self = require("./"); it("should have the correct values", function() { value.should.be.eql("default"); moduleSelf.should.be.eql(self); self.self.should.be.eql(self); }); webpack-3.5.6/test/cases/scope-hoisting/require-root-5604/module.js000066400000000000000000000000731315401342100250170ustar00rootroot00000000000000export default "default"; export var self = require("./"); webpack-3.5.6/test/cases/scope-hoisting/simple/000077500000000000000000000000001315401342100214345ustar00rootroot00000000000000webpack-3.5.6/test/cases/scope-hoisting/simple/index.js000066400000000000000000000002401315401342100230750ustar00rootroot00000000000000import value, { named } from "./module"; it("should have the correct values", function() { value.should.be.eql("default"); named.should.be.eql("named"); }); webpack-3.5.6/test/cases/scope-hoisting/simple/module.js000066400000000000000000000000661315401342100232610ustar00rootroot00000000000000export default "default"; export var named = "named"; webpack-3.5.6/test/checkArrayExpectation.js000066400000000000000000000027761315401342100207440ustar00rootroot00000000000000"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 UglifyJs/.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-3.5.6/test/compareLocations.test.js000066400000000000000000000075311315401342100207360ustar00rootroot00000000000000"use strict"; const should = require("should"); const compareLocations = require("../lib/compareLocations"); const createPosition = function(overides) { return Object.assign({ line: 10, column: 5 }, overides); }; const createLocation = function(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", () => compareLocations("alpha", "beta").should.be.exactly(-1)); it("returns 1 when the first string comes after the second string", () => compareLocations("beta", "alpha").should.be.exactly(1)); it("returns 0 when the first string is the same as the second string", () => compareLocations("charlie", "charlie").should.be.exactly(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", () => { return compareLocations(a, b).should.be.exactly(-1) }); it("returns 1 when the first location line number comes after the second location line number", () => compareLocations(b, a).should.be.exactly(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", () => compareLocations(a, b).should.be.exactly(-1)); it("returns 1 when the first location column number comes after the second location column number", () => compareLocations(b, a).should.be.exactly(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", () => compareLocations(a, b).should.be.exactly(-1)); it("returns 1 when the first location index number comes after the second location index number", () => compareLocations(b, a).should.be.exactly(1)); }); describe("same location", () => { beforeEach(() => { a = createLocation(); b = createLocation(); }); it("returns 0", () => { compareLocations(a, b).should.be.exactly(0); }); }); }); describe("string and object location comparison", () => { it("returns 1 when the first parameter is a string and the second parameter is an object", () => compareLocations("alpha", createLocation()).should.be.exactly(1)); it("returns -1 when the first parameter is an object and the second parameter is a string", () => compareLocations(createLocation(), "alpha").should.be.exactly(-1)); }); describe("unknown location type comparison", () => { it("returns 0 when the first parameter is an object and the second parameter is a number", () => compareLocations(createLocation(), 123).should.be.exactly(0)); it("returns undefined when the first parameter is a number and the second parameter is an object", () => should(compareLocations(123, createLocation())).be.undefined()); it("returns 0 when the first parameter is a string and the second parameter is a number", () => compareLocations("alpha", 123).should.be.exactly(0)); it("returns undefined when the first parameter is a number and the second parameter is a string", () => should(compareLocations(123, "alpha")).be.undefined()); it("returns undefined when both the first parameter and the second parameter is a number", () => should(compareLocations(123, 456)).be.undefined()); }); }); webpack-3.5.6/test/configCases/000077500000000000000000000000001315401342100163365ustar00rootroot00000000000000webpack-3.5.6/test/configCases/additional-pass/000077500000000000000000000000001315401342100214125ustar00rootroot00000000000000webpack-3.5.6/test/configCases/additional-pass/simple/000077500000000000000000000000001315401342100227035ustar00rootroot00000000000000webpack-3.5.6/test/configCases/additional-pass/simple/index.js000066400000000000000000000000631315401342100243470ustar00rootroot00000000000000it("should compile", function(done) { done(); }); webpack-3.5.6/test/configCases/additional-pass/simple/webpack.config.js000066400000000000000000000004241315401342100261210ustar00rootroot00000000000000var testPlugin = function() { var counter = 1; this.plugin("compilation", function(compilation) { var nr = counter++; compilation.plugin("need-additional-pass", function() { if(nr < 5) return true; }); }); }; module.exports = { plugins: [ testPlugin ] }; webpack-3.5.6/test/configCases/async-commons-chunk/000077500000000000000000000000001315401342100222325ustar00rootroot00000000000000webpack-3.5.6/test/configCases/async-commons-chunk/all-selected/000077500000000000000000000000001315401342100245705ustar00rootroot00000000000000webpack-3.5.6/test/configCases/async-commons-chunk/all-selected/a.js000066400000000000000000000000251315401342100253430ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/configCases/async-commons-chunk/all-selected/b.js000066400000000000000000000000251315401342100253440ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/configCases/async-commons-chunk/all-selected/c.js000066400000000000000000000000251315401342100253450ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/configCases/async-commons-chunk/all-selected/index.js000066400000000000000000000010461315401342100262360ustar00rootroot00000000000000it("should load the full async commons", function(done) { require.ensure(["./a"], function(require) { require("./a").should.be.eql("a"); done(); }); }); it("should load a chunk with async commons (AMD)", function(done) { require(["./a", "./b"], function(a, b) { a.should.be.eql("a"); b.should.be.eql("b"); done(); }); }); it("should load a chunk with async commons (require.ensure)", function(done) { require.ensure([], function(require) { require("./a").should.be.eql("a"); require("./c").should.be.eql("c"); done(); }); }); webpack-3.5.6/test/configCases/async-commons-chunk/all-selected/webpack.config.js000066400000000000000000000002151315401342100300040ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.CommonsChunkPlugin({ async: true }) ] }; webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/000077500000000000000000000000001315401342100242045ustar00rootroot00000000000000webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/a.js000066400000000000000000000000251315401342100247570ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/b.js000066400000000000000000000000251315401342100247600ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/c.js000066400000000000000000000000251315401342100247610ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/d.js000066400000000000000000000000251315401342100247620ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/e.js000066400000000000000000000000251315401342100247630ustar00rootroot00000000000000module.exports = "e";webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/index.js000066400000000000000000000016201315401342100256500ustar00rootroot00000000000000it("should load nested commons chunk", function(done) { var counter = 0; require.ensure(["./a"], function(require) { require("./a").should.be.eql("a"); require.ensure(["./c", "./d"], function(require) { require("./c").should.be.eql("c"); require("./d").should.be.eql("d"); if(++counter == 4) done(); }); require.ensure(["./c", "./e"], function(require) { require("./c").should.be.eql("c"); require("./e").should.be.eql("e"); if(++counter == 4) done(); }); }); require.ensure(["./b"], function(require) { require("./b").should.be.eql("b"); require.ensure(["./c", "./d"], function(require) { require("./c").should.be.eql("c"); require("./d").should.be.eql("d"); if(++counter == 4) done(); }); require.ensure(["./c", "./e"], function(require) { require("./c").should.be.eql("c"); require("./e").should.be.eql("e"); if(++counter == 4) done(); }); }); }); webpack-3.5.6/test/configCases/async-commons-chunk/duplicate/webpack.config.js000066400000000000000000000002151315401342100274200ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.CommonsChunkPlugin({ async: true }) ] }; webpack-3.5.6/test/configCases/async-commons-chunk/existing-name/000077500000000000000000000000001315401342100250025ustar00rootroot00000000000000webpack-3.5.6/test/configCases/async-commons-chunk/existing-name/a.js000066400000000000000000000000251315401342100255550ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/configCases/async-commons-chunk/existing-name/b.js000066400000000000000000000000251315401342100255560ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/configCases/async-commons-chunk/existing-name/c.js000066400000000000000000000000251315401342100255570ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/configCases/async-commons-chunk/existing-name/index.js000066400000000000000000000022411315401342100264460ustar00rootroot00000000000000require("should"); const sinon = require("sinon"); const chunkLoadingSpy = sinon.spy(__webpack_require__, "e"); it("should not have duplicate chunks in blocks", function(done) { // This split point should contain: a require.ensure([], function(require) { require("./a").should.be.eql("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) { require("./a").should.be.eql("a"); require("./b").should.be.eql("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) { require("./a").should.be.eql("a"); require("./b").should.be.eql("b"); require("./c").should.be.eql("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 chunkLoadingSpy.callCount.should.be.eql(6); chunkLoadingSpy.args.should.be.eql([["a"], ["a+b"], ["a"], ["a+b+c"], ["a+b"], ["a"]]); done(); }); webpack-3.5.6/test/configCases/async-commons-chunk/existing-name/webpack.config.js000066400000000000000000000004511315401342100302200ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.CommonsChunkPlugin({ chunks: ["a+b", "a+b+c"], async: "a+b", }), new webpack.optimize.CommonsChunkPlugin({ chunks: ["a", "a+b"], async: "a", }), new webpack.NamedChunksPlugin() ] }; webpack-3.5.6/test/configCases/async-commons-chunk/nested/000077500000000000000000000000001315401342100235145ustar00rootroot00000000000000webpack-3.5.6/test/configCases/async-commons-chunk/nested/a.js000066400000000000000000000000251315401342100242670ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/configCases/async-commons-chunk/nested/b.js000066400000000000000000000000251315401342100242700ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/configCases/async-commons-chunk/nested/c.js000066400000000000000000000000251315401342100242710ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/configCases/async-commons-chunk/nested/d.js000066400000000000000000000000251315401342100242720ustar00rootroot00000000000000module.exports = "d";webpack-3.5.6/test/configCases/async-commons-chunk/nested/index.js000066400000000000000000000011501315401342100251560ustar00rootroot00000000000000it("should load nested commons chunk", function(done) { require.ensure(["./a"], function(require) { require("./a").should.be.eql("a"); var counter = 0; require.ensure(["./b", "./c"], function(require) { require("./b").should.be.eql("b"); require("./c").should.be.eql("c"); if(++counter == 3) done(); }); require.ensure(["./b", "./d"], function(require) { require("./b").should.be.eql("b"); require("./d").should.be.eql("d"); if(++counter == 3) done(); }); require.ensure(["./b"], function(require) { require("./b").should.be.eql("b"); if(++counter == 3) done(); }); }); }); webpack-3.5.6/test/configCases/async-commons-chunk/nested/webpack.config.js000066400000000000000000000002151315401342100267300ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.CommonsChunkPlugin({ async: true }) ] }; webpack-3.5.6/test/configCases/async-commons-chunk/simple/000077500000000000000000000000001315401342100235235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/async-commons-chunk/simple/a.js000066400000000000000000000000251315401342100242760ustar00rootroot00000000000000module.exports = "a";webpack-3.5.6/test/configCases/async-commons-chunk/simple/b.js000066400000000000000000000000251315401342100242770ustar00rootroot00000000000000module.exports = "b";webpack-3.5.6/test/configCases/async-commons-chunk/simple/c.js000066400000000000000000000000251315401342100243000ustar00rootroot00000000000000module.exports = "c";webpack-3.5.6/test/configCases/async-commons-chunk/simple/index.js000066400000000000000000000010461315401342100251710ustar00rootroot00000000000000it("should load the full async commons", function(done) { require.ensure(["./a"], function(require) { require("./a").should.be.eql("a"); done(); }); }); it("should load a chunk with async commons (AMD)", function(done) { require(["./a", "./b"], function(a, b) { a.should.be.eql("a"); b.should.be.eql("b"); done(); }); }); it("should load a chunk with async commons (require.ensure)", function(done) { require.ensure([], function(require) { require("./a").should.be.eql("a"); require("./c").should.be.eql("c"); done(); }); }); webpack-3.5.6/test/configCases/async-commons-chunk/simple/webpack.config.js000066400000000000000000000002361315401342100267420ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: "main", async: true }) ] }; webpack-3.5.6/test/configCases/code-generation/000077500000000000000000000000001315401342100214015ustar00rootroot00000000000000webpack-3.5.6/test/configCases/code-generation/require-context-id/000077500000000000000000000000001315401342100251315ustar00rootroot00000000000000webpack-3.5.6/test/configCases/code-generation/require-context-id/folder/000077500000000000000000000000001315401342100264045ustar00rootroot00000000000000webpack-3.5.6/test/configCases/code-generation/require-context-id/folder/a.js000066400000000000000000000000261315401342100271600ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/configCases/code-generation/require-context-id/folder/b.js000066400000000000000000000000261315401342100271610ustar00rootroot00000000000000module.exports = "b"; webpack-3.5.6/test/configCases/code-generation/require-context-id/index.js000066400000000000000000000002701315401342100265750ustar00rootroot00000000000000it("should escape require.context id correctly", function() { var context = require.context("./folder"); context("./a").should.be.eql("a"); context.id.should.be.type("string"); }); webpack-3.5.6/test/configCases/code-generation/require-context-id/webpack.config.js000066400000000000000000000001621315401342100303460ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.HashedModuleIdsPlugin() ] }; webpack-3.5.6/test/configCases/code-generation/use-strict/000077500000000000000000000000001315401342100235035ustar00rootroot00000000000000webpack-3.5.6/test/configCases/code-generation/use-strict/harmony-with-strict.js000066400000000000000000000000421315401342100277710ustar00rootroot00000000000000"use strict"; export default "a"; webpack-3.5.6/test/configCases/code-generation/use-strict/harmony-with-strict2.js000066400000000000000000000001601315401342100300540ustar00rootroot00000000000000"use strict"; import * as a from "./harmony-without-strict2"; export default a; import "./harmony-with-strict3" webpack-3.5.6/test/configCases/code-generation/use-strict/harmony-with-strict3.js000066400000000000000000000000421315401342100300540ustar00rootroot00000000000000"use strict"; export default "a"; webpack-3.5.6/test/configCases/code-generation/use-strict/harmony-without-strict.js000066400000000000000000000000241315401342100305210ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/configCases/code-generation/use-strict/harmony-without-strict2.js000066400000000000000000000000241315401342100306030ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/configCases/code-generation/use-strict/index.js000066400000000000000000000016771315401342100251630ustar00rootroot00000000000000"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.should.be.eql([ "it(\"should include only one use strict per module\", function() {", "Object.defineProperty(__webpack_exports__, \"__esModule\", { value: true });", "Object.defineProperty(__webpack_exports__, \"__esModule\", { value: true });", "Object.defineProperty(__webpack_exports__, \"__esModule\", { value: true });", "Object.defineProperty(__webpack_exports__, \"__esModule\", { value: true });", "/* unused harmony default export */ var _unused_webpack_default_export = (\"a\");", ]); }); webpack-3.5.6/test/configCases/code-generation/use-strict/webpack.config.js000066400000000000000000000001121315401342100267130ustar00rootroot00000000000000module.exports = { node: { __dirname: false, __filename: false } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/000077500000000000000000000000001315401342100224135ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/extract-async-from-entry/000077500000000000000000000000001315401342100273005ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/extract-async-from-entry/index.js000066400000000000000000000001011315401342100307350ustar00rootroot00000000000000require("should"); it("should run successful", function() { }); webpack-3.5.6/test/configCases/commons-chunk-plugin/extract-async-from-entry/test.config.js000066400000000000000000000001601315401342100320560ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./manifest.js", "./main.js" ]; } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/extract-async-from-entry/webpack.config.js000066400000000000000000000005621315401342100325210ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { main: "./index", second: "./index" }, target: "web", output: { filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ minChunks: Infinity, name: "manifest" }), new CommonsChunkPlugin({ async: "async", minChunks: 2 }) ] }; webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/000077500000000000000000000000001315401342100243355ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/common.js000066400000000000000000000000331315401342100261570ustar00rootroot00000000000000module.exports = "common"; webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/first.js000066400000000000000000000003431315401342100260220ustar00rootroot00000000000000require("should"); require("./common"); it("should have the correct main flag for multi first module", function() { var multiModule = __webpack_require__.c[module.parents[0]]; multiModule.hot._main.should.be.eql(true); }); webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/second.js000066400000000000000000000003441315401342100261470ustar00rootroot00000000000000require("should"); require("./common"); it("should have the correct main flag for multi second module", function() { var multiModule = __webpack_require__.c[module.parents[0]]; multiModule.hot._main.should.be.eql(true); }); webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/shared.js000066400000000000000000000000331315401342100261350ustar00rootroot00000000000000module.exports = "shared"; webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/test.config.js000066400000000000000000000002001315401342100271060ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./first.js", "./second.js" ] } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/vendor.js000066400000000000000000000003541315401342100261720ustar00rootroot00000000000000require("./common"); module.exports = "vendor"; it("should have the correct main flag for multi vendor module", function() { var multiModule = __webpack_require__.c[module.parents[0]]; multiModule.hot._main.should.be.eql(true); }); webpack-3.5.6/test/configCases/commons-chunk-plugin/hot-multi/webpack.config.js000066400000000000000000000007061315401342100275560ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../../../lib/optimize/CommonsChunkPlugin"); var HotModuleReplacementPlugin = require("../../../../lib/HotModuleReplacementPlugin"); module.exports = { entry: { vendor: ["./vendor"], first: ["./shared", "./first"], second: ["./shared", "./second"] }, target: "web", output: { filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ name: "vendor" }), new HotModuleReplacementPlugin() ] }; webpack-3.5.6/test/configCases/commons-chunk-plugin/hot/000077500000000000000000000000001315401342100232055ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/hot/index.js000066400000000000000000000003751315401342100246570ustar00rootroot00000000000000require("should"); it("should have the correct main flag", function() { var a = require("./vendor"); a._main.should.be.eql(false); module.hot._main.should.be.eql(true); }); it("should be main", function() { require.main.should.be.eql(module); }); webpack-3.5.6/test/configCases/commons-chunk-plugin/hot/test.config.js000066400000000000000000000001551315401342100257670ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./main.js" ] } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/hot/vendor.js000066400000000000000000000000351315401342100250360ustar00rootroot00000000000000module.exports = module.hot; webpack-3.5.6/test/configCases/commons-chunk-plugin/hot/webpack.config.js000066400000000000000000000006231315401342100264240ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../../../lib/optimize/CommonsChunkPlugin"); var HotModuleReplacementPlugin = require("../../../../lib/HotModuleReplacementPlugin"); module.exports = { entry: { vendor: ["./vendor"], main: "./index" }, target: "web", output: { filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ name: "vendor" }), new HotModuleReplacementPlugin() ] }; webpack-3.5.6/test/configCases/commons-chunk-plugin/library/000077500000000000000000000000001315401342100240575ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/library/a.js000066400000000000000000000003171315401342100246360ustar00rootroot00000000000000var 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-3.5.6/test/configCases/commons-chunk-plugin/library/index.js000066400000000000000000000005511315401342100255250ustar00rootroot00000000000000require("should"); require.include("external1"); require.ensure([], function() { require.include("external2"); }) it("should have externals in vendor file", function() { var a = require("./a"); a.vendor.should.containEql("require(\"external0\")"); a.main.should.containEql("require(\"external1\")"); a.main.should.containEql("require(\"external2\")"); });webpack-3.5.6/test/configCases/commons-chunk-plugin/library/test.config.js000066400000000000000000000003151315401342100266370ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./main.js" ] }, modules: { "external0": "module 0", "external1": "module 1", "external2": "module 2" } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/library/webpack.config.js000066400000000000000000000006571315401342100273050ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { vendor: ["external0", "./a"], main: "./index" }, target: "web", output: { filename: "[name].js", libraryTarget: "umd" }, externals: ["external0", "external1", "external2", "fs", "path"], plugins: [ new CommonsChunkPlugin({ name: "vendor" }) ], node: { __filename: false, __dirname: false } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/move-entry/000077500000000000000000000000001315401342100245205ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/move-entry/a.js000066400000000000000000000000261315401342100252740ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/configCases/commons-chunk-plugin/move-entry/index.js000066400000000000000000000001701315401342100261630ustar00rootroot00000000000000require("should"); it("should not be moved", function() { new Error().stack.should.not.match(/webpackBootstrap/); }); webpack-3.5.6/test/configCases/commons-chunk-plugin/move-entry/test.config.js000066400000000000000000000001561315401342100273030ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./commons.js", "./main.js" ] } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/move-entry/webpack.config.js000066400000000000000000000004251315401342100277370ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { main: "./index", second: "./index" }, target: "web", output: { filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ name: "commons" }) ] }; webpack-3.5.6/test/configCases/commons-chunk-plugin/move-to-parent/000077500000000000000000000000001315401342100252705ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/move-to-parent/a.js000066400000000000000000000000241315401342100260420ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/configCases/commons-chunk-plugin/move-to-parent/index.js000066400000000000000000000002471315401342100267400ustar00rootroot00000000000000import "should"; it("should load a moved module", function(done) { import("./a") .then(a => { a.default.should.be.eql("a"); done(); }) .catch(done); }); webpack-3.5.6/test/configCases/commons-chunk-plugin/move-to-parent/webpack.config.js000066400000000000000000000004471315401342100305130ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { bundle0: "./index" }, target: "web", output: { filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ name: "bundle0", children: true, minChunks: 1 }) ] }; webpack-3.5.6/test/configCases/commons-chunk-plugin/simple/000077500000000000000000000000001315401342100237045ustar00rootroot00000000000000webpack-3.5.6/test/configCases/commons-chunk-plugin/simple/a.js000066400000000000000000000000261315401342100244600ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/configCases/commons-chunk-plugin/simple/index.js000066400000000000000000000002611315401342100253500ustar00rootroot00000000000000require("should"); it("should run", function() { var a = require("./a"); a.should.be.eql("a"); }); it("should be main", function() { require.main.should.be.eql(module); });webpack-3.5.6/test/configCases/commons-chunk-plugin/simple/test.config.js000066400000000000000000000001551315401342100264660ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./vendor.js", "./main.js" ] } }; webpack-3.5.6/test/configCases/commons-chunk-plugin/simple/webpack.config.js000066400000000000000000000004221315401342100271200ustar00rootroot00000000000000var CommonsChunkPlugin = require("../../../../lib/optimize/CommonsChunkPlugin"); module.exports = { entry: { vendor: ["./a"], main: "./index" }, target: "web", output: { filename: "[name].js" }, plugins: [ new CommonsChunkPlugin({ name: "vendor" }) ] }; webpack-3.5.6/test/configCases/compiletime/000077500000000000000000000000001315401342100206455ustar00rootroot00000000000000webpack-3.5.6/test/configCases/compiletime/error-not-found/000077500000000000000000000000001315401342100237055ustar00rootroot00000000000000webpack-3.5.6/test/configCases/compiletime/error-not-found/errors.js000066400000000000000000000000441315401342100255550ustar00rootroot00000000000000module.exports = [ /not found/ ]; webpack-3.5.6/test/configCases/compiletime/error-not-found/index.js000066400000000000000000000002501315401342100253470ustar00rootroot00000000000000import { NotHere } from './stub' it('should do nothing', function() { if (typeof NotHere !== 'undefined') { throw new Error('This shouldn\'t be here!'); } }); webpack-3.5.6/test/configCases/compiletime/error-not-found/stub.js000066400000000000000000000000461315401342100252200ustar00rootroot00000000000000const foo = 'bar' export default foo webpack-3.5.6/test/configCases/compiletime/error-not-found/webpack.config.js000066400000000000000000000001011315401342100271130ustar00rootroot00000000000000module.exports = { module: { strictExportPresence: true } }; webpack-3.5.6/test/configCases/compiletime/warn-not-found/000077500000000000000000000000001315401342100235235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/compiletime/warn-not-found/index.js000066400000000000000000000002501315401342100251650ustar00rootroot00000000000000import { NotHere } from './stub' it('should do nothing', function() { if (typeof NotHere !== 'undefined') { throw new Error('This shouldn\'t be here!'); } }); webpack-3.5.6/test/configCases/compiletime/warn-not-found/stub.js000066400000000000000000000000461315401342100250360ustar00rootroot00000000000000const foo = 'bar' export default foo webpack-3.5.6/test/configCases/compiletime/warn-not-found/warnings.js000066400000000000000000000000441315401342100257070ustar00rootroot00000000000000module.exports = [ /not found/ ]; webpack-3.5.6/test/configCases/compiletime/warn-not-found/webpack.config.js000066400000000000000000000000001315401342100267270ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/000077500000000000000000000000001315401342100223175ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/System.import/000077500000000000000000000000001315401342100251145ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/System.import/index.js000066400000000000000000000002371315401342100265630ustar00rootroot00000000000000it("should replace a async context with a manual map", function(done) { var a = "a"; import(a).then(function(a) { a.should.be.eql("b"); done(); }); }); webpack-3.5.6/test/configCases/context-replacement/System.import/modules/000077500000000000000000000000001315401342100265645ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/System.import/modules/module-b.js000066400000000000000000000000261315401342100306240ustar00rootroot00000000000000module.exports = "b"; webpack-3.5.6/test/configCases/context-replacement/System.import/webpack.config.js000066400000000000000000000003471315401342100303360ustar00rootroot00000000000000var path = require("path"); var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.ContextReplacementPlugin(/context-replacement/, path.resolve(__dirname, "modules"), { "a": "./module-b" }) ] }; webpack-3.5.6/test/configCases/context-replacement/a/000077500000000000000000000000001315401342100225375ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/a/index.js000066400000000000000000000003741315401342100242100ustar00rootroot00000000000000it("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) { r.should.be.eql("ok"); done(); }); });webpack-3.5.6/test/configCases/context-replacement/a/new-context/000077500000000000000000000000001315401342100250125ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/a/new-context/node_modules/000077500000000000000000000000001315401342100274675ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/a/new-context/node_modules/error.js000066400000000000000000000000421315401342100311520ustar00rootroot00000000000000This should result in an error }])webpack-3.5.6/test/configCases/context-replacement/a/new-context/node_modules/replaced.js000066400000000000000000000000261315401342100316020ustar00rootroot00000000000000module.exports = "ok";webpack-3.5.6/test/configCases/context-replacement/a/webpack.config.js000066400000000000000000000002611315401342100257540ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.ContextReplacementPlugin(/context-replacement.a$/, "new-context", true, /^replaced$/) ] }; webpack-3.5.6/test/configCases/context-replacement/b/000077500000000000000000000000001315401342100225405ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/b/error.js000066400000000000000000000000421315401342100242230ustar00rootroot00000000000000This should result in an error }])webpack-3.5.6/test/configCases/context-replacement/b/index.js000066400000000000000000000002451315401342100242060ustar00rootroot00000000000000it("should replace a context with a new regExp", function() { function rqInContext(x) { return require(x); } rqInContext("./only-this").should.be.eql("ok"); });webpack-3.5.6/test/configCases/context-replacement/b/only-this.js000066400000000000000000000000261315401342100250220ustar00rootroot00000000000000module.exports = "ok";webpack-3.5.6/test/configCases/context-replacement/b/webpack.config.js000066400000000000000000000002331315401342100257540ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.ContextReplacementPlugin(/context-replacement.b$/, /^\.\/only/) ] }; webpack-3.5.6/test/configCases/context-replacement/c/000077500000000000000000000000001315401342100225415ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/c/index.js000066400000000000000000000005641315401342100242130ustar00rootroot00000000000000it("should replace a context with a manual map", function() { function rqInContext(x) { return require(x); } rqInContext("a").should.be.eql("a"); rqInContext("b").should.be.eql("b"); rqInContext("./c").should.be.eql("b"); rqInContext("d").should.be.eql("d"); rqInContext("./d").should.be.eql("d"); (function() { rqInContext("module-b") }.should.throw()); }); webpack-3.5.6/test/configCases/context-replacement/c/modules/000077500000000000000000000000001315401342100242115ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/c/modules/a.js000066400000000000000000000000261315401342100247650ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/configCases/context-replacement/c/modules/module-b.js000066400000000000000000000000261315401342100262510ustar00rootroot00000000000000module.exports = "b"; webpack-3.5.6/test/configCases/context-replacement/c/node_modules/000077500000000000000000000000001315401342100252165ustar00rootroot00000000000000webpack-3.5.6/test/configCases/context-replacement/c/node_modules/d.js000066400000000000000000000000261315401342100257750ustar00rootroot00000000000000module.exports = "d"; webpack-3.5.6/test/configCases/context-replacement/c/webpack.config.js000066400000000000000000000004551315401342100257630ustar00rootroot00000000000000var 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-3.5.6/test/configCases/defaulter/000077500000000000000000000000001315401342100203115ustar00rootroot00000000000000webpack-3.5.6/test/configCases/defaulter/immutable-config/000077500000000000000000000000001315401342100235335ustar00rootroot00000000000000webpack-3.5.6/test/configCases/defaulter/immutable-config/index.js000066400000000000000000000000701315401342100251750ustar00rootroot00000000000000it("should compile and run the test", function() { }); webpack-3.5.6/test/configCases/defaulter/immutable-config/webpack.config.js000066400000000000000000000001521315401342100267470ustar00rootroot00000000000000module.exports = { resolve: Object.freeze({}) // this fails to compile when the object is not cloned }; webpack-3.5.6/test/configCases/delegated-hash/000077500000000000000000000000001315401342100211755ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/000077500000000000000000000000001315401342100224665ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/a.js000066400000000000000000000000001315401342100232320ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/b.js000066400000000000000000000000001315401342100232330ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/bundle.js000066400000000000000000000001021315401342100242660ustar00rootroot00000000000000module.exports = function(req) { return ["a", "b", "c"][req]; }; webpack-3.5.6/test/configCases/delegated-hash/simple/bundle2.js000066400000000000000000000000541315401342100243560ustar00rootroot00000000000000module.exports = ["a", "b", "c", "d", "e"]; webpack-3.5.6/test/configCases/delegated-hash/simple/d.js000066400000000000000000000000001315401342100232350ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/dir/000077500000000000000000000000001315401342100232445ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/dir/c.js000066400000000000000000000000001315401342100240120ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/e.js000066400000000000000000000000001315401342100232360ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/index.js000066400000000000000000000003641315401342100241360ustar00rootroot00000000000000it("should delegate the modules", function() { require("./a").should.be.eql("a"); require("./loader!./b").should.be.eql("b"); require("./dir/c").should.be.eql("c"); require("./d").should.be.eql("d"); require("./e").should.be.eql("e"); }); webpack-3.5.6/test/configCases/delegated-hash/simple/loader.js000066400000000000000000000000001315401342100242600ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated-hash/simple/webpack.config.js000066400000000000000000000011041315401342100257000ustar00rootroot00000000000000var 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-3.5.6/test/configCases/delegated/000077500000000000000000000000001315401342100202545ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated/simple/000077500000000000000000000000001315401342100215455ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated/simple/a.js000066400000000000000000000000001315401342100223110ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated/simple/b.js000066400000000000000000000000001315401342100223120ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated/simple/bundle.js000066400000000000000000000001001315401342100233430ustar00rootroot00000000000000module.exports = function(req) { return ["a", "b", "c"][req]; }webpack-3.5.6/test/configCases/delegated/simple/dir/000077500000000000000000000000001315401342100223235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated/simple/dir/c.js000066400000000000000000000000001315401342100230710ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated/simple/index.js000066400000000000000000000002541315401342100232130ustar00rootroot00000000000000it("should delegate the modules", function() { require("./a").should.be.eql("a"); require("./loader!./b").should.be.eql("b"); require("./dir/c").should.be.eql("c"); }); webpack-3.5.6/test/configCases/delegated/simple/loader.js000066400000000000000000000000001315401342100233370ustar00rootroot00000000000000webpack-3.5.6/test/configCases/delegated/simple/webpack.config.js000066400000000000000000000004631315401342100247660ustar00rootroot00000000000000var 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-3.5.6/test/configCases/devtools/000077500000000000000000000000001315401342100201755ustar00rootroot00000000000000webpack-3.5.6/test/configCases/devtools/harmony-eval-source-map/000077500000000000000000000000001315401342100246505ustar00rootroot00000000000000webpack-3.5.6/test/configCases/devtools/harmony-eval-source-map/index.js000066400000000000000000000000601315401342100263110ustar00rootroot00000000000000export {} it("should run fine", function() {}); webpack-3.5.6/test/configCases/devtools/harmony-eval-source-map/webpack.config.js000066400000000000000000000000621315401342100300640ustar00rootroot00000000000000module.exports = { devtool: "eval-source-map" }; webpack-3.5.6/test/configCases/devtools/harmony-eval/000077500000000000000000000000001315401342100225775ustar00rootroot00000000000000webpack-3.5.6/test/configCases/devtools/harmony-eval/index.js000066400000000000000000000000601315401342100242400ustar00rootroot00000000000000export {} it("should run fine", function() {}); webpack-3.5.6/test/configCases/devtools/harmony-eval/webpack.config.js000066400000000000000000000000471315401342100260160ustar00rootroot00000000000000module.exports = { devtool: "eval" }; webpack-3.5.6/test/configCases/dll-plugin/000077500000000000000000000000001315401342100204055ustar00rootroot00000000000000webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/000077500000000000000000000000001315401342100225565ustar00rootroot00000000000000webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/_d.js000066400000000000000000000000151315401342100234720ustar00rootroot00000000000000import "./d";webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/_e.js000066400000000000000000000000531315401342100234750ustar00rootroot00000000000000import "./e1"; import "./e2"; import "./e";webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/a.js000066400000000000000000000000261315401342100233320ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/b.js000066400000000000000000000000671315401342100233400ustar00rootroot00000000000000module.exports = function() { return import("./c"); } webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/c.js000066400000000000000000000000231315401342100233310ustar00rootroot00000000000000export default "c";webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/d.js000066400000000000000000000000231315401342100233320ustar00rootroot00000000000000export default "d";webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/e.js000066400000000000000000000000551315401342100233400ustar00rootroot00000000000000export * from "./e1"; export * from "./ee2"; webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/e1.js000066400000000000000000000000271315401342100234200ustar00rootroot00000000000000export * from "./ee1"; webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/e2.js000066400000000000000000000000271315401342100234210ustar00rootroot00000000000000export * from "./ee2"; webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/ee1.js000066400000000000000000000000511315401342100235620ustar00rootroot00000000000000export var x1 = 123; export var y1 = 456;webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/ee2.js000066400000000000000000000000511315401342100235630ustar00rootroot00000000000000export var x2 = 123; export var y2 = 456;webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/f.jsx000066400000000000000000000000251315401342100235260ustar00rootroot00000000000000module.exports = 'f';webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/g-loader.js000066400000000000000000000000671315401342100246110ustar00rootroot00000000000000module.exports = function(source) { return source; }; webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/g.abc.js000066400000000000000000000000431315401342100240630ustar00rootroot00000000000000module.exports = typeof module.id; webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/test.config.js000066400000000000000000000000301315401342100253300ustar00rootroot00000000000000exports.noTests = true; webpack-3.5.6/test/configCases/dll-plugin/0-create-dll/webpack.config.js000066400000000000000000000010421315401342100257710ustar00rootroot00000000000000var 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-3.5.6/test/configCases/dll-plugin/1-use-dll/000077500000000000000000000000001315401342100221105ustar00rootroot00000000000000webpack-3.5.6/test/configCases/dll-plugin/1-use-dll/e.js000066400000000000000000000000601315401342100226660ustar00rootroot00000000000000export * from "dll/e1"; export * from "dll/e2"; webpack-3.5.6/test/configCases/dll-plugin/1-use-dll/index.js000066400000000000000000000023301315401342100235530ustar00rootroot00000000000000var should = require("should"); import d from "dll/d"; import { x1, y2 } from "./e"; import { x2, y1 } from "dll/e"; it("should load a module from dll", function() { require("dll/a").should.be.eql("a"); }); it("should load a module of non-default type without extension from dll", function() { require("dll/f").should.be.eql("f"); }); it("should load an async module from dll", function(done) { require("dll/b")().then(function(c) { c.should.be.eql({ default: "c" }); done(); }).catch(done); }); it("should load an harmony module from dll (default export)", function() { d.should.be.eql("d"); }); it("should load an harmony module from dll (star export)", function() { x1.should.be.eql(123); x2.should.be.eql(123); y1.should.be.eql(456); y2.should.be.eql(456); }); it("should load a module with loader applied", function() { require("dll/g.abc.js").should.be.eql("number"); }); it("should give modules the correct ids", function() { Object.keys(__webpack_modules__).filter(m => !m.startsWith("../..")).should.be.eql([ "./e.js", "./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-3.5.6/test/configCases/dll-plugin/1-use-dll/webpack.config.js000066400000000000000000000005751315401342100253350ustar00rootroot00000000000000var 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-3.5.6/test/configCases/dll-plugin/2-use-dll-without-scope/000077500000000000000000000000001315401342100247215ustar00rootroot00000000000000webpack-3.5.6/test/configCases/dll-plugin/2-use-dll-without-scope/e.js000066400000000000000000000001101315401342100254730ustar00rootroot00000000000000export * from "../0-create-dll/e1"; export * from "../0-create-dll/e2"; webpack-3.5.6/test/configCases/dll-plugin/2-use-dll-without-scope/index.js000066400000000000000000000026001315401342100263640ustar00rootroot00000000000000var should = require("should"); import 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() { require("../0-create-dll/a").should.be.eql("a"); }); it("should load a module of non-default type without extension from dll", function() { require("../0-create-dll/f").should.be.eql("f"); }); it("should load an async module from dll", function(done) { require("../0-create-dll/b")().then(function(c) { c.should.be.eql({ default: "c" }); done(); }).catch(done); }); it("should load an harmony module from dll (default export)", function() { d.should.be.eql("d"); }); it("should load an harmony module from dll (star export)", function() { x1.should.be.eql(123); x2.should.be.eql(123); y1.should.be.eql(456); y2.should.be.eql(456); }); it("should load a module with loader applied", function() { require("../0-create-dll/g.abc.js").should.be.eql("number"); }); it("should give modules the correct ids", function() { Object.keys(__webpack_modules__).filter(m => !m.startsWith("../..")).should.be.eql([ "../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", "./e.js", "./index.js", "dll-reference ../0-create-dll/dll.js" ]); }); webpack-3.5.6/test/configCases/dll-plugin/2-use-dll-without-scope/webpack.config.js000066400000000000000000000011671315401342100301440ustar00rootroot00000000000000var 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-3.5.6/test/configCases/dll-plugin/3-use-dll-with-hashid/000077500000000000000000000000001315401342100243215ustar00rootroot00000000000000webpack-3.5.6/test/configCases/dll-plugin/3-use-dll-with-hashid/e.js000066400000000000000000000001101315401342100250730ustar00rootroot00000000000000export * from "../0-create-dll/e1"; export * from "../0-create-dll/e2"; webpack-3.5.6/test/configCases/dll-plugin/3-use-dll-with-hashid/e1.js000066400000000000000000000000601315401342100251600ustar00rootroot00000000000000export * from "dll/e1"; export * from "dll/e2"; webpack-3.5.6/test/configCases/dll-plugin/3-use-dll-with-hashid/index.js000066400000000000000000000014761315401342100257760ustar00rootroot00000000000000var should = require("should"); import 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() { require("../0-create-dll/a").should.be.eql("a"); }); it("should load an async module from dll", function(done) { require("../0-create-dll/b")().then(function(c) { c.should.be.eql({ default: "c" }); done(); }).catch(done); }); it("should load an harmony module from dll (default export)", function() { d.should.be.eql("d"); }); it("should load an harmony module from dll (star export)", function() { x1.should.be.eql(123); x2.should.be.eql(123); y1.should.be.eql(456); y2.should.be.eql(456); }); it("should load a module with loader applied", function() { require("../0-create-dll/g.abc.js").should.be.eql("number"); }); webpack-3.5.6/test/configCases/dll-plugin/3-use-dll-with-hashid/webpack.config.js000066400000000000000000000011151315401342100275350ustar00rootroot00000000000000var 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-3.5.6/test/configCases/entry/000077500000000000000000000000001315401342100174775ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/function-promise/000077500000000000000000000000001315401342100230005ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/function-promise/a.js000066400000000000000000000000551315401342100235560ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-3.5.6/test/configCases/entry/function-promise/b.js000066400000000000000000000000551315401342100235570ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-3.5.6/test/configCases/entry/function-promise/test.config.js000066400000000000000000000001331315401342100255560ustar00rootroot00000000000000module.exports = { findBundle: function() { return [ "./a.js", "./b.js" ] } }; webpack-3.5.6/test/configCases/entry/function-promise/webpack.config.js000066400000000000000000000002071315401342100262150ustar00rootroot00000000000000module.exports = { entry() { return Promise.resolve({ a: "./a", b: ["./b"] }); }, output: { filename: "[name].js" } }; webpack-3.5.6/test/configCases/entry/function/000077500000000000000000000000001315401342100213245ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/function/a.js000066400000000000000000000000551315401342100221020ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-3.5.6/test/configCases/entry/function/b.js000066400000000000000000000000551315401342100221030ustar00rootroot00000000000000it("should compile", (done) => { done() }); webpack-3.5.6/test/configCases/entry/function/test.config.js000066400000000000000000000001331315401342100241020ustar00rootroot00000000000000module.exports = { findBundle: function() { return [ "./a.js", "./b.js" ] } }; webpack-3.5.6/test/configCases/entry/function/webpack.config.js000066400000000000000000000001661315401342100245450ustar00rootroot00000000000000module.exports = { entry() { return { a: "./a", b: ["./b"] }; }, output: { filename: "[name].js" } }; webpack-3.5.6/test/configCases/entry/issue-1068/000077500000000000000000000000001315401342100212235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/issue-1068/a.js000066400000000000000000000000261315401342100217770ustar00rootroot00000000000000global.order = ["a"]; webpack-3.5.6/test/configCases/entry/issue-1068/b.js000066400000000000000000000000301315401342100217730ustar00rootroot00000000000000global.order.push("b"); webpack-3.5.6/test/configCases/entry/issue-1068/c.js000066400000000000000000000000301315401342100217740ustar00rootroot00000000000000global.order.push("c"); webpack-3.5.6/test/configCases/entry/issue-1068/d.js000066400000000000000000000000301315401342100217750ustar00rootroot00000000000000global.order.push("d"); webpack-3.5.6/test/configCases/entry/issue-1068/e.js000066400000000000000000000000301315401342100217760ustar00rootroot00000000000000global.order.push("e"); webpack-3.5.6/test/configCases/entry/issue-1068/f.js000066400000000000000000000000301315401342100217770ustar00rootroot00000000000000global.order.push("f"); webpack-3.5.6/test/configCases/entry/issue-1068/g.js000066400000000000000000000000301315401342100220000ustar00rootroot00000000000000global.order.push("g"); webpack-3.5.6/test/configCases/entry/issue-1068/h.js000066400000000000000000000000301315401342100220010ustar00rootroot00000000000000global.order.push("h"); webpack-3.5.6/test/configCases/entry/issue-1068/i.js000066400000000000000000000000301315401342100220020ustar00rootroot00000000000000global.order.push("i"); webpack-3.5.6/test/configCases/entry/issue-1068/j.js000066400000000000000000000000301315401342100220030ustar00rootroot00000000000000global.order.push("j"); webpack-3.5.6/test/configCases/entry/issue-1068/k.js000066400000000000000000000000301315401342100220040ustar00rootroot00000000000000global.order.push("k"); webpack-3.5.6/test/configCases/entry/issue-1068/test.js000066400000000000000000000003321315401342100225360ustar00rootroot00000000000000var order = global.order; delete global.order; it("should run the modules in the correct order", function() { order.should.be.eql([ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" ]); }); webpack-3.5.6/test/configCases/entry/issue-1068/webpack.config.js000066400000000000000000000002211315401342100244340ustar00rootroot00000000000000module.exports = { entry: [ "./a", "./b", "./c", "./d", "./e", "./f", "./g", "./h", "./i", "./j", "./k", "./test" ] }; webpack-3.5.6/test/configCases/entry/require-entry-point/000077500000000000000000000000001315401342100234415ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/require-entry-point/entry-point.js000066400000000000000000000000001315401342100262550ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/require-entry-point/entry-point2.js000066400000000000000000000000001315401342100263370ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/require-entry-point/require-entry-point.js000066400000000000000000000002221315401342100277350ustar00rootroot00000000000000it("should require entry points fine", function() { require("./require-entry-point"); require("./entry-point"); require("./entry-point2"); }); webpack-3.5.6/test/configCases/entry/require-entry-point/webpack.config.js000066400000000000000000000002341315401342100266560ustar00rootroot00000000000000module.exports = { entry: { bundle0: "./require-entry-point", a: "./entry-point", b: ["./entry-point2"] }, output: { filename: "[name].js" } }; webpack-3.5.6/test/configCases/entry/single-entry-point/000077500000000000000000000000001315401342100232465ustar00rootroot00000000000000webpack-3.5.6/test/configCases/entry/single-entry-point/single-entry-point.js000066400000000000000000000001321315401342100273470ustar00rootroot00000000000000it("should require entry points fine", function() { require("./single-entry-point"); }); webpack-3.5.6/test/configCases/entry/single-entry-point/webpack.config.js000066400000000000000000000000651315401342100264650ustar00rootroot00000000000000module.exports = { entry: "./single-entry-point" }; webpack-3.5.6/test/configCases/errors/000077500000000000000000000000001315401342100176525ustar00rootroot00000000000000webpack-3.5.6/test/configCases/errors/entry-not-found/000077500000000000000000000000001315401342100227225ustar00rootroot00000000000000webpack-3.5.6/test/configCases/errors/entry-not-found/errors.js000066400000000000000000000001021315401342100245650ustar00rootroot00000000000000module.exports = [ [/^Entry module not found/, /.\/index\.js/] ];webpack-3.5.6/test/configCases/errors/entry-not-found/webpack.config.js000066400000000000000000000000251315401342100261350ustar00rootroot00000000000000module.exports = {}; webpack-3.5.6/test/configCases/externals/000077500000000000000000000000001315401342100203435ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/externals-in-chunk/000077500000000000000000000000001315401342100240625ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/externals-in-chunk/chunk.js000066400000000000000000000001011315401342100255200ustar00rootroot00000000000000exports.a = require("external"); exports.b = import("./chunk2"); webpack-3.5.6/test/configCases/externals/externals-in-chunk/chunk2.js000066400000000000000000000000461315401342100256120ustar00rootroot00000000000000module.exports = require("external2");webpack-3.5.6/test/configCases/externals/externals-in-chunk/index.js000066400000000000000000000007741315401342100255370ustar00rootroot00000000000000it("should move externals in chunks into entry chunk", function(done) { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); source.should.containEql("1+" + (1+1)); source.should.containEql("3+" + (2+2)); source.should.containEql("5+" + (3+3)); import("./chunk").then(function(chunk) { chunk.a.should.be.eql(3); chunk.b.then(function(chunk2) { chunk2.should.be.eql(7); import("external3").then(function(ex) { ex.should.be.eql(11); done(); }); }); }); }); webpack-3.5.6/test/configCases/externals/externals-in-chunk/webpack.config.js000066400000000000000000000002261315401342100273000ustar00rootroot00000000000000module.exports = { externals: { external: "1+2", external2: "3+4", external3: "5+6" }, node: { __dirname: false, __filename: false } }; webpack-3.5.6/test/configCases/externals/externals-in-commons-chunk/000077500000000000000000000000001315401342100255335ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/externals-in-commons-chunk/index.js000066400000000000000000000012331315401342100271770ustar00rootroot00000000000000it("should not move externals into the commons chunk", function() { require("should"); 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"); source1.should.containEql("1+" + (1+1)); source1.should.containEql("3+" + (2+2)); source2.should.containEql("1+" + (1+1)); source2.should.containEql("5+" + (3+3)); source3.should.not.containEql("1+" + (1+1)); source3.should.not.containEql("3+" + (2+2)); source3.should.not.containEql("5+" + (3+3)); require("external"); require("external2"); }); webpack-3.5.6/test/configCases/externals/externals-in-commons-chunk/other.js000066400000000000000000000000531315401342100272100ustar00rootroot00000000000000require("external"); require("external3"); webpack-3.5.6/test/configCases/externals/externals-in-commons-chunk/test.config.js000066400000000000000000000001551315401342100303150ustar00rootroot00000000000000module.exports = { findBundle: function(i, options) { return [ "./common.js", "./main.js" ] } }; webpack-3.5.6/test/configCases/externals/externals-in-commons-chunk/webpack.config.js000066400000000000000000000006201315401342100307470ustar00rootroot00000000000000var webpack = require("../../../../"); module.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 }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: "common" }) ] }; webpack-3.5.6/test/configCases/externals/harmony/000077500000000000000000000000001315401342100220205ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/harmony/index.js000066400000000000000000000001741315401342100234670ustar00rootroot00000000000000import external from "external"; it("should harmony import a dependency", function() { external.should.be.eql("abc"); }); webpack-3.5.6/test/configCases/externals/harmony/webpack.config.js000066400000000000000000000000771315401342100252420ustar00rootroot00000000000000module.exports = { externals: { external: "var 'abc'" } }; webpack-3.5.6/test/configCases/externals/optional-externals-cjs/000077500000000000000000000000001315401342100247505ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/optional-externals-cjs/index.js000066400000000000000000000003471315401342100264210ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { e.should.be.instanceof(Error); e.code.should.be.eql("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); });webpack-3.5.6/test/configCases/externals/optional-externals-cjs/webpack.config.js000066400000000000000000000001521315401342100301640ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "commonjs2" }, externals: { external: "external" } }; webpack-3.5.6/test/configCases/externals/optional-externals-root/000077500000000000000000000000001315401342100251545ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/optional-externals-root/index.js000066400000000000000000000003471315401342100266250ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { e.should.be.instanceof(Error); e.code.should.be.eql("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); });webpack-3.5.6/test/configCases/externals/optional-externals-root/webpack.config.js000066400000000000000000000001441315401342100303710ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "var" }, externals: { external: "external" } }; webpack-3.5.6/test/configCases/externals/optional-externals-umd/000077500000000000000000000000001315401342100247565ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/optional-externals-umd/index.js000066400000000000000000000003471315401342100264270ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { e.should.be.instanceof(Error); e.code.should.be.eql("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); });webpack-3.5.6/test/configCases/externals/optional-externals-umd/webpack.config.js000066400000000000000000000001441315401342100301730ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd" }, externals: { external: "external" } }; webpack-3.5.6/test/configCases/externals/optional-externals-umd2-mixed/000077500000000000000000000000001315401342100261445ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/optional-externals-umd2-mixed/index.js000066400000000000000000000003761315401342100276170ustar00rootroot00000000000000it("should not fail on optional externals", function() { require("external2"); try { require("external"); } catch(e) { e.should.be.instanceof(Error); e.code.should.be.eql("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); });webpack-3.5.6/test/configCases/externals/optional-externals-umd2-mixed/webpack.config.js000066400000000000000000000001701315401342100313600ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd2" }, externals: { external: "external", external2: "fs" } }; webpack-3.5.6/test/configCases/externals/optional-externals-umd2/000077500000000000000000000000001315401342100250405ustar00rootroot00000000000000webpack-3.5.6/test/configCases/externals/optional-externals-umd2/index.js000066400000000000000000000003471315401342100265110ustar00rootroot00000000000000it("should not fail on optional externals", function() { try { require("external"); } catch(e) { e.should.be.instanceof(Error); e.code.should.be.eql("MODULE_NOT_FOUND"); return; } throw new Error("It doesn't fail"); });webpack-3.5.6/test/configCases/externals/optional-externals-umd2/webpack.config.js000066400000000000000000000001451315401342100302560ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd2" }, externals: { external: "external" } }; webpack-3.5.6/test/configCases/extract-text/000077500000000000000000000000001315401342100207725ustar00rootroot00000000000000webpack-3.5.6/test/configCases/extract-text/issue-14/000077500000000000000000000000001315401342100223445ustar00rootroot00000000000000webpack-3.5.6/test/configCases/extract-text/issue-14/base.css000066400000000000000000000000141315401342100237630ustar00rootroot00000000000000body{base:0}webpack-3.5.6/test/configCases/extract-text/issue-14/index.js000066400000000000000000000011251315401342100240100ustar00rootroot00000000000000var should = require("should"); var path = require("path"); var fs = require("fs"); it("should behave correctly with styles extracted", function(done) { var a = require("./styleA.css"); var bundle = fs.readFileSync(path.join(__dirname, "bundle0.js"), "utf-8"); var style = fs.readFileSync(path.join(__dirname, "style.css"), "utf-8"); bundle.should.not.match(/body\{a:1\}/); style.should.be.eql("body{base:0}body{" + "a:1}"); a.should.be.eql({}); require.ensure([], function(require) { var b = require("./styleB.css"); (b + "").should.be.eql("body{base:0}body{b:2}"); done(); }); });webpack-3.5.6/test/configCases/extract-text/issue-14/styleA.css000066400000000000000000000000341315401342100243140ustar00rootroot00000000000000@import "base.css";body{a:1}webpack-3.5.6/test/configCases/extract-text/issue-14/styleB.css000066400000000000000000000000341315401342100243150ustar00rootroot00000000000000@import "base.css";body{b:2}webpack-3.5.6/test/configCases/extract-text/issue-14/webpack.config.js000066400000000000000000000004071315401342100255630ustar00rootroot00000000000000var ETP = require("extract-text-webpack-plugin"); module.exports = { node: { __dirname: false, __filename: false }, module: { loaders: [ { test: /\.css$/, loader: ETP.extract("css-loader") } ] }, plugins: [ new ETP("style.css") ] }; webpack-3.5.6/test/configCases/filename-template/000077500000000000000000000000001315401342100217275ustar00rootroot00000000000000webpack-3.5.6/test/configCases/filename-template/module-filename-template/000077500000000000000000000000001315401342100266035ustar00rootroot00000000000000webpack-3.5.6/test/configCases/filename-template/module-filename-template/index.js000066400000000000000000000004061315401342100302500ustar00rootroot00000000000000it("should include test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); map.sources.should.containEql("dummy:///./test.js"); }); require.include("./test.js"); webpack-3.5.6/test/configCases/filename-template/module-filename-template/test.js000066400000000000000000000000111315401342100301100ustar00rootroot00000000000000// empty webpack-3.5.6/test/configCases/filename-template/module-filename-template/webpack.config.js000066400000000000000000000003641315401342100320240ustar00rootroot00000000000000module.exports = { output: { devtoolLineToLine: true, devtoolModuleFilenameTemplate: function(info) { return "dummy:///" + info.resourcePath; } }, node: { __dirname: false, __filename: false }, devtool: "cheap-source-map" }; webpack-3.5.6/test/configCases/hash-length/000077500000000000000000000000001315401342100205405ustar00rootroot00000000000000webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/000077500000000000000000000000001315401342100240345ustar00rootroot00000000000000webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/000077500000000000000000000000001315401342100251365ustar00rootroot00000000000000webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file1.js000066400000000000000000000000341315401342100264710ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file10.js000066400000000000000000000000341315401342100265510ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file11.js000066400000000000000000000000341315401342100265520ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file12.js000066400000000000000000000000341315401342100265530ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file13.js000066400000000000000000000000341315401342100265540ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file14.js000066400000000000000000000000341315401342100265550ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file15.js000066400000000000000000000000341315401342100265560ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file2.js000066400000000000000000000000341315401342100264720ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file3.js000066400000000000000000000000341315401342100264730ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file4.js000066400000000000000000000000341315401342100264740ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file5.js000066400000000000000000000000341315401342100264750ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file6.js000066400000000000000000000000341315401342100264760ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file7.js000066400000000000000000000000341315401342100264770ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file8.js000066400000000000000000000000341315401342100265000ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/files/file9.js000066400000000000000000000000341315401342100265010ustar00rootroot00000000000000module.exports = module.id; webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/index.js000066400000000000000000000003061315401342100255000ustar00rootroot00000000000000it("should have unique ids", function () { var ids = []; for(var i = 1; i <= 15; i++) { var id = require("./files/file" + i + ".js"); ids.indexOf(id).should.be.eql(-1); ids.push(id); } }); webpack-3.5.6/test/configCases/hash-length/hashed-module-ids/webpack.config.js000066400000000000000000000005531315401342100272550ustar00rootroot00000000000000var 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-3.5.6/test/configCases/hash-length/output-filename/000077500000000000000000000000001315401342100236565ustar00rootroot00000000000000webpack-3.5.6/test/configCases/hash-length/output-filename/chunk.js000066400000000000000000000000321315401342100253170ustar00rootroot00000000000000module.exports = "chunk"; webpack-3.5.6/test/configCases/hash-length/output-filename/index.js000066400000000000000000000002741315401342100253260ustar00rootroot00000000000000it("should compile and run the test " + NAME, function () {}); it("should load additional chunks in " + NAME, function (done) { require(['./chunk'], function () { done(); }); }); webpack-3.5.6/test/configCases/hash-length/output-filename/test.config.js000066400000000000000000000016231315401342100264410ustar00rootroot00000000000000var fs = require("fs"); require("should"); var findFile = function(files, regex) { return files.find(function(file) { if(regex.test(file)) { return true; } }); }; var verifyFilenameLength = function(filename, expectedNameLength) { filename.should.match(new RegExp("^.{" + expectedNameLength + "}$")); }; module.exports = { findBundle: function(i, options) { var files = fs.readdirSync(options.output.path); var bundleDetects = [{ regex: new RegExp("^0.bundle" + i, "i"), expectedNameLength: options.amd.expectedChunkFilenameLength }, { regex: new RegExp("^bundle" + i, "i"), expectedNameLength: options.amd.expectedFilenameLength }]; var bundleDetect; var filename; for(bundleDetect of bundleDetects) { filename = findFile(files, bundleDetect.regex); verifyFilenameLength( filename, bundleDetect.expectedNameLength ); } return "./" + filename; } }; webpack-3.5.6/test/configCases/hash-length/output-filename/webpack.config.js000066400000000000000000000047521315401342100271040ustar00rootroot00000000000000var 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 } } ]; module.exports.forEach(function(options) { options.plugins = options.plugins || []; options.plugins.push(new webpack.DefinePlugin({ NAME: JSON.stringify(options.name) })); }); webpack-3.5.6/test/configCases/ignore/000077500000000000000000000000001315401342100176215ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/only-resource-context/000077500000000000000000000000001315401342100241115ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/only-resource-context/src/000077500000000000000000000000001315401342100247005ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/only-resource-context/src/ignored-module.js000066400000000000000000000000341315401342100301450ustar00rootroot00000000000000module.exports = "ignored"; webpack-3.5.6/test/configCases/ignore/only-resource-context/src/normal-module.js000066400000000000000000000000331315401342100300050ustar00rootroot00000000000000module.exports = "normal"; webpack-3.5.6/test/configCases/ignore/only-resource-context/test.js000066400000000000000000000006751315401342100254360ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore ignored resources", function() { const folderBContext = function(mod) { require("./src/" + mod); }; (function() { folderBContext("ignored-module"); }).should.throw(); }); it("should not ignore resources that do not match", function() { const folderBContext = function(mod) { require("./src/" + mod); }; (function() { folderBContext("normal-module"); }).should.not.throw(); }); webpack-3.5.6/test/configCases/ignore/only-resource-context/webpack.config.js000066400000000000000000000002561315401342100273320ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin(/ignored-module/) ], }; webpack-3.5.6/test/configCases/ignore/only-resource/000077500000000000000000000000001315401342100224275ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/only-resource/ignored-module.js000066400000000000000000000000341315401342100256740ustar00rootroot00000000000000module.exports = "ignored"; webpack-3.5.6/test/configCases/ignore/only-resource/normal-module.js000066400000000000000000000000331315401342100255340ustar00rootroot00000000000000module.exports = "normal"; webpack-3.5.6/test/configCases/ignore/only-resource/test.js000066400000000000000000000004431315401342100237450ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore ignored resources", function() { (function() { require("./ignored-module"); }).should.throw(); }); it("should not ignore resources that do not match", function() { (function() { require("./normal-module"); }).should.not.throw(); }); webpack-3.5.6/test/configCases/ignore/only-resource/webpack.config.js000066400000000000000000000002561315401342100256500ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin(/ignored-module/) ], }; webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/000077500000000000000000000000001315401342100265625ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-a/000077500000000000000000000000001315401342100302535ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-a/ignored-module.js000066400000000000000000000000341315401342100335200ustar00rootroot00000000000000module.exports = "ignored"; webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-a/normal-module.js000066400000000000000000000000551315401342100333640ustar00rootroot00000000000000module.exports = require("./normal-module"); webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-b/000077500000000000000000000000001315401342100302545ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-b/ignored-module.js000066400000000000000000000000341315401342100335210ustar00rootroot00000000000000module.exports = "ignored"; webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-b/normal-module.js000066400000000000000000000000561315401342100333660ustar00rootroot00000000000000module.exports = require("./ignored-module"); only-context-match-require.js000066400000000000000000000000431315401342100357370ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-bmodule.exports = "should be fine"; only-context-match.js000066400000000000000000000000721315401342100342670ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/folder-bmodule.exports = require("./only-context-match-require"); webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/test.js000066400000000000000000000014711315401342100301020ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore context modules that match resource regex and context", function() { const folderBContext = function(mod) { require("./folder-b/" + mod); }; (function() { folderBContext("normal-module"); }).should.throw(); }); it("should not ignore context modules that dont match the resource", function() { const folderBContext = function(mod) { require("./folder-b/" + mod); }; (function() { folderBContext("only-context-match"); }).should.not.throw(); }); it("should not ignore context modules that dont match the context", function() { const folderBContext = function(mod) { require("./folder-a/" + mod); }; (function() { folderBContext("normal-module"); }).should.not.throw(); (function() { folderBContext("ignored-module"); }).should.not.throw(); }); webpack-3.5.6/test/configCases/ignore/resource-and-context-contextmodule/webpack.config.js000066400000000000000000000002721315401342100320010ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin(/ignored-module/, /folder-b/) ], }; webpack-3.5.6/test/configCases/ignore/resource-and-context/000077500000000000000000000000001315401342100236725ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-a/000077500000000000000000000000001315401342100253635ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-a/ignored-module.js000066400000000000000000000000341315401342100306300ustar00rootroot00000000000000module.exports = "ignored"; webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-a/normal-module.js000066400000000000000000000000551315401342100304740ustar00rootroot00000000000000module.exports = require("./normal-module"); webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-b/000077500000000000000000000000001315401342100253645ustar00rootroot00000000000000webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-b/ignored-module.js000066400000000000000000000000341315401342100306310ustar00rootroot00000000000000module.exports = "ignored"; webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-b/normal-module.js000066400000000000000000000000561315401342100304760ustar00rootroot00000000000000module.exports = require("./ignored-module"); webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-b/only-context-match-require.js000066400000000000000000000000431315401342100331260ustar00rootroot00000000000000module.exports = "should be fine"; webpack-3.5.6/test/configCases/ignore/resource-and-context/folder-b/only-context-match.js000066400000000000000000000000721315401342100314560ustar00rootroot00000000000000module.exports = require("./only-context-match-require"); webpack-3.5.6/test/configCases/ignore/resource-and-context/test.js000066400000000000000000000010341315401342100252050ustar00rootroot00000000000000/* globals it */ "use strict"; it("should ignore resources that match resource regex and context", function() { (function() { require("./folder-b/normal-module"); }).should.throw(); }); it("should not ignore resources that match resource but not context", function() { (function() { require("./folder-a/normal-module"); }).should.not.throw(); }); it("should not ignore resources that do not match resource but do match context", function() { (function() { require("./folder-b/only-context-match"); }).should.not.throw(); }); webpack-3.5.6/test/configCases/ignore/resource-and-context/webpack.config.js000066400000000000000000000002721315401342100271110ustar00rootroot00000000000000"use strict"; const IgnorePlugin = require("../../../../lib/IgnorePlugin"); module.exports = { entry: "./test.js", plugins: [ new IgnorePlugin(/ignored-module/, /folder-b/) ], }; webpack-3.5.6/test/configCases/issues/000077500000000000000000000000001315401342100176515ustar00rootroot00000000000000webpack-3.5.6/test/configCases/issues/issue-3596/000077500000000000000000000000001315401342100214055ustar00rootroot00000000000000webpack-3.5.6/test/configCases/issues/issue-3596/b.js000066400000000000000000000001321315401342100221600ustar00rootroot00000000000000it("should not be executed", function() { throw new Error("should not be executed"); }); webpack-3.5.6/test/configCases/issues/issue-3596/index.js000066400000000000000000000000571315401342100230540ustar00rootroot00000000000000it("should compile correctly", function() {}); webpack-3.5.6/test/configCases/issues/issue-3596/webpack.config.js000066400000000000000000000004051315401342100246220ustar00rootroot00000000000000module.exports = { entry: { bundle0: "./index", b: "./b" }, output: { filename: "[name].js" }, plugins: [ function() { this.plugin("emit", function(compilation, callback) { delete compilation.assets["b.js"]; callback(); }); } ] }; webpack-3.5.6/test/configCases/library/000077500000000000000000000000001315401342100200025ustar00rootroot00000000000000webpack-3.5.6/test/configCases/library/0-create-library/000077500000000000000000000000001315401342100230445ustar00rootroot00000000000000webpack-3.5.6/test/configCases/library/0-create-library/a.js000066400000000000000000000000241315401342100236160ustar00rootroot00000000000000export var a = "a"; webpack-3.5.6/test/configCases/library/0-create-library/index.js000066400000000000000000000001711315401342100245100ustar00rootroot00000000000000export * from "./a"; export default "default-value"; export var b = "b"; export { default as external } from "external"; webpack-3.5.6/test/configCases/library/0-create-library/non-external.js000066400000000000000000000000371315401342100260140ustar00rootroot00000000000000export default "non-external"; webpack-3.5.6/test/configCases/library/0-create-library/test.config.js000066400000000000000000000000301315401342100256160ustar00rootroot00000000000000exports.noTests = true; webpack-3.5.6/test/configCases/library/0-create-library/webpack.config.js000066400000000000000000000015571315401342100262720ustar00rootroot00000000000000module.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-3.5.6/test/configCases/library/1-use-library/000077500000000000000000000000001315401342100223765ustar00rootroot00000000000000webpack-3.5.6/test/configCases/library/1-use-library/default-test.js000066400000000000000000000003171315401342100253360ustar00rootroot00000000000000import d from "library"; var data = require("library"); it("should get default export from library (" + NAME + ")", function() { data.should.be.eql("default-value"); d.should.be.eql("default-value"); }); webpack-3.5.6/test/configCases/library/1-use-library/global-test.js000066400000000000000000000004051315401342100251500ustar00rootroot00000000000000var data = require("library"); it("should be able get items from library (" + NAME + ")", function() { data.should.have.property("default").be.eql("default-value"); data.should.have.property("a").be.eql("a"); data.should.have.property("b").be.eql("b"); }); webpack-3.5.6/test/configCases/library/1-use-library/index.js000066400000000000000000000006761315401342100240540ustar00rootroot00000000000000import d from "library"; import { a, b, external } from "library"; it("should be able to import hamorny exports from library (" + NAME + ")", function() { d.should.be.eql("default-value"); a.should.be.eql("a"); b.should.be.eql("b"); if(typeof TEST_EXTERNAL !== "undefined" && TEST_EXTERNAL) { external.should.be.eql(["external"]); external.should.be.equal(require("external")); } else { external.should.be.eql("non-external"); } }); webpack-3.5.6/test/configCases/library/1-use-library/node_modules/000077500000000000000000000000001315401342100250535ustar00rootroot00000000000000webpack-3.5.6/test/configCases/library/1-use-library/node_modules/external.js000066400000000000000000000000371315401342100272330ustar00rootroot00000000000000module.exports = ["external"]; webpack-3.5.6/test/configCases/library/1-use-library/webpack.config.js000066400000000000000000000025541315401342100256220ustar00rootroot00000000000000var 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-3.5.6/test/configCases/library/a/000077500000000000000000000000001315401342100202225ustar00rootroot00000000000000webpack-3.5.6/test/configCases/library/a/index.js000066400000000000000000000000421315401342100216630ustar00rootroot00000000000000it("should run", function() { });webpack-3.5.6/test/configCases/library/a/webpack.config.js000066400000000000000000000000741315401342100234410ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "this" } }; webpack-3.5.6/test/configCases/library/b/000077500000000000000000000000001315401342100202235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/library/b/index.js000066400000000000000000000007221315401342100216710ustar00rootroot00000000000000it("should run", function() { }); it("should have exported", function(done) { setTimeout(function() { exported.object.should.be.eql(module.exports.object); exported.second.should.be.eql(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-3.5.6/test/configCases/library/b/webpack.config.js000066400000000000000000000000761315401342100234440ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "global" } }; webpack-3.5.6/test/configCases/library/umd/000077500000000000000000000000001315401342100205675ustar00rootroot00000000000000webpack-3.5.6/test/configCases/library/umd/index.js000066400000000000000000000000421315401342100222300ustar00rootroot00000000000000it("should run", function() { });webpack-3.5.6/test/configCases/library/umd/webpack.config.js000066400000000000000000000002311315401342100240010ustar00rootroot00000000000000module.exports = { output: { libraryTarget: "umd", library: { root: "testLibrary", amd: "test-library", commonjs: "test-library" } } }; webpack-3.5.6/test/configCases/loaders/000077500000000000000000000000001315401342100177675ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/generate-ident/000077500000000000000000000000001315401342100226625ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/generate-ident/a.js000066400000000000000000000000001315401342100234260ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/generate-ident/b.js000066400000000000000000000000001315401342100234270ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/generate-ident/c.js000066400000000000000000000000001315401342100234300ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/generate-ident/index.js000066400000000000000000000003141315401342100243250ustar00rootroot00000000000000it("should correctly pass complex query object with remaining request", function() { require("./a").should.be.eql("ok"); require("./b").should.be.eql("maybe"); require("./c").should.be.eql("yes"); }); webpack-3.5.6/test/configCases/loaders/generate-ident/loader1.js000066400000000000000000000002151315401342100245450ustar00rootroot00000000000000module.exports.pitch = function(remainingRequest) { return "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");"; }; webpack-3.5.6/test/configCases/loaders/generate-ident/loader2.js000066400000000000000000000001451315401342100245500ustar00rootroot00000000000000module.exports = function(source) { return "module.exports = " + JSON.stringify(this.query.f()); }; webpack-3.5.6/test/configCases/loaders/generate-ident/webpack.config.js000066400000000000000000000011321315401342100260750ustar00rootroot00000000000000module.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"; } } } } ] } }; webpack-3.5.6/test/configCases/loaders/issue-3320/000077500000000000000000000000001315401342100215045ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/issue-3320/a.js000066400000000000000000000000001315401342100222500ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/issue-3320/b.js000066400000000000000000000000001315401342100222510ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/issue-3320/b2.js000066400000000000000000000000001315401342100223330ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/issue-3320/b3.js000066400000000000000000000000001315401342100223340ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/issue-3320/index.js000066400000000000000000000012021315401342100231440ustar00rootroot00000000000000it("should resolve aliased loader module with query", function() { var foo = require('./a'); foo.should.be.eql("someMessage"); }); it("should favor explicit loader query over aliased query (options in rule)", function() { var foo = require('./b'); foo.should.be.eql("someOtherMessage"); }); it("should favor explicit loader query over aliased query (inline query in rule)", function() { var foo = require('./b2'); foo.should.be.eql("someOtherMessage"); }); it("should favor explicit loader query over aliased query (inline query in rule.use)", function() { var foo = require('./b3'); foo.should.be.eql("someOtherMessage"); }); webpack-3.5.6/test/configCases/loaders/issue-3320/node_modules/000077500000000000000000000000001315401342100241615ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/issue-3320/node_modules/any-loader.js000066400000000000000000000003351315401342100265530ustar00rootroot00000000000000var loaderUtils = require('loader-utils'); module.exports = function(source) { var loaderContext = this; var options = loaderUtils.getOptions(loaderContext); return "module.exports=" + JSON.stringify(options.foo); } webpack-3.5.6/test/configCases/loaders/issue-3320/webpack.config.js000066400000000000000000000010331315401342100247170ustar00rootroot00000000000000module.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-3.5.6/test/configCases/loaders/remaining-request/000077500000000000000000000000001315401342100234265ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/remaining-request/a.js000066400000000000000000000000001315401342100241720ustar00rootroot00000000000000webpack-3.5.6/test/configCases/loaders/remaining-request/index.js000066400000000000000000000001761315401342100250770ustar00rootroot00000000000000it("should correctly pass complex query object with remaining request", function() { require("./a").should.be.eql("ok"); }); webpack-3.5.6/test/configCases/loaders/remaining-request/loader1.js000066400000000000000000000002151315401342100253110ustar00rootroot00000000000000module.exports.pitch = function(remainingRequest) { return "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");"; }; webpack-3.5.6/test/configCases/loaders/remaining-request/loader2.js000066400000000000000000000001451315401342100253140ustar00rootroot00000000000000module.exports = function(source) { return "module.exports = " + JSON.stringify(this.query.f()); }; webpack-3.5.6/test/configCases/loaders/remaining-request/webpack.config.js000066400000000000000000000004041315401342100266420ustar00rootroot00000000000000module.exports = { module: { rules: [ { test: /a\.js$/, use: [ "./loader1", { loader: "./loader2", options: { ident: "loader2", f: function() { return "ok"; } } } ] } ] } }; webpack-3.5.6/test/configCases/no-parse/000077500000000000000000000000001315401342100200625ustar00rootroot00000000000000webpack-3.5.6/test/configCases/no-parse/module.exports/000077500000000000000000000000001315401342100230525ustar00rootroot00000000000000webpack-3.5.6/test/configCases/no-parse/module.exports/index.js000066400000000000000000000002551315401342100245210ustar00rootroot00000000000000it("should correctly export stuff from not parsed modules", function() { require("./not-parsed-a").should.be.eql("ok"); require("./not-parsed-b").should.be.eql("ok"); }); webpack-3.5.6/test/configCases/no-parse/module.exports/not-parsed-a.js000066400000000000000000000000271315401342100257010ustar00rootroot00000000000000module.exports = "ok"; webpack-3.5.6/test/configCases/no-parse/module.exports/not-parsed-b.js000066400000000000000000000001241315401342100257000ustar00rootroot00000000000000Object.defineProperty(module, "exports", { get: function() { return "ok"; } }); webpack-3.5.6/test/configCases/no-parse/module.exports/webpack.config.js000066400000000000000000000000741315401342100262710ustar00rootroot00000000000000module.exports = { module: { noParse: /not-parsed/ } }; webpack-3.5.6/test/configCases/no-parse/no-parse-function/000077500000000000000000000000001315401342100234315ustar00rootroot00000000000000webpack-3.5.6/test/configCases/no-parse/no-parse-function/index.js000066400000000000000000000002551315401342100251000ustar00rootroot00000000000000it("should correctly export stuff from not parsed modules", function() { require("./not-parsed-a").should.be.eql("ok"); require("./not-parsed-b").should.be.eql("ok"); }); webpack-3.5.6/test/configCases/no-parse/no-parse-function/not-parsed-a.js000066400000000000000000000000271315401342100262600ustar00rootroot00000000000000module.exports = "ok"; webpack-3.5.6/test/configCases/no-parse/no-parse-function/not-parsed-b.js000066400000000000000000000001241315401342100262570ustar00rootroot00000000000000Object.defineProperty(module, "exports", { get: function() { return "ok"; } }); webpack-3.5.6/test/configCases/no-parse/no-parse-function/webpack.config.js000066400000000000000000000001551315401342100266500ustar00rootroot00000000000000module.exports = { module: { noParse: function(content) { return /not-parsed/.test(content); } } }; webpack-3.5.6/test/configCases/parsing/000077500000000000000000000000001315401342100200015ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/context/000077500000000000000000000000001315401342100214655ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/context/index.js000066400000000000000000000005331315401342100231330ustar00rootroot00000000000000it("should automatically create contexts", function() { var template = "tmpl", templateFull = "./tmpl.js"; require("../../../cases/parsing/context/templates/templateLoader")(templateFull).should.be.eql("test template"); require("../../../cases/parsing/context/templates/templateLoaderIndirect")(templateFull).should.be.eql("test template"); });webpack-3.5.6/test/configCases/parsing/context/warnings.js000066400000000000000000000001301315401342100236450ustar00rootroot00000000000000module.exports = [ [/Module parse failed/, /dump-file\.txt/, /templates \^\\\.\\\//] ];webpack-3.5.6/test/configCases/parsing/context/webpack.config.js000066400000000000000000000002411315401342100247000ustar00rootroot00000000000000module.exports = { module: { unknownContextRegExp: /^\.\//, unknownContextCritical: false, exprContextRegExp: /^\.\//, exprContextCritical: false } }; webpack-3.5.6/test/configCases/parsing/extended-api/000077500000000000000000000000001315401342100223505ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/extended-api/index.js000066400000000000000000000004751315401342100240230ustar00rootroot00000000000000it("should have __webpack_hash__", function() { (typeof __webpack_hash__).should.be.type("string"); __webpack_hash__.should.match(/^[0-9a-f]{20}$/); }); it("should have __webpack_chunkname__", function() { (typeof __webpack_chunkname__).should.be.type("string"); __webpack_chunkname__.should.be.eql('other'); }); webpack-3.5.6/test/configCases/parsing/extended-api/webpack.config.js000066400000000000000000000002401315401342100255620ustar00rootroot00000000000000"use strict"; const webpack = require("../../../../"); module.exports = { entry: { other: "./index" }, plugins: [ new webpack.ExtendedAPIPlugin() ] }; webpack-3.5.6/test/configCases/parsing/harmony-global/000077500000000000000000000000001315401342100227145ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/harmony-global/index.js000066400000000000000000000002421315401342100243570ustar00rootroot00000000000000require("should"); it("should be able to use global in a harmony module", function() { var x = require("./module1"); (x.default === global).should.be.ok(); }); webpack-3.5.6/test/configCases/parsing/harmony-global/module.js000066400000000000000000000000221315401342100245310ustar00rootroot00000000000000export default 1; webpack-3.5.6/test/configCases/parsing/harmony-global/module1.js000066400000000000000000000001711315401342100246170ustar00rootroot00000000000000var freeGlobal = typeof global === "object" && global && global.Object === Object && global; export default freeGlobal; webpack-3.5.6/test/configCases/parsing/harmony-global/webpack.config.js000066400000000000000000000001101315401342100261220ustar00rootroot00000000000000module.exports = { target: "web", performance: { hints: false } }; webpack-3.5.6/test/configCases/parsing/harmony-this-concat/000077500000000000000000000000001315401342100236705ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/harmony-this-concat/abc.js000066400000000000000000000002651315401342100247560ustar00rootroot00000000000000function returnThis() { if(typeof this === "undefined") return "undefined"; return this; } var a = returnThis; var b = returnThis; export { a, b } export default returnThis; webpack-3.5.6/test/configCases/parsing/harmony-this-concat/index.js000066400000000000000000000012771315401342100253440ustar00rootroot00000000000000"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 d().should.be.eql("undefined"); x a().should.be.eql("undefined"); x B().should.be.eql("undefined"); x abc.a().should.be.type("object"); x var thing = abc.a(); Object.keys(thing).should.be.eql(["a", "b", "default"]); }); import C2, { C } from "./new"; import * as New from "./new"; it("should be possible to use new correctly", function() { x new C().should.match({ok: true}); x new C2().should.match({ok: true}); x new New.C().should.match({ok: true}); }); webpack-3.5.6/test/configCases/parsing/harmony-this-concat/new.js000066400000000000000000000001411315401342100250130ustar00rootroot00000000000000function C() { this.ok = this.pok; } C.prototype.pok = true; export default C; export { C }; webpack-3.5.6/test/configCases/parsing/harmony-this-concat/webpack.config.js000066400000000000000000000002611315401342100271050ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { module: { strictThisContextOnImports: true }, plugins: [ new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-3.5.6/test/configCases/parsing/harmony-this/000077500000000000000000000000001315401342100224235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/harmony-this/abc.js000066400000000000000000000002651315401342100235110ustar00rootroot00000000000000function returnThis() { if(typeof this === "undefined") return "undefined"; return this; } var a = returnThis; var b = returnThis; export { a, b } export default returnThis; webpack-3.5.6/test/configCases/parsing/harmony-this/index.js000066400000000000000000000012771315401342100240770ustar00rootroot00000000000000"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 d().should.be.eql("undefined"); x a().should.be.eql("undefined"); x B().should.be.eql("undefined"); x abc.a().should.be.type("object"); x var thing = abc.a(); Object.keys(thing).should.be.eql(["a", "b", "default"]); }); import C2, { C } from "./new"; import * as New from "./new"; it("should be possible to use new correctly", function() { x new C().should.match({ok: true}); x new C2().should.match({ok: true}); x new New.C().should.match({ok: true}); }); webpack-3.5.6/test/configCases/parsing/harmony-this/new.js000066400000000000000000000001411315401342100235460ustar00rootroot00000000000000function C() { this.ok = this.pok; } C.prototype.pok = true; export default C; export { C }; webpack-3.5.6/test/configCases/parsing/harmony-this/webpack.config.js000066400000000000000000000001071315401342100256370ustar00rootroot00000000000000module.exports = { module: { strictThisContextOnImports: true } }; webpack-3.5.6/test/configCases/parsing/issue-336/000077500000000000000000000000001315401342100214425ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/issue-336/index.js000066400000000000000000000001671315401342100231130ustar00rootroot00000000000000it("should provide a module to a free var in a var decl", function() { var x = aaa.test; x.should.be.eql("test"); });webpack-3.5.6/test/configCases/parsing/issue-336/node_modules/000077500000000000000000000000001315401342100241175ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/issue-336/node_modules/aaa.js000066400000000000000000000000431315401342100251740ustar00rootroot00000000000000module.exports = { test: "test" };webpack-3.5.6/test/configCases/parsing/issue-336/webpack.config.js000066400000000000000000000002141315401342100246550ustar00rootroot00000000000000var ProvidePlugin = require("../../../../lib/ProvidePlugin"); module.exports = { plugins: [ new ProvidePlugin({ aaa: "aaa" }) ] }; webpack-3.5.6/test/configCases/parsing/issue-5624/000077500000000000000000000000001315401342100215275ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/issue-5624/index.js000066400000000000000000000004061315401342100231740ustar00rootroot00000000000000import * as M from "./module"; it("should allow conditionals as callee", function() { var x = (true ? M.fn : M.fn)(); x.should.be.eql("ok"); }); it("should allow conditionals as object", function() { var x = (true ? M : M).fn(); x.should.be.eql("ok"); }); webpack-3.5.6/test/configCases/parsing/issue-5624/module.js000066400000000000000000000000471315401342100233530ustar00rootroot00000000000000export function fn() { return "ok"; } webpack-3.5.6/test/configCases/parsing/issue-5624/webpack.config.js000066400000000000000000000001071315401342100247430ustar00rootroot00000000000000module.exports = { module: { strictThisContextOnImports: true } }; webpack-3.5.6/test/configCases/parsing/node-source-plugin-off/000077500000000000000000000000001315401342100242705ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/node-source-plugin-off/index.js000066400000000000000000000002251315401342100257340ustar00rootroot00000000000000require("should"); it("should not load node-libs-browser when node option is false", function() { (typeof process).should.be.eql("undefined"); }); webpack-3.5.6/test/configCases/parsing/node-source-plugin-off/webpack.config.js000066400000000000000000000000631315401342100275050ustar00rootroot00000000000000module.exports = { target: "web", node: false }; webpack-3.5.6/test/configCases/parsing/node-source-plugin/000077500000000000000000000000001315401342100235205ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/node-source-plugin/index.js000066400000000000000000000002071315401342100251640ustar00rootroot00000000000000require("should"); it("should add node-libs-browser to target web by default", function() { process.browser.should.be.eql(true); }); webpack-3.5.6/test/configCases/parsing/node-source-plugin/webpack.config.js000066400000000000000000000001021315401342100267270ustar00rootroot00000000000000module.exports = { target: "web", node: { process: true } }; webpack-3.5.6/test/configCases/parsing/relative-filedirname/000077500000000000000000000000001315401342100240715ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/relative-filedirname/dir/000077500000000000000000000000001315401342100246475ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/relative-filedirname/dir/file.js000066400000000000000000000000741315401342100261250ustar00rootroot00000000000000exports.filename = __filename; exports.dirname = __dirname; webpack-3.5.6/test/configCases/parsing/relative-filedirname/index.js000066400000000000000000000003731315401342100255410ustar00rootroot00000000000000it("should define __dirname and __filename", function() { __dirname.should.be.eql(""); __filename.should.be.eql("index.js"); require("./dir/file").dirname.should.be.eql("dir"); require("./dir/file").filename.should.match(/^dir[\\\/]file.js$/); });webpack-3.5.6/test/configCases/parsing/relative-filedirname/webpack.config.js000066400000000000000000000001101315401342100272770ustar00rootroot00000000000000module.exports = { node: { __filename: true, __dirname: true } }; webpack-3.5.6/test/configCases/parsing/require.main/000077500000000000000000000000001315401342100224005ustar00rootroot00000000000000webpack-3.5.6/test/configCases/parsing/require.main/index.js000066400000000000000000000001271315401342100240450ustar00rootroot00000000000000it("should define require.main", function() { require.main.should.be.eql(module); }); webpack-3.5.6/test/configCases/parsing/require.main/webpack.config.js000066400000000000000000000000261315401342100256140ustar00rootroot00000000000000module.exports = { }; webpack-3.5.6/test/configCases/plugins/000077500000000000000000000000001315401342100200175ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/banner-plugin-hashing/000077500000000000000000000000001315401342100241775ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/banner-plugin-hashing/index.js000066400000000000000000000023771315401342100256550ustar00rootroot00000000000000const 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", () => { REGEXP_HASH.test(banner["hash"]).should.be.true; }); it("should interpolate chunkHash in chunk banner", () => { REGEXP_HASH.test(banner["chunkhash"]).should.be.true; }); it("should interpolate file into chunk banner", () => { banner["file"].should.equal("dist/banner.js"); }); it("should interpolate name in chunk banner", () => { banner["name"].should.equal("dist/banner"); }); it("should interpolate basename in chunk banner", () => { banner["filebase"].should.equal("banner.js"); }); it("should interpolate query in chunk banner", () => { banner["query"].should.equal("?value"); }); it("should parse entry into file in chunk banner", () => { banner["file"].should.not.equal(banner["filebase"]); }); it("should parse entry into name in chunk banner", () => { banner["filebase"].should.not.equal(banner["name"]); }); require.include("./test.js"); webpack-3.5.6/test/configCases/plugins/banner-plugin-hashing/test.config.js000066400000000000000000000001631315401342100267600ustar00rootroot00000000000000var fs = require("fs"); module.exports = { findBundle: function(i, options) { return "./dist/banner.js"; } }; webpack-3.5.6/test/configCases/plugins/banner-plugin-hashing/test.js000066400000000000000000000000451315401342100255130ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-3.5.6/test/configCases/plugins/banner-plugin-hashing/vendors.js000066400000000000000000000000451315401342100262140ustar00rootroot00000000000000var bar = {}; module.exports = bar; webpack-3.5.6/test/configCases/plugins/banner-plugin-hashing/webpack.config.js000066400000000000000000000006331315401342100274170ustar00rootroot00000000000000"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-3.5.6/test/configCases/plugins/banner-plugin/000077500000000000000000000000001315401342100225605ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/banner-plugin/index.js000066400000000000000000000007061315401342100242300ustar00rootroot00000000000000it("should contain banner in bundle0 chunk", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); source.should.containEql("A test value"); }); it("should not contain banner in vendors chunk", function() { var fs = require("fs"), path = require("path"); var source = fs.readFileSync(path.join(__dirname, "vendors.js"), "utf-8"); source.should.not.containEql("A test value"); }); require.include("./test.js"); webpack-3.5.6/test/configCases/plugins/banner-plugin/test.js000066400000000000000000000000451315401342100240740ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-3.5.6/test/configCases/plugins/banner-plugin/vendors.js000066400000000000000000000000451315401342100245750ustar00rootroot00000000000000var bar = {}; module.exports = bar; webpack-3.5.6/test/configCases/plugins/banner-plugin/webpack.config.js000066400000000000000000000005051315401342100257760ustar00rootroot00000000000000var 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: "A test value", exclude: ["vendors.js"] }) ] }; webpack-3.5.6/test/configCases/plugins/define-plugin/000077500000000000000000000000001315401342100225455ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/define-plugin/a.js000066400000000000000000000000001315401342100233110ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/define-plugin/index.js000066400000000000000000000071271315401342100242210ustar00rootroot00000000000000/* globals it, should */ it("should define FALSE", function() { FALSE.should.be.eql(false); (typeof TRUE).should.be.eql("boolean"); var x = require(FALSE ? "fail" : "./a"); var y = FALSE ? require("fail") : require("./a"); }); it("should define CODE", function() { CODE.should.be.eql(3); (typeof CODE).should.be.eql("number"); if(CODE !== 3) require("fail"); if(typeof CODE !== "number") require("fail"); }); it("should define FUNCTION", function() { (FUNCTION(5)).should.be.eql(6); (typeof FUNCTION).should.be.eql("function"); if(typeof FUNCTION !== "function") require("fail"); }); it("should define UNDEFINED", function() { (typeof UNDEFINED).should.be.eql("undefined"); if(typeof UNDEFINED !== "undefined") require("fail"); }); it("should define REGEXP", function() { REGEXP.toString().should.be.eql("/abc/i"); (typeof REGEXP).should.be.eql("object"); if(typeof REGEXP !== "object") require("fail"); }); it("should define OBJECT", function() { var o = OBJECT; o.SUB.FUNCTION(10).should.be.eql(11); }); it("should define OBJECT.SUB.CODE", function() { (typeof OBJECT.SUB.CODE).should.be.eql("number"); OBJECT.SUB.CODE.should.be.eql(3); if(OBJECT.SUB.CODE !== 3) require("fail"); if(typeof OBJECT.SUB.CODE !== "number") require("fail"); (function(sub) { // should not crash sub.CODE.should.be.eql(3); }(OBJECT.SUB)); }); it("should define OBJECT.SUB.STRING", function() { (typeof OBJECT.SUB.STRING).should.be.eql("string"); OBJECT.SUB.STRING.should.be.eql("string"); if(OBJECT.SUB.STRING !== "string") require("fail"); if(typeof OBJECT.SUB.STRING !== "string") require("fail"); (function(sub) { // should not crash sub.STRING.should.be.eql("string"); }(OBJECT.SUB)); }); it("should define process.env.DEFINED_NESTED_KEY", function() { (process.env.DEFINED_NESTED_KEY).should.be.eql(5); (typeof process.env.DEFINED_NESTED_KEY).should.be.eql("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; x.should.be.eql(5); var indirect = process.env; (indirect.DEFINED_NESTED_KEY).should.be.eql(5); (function(env) { (env.DEFINED_NESTED_KEY).should.be.eql(5); (typeof env.DEFINED_NESTED_KEY).should.be.eql("number"); if(env.DEFINED_NESTED_KEY !== 5) require("fail"); if(typeof env.DEFINED_NESTED_KEY !== "number") require("fail"); var x = env.DEFINED_NESTED_KEY; x.should.be.eql(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"; process.env.TEST.should.be.eql("test"); }); it("should not have brakets 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() { (typeof wurst).should.eql("undefined"); // <- is recursivly defined in config }); it("should not explode on recursive statements", function() { (function() { wurst; // <- is recursivly defined in config }).should.throw("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; TEST.should.be.eql("test"); DEFINED_NESTED_KEY.should.be.eql(5); }); webpack-3.5.6/test/configCases/plugins/define-plugin/webpack.config.js000066400000000000000000000012451315401342100257650ustar00rootroot00000000000000var DefinePlugin = require("../../../../lib/DefinePlugin"); module.exports = { plugins: [ new DefinePlugin({ TRUE: true, FALSE: false, UNDEFINED: undefined, FUNCTION: function(a) { return a + 1; }, CODE: "(1+2)", REGEXP: /abc/i, OBJECT: { SUB: { UNDEFINED: undefined, FUNCTION: 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", }) ] }; webpack-3.5.6/test/configCases/plugins/environment-plugin/000077500000000000000000000000001315401342100236575ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/environment-plugin/errors.js000066400000000000000000000014331315401342100255320ustar00rootroot00000000000000const 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-3.5.6/test/configCases/plugins/environment-plugin/index.js000066400000000000000000000016101315401342100253220ustar00rootroot00000000000000it("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-3.5.6/test/configCases/plugins/environment-plugin/warnings.js000066400000000000000000000001131315401342100260400ustar00rootroot00000000000000module.exports = [ [/(ddd)/, /DDD environment variable is undefined./] ]; webpack-3.5.6/test/configCases/plugins/environment-plugin/webpack.config.js000066400000000000000000000022141315401342100270740ustar00rootroot00000000000000"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-3.5.6/test/configCases/plugins/lib-manifest-plugin/000077500000000000000000000000001315401342100236655ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/lib-manifest-plugin/a.js000066400000000000000000000000261315401342100244410ustar00rootroot00000000000000module.exports = "a"; webpack-3.5.6/test/configCases/plugins/lib-manifest-plugin/index.js000066400000000000000000000011051315401342100253270ustar00rootroot00000000000000var fs = require("fs"); var path = require("path"); it("should complete", function(done) { require.ensure(["./a"], function(require) { require("./a").should.be.eql("a"); done(); }); }); it("should write the correct manifest", function() { var manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'bundle0-manifest.json'), "utf-8")); manifest.should.have.key("content", "name"); manifest.content.should.not.have.property("./a.js"); manifest.content.should.have.property("./index.js"); manifest.content["./index.js"].should.have.property("id").eql(module.id); }); webpack-3.5.6/test/configCases/plugins/lib-manifest-plugin/webpack.config.js000066400000000000000000000005511315401342100271040ustar00rootroot00000000000000var 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-3.5.6/test/configCases/plugins/loader-options-plugin/000077500000000000000000000000001315401342100242525ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/loader-options-plugin/index.js000066400000000000000000000004321315401342100257160ustar00rootroot00000000000000it("should set correct options on js files", function() { require("./loader!./index.js").should.be.eql({ minimize: true, jsfile: true }); }); it("should set correct options on other files", function() { require("./loader!./txt.txt").should.be.eql({ minimize: true }); }); webpack-3.5.6/test/configCases/plugins/loader-options-plugin/loader.js000066400000000000000000000002061315401342100260540ustar00rootroot00000000000000module.exports = function() { return "module.exports = " + JSON.stringify({ minimize: this.minimize, jsfile: this.jsfile }); }; webpack-3.5.6/test/configCases/plugins/loader-options-plugin/txt.txt000066400000000000000000000000001315401342100256200ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/loader-options-plugin/webpack.config.js000066400000000000000000000003241315401342100274670ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.LoaderOptionsPlugin({ minimize: true }), new webpack.LoaderOptionsPlugin({ test: /\.js$/, jsfile: true }) ] }; webpack-3.5.6/test/configCases/plugins/min-chunk-size/000077500000000000000000000000001315401342100226605ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/min-chunk-size/a.js000066400000000000000000000000241315401342100234320ustar00rootroot00000000000000export default "a"; webpack-3.5.6/test/configCases/plugins/min-chunk-size/b.js000066400000000000000000000000241315401342100234330ustar00rootroot00000000000000export default "b"; webpack-3.5.6/test/configCases/plugins/min-chunk-size/index.js000066400000000000000000000010351315401342100243240ustar00rootroot00000000000000it("should combine two chunk if too small", done => { // b should not yet available var bf = __webpack_modules__[require.resolveWeak("./b")]; (typeof bf).should.be.eql("undefined"); // load a import("./a").then(a => { a.default.should.be.eql("a"); // check if b is available too var bf = __webpack_modules__[require.resolveWeak("./b")]; (typeof bf).should.be.eql("function"); // load b (just to check if it's ok) import("./b").then(b => { b.default.should.be.eql("b"); done(); }).catch(done); }).catch(done); }); webpack-3.5.6/test/configCases/plugins/min-chunk-size/webpack.config.js000066400000000000000000000002221315401342100260720ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.MinChunkSizePlugin({ minChunkSize: 30 }) ] }; webpack-3.5.6/test/configCases/plugins/new-watching-plugin/000077500000000000000000000000001315401342100237065ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/new-watching-plugin/index.js000066400000000000000000000000401315401342100253450ustar00rootroot00000000000000it("should run", function() {});webpack-3.5.6/test/configCases/plugins/new-watching-plugin/warnings.js000066400000000000000000000000601315401342100260700ustar00rootroot00000000000000module.exports = [ [/no longer necessary/], ]; webpack-3.5.6/test/configCases/plugins/new-watching-plugin/webpack.config.js000066400000000000000000000001561315401342100271260ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.NewWatchingPlugin() ] }; webpack-3.5.6/test/configCases/plugins/provide-plugin/000077500000000000000000000000001315401342100227635ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/provide-plugin/aaa.js000066400000000000000000000000271315401342100240420ustar00rootroot00000000000000module.exports = "aaa";webpack-3.5.6/test/configCases/plugins/provide-plugin/bbbccc.js000066400000000000000000000000321315401342100245120ustar00rootroot00000000000000module.exports = "bbbccc";webpack-3.5.6/test/configCases/plugins/provide-plugin/ddd.js000066400000000000000000000001001315401342100240430ustar00rootroot00000000000000var ddd = { eee: { "3-f": "fff" } }; module.exports = ddd; webpack-3.5.6/test/configCases/plugins/provide-plugin/env.js000066400000000000000000000000371315401342100241110ustar00rootroot00000000000000module.exports = "development";webpack-3.5.6/test/configCases/plugins/provide-plugin/harmony.js000066400000000000000000000001471315401342100250000ustar00rootroot00000000000000export default "ECMAScript 2015"; export const alias = "ECMAScript Harmony"; export const year = 2015; webpack-3.5.6/test/configCases/plugins/provide-plugin/index.js000066400000000000000000000031011315401342100244230ustar00rootroot00000000000000it("should provide a module for a simple free var", function() { aaa.should.be.eql("aaa"); }); it("should provide a module for a nested var", function() { (bbb.ccc).should.be.eql("bbbccc"); var x = bbb.ccc; x.should.be.eql("bbbccc"); }); it("should provide a module for a nested var within a IIFE's argument", function() { (function(process) { (process.env.NODE_ENV).should.be.eql("development"); var x = process.env.NODE_ENV; x.should.be.eql("development"); }(process)); }); it("should provide a module for a nested var within a IIFE's this", function() { (function() { (this.env.NODE_ENV).should.be.eql("development"); var x = this.env.NODE_ENV; x.should.be.eql("development"); }.call(process)); }); it("should provide a module for a nested var within a nested IIFE's this", function() { (function() { (function() { (this.env.NODE_ENV).should.be.eql("development"); var x = this.env.NODE_ENV; x.should.be.eql("development"); }.call(this)); }.call(process)); }); it("should not provide a module for a part of a var", function() { (typeof bbb).should.be.eql("undefined"); }); it("should provide a module for a property request", function() { (dddeeefff).should.be.eql("fff"); var x = dddeeefff; x.should.be.eql("fff"); }); it("should provide ES2015 modules", function() { (es2015.default).should.be.eql("ECMAScript 2015"); (es2015.alias).should.be.eql("ECMAScript Harmony"); (es2015.year).should.be.eql(2015); (es2015_name).should.be.eql("ECMAScript 2015"); (es2015_alias).should.be.eql("ECMAScript Harmony"); (es2015_year).should.be.eql(2015); }); webpack-3.5.6/test/configCases/plugins/provide-plugin/webpack.config.js000066400000000000000000000006101315401342100261760ustar00rootroot00000000000000var 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"], }) ] }; webpack-3.5.6/test/configCases/plugins/uglifyjs-plugin/000077500000000000000000000000001315401342100231475ustar00rootroot00000000000000webpack-3.5.6/test/configCases/plugins/uglifyjs-plugin/compress.js000066400000000000000000000003011315401342100253320ustar00rootroot00000000000000function 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-3.5.6/test/configCases/plugins/uglifyjs-plugin/extract.js000066400000000000000000000003751315401342100251640ustar00rootroot00000000000000/** @preserve comment should be extracted extract-test.1 */ var foo = {}; // 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-3.5.6/test/configCases/plugins/uglifyjs-plugin/ie8.js000066400000000000000000000002341315401342100241710ustar00rootroot00000000000000function t(e) { return function(error) { try { e() } catch(e) { error(e) } } } module.exports = t; webpack-3.5.6/test/configCases/plugins/uglifyjs-plugin/index.js000066400000000000000000000050131315401342100246130ustar00rootroot00000000000000it("should contain no comments in out chunk", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); source.should.not.match(/[^\"]comment should be stripped test\.1[^\"]/); source.should.not.match(/[^\"]comment should be stripped test\.2[^\"]/); source.should.not.match(/[^\"]comment should be stripped test\.3[^\"]/); }); it("should contain comments in vendors chunk", function() { var fs = require("fs"), path = require("path"); var source = fs.readFileSync(path.join(__dirname, "vendors.js"), "utf-8"); source.should.containEql("comment should not be stripped vendors.1"); source.should.containEql("// comment should not be stripped vendors.2"); source.should.containEql(" * comment should not be stripped vendors.3"); }); // this test is based off https://github.com/mishoo/UglifyJS2/blob/master/test/compress/screw-ie8.js it("should pass mangle options", function() { var fs = require("fs"), path = require("path"); var source = fs.readFileSync(path.join(__dirname, "ie8.js"), "utf-8"); source.should.containEql("function r(t){return function(n){try{t()}catch(t){n(t)}}}"); }); it("should extract comments to separate file", function() { var fs = require("fs"), path = require("path"); var source = fs.readFileSync(path.join(__dirname, "extract.js.LICENSE"), "utf-8"); source.should.containEql("comment should be extracted extract-test.1"); source.should.not.containEql("comment should be stripped extract-test.2"); source.should.containEql("comment should be extracted extract-test.3"); source.should.not.containEql("comment should be stripped extract-test.4"); }); it("should remove extracted comments and insert a banner", function() { var fs = require("fs"), path = require("path"); var source = fs.readFileSync(path.join(__dirname, "extract.js"), "utf-8"); source.should.not.containEql("comment should be extracted extract-test.1"); source.should.not.containEql("comment should be stripped extract-test.2"); source.should.not.containEql("comment should be extracted extract-test.3"); source.should.not.containEql("comment should be stripped extract-test.4"); source.should.containEql("/*! For license information please see extract.js.LICENSE */"); }); it("should pass compress options", function() { var fs = require("fs"), path = require("path"); var source = fs.readFileSync(path.join(__dirname, "compress.js"), "utf-8"); source.should.containEql("function e(){var o=2;o=3,console.log(1+o),console.log(o+3),console.log(4),console.log(1+o+3)}"); }); require.include("./test.js"); webpack-3.5.6/test/configCases/plugins/uglifyjs-plugin/test.js000066400000000000000000000002551315401342100244660ustar00rootroot00000000000000/** @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-3.5.6/test/configCases/plugins/uglifyjs-plugin/vendors.js000066400000000000000000000003021315401342100251600ustar00rootroot00000000000000/** @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-3.5.6/test/configCases/plugins/uglifyjs-plugin/webpack.config.js000066400000000000000000000014361315401342100263710ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { node: { __dirname: false, __filename: false }, entry: { bundle0: ["./index.js"], vendors: ["./vendors.js"], ie8: ["./ie8.js"], extract: ["./extract.js"], compress: ["./compress.js"] }, output: { filename: "[name].js" }, plugins: [ new webpack.optimize.UglifyJsPlugin({ comments: false, exclude: ["vendors.js", "extract.js"], mangle: { screw_ie8: false } }), new webpack.optimize.UglifyJsPlugin({ extractComments: true, include: ["extract.js"], mangle: { screw_ie8: false } }), new webpack.optimize.UglifyJsPlugin({ include: ["compress.js"], compress: { conditionals: true, evaluate: true, passes: 2, reduce_vars: true, unused: true } }), ] }; webpack-3.5.6/test/configCases/records/000077500000000000000000000000001315401342100177775ustar00rootroot00000000000000webpack-3.5.6/test/configCases/records/issue-295/000077500000000000000000000000001315401342100214445ustar00rootroot00000000000000webpack-3.5.6/test/configCases/records/issue-295/file.js000066400000000000000000000000161315401342100227160ustar00rootroot00000000000000// just a filewebpack-3.5.6/test/configCases/records/issue-295/loader.js000066400000000000000000000000671315401342100232530ustar00rootroot00000000000000module.exports = function(source) { return source; }; webpack-3.5.6/test/configCases/records/issue-295/test.js000066400000000000000000000004521315401342100227620ustar00rootroot00000000000000require("./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"); content.should.not.match(/webpack|issue/); }); webpack-3.5.6/test/configCases/records/issue-295/webpack.config.js000066400000000000000000000003211315401342100246560ustar00rootroot00000000000000var path = require("path"); module.exports = { entry: "./test", recordsPath: path.resolve(__dirname, "../../../js/config/records/issue-295/records.json"), target: "node", node: { __dirname: false } }; webpack-3.5.6/test/configCases/records/issue-2991/000077500000000000000000000000001315401342100215315ustar00rootroot00000000000000webpack-3.5.6/test/configCases/records/issue-2991/pkgs/000077500000000000000000000000001315401342100224755ustar00rootroot00000000000000webpack-3.5.6/test/configCases/records/issue-2991/pkgs/somepackage/000077500000000000000000000000001315401342100247545ustar00rootroot00000000000000webpack-3.5.6/test/configCases/records/issue-2991/pkgs/somepackage/package.json000066400000000000000000000000421315401342100272360ustar00rootroot00000000000000{ "browser": { "foo": false } } webpack-3.5.6/test/configCases/records/issue-2991/test.js000066400000000000000000000012001315401342100230370ustar00rootroot00000000000000try { 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"); content.should.eql(`{ "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 }, "byBlocks": {}, "usedIds": { "0": 0 } } }`); }); webpack-3.5.6/test/configCases/records/issue-2991/webpack.config.js000066400000000000000000000004761315401342100247560ustar00rootroot00000000000000var 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-3.5.6/test/configCases/rule-set/000077500000000000000000000000001315401342100200765ustar00rootroot00000000000000webpack-3.5.6/test/configCases/rule-set/chaining/000077500000000000000000000000001315401342100216565ustar00rootroot00000000000000webpack-3.5.6/test/configCases/rule-set/chaining/abc.js000066400000000000000000000000321315401342100227340ustar00rootroot00000000000000module.exports = ["abc"]; webpack-3.5.6/test/configCases/rule-set/chaining/def.js000066400000000000000000000000321315401342100227450ustar00rootroot00000000000000module.exports = ["def"]; webpack-3.5.6/test/configCases/rule-set/chaining/index.js000066400000000000000000000004651315401342100233300ustar00rootroot00000000000000it("should match rule with multiple loaders in 'loader'", function() { var abc = require("./abc"); abc.should.be.eql([ "abc", "?b", "?a" ]); }); it("should match rule with multiple loaders in 'loaders'", function() { var def = require("./def"); def.should.be.eql([ "def", "?d", "?c" ]); }); webpack-3.5.6/test/configCases/rule-set/chaining/loader.js000066400000000000000000000003511315401342100234610ustar00rootroot00000000000000module.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-3.5.6/test/configCases/rule-set/chaining/webpack.config.js000066400000000000000000000003051315401342100250720ustar00rootroot00000000000000module.exports = { module: { rules: [ { resource: /abc\.js$/, loader: "./loader?a!./loader?b" }, { resource: /def\.js$/, loaders: "./loader?c!./loader?d" } ] } }; webpack-3.5.6/test/configCases/rule-set/compiler/000077500000000000000000000000001315401342100217105ustar00rootroot00000000000000webpack-3.5.6/test/configCases/rule-set/compiler/a.js000066400000000000000000000000471315401342100224670ustar00rootroot00000000000000module.exports = "loader not matched"; webpack-3.5.6/test/configCases/rule-set/compiler/b.js000066400000000000000000000000471315401342100224700ustar00rootroot00000000000000module.exports = "loader not matched"; webpack-3.5.6/test/configCases/rule-set/compiler/index.js000066400000000000000000000002721315401342100233560ustar00rootroot00000000000000it("should match rule with compiler name", function() { var a = require("./a"); a.should.be.eql("loader matched"); var b = require("./b"); b.should.be.eql("loader not matched"); }); webpack-3.5.6/test/configCases/rule-set/compiler/loader.js000066400000000000000000000001501315401342100235100ustar00rootroot00000000000000module.exports = function(source) { return "module.exports = " + JSON.stringify("loader matched"); }; webpack-3.5.6/test/configCases/rule-set/compiler/webpack.config.js000066400000000000000000000003521315401342100251260ustar00rootroot00000000000000module.exports = { name: "compiler-name", module: { rules: [ { test: /a\.js$/, compiler: "compiler", use: "./loader" }, { test: /b\.js$/, compiler: "other-compiler", use: "./loader" } ] } }; webpack-3.5.6/test/configCases/rule-set/custom/000077500000000000000000000000001315401342100214105ustar00rootroot00000000000000webpack-3.5.6/test/configCases/rule-set/custom/a.js000066400000000000000000000000301315401342100221570ustar00rootroot00000000000000module.exports = ["a"]; webpack-3.5.6/test/configCases/rule-set/custom/b.js000066400000000000000000000000301315401342100221600ustar00rootroot00000000000000module.exports = ["b"]; webpack-3.5.6/test/configCases/rule-set/custom/call-a.js000066400000000000000000000000631315401342100230760ustar00rootroot00000000000000module.exports = require("./a" + __resourceQuery); webpack-3.5.6/test/configCases/rule-set/custom/index.js000066400000000000000000000010541315401342100230550ustar00rootroot00000000000000it("should match a custom loader", function() { var a = require("./a"); a.should.be.eql([ "a", { issuer: "index.js", resource: "a.js", resourceQuery: "" } ]); var b = require("./b?hello"); b.should.be.eql([ "b", { issuer: "index.js", resource: "b.js", resourceQuery: "?hello" } ]); var ca = require("./call-a?hello"); ca.should.be.eql([ "a", { issuer: "call-a.js", resource: "a.js", resourceQuery: "?hello" }, { issuer: "index.js", resource: "call-a.js", resourceQuery: "?hello" } ]); }); webpack-3.5.6/test/configCases/rule-set/custom/loader.js000066400000000000000000000003511315401342100232130ustar00rootroot00000000000000module.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-3.5.6/test/configCases/rule-set/custom/webpack.config.js000066400000000000000000000005251315401342100246300ustar00rootroot00000000000000module.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-3.5.6/test/configCases/rule-set/query/000077500000000000000000000000001315401342100212435ustar00rootroot00000000000000webpack-3.5.6/test/configCases/rule-set/query/a.js000066400000000000000000000000301315401342100220120ustar00rootroot00000000000000module.exports = ["a"]; webpack-3.5.6/test/configCases/rule-set/query/index.js000066400000000000000000000004011315401342100227030ustar00rootroot00000000000000it("should match rule with resource query", function() { var a1 = require("./a"); a1.should.be.eql([ "a" ]); var a2 = require("./a?loader"); a2.should.be.eql([ "a", "?query" ]); var a3 = require("./a?other"); a3.should.be.eql([ "a" ]); }); webpack-3.5.6/test/configCases/rule-set/query/loader.js000066400000000000000000000003511315401342100230460ustar00rootroot00000000000000module.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-3.5.6/test/configCases/rule-set/query/webpack.config.js000066400000000000000000000001671315401342100244650ustar00rootroot00000000000000module.exports = { module: { rules: [ { resourceQuery: /^\?loader/, use: "./loader?query" } ] } }; webpack-3.5.6/test/configCases/rule-set/simple-use-fn-array/000077500000000000000000000000001315401342100236765ustar00rootroot00000000000000webpack-3.5.6/test/configCases/rule-set/simple-use-fn-array/a.js000066400000000000000000000000301315401342100244450ustar00rootroot00000000000000module.exports = ["a"]; webpack-3.5.6/test/configCases/rule-set/simple-use-fn-array/ab.js000066400000000000000000000000311315401342100246100ustar00rootroot00000000000000module.exports = ["ab"]; webpack-3.5.6/test/configCases/rule-set/simple-use-fn-array/b.js000066400000000000000000000000441315401342100244530ustar00rootroot00000000000000module.exports = [require("./a")]; webpack-3.5.6/test/configCases/rule-set/simple-use-fn-array/c.js000066400000000000000000000000151315401342100244520ustar00rootroot00000000000000// never usedwebpack-3.5.6/test/configCases/rule-set/simple-use-fn-array/index.js000066400000000000000000000005711315401342100253460ustar00rootroot00000000000000it("should match only one rule in a oneOf block", function() { var ab = require("./ab"); ab.should.be.eql([ "ab", "?first" ]); }); it("should match with issuer and any option value", function() { var a = require("./a"); var b = require("./b"); a.should.be.eql([ "a", "?third", ]); b.should.be.eql([[ "a", "second-3", "?second-2", "?second-1", ]]); }); webpack-3.5.6/test/configCases/rule-set/simple-use-fn-array/loader.js000066400000000000000000000003511315401342100255010ustar00rootroot00000000000000module.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-3.5.6/test/configCases/rule-set/simple-use-fn-array/webpack.config.js000066400000000000000000000015561315401342100271230ustar00rootroot00000000000000 function 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-3.5.6/test/configCases/rule-set/simple/000077500000000000000000000000001315401342100213675ustar00rootroot00000000000000webpack-3.5.6/test/configCases/rule-set/simple/a.js000066400000000000000000000000301315401342100221360ustar00rootroot00000000000000module.exports = ["a"]; webpack-3.5.6/test/configCases/rule-set/simple/ab.js000066400000000000000000000000311315401342100223010ustar00rootroot00000000000000module.exports = ["ab"]; webpack-3.5.6/test/configCases/rule-set/simple/b.js000066400000000000000000000000441315401342100221440ustar00rootroot00000000000000module.exports = [require("./a")]; webpack-3.5.6/test/configCases/rule-set/simple/c.js000066400000000000000000000000151315401342100221430ustar00rootroot00000000000000// never usedwebpack-3.5.6/test/configCases/rule-set/simple/index.js000066400000000000000000000005711315401342100230370ustar00rootroot00000000000000it("should match only one rule in a oneOf block", function() { var ab = require("./ab"); ab.should.be.eql([ "ab", "?first" ]); }); it("should match with issuer and any option value", function() { var a = require("./a"); var b = require("./b"); a.should.be.eql([ "a", "?third", ]); b.should.be.eql([[ "a", "second-3", "?second-2", "?second-1", ]]); }); webpack-3.5.6/test/configCases/rule-set/simple/loader.js000066400000000000000000000003511315401342100231720ustar00rootroot00000000000000module.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-3.5.6/test/configCases/rule-set/simple/webpack.config.js000066400000000000000000000013371315401342100246110ustar00rootroot00000000000000module.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-3.5.6/test/configCases/runtime/000077500000000000000000000000001315401342100200215ustar00rootroot00000000000000webpack-3.5.6/test/configCases/runtime/opt-in-finally/000077500000000000000000000000001315401342100226635ustar00rootroot00000000000000webpack-3.5.6/test/configCases/runtime/opt-in-finally/exception.js000066400000000000000000000000361315401342100252160ustar00rootroot00000000000000throw new Error("Exception"); webpack-3.5.6/test/configCases/runtime/opt-in-finally/index.js000066400000000000000000000003061315401342100243270ustar00rootroot00000000000000it("should throw exception on every try to load a module", function() { (function() { require("./exception"); }).should.throw(); (function() { require("./exception"); }).should.throw(); }); webpack-3.5.6/test/configCases/runtime/opt-in-finally/webpack.config.js000066400000000000000000000001121315401342100260730ustar00rootroot00000000000000module.exports = { output: { strictModuleExceptionHandling: true } }; webpack-3.5.6/test/configCases/scope-hoisting/000077500000000000000000000000001315401342100212715ustar00rootroot00000000000000webpack-3.5.6/test/configCases/scope-hoisting/dll-plugin/000077500000000000000000000000001315401342100233405ustar00rootroot00000000000000webpack-3.5.6/test/configCases/scope-hoisting/dll-plugin/index.js000066400000000000000000000001751315401342100250100ustar00rootroot00000000000000import value from "dll/module"; it("should not scope hoist delegated modules", function() { value.should.be.eql("ok"); }); webpack-3.5.6/test/configCases/scope-hoisting/dll-plugin/webpack.config.js000066400000000000000000000005561315401342100265640ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.DllReferencePlugin({ name: "function(id) { return {default: 'ok'}; }", scope: "dll", content: { "./module": { id: 1, meta: { harmonyModule: true }, exports: ["default"] } } }), new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-3.5.6/test/configCases/scope-hoisting/named-modules/000077500000000000000000000000001315401342100240235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/scope-hoisting/named-modules/index.js000066400000000000000000000001551315401342100254710ustar00rootroot00000000000000import value from "./module"; it("should generate valid code", function() { value.should.be.eql("ok"); }); webpack-3.5.6/test/configCases/scope-hoisting/named-modules/module.js000066400000000000000000000000721315401342100256450ustar00rootroot00000000000000import module2 from "./module2"; export default module2; webpack-3.5.6/test/configCases/scope-hoisting/named-modules/module2.js000066400000000000000000000000271315401342100257270ustar00rootroot00000000000000module.exports = "ok"; webpack-3.5.6/test/configCases/scope-hoisting/named-modules/webpack.config.js000066400000000000000000000002431315401342100272400ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { plugins: [ new webpack.NamedModulesPlugin(), new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-3.5.6/test/configCases/scope-hoisting/strictThisContextOnImports/000077500000000000000000000000001315401342100266515ustar00rootroot00000000000000webpack-3.5.6/test/configCases/scope-hoisting/strictThisContextOnImports/index.js000066400000000000000000000006371315401342100303240ustar00rootroot00000000000000import value, { identity } from "./module"; import * as m from "./module"; it("should parse and translate identifiers correctly", function() { identity(value).should.be.eql(1234); m.identity(value).should.be.eql(1234); m.identity(identity).should.be.eql(identity); m.identity(m.identity).should.be.eql(m.identity); identity(m.identity).should.be.eql(m.identity); identity(m.default).should.be.eql(1234); }); webpack-3.5.6/test/configCases/scope-hoisting/strictThisContextOnImports/module.js000066400000000000000000000000771315401342100305000ustar00rootroot00000000000000export function identity(a) { return a; } export default 1234; webpack-3.5.6/test/configCases/scope-hoisting/strictThisContextOnImports/webpack.config.js000066400000000000000000000002611315401342100320660ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { module: { strictThisContextOnImports: true }, plugins: [ new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-3.5.6/test/configCases/simple/000077500000000000000000000000001315401342100176275ustar00rootroot00000000000000webpack-3.5.6/test/configCases/simple/empty-config/000077500000000000000000000000001315401342100222305ustar00rootroot00000000000000webpack-3.5.6/test/configCases/simple/empty-config/index.js000066400000000000000000000000671315401342100237000ustar00rootroot00000000000000it("should compile and run the test", function() { });webpack-3.5.6/test/configCases/simple/empty-config/webpack.config.js000066400000000000000000000000271315401342100254450ustar00rootroot00000000000000module.exports = { }; webpack-3.5.6/test/configCases/simple/multi-compiler-functions-export/000077500000000000000000000000001315401342100261165ustar00rootroot00000000000000webpack-3.5.6/test/configCases/simple/multi-compiler-functions-export/index.js000066400000000000000000000001271315401342100275630ustar00rootroot00000000000000it("should run a multi compiler with functions with export default", function() { }); webpack-3.5.6/test/configCases/simple/multi-compiler-functions-export/webpack.config.js000066400000000000000000000000651315401342100313350ustar00rootroot00000000000000exports.default = [ function() { return {}; } ]; webpack-3.5.6/test/configCases/simple/multi-compiler-functions/000077500000000000000000000000001315401342100245775ustar00rootroot00000000000000webpack-3.5.6/test/configCases/simple/multi-compiler-functions/index.js000066400000000000000000000001031315401342100262360ustar00rootroot00000000000000it("should run a multi compiler with functions", function() { }); webpack-3.5.6/test/configCases/simple/multi-compiler-functions/webpack.config.js000066400000000000000000000000641315401342100300150ustar00rootroot00000000000000module.exports = [ function() { return {}; } ]; webpack-3.5.6/test/configCases/simple/multi-compiler/000077500000000000000000000000001315401342100225715ustar00rootroot00000000000000webpack-3.5.6/test/configCases/simple/multi-compiler/index.js000066400000000000000000000000631315401342100242350ustar00rootroot00000000000000it("should run a multi compiler", function() { });webpack-3.5.6/test/configCases/simple/multi-compiler/webpack.config.js000066400000000000000000000000351315401342100260050ustar00rootroot00000000000000module.exports = [ { } ]; webpack-3.5.6/test/configCases/source-map/000077500000000000000000000000001315401342100204115ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/exclude-chunks-source-map/000077500000000000000000000000001315401342100254045ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/exclude-chunks-source-map/index.js000066400000000000000000000007771315401342100270640ustar00rootroot00000000000000it("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); map.sources.should.containEql("webpack:///./test.js"); }); it("should not produce a SourceMap for vendors chunk", function() { var fs = require("fs"), path = require("path"), assert = require("assert"); fs.existsSync(path.join(__dirname, "vendors.js.map")).should.be.false(); }); require.include("./test.js"); webpack-3.5.6/test/configCases/source-map/exclude-chunks-source-map/test.js000066400000000000000000000000451315401342100267200ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-3.5.6/test/configCases/source-map/exclude-chunks-source-map/vendors.js000066400000000000000000000000451315401342100274210ustar00rootroot00000000000000var bar = {}; module.exports = bar; webpack-3.5.6/test/configCases/source-map/exclude-chunks-source-map/webpack.config.js000066400000000000000000000005171315401342100306250ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { 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-3.5.6/test/configCases/source-map/line-to-line/000077500000000000000000000000001315401342100227055ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/line-to-line/index.js000066400000000000000000000004071315401342100243530ustar00rootroot00000000000000it("should include test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); map.sources.should.containEql("webpack:///./test.js"); }); require.include("./test.js"); webpack-3.5.6/test/configCases/source-map/line-to-line/test.js000066400000000000000000000000441315401342100242200ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-3.5.6/test/configCases/source-map/line-to-line/webpack.config.js000066400000000000000000000002211315401342100261160ustar00rootroot00000000000000module.exports = { output: { devtoolLineToLine: true }, node: { __dirname: false, __filename: false }, devtool: "cheap-source-map" }; webpack-3.5.6/test/configCases/source-map/module-names/000077500000000000000000000000001315401342100227775ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/module-names/index.js000066400000000000000000000013741315401342100244510ustar00rootroot00000000000000function 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"); map.sources.should.containEql("module"); map.sources.should.containEql("fallback"); map.sources.should.containEql("fallback**"); map = getSourceMap("chunk-a.js"); map.sources.should.containEql("fallback*"); map = getSourceMap("chunk-b.js"); map.sources.should.containEql("fallback*"); map.sources.should.containEql("fallback***"); }); require.ensure(["./test.js"], function(require) {}, "chunk-a"); require.ensure(["./test.js", "./test.js?1"], function(require) {}, "chunk-b"); webpack-3.5.6/test/configCases/source-map/module-names/test.js000066400000000000000000000000441315401342100243120ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-3.5.6/test/configCases/source-map/module-names/webpack.config.js000066400000000000000000000003561315401342100262210ustar00rootroot00000000000000module.exports = { output: { chunkFilename: "[name].js", devtoolModuleFilenameTemplate: "module", devtoolFallbackModuleFilenameTemplate: "fallback" }, node: { __dirname: false, __filename: false }, devtool: "source-map" }; webpack-3.5.6/test/configCases/source-map/nosources/000077500000000000000000000000001315401342100224315ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/nosources/index.js000066400000000000000000000004321315401342100240750ustar00rootroot00000000000000it("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); map.should.not.have.property('sourcesContent'); }); require.include("./test.js"); webpack-3.5.6/test/configCases/source-map/nosources/test.js000066400000000000000000000000451315401342100237450ustar00rootroot00000000000000var foo = {}; module.exports = foo; webpack-3.5.6/test/configCases/source-map/nosources/webpack.config.js000066400000000000000000000001551315401342100256500ustar00rootroot00000000000000module.exports = { node: { __dirname: false, __filename: false }, devtool: "nosources-source-map", }; webpack-3.5.6/test/configCases/source-map/relative-source-map-path/000077500000000000000000000000001315401342100252275ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/relative-source-map-path/index.js000066400000000000000000000006311315401342100266740ustar00rootroot00000000000000it("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); match[1].should.be.eql("bundle0.js.map"); }); it("should have a relative url to the source-map with prefix", function(done) { require.ensure([], function(require) { require("./test.js"); done(); }); }); webpack-3.5.6/test/configCases/source-map/relative-source-map-path/test.js000066400000000000000000000002461315401342100265460ustar00rootroot00000000000000var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); var match = /sourceMappingURL\s*=\s*(.*)/.exec(source); match[1].should.be.eql("c.js.map");webpack-3.5.6/test/configCases/source-map/relative-source-map-path/webpack.config.js000066400000000000000000000002231315401342100304420ustar00rootroot00000000000000module.exports = { output: { chunkFilename: "js/chunks/c.js" }, node: { __dirname: false, __filename: false }, devtool: "source-map" }; webpack-3.5.6/test/configCases/source-map/source-map-filename-contenthash/000077500000000000000000000000001315401342100265565ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/source-map-filename-contenthash/index.js000066400000000000000000000004531315401342100302250ustar00rootroot00000000000000it("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); match.length.should.be.eql(4); }); webpack-3.5.6/test/configCases/source-map/source-map-filename-contenthash/webpack.config.js000066400000000000000000000004651315401342100320010ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { node: { __dirname: false, __filename: false }, devtool: "source-map", output: { sourceMapFilename: "[file]-[contenthash].map?[contenthash]-[contenthash]", }, plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: true }) ] }; webpack-3.5.6/test/configCases/source-map/sources-array-production-cheap-map/000077500000000000000000000000001315401342100272255ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/sources-array-production-cheap-map/index.js000066400000000000000000000004071315401342100306730ustar00rootroot00000000000000it("should include test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); map.sources.should.containEql("webpack:///./test.js"); }); require.include("./test.js"); webpack-3.5.6/test/configCases/source-map/sources-array-production-cheap-map/test.js000066400000000000000000000000441315401342100305400ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-3.5.6/test/configCases/source-map/sources-array-production-cheap-map/webpack.config.js000066400000000000000000000004301315401342100324400ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { node: { __dirname: false, __filename: false }, plugins: [ new webpack.SourceMapDevToolPlugin({ filename: "[file].map", cheap: true }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true }) ] }; webpack-3.5.6/test/configCases/source-map/sources-array-production/000077500000000000000000000000001315401342100253745ustar00rootroot00000000000000webpack-3.5.6/test/configCases/source-map/sources-array-production/index.js000066400000000000000000000004071315401342100270420ustar00rootroot00000000000000it("should include test.js in SourceMap", function() { var fs = require("fs"); var source = fs.readFileSync(__filename + ".map", "utf-8"); var map = JSON.parse(source); map.sources.should.containEql("webpack:///./test.js"); }); require.include("./test.js"); webpack-3.5.6/test/configCases/source-map/sources-array-production/test.js000066400000000000000000000000441315401342100267070ustar00rootroot00000000000000var foo = {}; module.exports = foo;webpack-3.5.6/test/configCases/source-map/sources-array-production/webpack.config.js000066400000000000000000000003311315401342100306070ustar00rootroot00000000000000var webpack = require("../../../../"); module.exports = { node: { __dirname: false, __filename: false }, devtool: "source-map", plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: true }) ] }; webpack-3.5.6/test/configCases/target/000077500000000000000000000000001315401342100176245ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/buffer-default/000077500000000000000000000000001315401342100225175ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/buffer-default/index.js000066400000000000000000000003651315401342100241700ustar00rootroot00000000000000require("should"); it("should provide a global Buffer shim", function () { Buffer.should.be.a.Function(); }); it("should provide the buffer module", function () { var buffer = require("buffer"); (typeof buffer).should.be.eql("object"); }); webpack-3.5.6/test/configCases/target/buffer-default/webpack.config.js000066400000000000000000000000461315401342100257350ustar00rootroot00000000000000module.exports = { target: "web", }; webpack-3.5.6/test/configCases/target/buffer/000077500000000000000000000000001315401342100210755ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/buffer/index.js000066400000000000000000000004211315401342100225370ustar00rootroot00000000000000require("should"); it("should provide a global Buffer shim", function () { Buffer.should.be.a.Function(); }); it("should fail on the buffer module"/*, function () { (function(argument) { try { require("buffer"); } catch(e) { throw e; } }).should.throw(); }*/); webpack-3.5.6/test/configCases/target/buffer/webpack.config.js000066400000000000000000000001221315401342100243060ustar00rootroot00000000000000module.exports = { target: "web", node: { Buffer: true, buffer: false } }; webpack-3.5.6/test/configCases/target/node-dynamic-import/000077500000000000000000000000001315401342100235035ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/node-dynamic-import/dir/000077500000000000000000000000001315401342100242615ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/node-dynamic-import/dir/one.js000066400000000000000000000000241315401342100253740ustar00rootroot00000000000000module.exports = 1; webpack-3.5.6/test/configCases/target/node-dynamic-import/dir/three.js000066400000000000000000000000241315401342100257220ustar00rootroot00000000000000module.exports = 3; webpack-3.5.6/test/configCases/target/node-dynamic-import/dir/two.js000066400000000000000000000000241315401342100254240ustar00rootroot00000000000000module.exports = 2; webpack-3.5.6/test/configCases/target/node-dynamic-import/dir2/000077500000000000000000000000001315401342100243435ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/node-dynamic-import/dir2/one.js000066400000000000000000000000241315401342100254560ustar00rootroot00000000000000module.exports = 1; webpack-3.5.6/test/configCases/target/node-dynamic-import/dir2/three.js000066400000000000000000000000241315401342100260040ustar00rootroot00000000000000module.exports = 3; webpack-3.5.6/test/configCases/target/node-dynamic-import/dir2/two.js000066400000000000000000000000241315401342100255060ustar00rootroot00000000000000module.exports = 2; webpack-3.5.6/test/configCases/target/node-dynamic-import/index.js000066400000000000000000000027361315401342100251600ustar00rootroot00000000000000function testCase(load, done) { load("two", 2, function() { var sync = true; load("one", 1, function() { sync.should.be.eql(false); load("three", 3, function() { var sync = true; load("two", 2, function() { sync.should.be.eql(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) => {result.should.be.eql(expected); callback()}) .catch((err) => {done(err)}); } testCase(load, done); }); it("should be able to use expressions in System.import", function(done) { function load(name, expected, callback) { System.import("./dir2/" + name).then((result) => { result.should.be.eql(expected); callback(); }).catch((err) => { done(err); }); } testCase(load, done); }); it("should convert to function in node", function() { (typeof __webpack_require__.e).should.be.eql("function"); }) it("should be able to use import", function(done) { import("./two").then((two) => { two.should.be.eql(2); done(); }).catch(function(err) { done(err); }); }); it("should be able to use System.import", function(done) { System.import("./two").then((two) => { two.should.be.eql(2); done(); }).catch(function(err) { done(err); }); }); webpack-3.5.6/test/configCases/target/node-dynamic-import/test.filter.js000066400000000000000000000002261315401342100263040ustar00rootroot00000000000000var supportsArrowFn = require("../../../helpers/supportsArrowFunctionExpression"); module.exports = function(config) { return supportsArrowFn(); }; webpack-3.5.6/test/configCases/target/node-dynamic-import/two.js000066400000000000000000000000231315401342100246450ustar00rootroot00000000000000module.exports = 2;webpack-3.5.6/test/configCases/target/node-dynamic-import/webpack.config.js000066400000000000000000000001111315401342100267120ustar00rootroot00000000000000module.exports = { target: "node", performance: { hints: false } }; webpack-3.5.6/test/configCases/target/strict-mode-global/000077500000000000000000000000001315401342100233145ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/strict-mode-global/index.js000066400000000000000000000002701315401342100247600ustar00rootroot00000000000000"use strict"; require("should"); it("should be able to use global in strict mode", function() { (typeof global).should.be.eql("object"); (global === null).should.be.eql(false) }); webpack-3.5.6/test/configCases/target/strict-mode-global/webpack.config.js000066400000000000000000000000451315401342100265310ustar00rootroot00000000000000module.exports = { target: "web" }; webpack-3.5.6/test/configCases/target/umd-auxiliary-comments-object/000077500000000000000000000000001315401342100255055ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/umd-auxiliary-comments-object/index.js000066400000000000000000000006401315401342100271520ustar00rootroot00000000000000it("should run", function() { }); it("should have auxiliary comments", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); source.should.containEql("//test " + "comment " + "commonjs"); source.should.containEql("//test " + "comment " + "commonjs2"); source.should.containEql("//test " + "comment " + "amd"); source.should.containEql("//test " + "comment " + "root"); }); webpack-3.5.6/test/configCases/target/umd-auxiliary-comments-object/webpack.config.js000066400000000000000000000005051315401342100307230ustar00rootroot00000000000000module.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-3.5.6/test/configCases/target/umd-auxiliary-comments-string/000077500000000000000000000000001315401342100255455ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/umd-auxiliary-comments-string/index.js000066400000000000000000000003411315401342100272100ustar00rootroot00000000000000it("should run", function() { }); it("should have auxiliary comment string", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); source.should.containEql("//test " + "comment"); }); webpack-3.5.6/test/configCases/target/umd-auxiliary-comments-string/webpack.config.js000066400000000000000000000003071315401342100307630ustar00rootroot00000000000000module.exports = { output: { library: "NamedLibrary", libraryTarget: "umd", umdNamedDefine: true, auxiliaryComment: "test comment" }, node: { __dirname: false, __filename: false } }; webpack-3.5.6/test/configCases/target/umd-named-define/000077500000000000000000000000001315401342100227235ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/umd-named-define/index.js000066400000000000000000000003231315401342100243660ustar00rootroot00000000000000it("should run", function() { }); it("should name define", function() { var fs = require("fs"); var source = fs.readFileSync(__filename, "utf-8"); source.should.containEql("define(\"NamedLibrary\","); }); webpack-3.5.6/test/configCases/target/umd-named-define/webpack.config.js000066400000000000000000000002431315401342100261400ustar00rootroot00000000000000module.exports = { output: { library: "NamedLibrary", libraryTarget: "umd", umdNamedDefine: true }, node: { __dirname: false, __filename: false } }; webpack-3.5.6/test/configCases/target/web/000077500000000000000000000000001315401342100204015ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/web/index.js000066400000000000000000000050431315401342100220500ustar00rootroot00000000000000require("should"); // shimming global XMLHttpRequest object so the http-module is happy. global.XMLHttpRequest = function() {}; global.XMLHttpRequest.prototype.open = function() {}; it("should provide a global Buffer constructor", function() { Buffer.should.be.a.Function(); }); // Webpack is not providing a console shim by default // @see lib/WebpackOptionsDefaulter.js // Uncomment this when defaults are changed //it("should provide a global console shim", function () { // console.should.be.an.Object(); // console.time.should.be.a.Function(); //}); it("should provide a global process shim", function () { process.should.be.an.Object(); }); it("should provide a global setImmediate shim", function () { setImmediate.should.be.a.Function(); }); it("should provide a global clearImmediate shim", function () { clearImmediate.should.be.a.Function(); }); it("should provide an assert shim", function () { require("assert").should.be.a.Function(); }); it("should provide a util shim", function () { require("util").should.be.an.Object(); }); it("should provide a buffer shim", function () { require("buffer").should.be.an.Object(); }); it("should provide a crypto shim", function () { require("crypto").should.be.an.Object(); }); it("should provide a domain shim", function () { require("domain").should.be.an.Object(); }); it("should provide an events shim", function () { require("events").should.be.a.Function(); }); it("should provide an http shim", function () { require("http").should.be.an.Object(); }); it("should provide an https shim", function () { require("https").should.be.an.Object(); }); it("should provide an os shim", function () { require("os").should.be.an.Object(); }); it("should provide a path shim", function () { require("path").should.be.an.Object(); }); it("should provide a punycode shim", function () { require("punycode").should.be.an.Object(); }); it("should provide a stream shim", function () { require("stream").should.be.a.Function(); }); it("should provide a tty shim", function () { require("tty").should.be.an.Object(); }); it("should provide a url shim", function () { require("url").should.be.an.Object(); }); it("should provide a util shim", function () { require("util").should.be.an.Object(); }); it("should provide a vm shim", function () { require("vm").should.be.an.Object(); }); it("should provide a zlib shim", function () { require("zlib").should.be.an.Object(); }); it("should provide a shim for a path in a build-in module", function () { require("process/in.js").should.be.eql("in process"); }); webpack-3.5.6/test/configCases/target/web/node_modules/000077500000000000000000000000001315401342100230565ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/web/node_modules/process/000077500000000000000000000000001315401342100245345ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/web/node_modules/process/in.js000066400000000000000000000000371315401342100255000ustar00rootroot00000000000000module.exports = "in process"; webpack-3.5.6/test/configCases/target/web/node_modules/process/index.js000066400000000000000000000000511315401342100261750ustar00rootroot00000000000000throw new Error("Should not be loaded"); webpack-3.5.6/test/configCases/target/web/webpack.config.js000066400000000000000000000001101315401342100236070ustar00rootroot00000000000000module.exports = { target: "web", performance: { hints: false } }; webpack-3.5.6/test/configCases/target/webworker/000077500000000000000000000000001315401342100216335ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/webworker/index.js000066400000000000000000000047041315401342100233050ustar00rootroot00000000000000var should = require("should"); // shimming global window object so the http-module is happy. // window is assigned without var on purpose. global.XMLHttpRequest = function() {}; global.XMLHttpRequest.prototype.open = function() {}; it("should provide a global Buffer constructor", function() { Buffer.should.be.a.Function(); }); it("should provide a global console shim", function () { console.should.be.an.Object(); console.time.should.be.a.Function(); }); it("should provide a global process shim", function () { process.should.be.an.Object(); }); it("should provide a global setImmediate shim", function () { setImmediate.should.be.a.Function(); }); it("should provide a global clearImmediate shim", function () { clearImmediate.should.be.a.Function(); }); it("should provide an assert shim", function () { require("assert").should.be.a.Function(); }); it("should provide a util shim", function () { require("util").should.be.an.Object(); }); it("should provide a buffer shim", function () { require("buffer").should.be.an.Object(); }); it("should provide a crypto shim", function () { require("crypto").should.be.an.Object(); }); it("should provide a domain shim", function () { require("domain").should.be.an.Object(); }); it("should provide an events shim", function () { require("events").should.be.a.Function(); }); it("should provide an http shim", function () { require("http").should.be.an.Object(); }); it("should provide an https shim", function () { require("https").should.be.an.Object(); }); it("should provide an os shim", function () { require("os").should.be.an.Object(); }); it("should provide a path shim", function () { require("path").should.be.an.Object(); }); it("should provide a punycode shim", function () { require("punycode").should.be.an.Object(); }); it("should provide a stream shim", function () { require("stream").should.be.a.Function(); }); it("should provide a tty shim", function () { require("tty").should.be.an.Object(); }); it("should provide a url shim", function () { require("url").should.be.an.Object(); }); it("should provide a util shim", function () { require("util").should.be.an.Object(); }); it("should provide a vm shim", function () { require("vm").should.be.an.Object(); }); it("should provide a zlib shim", function () { require("zlib").should.be.an.Object(); }); it("should provide a shim for a path in a build-in module", function () { require("process/in.js").should.be.eql("in process"); }); webpack-3.5.6/test/configCases/target/webworker/node_modules/000077500000000000000000000000001315401342100243105ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/webworker/node_modules/process/000077500000000000000000000000001315401342100257665ustar00rootroot00000000000000webpack-3.5.6/test/configCases/target/webworker/node_modules/process/in.js000066400000000000000000000000371315401342100267320ustar00rootroot00000000000000module.exports = "in process"; webpack-3.5.6/test/configCases/target/webworker/node_modules/process/index.js000066400000000000000000000000511315401342100274270ustar00rootroot00000000000000throw new Error("Should not be loaded"); webpack-3.5.6/test/configCases/target/webworker/webpack.config.js000066400000000000000000000003211315401342100250450ustar00rootroot00000000000000module.exports = { target: "webworker", performance: { hints: false }, module: { loaders: [ { test: /\.json$/, loader: "json-loader" } ] }, node: { __dirname: false, __filename: false } }; webpack-3.5.6/test/fixtures/000077500000000000000000000000001315401342100157635ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/a.js000066400000000000000000000000671315401342100165440ustar00rootroot00000000000000module.exports = function a() { return "This is a"; };webpack-3.5.6/test/fixtures/abc.js000066400000000000000000000001231315401342100170420ustar00rootroot00000000000000exports.a = require("./a"); exports.b = require("./b"); exports.c = require("./c");webpack-3.5.6/test/fixtures/abc.txt000066400000000000000000000000031315401342100172420ustar00rootroot00000000000000abcwebpack-3.5.6/test/fixtures/b.js000066400000000000000000000000671315401342100165450ustar00rootroot00000000000000module.exports = function b() { return "This is b"; };webpack-3.5.6/test/fixtures/c.js000066400000000000000000000001101315401342100165330ustar00rootroot00000000000000module.exports = function b() { require("./a"); return "This is c"; };webpack-3.5.6/test/fixtures/chunks.js000066400000000000000000000001001315401342100176030ustar00rootroot00000000000000require.ensure(["./a"], function(require) { require("./b"); });webpack-3.5.6/test/fixtures/complex.js000066400000000000000000000006151315401342100177720ustar00rootroot00000000000000var 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-3.5.6/test/fixtures/delay-loader.js000066400000000000000000000001651315401342100206650ustar00rootroot00000000000000module.exports = function(source) { var cb = this.async(); setTimeout(function() { cb(null, source); }, 500); };webpack-3.5.6/test/fixtures/errors/000077500000000000000000000000001315401342100172775ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/errors/case-sensitive.js000066400000000000000000000000451315401342100225560ustar00rootroot00000000000000require("./file"); require("./FILE");webpack-3.5.6/test/fixtures/errors/entry-point.js000066400000000000000000000000001315401342100221130ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/errors/file.js000066400000000000000000000000001315401342100205420ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/errors/missingFile.js000066400000000000000000000001441315401342100221050ustar00rootroot00000000000000 // on line 4 require("./missing"); // on line 12 char 10 require("./dir/missing2");webpack-3.5.6/test/fixtures/errors/no-errors-deprecate.js000066400000000000000000000000231315401342100235100ustar00rootroot00000000000000require('./file'); webpack-3.5.6/test/fixtures/errors/require.extensions.js000066400000000000000000000000521315401342100235040ustar00rootroot00000000000000require.extensions[".js"] = function() {};webpack-3.5.6/test/fixtures/items/000077500000000000000000000000001315401342100171045ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/items/item (0).js000066400000000000000000000000231315401342100206340ustar00rootroot00000000000000module.exports = 0;webpack-3.5.6/test/fixtures/items/item (1).js000066400000000000000000000000231315401342100206350ustar00rootroot00000000000000module.exports = 1;webpack-3.5.6/test/fixtures/items/item (2).js000066400000000000000000000000231315401342100206360ustar00rootroot00000000000000module.exports = 2;webpack-3.5.6/test/fixtures/items/item (3).js000066400000000000000000000000231315401342100206370ustar00rootroot00000000000000module.exports = 3;webpack-3.5.6/test/fixtures/items/item (4).js000066400000000000000000000000231315401342100206400ustar00rootroot00000000000000module.exports = 4;webpack-3.5.6/test/fixtures/items/item (5).js000066400000000000000000000000231315401342100206410ustar00rootroot00000000000000module.exports = 5;webpack-3.5.6/test/fixtures/items/item (6).js000066400000000000000000000000231315401342100206420ustar00rootroot00000000000000module.exports = 6;webpack-3.5.6/test/fixtures/items/item (7).js000066400000000000000000000000231315401342100206430ustar00rootroot00000000000000module.exports = 7;webpack-3.5.6/test/fixtures/items/item (8).js000066400000000000000000000000231315401342100206440ustar00rootroot00000000000000module.exports = 8;webpack-3.5.6/test/fixtures/items/item (9).js000066400000000000000000000000231315401342100206450ustar00rootroot00000000000000module.exports = 9;webpack-3.5.6/test/fixtures/lib/000077500000000000000000000000001315401342100165315ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/lib/complex1.js000066400000000000000000000000401315401342100206110ustar00rootroot00000000000000module.exports = "lib complex1";webpack-3.5.6/test/fixtures/main1.js000066400000000000000000000002221315401342100173220ustar00rootroot00000000000000var a = require("./a"); if(x) { for(var i = 0; i < 100; i++) { while(true) require("./b"); do { i++; } while(require("m1/a")()); } }webpack-3.5.6/test/fixtures/main2.js000066400000000000000000000002741315401342100173320ustar00rootroot00000000000000var 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-3.5.6/test/fixtures/main3.js000066400000000000000000000001261315401342100173270ustar00rootroot00000000000000var a = require("./a"); require.ensure([], function(require) { require("./c.js"); });webpack-3.5.6/test/fixtures/main4.js000066400000000000000000000000721315401342100173300ustar00rootroot00000000000000var six = 6; require("bundle!./items/item (" + six + ")");webpack-3.5.6/test/fixtures/node_modules/000077500000000000000000000000001315401342100204405ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/node_modules/complexm/000077500000000000000000000000001315401342100222645ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/node_modules/complexm/step1.js000066400000000000000000000000611315401342100236530ustar00rootroot00000000000000module.exports = require("m1/a") + require("m1");webpack-3.5.6/test/fixtures/node_modules/complexm/step2.js000066400000000000000000000000311315401342100236510ustar00rootroot00000000000000module.exports = "Step2";webpack-3.5.6/test/fixtures/node_modules/complexm/web_modules/000077500000000000000000000000001315401342100245715ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/node_modules/complexm/web_modules/m1/000077500000000000000000000000001315401342100251065ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/node_modules/complexm/web_modules/m1/a.js000066400000000000000000000000441315401342100256620ustar00rootroot00000000000000module.exports = "the correct a.js";webpack-3.5.6/test/fixtures/node_modules/complexm/web_modules/m1/index.js000066400000000000000000000000551315401342100265530ustar00rootroot00000000000000module.exports = " :) " + require("m2/b.js");webpack-3.5.6/test/fixtures/node_modules/m1/000077500000000000000000000000001315401342100207555ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/node_modules/m1/a.js000066400000000000000000000000721315401342100215320ustar00rootroot00000000000000module.exports = function a() { return "This is m1/a"; };webpack-3.5.6/test/fixtures/node_modules/m1/b.js000066400000000000000000000000721315401342100215330ustar00rootroot00000000000000module.exports = function a() { return "This is m1/b"; };webpack-3.5.6/test/fixtures/node_modules/m2-loader/000077500000000000000000000000001315401342100222225ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/node_modules/m2-loader/b.js000066400000000000000000000001141315401342100227750ustar00rootroot00000000000000module.exports = function() { "module.exports = 'This is m2-loader/b';"; } webpack-3.5.6/test/fixtures/node_modules/m2/000077500000000000000000000000001315401342100207565ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/node_modules/m2/b.js000066400000000000000000000000411315401342100215300ustar00rootroot00000000000000module.exports = "This is m2/b"; webpack-3.5.6/test/fixtures/nodetest/000077500000000000000000000000001315401342100176105ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/nodetest/entry.js000066400000000000000000000002521315401342100213060ustar00rootroot00000000000000exports.loadChunk = function(id, cb) { require(["./file" + id], function(result) { cb(result); }); }; exports.nextTick = process.nextTick; exports.fs = require("fs");webpack-3.5.6/test/fixtures/nodetest/file456.js000066400000000000000000000000251315401342100213210ustar00rootroot00000000000000module.exports = 123;webpack-3.5.6/test/fixtures/nodetest/file567.js000066400000000000000000000000221315401342100213210ustar00rootroot00000000000000define({ a: 1 });webpack-3.5.6/test/fixtures/subdir/000077500000000000000000000000001315401342100172535ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/subdir/watched-file.txt000066400000000000000000000000001315401342100223360ustar00rootroot00000000000000webpack-3.5.6/test/fixtures/watched-file.txt000066400000000000000000000000001315401342100210460ustar00rootroot00000000000000webpack-3.5.6/test/formatLocation.test.js000066400000000000000000000025251315401342100204130ustar00rootroot00000000000000"use strict"; const should = require("should"); 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}`, () => { formatLocation(testCase.loc).should.be.eql(testCase.result); }); }); }); webpack-3.5.6/test/helpers/000077500000000000000000000000001315401342100155545ustar00rootroot00000000000000webpack-3.5.6/test/helpers/PluginEnvironment.js000066400000000000000000000004321315401342100215740ustar00rootroot00000000000000module.exports = function PluginEnvironment() { var events = []; this.getEnvironmentStub = function() { return { plugin: function(name, handler) { events.push({ name, handler }); } }; }; this.getEventBindings = function() { return events; }; }; webpack-3.5.6/test/helpers/TemplatePluginEnvironment.js000066400000000000000000000011241315401342100232670ustar00rootroot00000000000000var 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-3.5.6/test/helpers/applyPluginWithOptions.js000066400000000000000000000007021315401342100226250ustar00rootroot00000000000000var 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-3.5.6/test/helpers/supportDefaultAssignment.js000066400000000000000000000004231315401342100231630ustar00rootroot00000000000000module.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-3.5.6/test/helpers/supportsArrowFunctionExpression.js000066400000000000000000000003111315401342100246050ustar00rootroot00000000000000module.exports = function supportArrowFunctionExpression() { try { eval("var foo = function(fn) {return fn.toString()}; foo(() => {return 'a'})"); return true; } catch(e) { return false; } }; webpack-3.5.6/test/helpers/supportsBlockScoping.js000066400000000000000000000003121315401342100223030ustar00rootroot00000000000000module.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-3.5.6/test/helpers/supportsDefaultArgs.js000066400000000000000000000002521315401342100221320ustar00rootroot00000000000000module.exports = function supportsDefaultArgs() { try { var f = eval("(function f(a = 123) { return a; })"); return f() === 123; } catch(e) { return false; } }; webpack-3.5.6/test/helpers/supportsES6.js000066400000000000000000000001721315401342100203270ustar00rootroot00000000000000module.exports = function supportsES6() { try { eval("class A {}"); return true; } catch(e) { return false; } }; webpack-3.5.6/test/helpers/supportsForOf.js000066400000000000000000000003071315401342100207450ustar00rootroot00000000000000module.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-3.5.6/test/helpers/supportsIteratorDestructuring.js000066400000000000000000000002741315401342100243110ustar00rootroot00000000000000module.exports = function supportsIteratorDestructuring() { try { var f = eval("(function f([, x, ...y]) { return x; })"); return f([1, 2]) === 2; } catch(e) { return false; } }; webpack-3.5.6/test/helpers/supportsObjectDestructuring.js000066400000000000000000000003011315401342100237150ustar00rootroot00000000000000module.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-3.5.6/test/helpers/supportsTemplateStrings.js000066400000000000000000000002711315401342100230570ustar00rootroot00000000000000module.exports = function supportsTemplateStrings() { try { var f = eval("(function f() { return String.raw`a\\b`; })"); return f() === "a\\b"; } catch(e) { return false; } }; webpack-3.5.6/test/hotCases/000077500000000000000000000000001315401342100156635ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/chunks/000077500000000000000000000000001315401342100171565ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/chunks/accept-system-import/000077500000000000000000000000001315401342100232475ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/chunks/accept-system-import/chunk.js000066400000000000000000000000401315401342100247070ustar00rootroot00000000000000export { value } from "./file"; webpack-3.5.6/test/hotCases/chunks/accept-system-import/chunk2.js000066400000000000000000000000401315401342100247710ustar00rootroot00000000000000export { value } from "./file"; webpack-3.5.6/test/hotCases/chunks/accept-system-import/file.js000066400000000000000000000000601315401342100245200ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-3.5.6/test/hotCases/chunks/accept-system-import/index.js000066400000000000000000000011271315401342100247150ustar00rootroot00000000000000it("should import a changed chunk", function(done) { System.import("./chunk").then(function(chunk) { chunk.value.should.be.eql(1); System.import("./chunk2").then(function(chunk2) { chunk2.value.should.be.eql(1); NEXT(require("../../update")(done)); module.hot.accept(["./chunk", "./chunk2"], function() { System.import("./chunk").then(function(chunk) { chunk.value.should.be.eql(2); System.import("./chunk2").then(function(chunk2) { chunk2.value.should.be.eql(2); done(); }).catch(done); }).catch(done); }); }).catch(done); }).catch(done); }); webpack-3.5.6/test/hotCases/chunks/dynamic-system-import/000077500000000000000000000000001315401342100234345ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/chunks/dynamic-system-import/chunk1.js000066400000000000000000000000751315401342100251650ustar00rootroot00000000000000export { value } from "./file"; module.hot.accept("./file"); webpack-3.5.6/test/hotCases/chunks/dynamic-system-import/chunk2.js000066400000000000000000000000751315401342100251660ustar00rootroot00000000000000export { value } from "./file"; module.hot.accept("./file"); webpack-3.5.6/test/hotCases/chunks/dynamic-system-import/file.js000066400000000000000000000000601315401342100247050ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-3.5.6/test/hotCases/chunks/dynamic-system-import/index.js000066400000000000000000000006441315401342100251050ustar00rootroot00000000000000it("should import a changed chunk (dynamic import)", function(done) { function load(name) { return System.import("./chunk" + name); } load(1).then(function(chunk) { chunk.value.should.be.eql(1); NEXT(require("../../update")(done, true, function() { chunk.value.should.be.eql(2); load(2).then(function(chunk2) { chunk2.value.should.be.eql(2); done(); }).catch(done); })); }).catch(done); }); webpack-3.5.6/test/hotCases/chunks/system-import/000077500000000000000000000000001315401342100220125ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/chunks/system-import/chunk.js000066400000000000000000000002721315401342100234610ustar00rootroot00000000000000export { value } from "./file"; export { value as value2 } from "./file2"; export var counter = 0; module.hot.accept("./file"); module.hot.accept("./file2", function() { counter++; }); webpack-3.5.6/test/hotCases/chunks/system-import/chunk2.js000066400000000000000000000002721315401342100235430ustar00rootroot00000000000000export { value } from "./file"; export { value as value2 } from "./file2"; export var counter = 0; module.hot.accept("./file"); module.hot.accept("./file2", function() { counter++; }); webpack-3.5.6/test/hotCases/chunks/system-import/file.js000066400000000000000000000000601315401342100232630ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-3.5.6/test/hotCases/chunks/system-import/file2.js000066400000000000000000000000601315401342100233450ustar00rootroot00000000000000export var value = 3; --- export var value = 4; webpack-3.5.6/test/hotCases/chunks/system-import/index.js000066400000000000000000000011031315401342100234520ustar00rootroot00000000000000it("should import a changed chunk", function(done) { System.import("./chunk").then(function(chunk) { chunk.value.should.be.eql(1); chunk.value2.should.be.eql(3); chunk.counter.should.be.eql(0); NEXT(require("../../update")(done, true, function() { chunk.value.should.be.eql(2); chunk.value2.should.be.eql(4); chunk.counter.should.be.eql(1); System.import("./chunk2").then(function(chunk2) { chunk2.value.should.be.eql(2); chunk2.value2.should.be.eql(4); chunk2.counter.should.be.eql(0); done(); }).catch(done); })); }).catch(done); }); webpack-3.5.6/test/hotCases/concat/000077500000000000000000000000001315401342100171325ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/concat/reload-compat-flag/000077500000000000000000000000001315401342100225705ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/concat/reload-compat-flag/a.js000066400000000000000000000000221315401342100233400ustar00rootroot00000000000000export default 1; webpack-3.5.6/test/hotCases/concat/reload-compat-flag/index.js000066400000000000000000000005571315401342100242440ustar00rootroot00000000000000var x = require("./module"); it("should allow to hot replace modules in a ConcatenatedModule", function(done) { x.should.be.eql({ default: "ok1", __esModule: true }); module.hot.accept("./module", function() { x = require("./module"); x.should.be.eql({ default: "ok2", __esModule: true }); done(); }); NEXT(require("../../update")(done)); }); webpack-3.5.6/test/hotCases/concat/reload-compat-flag/module.js000066400000000000000000000001161315401342100244110ustar00rootroot00000000000000import "./a"; export default "ok1"; --- import "./a"; export default "ok2"; webpack-3.5.6/test/hotCases/concat/reload-compat-flag/webpack.config.js000066400000000000000000000002211315401342100260010ustar00rootroot00000000000000"use strict"; const webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-3.5.6/test/hotCases/concat/reload-external/000077500000000000000000000000001315401342100222205ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/concat/reload-external/a.js000066400000000000000000000001021315401342100227670ustar00rootroot00000000000000export default 1; --- export default 2; --- export default 2; --- webpack-3.5.6/test/hotCases/concat/reload-external/b.js000066400000000000000000000001051315401342100227730ustar00rootroot00000000000000export default 10; --- export default 10; --- export default 20; --- webpack-3.5.6/test/hotCases/concat/reload-external/index.js000066400000000000000000000000231315401342100236600ustar00rootroot00000000000000import "./module"; webpack-3.5.6/test/hotCases/concat/reload-external/module.js000066400000000000000000000006471315401342100240520ustar00rootroot00000000000000import value1 from "./a"; import value2 from "./b"; it("should allow to hot replace modules in a ConcatenatedModule", function(done) { value1.should.be.eql(1); value2.should.be.eql(10); module.hot.accept("./a", function() { value1.should.be.eql(2); NEXT(require("../../update")(done)); }); module.hot.accept("./b", function() { value2.should.be.eql(20); done(); }); NEXT(require("../../update")(done)); }); webpack-3.5.6/test/hotCases/concat/reload-external/webpack.config.js000066400000000000000000000002211315401342100254310ustar00rootroot00000000000000"use strict"; const webpack = require("../../../../"); module.exports = { plugins: [ new webpack.optimize.ModuleConcatenationPlugin() ] }; webpack-3.5.6/test/hotCases/errors/000077500000000000000000000000001315401342100171775ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/errors/decline/000077500000000000000000000000001315401342100206025ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/errors/decline/a.js000066400000000000000000000001561315401342100213620ustar00rootroot00000000000000import b from "./b"; export default b; if(module.hot) { module.hot.decline("./b"); module.hot.accept(); } webpack-3.5.6/test/hotCases/errors/decline/b.js000066400000000000000000000000361315401342100213600ustar00rootroot00000000000000export { default } from "./c" webpack-3.5.6/test/hotCases/errors/decline/c.js000066400000000000000000000000501315401342100213550ustar00rootroot00000000000000export default 1; --- export default 2; webpack-3.5.6/test/hotCases/errors/decline/index.js000066400000000000000000000005561315401342100222550ustar00rootroot00000000000000import a from "./a"; it("should abort when module is declined by parent", function(done) { a.should.be.eql(1); NEXT(require("../../update")(function(err) { try { err.message.should.match(/Aborted because of declined dependency: \.\/b\.js in \.\/a\.js\nUpdate propagation: \.\/c\.js -> \.\/b\.js -> \.\/a\.js/); done(); } catch(e) { done(e); } })); }); webpack-3.5.6/test/hotCases/errors/events/000077500000000000000000000000001315401342100205035ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/errors/events/a.js000066400000000000000000000000501315401342100212540ustar00rootroot00000000000000export default 1; --- export default 2; webpack-3.5.6/test/hotCases/errors/events/b.js000066400000000000000000000001031315401342100212540ustar00rootroot00000000000000import c from "./c" if(module.hot) { module.hot.accept("./c"); } webpack-3.5.6/test/hotCases/errors/events/c.js000066400000000000000000000000501315401342100212560ustar00rootroot00000000000000export default 1; --- export default 2; webpack-3.5.6/test/hotCases/errors/events/d.js000066400000000000000000000001001315401342100212530ustar00rootroot00000000000000import e from "./e"; if(module.hot) { module.hot.decline(); } webpack-3.5.6/test/hotCases/errors/events/e.js000066400000000000000000000000501315401342100212600ustar00rootroot00000000000000export default 1; --- export default 2; webpack-3.5.6/test/hotCases/errors/events/f.js000066400000000000000000000001041315401342100212610ustar00rootroot00000000000000import g from "./g"; if(module.hot) { module.hot.decline("./g"); }webpack-3.5.6/test/hotCases/errors/events/g.js000066400000000000000000000000501315401342100212620ustar00rootroot00000000000000export default 1; --- export default 2; webpack-3.5.6/test/hotCases/errors/events/h.js000066400000000000000000000001041315401342100212630ustar00rootroot00000000000000import i from "./i"; if(module.hot) { module.hot.accept("./i"); } webpack-3.5.6/test/hotCases/errors/events/i.js000066400000000000000000000001311315401342100212640ustar00rootroot00000000000000export default 1; --- export default 2; throw new Error("Error while loading module h"); webpack-3.5.6/test/hotCases/errors/events/index.js000066400000000000000000000032741315401342100221560ustar00rootroot00000000000000import 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", function(done) { var events = []; var options = { ignoreUnaccepted: true, ignoreDeclined: true, ignoreErrored: true, onDeclined: function(data) { events.push(data); }, onUnaccepted: function(data) { events.push(data); }, onAccepted: function(data) { events.push(data); }, onErrored: function(data) { events.push(data); } }; function waitForUpdate(fn) { NEXT(require("../../update")(done, options, function() { try { fn(); } catch(e) { done(e); } })); } waitForUpdate(function() { events.should.be.eql([ { 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-3.5.6/test/hotCases/errors/events/j.js000066400000000000000000000001561315401342100212740ustar00rootroot00000000000000export default 1; module.hot.accept(); --- export default 2; throw new Error("Error while loading module j"); webpack-3.5.6/test/hotCases/errors/self-decline/000077500000000000000000000000001315401342100215315ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/errors/self-decline/a.js000066400000000000000000000001231315401342100223030ustar00rootroot00000000000000import b from "./b"; export default b; if(module.hot) { module.hot.decline(); } webpack-3.5.6/test/hotCases/errors/self-decline/b.js000066400000000000000000000000361315401342100223070ustar00rootroot00000000000000export { default } from "./c" webpack-3.5.6/test/hotCases/errors/self-decline/c.js000066400000000000000000000000501315401342100223040ustar00rootroot00000000000000export default 1; --- export default 2; webpack-3.5.6/test/hotCases/errors/self-decline/index.js000066400000000000000000000005321315401342100231760ustar00rootroot00000000000000import a from "./a"; it("should abort when module is declined by itself", function(done) { a.should.be.eql(1); NEXT(require("../../update")(function(err) { try { err.message.should.match(/Aborted because of self decline: \.\/a\.js\nUpdate propagation: \.\/c\.js -> \.\/b\.js -> \.\/a\.js/); done(); } catch(e) { done(e); } })); }); webpack-3.5.6/test/hotCases/errors/unaccepted-ignored/000077500000000000000000000000001315401342100227375ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/errors/unaccepted-ignored/a.js000066400000000000000000000001241315401342100235120ustar00rootroot00000000000000export default 2; --- export default 3; --- export default 3; --- export default 4; webpack-3.5.6/test/hotCases/errors/unaccepted-ignored/b.js000066400000000000000000000001611315401342100235140ustar00rootroot00000000000000import c from "./c" export default function get() { return c; } if(module.hot) { module.hot.accept("./c"); } webpack-3.5.6/test/hotCases/errors/unaccepted-ignored/c.js000066400000000000000000000001241315401342100235140ustar00rootroot00000000000000export default 1; --- export default 1; --- export default 2; --- export default 3; webpack-3.5.6/test/hotCases/errors/unaccepted-ignored/index.js000066400000000000000000000010521315401342100244020ustar00rootroot00000000000000import a from "./a"; import get from "./b"; var options = { ignoreUnaccepted: true }; it("should ignore unaccepted module updates", function(done) { function waitForUpdate(fn) { NEXT(require("../../update")(done, options, fn)); } a.should.be.eql(2); get().should.be.eql(1); waitForUpdate(function() { a.should.be.eql(2); get().should.be.eql(1); waitForUpdate(function() { a.should.be.eql(2); get().should.be.eql(2); waitForUpdate(function() { a.should.be.eql(2); get().should.be.eql(3); done(); }); }); }); }); webpack-3.5.6/test/hotCases/errors/unaccepted/000077500000000000000000000000001315401342100213125ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/errors/unaccepted/a.js000066400000000000000000000000211315401342100220610ustar00rootroot00000000000000export default 2;webpack-3.5.6/test/hotCases/errors/unaccepted/b.js000066400000000000000000000000361315401342100220700ustar00rootroot00000000000000export { default } from "./c" webpack-3.5.6/test/hotCases/errors/unaccepted/c.js000066400000000000000000000000501315401342100220650ustar00rootroot00000000000000export default 1; --- export default 2; webpack-3.5.6/test/hotCases/errors/unaccepted/index.js000066400000000000000000000006011315401342100227540ustar00rootroot00000000000000import a from "./a"; import b from "./b"; it("should abort when module is not accepted", function(done) { a.should.be.eql(2); b.should.be.eql(1); NEXT(require("../../update")(function(err) { try { err.message.should.match(/Aborted because \.\/c\.js is not accepted\nUpdate propagation: \.\/c\.js -> \.\/b\.js -> \.\/index\.js/); done(); } catch(e) { done(e); } })); }); webpack-3.5.6/test/hotCases/fake-update-loader.js000066400000000000000000000002721315401342100216540ustar00rootroot00000000000000module.exports = function(source) { this.cacheable(false); var idx = this.options.updateIndex; var items = source.split(/---+\r?\n/g); return items[idx] || items[items.length - 1]; }webpack-3.5.6/test/hotCases/harmony/000077500000000000000000000000001315401342100173405ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/harmony/auto-import-multiple/000077500000000000000000000000001315401342100234515ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/harmony/auto-import-multiple/commonjs.js000066400000000000000000000000561315401342100256350ustar00rootroot00000000000000module.exports = 10; --- module.exports = 20; webpack-3.5.6/test/hotCases/harmony/auto-import-multiple/file.js000066400000000000000000000000601315401342100247220ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-3.5.6/test/hotCases/harmony/auto-import-multiple/index.js000066400000000000000000000007111315401342100251150ustar00rootroot00000000000000import { value } from "./file"; import value2 from "./commonjs"; it("should auto-import multiple ES6 imported values on accept", function(done) { value.should.be.eql(1); value2.should.be.eql(10); module.hot.accept(["./file", "./commonjs"], function() { value.should.be.eql(2); value2.should.be.eql(20); outside(); done(); }); NEXT(require("../../update")(done)); }); function outside() { value.should.be.eql(2); value2.should.be.eql(20); } webpack-3.5.6/test/hotCases/harmony/auto-import/000077500000000000000000000000001315401342100216205ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/harmony/auto-import/file.js000066400000000000000000000000601315401342100230710ustar00rootroot00000000000000export var value = 1; --- export var value = 2; webpack-3.5.6/test/hotCases/harmony/auto-import/index.js000066400000000000000000000004761315401342100232740ustar00rootroot00000000000000import { value } from "./file"; it("should auto-import a ES6 imported value on accept", function(done) { value.should.be.eql(1); module.hot.accept("./file", function() { value.should.be.eql(2); outside(); done(); }); NEXT(require("../../update")(done)); }); function outside() { value.should.be.eql(2); } webpack-3.5.6/test/hotCases/hash/000077500000000000000000000000001315401342100166065ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/hash/separate-css-file/000077500000000000000000000000001315401342100221155ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/hash/separate-css-file/file.css000066400000000000000000000000721315401342100235450ustar00rootroot00000000000000body { background: red; } --- body { background: green; } webpack-3.5.6/test/hotCases/hash/separate-css-file/index.js000066400000000000000000000004301315401342100235570ustar00rootroot00000000000000import "./file.css"; it("should not change hash of file after css update", function(done) { var hash1 = STATS.chunks[0].hash; NEXT(require("../../update")(done, true, function(newSTATS) { var hash2 = newSTATS.chunks[0].hash; hash1.should.be.eql(hash2); done(); })); }); webpack-3.5.6/test/hotCases/recover/000077500000000000000000000000001315401342100173305ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/recover/recover-after-error/000077500000000000000000000000001315401342100232235ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/recover/recover-after-error/a.js000066400000000000000000000001311315401342100237740ustar00rootroot00000000000000export default 1; --- export default 2; throw new Error("Failed"); --- export default 3; webpack-3.5.6/test/hotCases/recover/recover-after-error/index.js000066400000000000000000000006001315401342100246640ustar00rootroot00000000000000import a from "./a"; it("should abort when module is not accepted", function(done) { a.should.be.eql(1); NEXT(require("../../update")(done, { ignoreErrored: true }, function() { a.should.be.eql(1); NEXT(require("../../update")(done, { ignoreErrored: true }, function() { a.should.be.eql(3); done(); })); })); }); if(module.hot) { module.hot.accept("./a"); } webpack-3.5.6/test/hotCases/recover/recover-after-loader-error/000077500000000000000000000000001315401342100244675ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/recover/recover-after-loader-error/a.js000066400000000000000000000000711315401342100252430ustar00rootroot00000000000000export default 1; --- Loader error --- export default 3; webpack-3.5.6/test/hotCases/recover/recover-after-loader-error/errors1.js000066400000000000000000000000471315401342100264230ustar00rootroot00000000000000module.exports = [ [/Loader error/] ] webpack-3.5.6/test/hotCases/recover/recover-after-loader-error/index.js000066400000000000000000000006221315401342100261340ustar00rootroot00000000000000import a from "./loader!./a"; it("should abort when module is not accepted", function(done) { a.should.be.eql(1); NEXT(require("../../update")(done, { ignoreErrored: true }, function() { a.should.be.eql(1); NEXT(require("../../update")(done, { ignoreErrored: true }, function() { a.should.be.eql(3); done(); })); })); }); if(module.hot) { module.hot.accept("./loader!./a"); } webpack-3.5.6/test/hotCases/recover/recover-after-loader-error/loader.js000066400000000000000000000001731315401342100262740ustar00rootroot00000000000000module.exports = function(source) { if(source.indexOf("error") >= 0) throw new Error(source.trim()); return source; }; webpack-3.5.6/test/hotCases/recover/recover-after-parsing-error/000077500000000000000000000000001315401342100246645ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/recover/recover-after-parsing-error/a.js000066400000000000000000000001031315401342100254340ustar00rootroot00000000000000export default 1; --- ]}); export default 2; --- export default 3; webpack-3.5.6/test/hotCases/recover/recover-after-parsing-error/errors1.js000066400000000000000000000000551315401342100266170ustar00rootroot00000000000000module.exports = [ [/Module parse failed/] ]webpack-3.5.6/test/hotCases/recover/recover-after-parsing-error/index.js000066400000000000000000000006001315401342100263250ustar00rootroot00000000000000import a from "./a"; it("should abort when module is not accepted", function(done) { a.should.be.eql(1); NEXT(require("../../update")(done, { ignoreErrored: true }, function() { a.should.be.eql(1); NEXT(require("../../update")(done, { ignoreErrored: true }, function() { a.should.be.eql(3); done(); })); })); }); if(module.hot) { module.hot.accept("./a"); } webpack-3.5.6/test/hotCases/runtime/000077500000000000000000000000001315401342100173465ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/accept/000077500000000000000000000000001315401342100206055ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/accept/file.js000066400000000000000000000000541315401342100220610ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-3.5.6/test/hotCases/runtime/accept/index.js000066400000000000000000000005351315401342100222550ustar00rootroot00000000000000var value = require("./file"); it("should accept a dependencies and require a new value", function(done) { value.should.be.eql(1); module.hot.accept("./file", function() { value = require("./file"); value.should.be.eql(2); outside(); done(); }); NEXT(require("../../update")(done)); }); function outside() { value.should.be.eql(2); } webpack-3.5.6/test/hotCases/runtime/bubble-update/000077500000000000000000000000001315401342100220615ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/bubble-update/file.js000066400000000000000000000000541315401342100233350ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-3.5.6/test/hotCases/runtime/bubble-update/index.js000066400000000000000000000004551315401342100235320ustar00rootroot00000000000000var value = require("./parent-file"); it("should bubble update from a nested dependency", function(done) { value.should.be.eql(1); module.hot.accept("./parent-file", function() { value = require("./parent-file"); value.should.be.eql(2); done(); }); NEXT(require("../../update")(done)); }); webpack-3.5.6/test/hotCases/runtime/bubble-update/parent-file.js000066400000000000000000000000441315401342100246230ustar00rootroot00000000000000module.exports = require("./file"); webpack-3.5.6/test/hotCases/runtime/circular/000077500000000000000000000000001315401342100211525ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/circular/a.js000066400000000000000000000001361315401342100217300ustar00rootroot00000000000000import "./"; import "./b"; export default 1; --- import "./"; import "./b"; export default 2; webpack-3.5.6/test/hotCases/runtime/circular/b.js000066400000000000000000000001201315401342100217220ustar00rootroot00000000000000import "./a"; export default 1; module.hot.accept("./a"); --- export default 2; webpack-3.5.6/test/hotCases/runtime/circular/index.js000066400000000000000000000003421315401342100226160ustar00rootroot00000000000000import a from "./a"; it("should not throw on circular dependencies", function(done) { a.should.be.eql(1); module.hot.accept("./a", function() { a.should.be.eql(2); done(); }); NEXT(require("../../update")(done)); }); webpack-3.5.6/test/hotCases/runtime/dispose-removed-chunk/000077500000000000000000000000001315401342100235615ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/dispose-removed-chunk/a.js000066400000000000000000000000321315401342100243320ustar00rootroot00000000000000export default Date.now();webpack-3.5.6/test/hotCases/runtime/dispose-removed-chunk/b.js000066400000000000000000000000001315401342100243260ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/dispose-removed-chunk/index.js000066400000000000000000000007421315401342100252310ustar00rootroot00000000000000it("should dispose a chunk which is removed from bundle", function(done) { var m1 = require("./module"); NEXT(require("../../update")(done, true, function() { var m2 = require("./module"); NEXT(require("../../update")(done, true, function() { var m3 = require("./module"); Promise.all([m1.default, m2.default, m3.default]).then(function(arr) { arr[0].should.be.not.eql(arr[2]); done(); }); })); })); }); if(module.hot) { module.hot.accept("./module"); } webpack-3.5.6/test/hotCases/runtime/dispose-removed-chunk/module.js000066400000000000000000000001671315401342100254100ustar00rootroot00000000000000export default System.import("./a"); --- export default System.import("./b"); --- export default System.import("./a"); webpack-3.5.6/test/hotCases/runtime/dispose-removed-module/000077500000000000000000000000001315401342100237365ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/dispose-removed-module/a.js000066400000000000000000000002741315401342100245170ustar00rootroot00000000000000var callback; export default function setHandler(cb) { callback = cb; }; if(module.hot) { module.hot.dispose(function() { callback(module.id); }); } --- --- export default module.id;webpack-3.5.6/test/hotCases/runtime/dispose-removed-module/b.js000066400000000000000000000000211315401342100245060ustar00rootroot00000000000000export default 1;webpack-3.5.6/test/hotCases/runtime/dispose-removed-module/index.js000066400000000000000000000007431315401342100254070ustar00rootroot00000000000000var m = require("./module"); it("should dispose a module which is removed from bundle", function(done) { var disposed = []; m.setHandler(function(id) { disposed.push(id); }); NEXT(require("../../update")(done, true, function() { require("./module"); NEXT(require("../../update")(done, true, function() { var newModule = require("./module"); disposed.should.be.eql([newModule.default]); done(); })); })); }); if(module.hot) { module.hot.accept("./module"); } webpack-3.5.6/test/hotCases/runtime/dispose-removed-module/module.js000066400000000000000000000001531315401342100255600ustar00rootroot00000000000000export { default as setHandler } from "./a"; --- import "./b" --- export { default as default } from "./a";webpack-3.5.6/test/hotCases/runtime/self-accept-and-dispose/000077500000000000000000000000001315401342100237405ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/self-accept-and-dispose/file.js000066400000000000000000000002741315401342100252200ustar00rootroot00000000000000var callback; module.hot.accept(); module.hot.dispose(function(data) { data.callback = callback; }); module.exports = function(cb) { callback = cb; } --- module.hot.data.callback(); webpack-3.5.6/test/hotCases/runtime/self-accept-and-dispose/index.js000066400000000000000000000001761315401342100254110ustar00rootroot00000000000000it("should accept itself and pass data", function(done) { require("./file")(done); NEXT(require("../../update")(done)); }); webpack-3.5.6/test/hotCases/runtime/update-multiple-modules/000077500000000000000000000000001315401342100241275ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/update-multiple-modules/fileA.js000066400000000000000000000000541315401342100255040ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-3.5.6/test/hotCases/runtime/update-multiple-modules/fileB.js000066400000000000000000000000541315401342100255050ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; webpack-3.5.6/test/hotCases/runtime/update-multiple-modules/index.js000066400000000000000000000004571315401342100256020ustar00rootroot00000000000000var value = require("./parent-file"); it("should update multiple modules at the same time", function(done) { value.should.be.eql(2); module.hot.accept("./parent-file", function() { value = require("./parent-file"); value.should.be.eql(4); done(); }); NEXT(require("../../update")(done)); }); webpack-3.5.6/test/hotCases/runtime/update-multiple-modules/parent-file.js000066400000000000000000000000721315401342100266720ustar00rootroot00000000000000module.exports = require("./fileA") + require("./fileB"); webpack-3.5.6/test/hotCases/runtime/update-multiple-times/000077500000000000000000000000001315401342100236005ustar00rootroot00000000000000webpack-3.5.6/test/hotCases/runtime/update-multiple-times/file.js000066400000000000000000000001641315401342100250560ustar00rootroot00000000000000module.exports = 1; --- module.exports = 2; --- module.exports = 3; --- module.exports = 4; --- module.exports = 5; webpack-3.5.6/test/hotCases/runtime/update-multiple-times/index.js000066400000000000000000000005711315401342100252500ustar00rootroot00000000000000var value = require("./file"); it("should accept a dependencies multiple times", function(done) { value.should.be.eql(1); module.hot.accept("./file", function() { var oldValue = value; value = require("./file"); value.should.be.eql(oldValue + 1); if(value < 4) NEXT(require("../../update")(done)); else done(); }); NEXT(require("../../update")(done)); }); webpack-3.5.6/test/hotCases/update.js000066400000000000000000000003371315401342100175060ustar00rootroot00000000000000module.exports = function(done, options, callback) { return function(stats) { module.hot.check(options || true).then(function() { if(callback) callback(stats); }).catch(function(err) { done(err); }); } }; webpack-3.5.6/test/hotPlayground/000077500000000000000000000000001315401342100167515ustar00rootroot00000000000000webpack-3.5.6/test/hotPlayground/.gitignore000066400000000000000000000000501315401342100207340ustar00rootroot00000000000000*bundle-update.js bundle.js records.jsonwebpack-3.5.6/test/hotPlayground/addStyle.js000066400000000000000000000010121315401342100210520ustar00rootroot00000000000000/* 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-3.5.6/test/hotPlayground/applyStyle2.js000066400000000000000000000002111315401342100215310ustar00rootroot00000000000000// This file can update, because it accept itself. // A dispose handler removes the old