├── .gitignore ├── demo1 ├── README.md ├── index.html ├── index.js ├── package-lock.json └── package.json ├── demo10 ├── README.md ├── package.json ├── public │ └── index.html ├── src │ └── index.js ├── webpack.config.js └── webpack.dll.js ├── demo11 ├── .babelrc ├── .eslintrc.js ├── README.md ├── package-lock.json ├── package.json ├── src │ ├── adapters │ │ └── xhr.ts │ ├── cancel │ │ ├── Cancel.ts │ │ ├── CancelToken.ts │ │ └── isCancel.ts │ ├── core │ │ ├── Axios.ts │ │ ├── InterceptorManager.ts │ │ ├── buildFullPath.ts │ │ ├── createError.ts │ │ ├── dispatchRequest.ts │ │ ├── enhanceError.ts │ │ ├── mergeConfig.ts │ │ ├── settle.ts │ │ └── transformData.ts │ ├── defaults.ts │ ├── helpers │ │ ├── README.md │ │ ├── bind.ts │ │ ├── buildURL.ts │ │ ├── combineURLs.ts │ │ ├── cookies.ts │ │ ├── deprecatedMethod.ts │ │ ├── isAbsoluteURL.ts │ │ ├── isURLSameOrigin.ts │ │ ├── normalizeHeaderName.ts │ │ ├── parseHeaders.ts │ │ └── spread.ts │ ├── index.js │ └── utils.ts ├── tsconfig.json ├── webpack.config.js └── webpack.happy.js ├── demo12 ├── .babelrc ├── README.md ├── package-lock.json ├── package.json ├── public │ └── index.html ├── src │ ├── index.js │ └── utils.js └── webpack.config.js ├── demo13 ├── .babelrc ├── README.md ├── package.json ├── src │ └── index.js └── webpack.config.js ├── demo14 ├── .babelrc ├── README.md ├── package-lock.json ├── package.json ├── public │ └── index.html ├── src │ ├── async.js │ ├── async_a.js │ ├── async_b.js │ ├── detail.js │ ├── home.js │ ├── list.js │ └── utils.js ├── webpack.config.js └── yarn.lock ├── demo15 ├── READMD.md ├── package.json ├── public │ └── index.html ├── src │ └── index.js └── webpack.config.js ├── demo16 ├── .babelrc ├── README.md ├── package.json ├── src │ └── index.js └── webpack.config.js ├── demo17 ├── .babelrc ├── README.md ├── package.json ├── src │ └── index.js └── webpack.config.js ├── demo18 ├── .babelrc ├── README.md ├── package.json ├── src │ └── index.js └── webpack.config.js ├── demo19 ├── README.md ├── loader │ ├── banner-loader.js │ ├── banner1.txt │ ├── banner2.txt │ ├── cleanlog-loader.js │ ├── less-loader.js │ ├── schema.json │ └── style-loader.js ├── package.json ├── public │ └── index.html ├── src │ ├── index.js │ └── index.less └── webpack.config.js ├── demo2 ├── index.html ├── src │ ├── header.js │ └── index.js └── webpack.config.js ├── demo20 ├── README.md ├── package.json ├── plugins │ ├── FileListPlugin.js │ └── MyPlugin.js ├── public │ └── index.html ├── src │ └── index.js └── webpack.config.js ├── demo3 ├── README.md ├── index.html ├── package.json ├── src │ ├── common.js │ ├── detail.js │ ├── home.js │ └── list.js └── webpack.config.js ├── demo4 ├── .babelrc ├── .browserslistrc ├── READMD.md ├── index.html ├── package.json ├── postcss.config.js ├── src │ ├── bg.png │ ├── bg1.png │ ├── foot.css │ ├── head.css │ ├── index.css │ ├── index.js │ ├── left.scss │ └── right.less └── webpack.config.js ├── demo5 ├── .babelrc ├── README.md ├── package.json ├── public │ └── index.html ├── src │ ├── App.vue │ └── main.js └── webpack.config.js ├── demo6 ├── .babelrc ├── README.md ├── package.json ├── public │ ├── index.html │ └── js │ │ └── js.cookie.min.js ├── src │ ├── index.css │ ├── index.js │ └── math.js └── webpack.dev.config.js ├── demo7 ├── .browserslistrc ├── README.md ├── package.json ├── postcss.config.js ├── public │ ├── index.html │ └── js │ │ └── js.cookie.min.js ├── src │ ├── index.js │ └── index.less └── webpack.config.js ├── demo8 ├── .babelrc ├── .browserslistrc ├── .eslintrc ├── READMD.md ├── index.html ├── package.json ├── postcss.config.js ├── src │ ├── bg.png │ ├── bg1.png │ ├── foot.css │ ├── head.css │ ├── index.css │ ├── index.js │ ├── left.scss │ └── right.less └── webpack.config.js └── demo9 ├── .babelrc ├── .eslintrc.js ├── README.md ├── package-lock.json ├── package.json ├── src ├── adapters │ └── xhr.ts ├── axios.ts ├── cancel │ ├── Cancel.ts │ ├── CancelToken.ts │ └── isCancel.ts ├── core │ ├── Axios.ts │ ├── InterceptorManager.ts │ ├── buildFullPath.ts │ ├── createError.ts │ ├── dispatchRequest.ts │ ├── enhanceError.ts │ ├── mergeConfig.ts │ ├── settle.ts │ └── transformData.ts ├── defaults.ts ├── helpers │ ├── README.md │ ├── bind.ts │ ├── buildURL.ts │ ├── combineURLs.ts │ ├── cookies.ts │ ├── deprecatedMethod.ts │ ├── isAbsoluteURL.ts │ ├── isURLSameOrigin.ts │ ├── normalizeHeaderName.ts │ ├── parseHeaders.ts │ └── spread.ts ├── index.ts └── utils.ts ├── tsconfig.json ├── webpack.config.js └── webpack.config.optimize.js /.gitignore: -------------------------------------------------------------------------------- 1 | */node_modules 2 | */dist 3 | */public/vendor 4 | */package-lock.json -------------------------------------------------------------------------------- /demo1/README.md: -------------------------------------------------------------------------------- 1 | # 命令行 2 | 3 | ```js 4 | webpack index.js -o dist/bundle.js 5 | ``` 6 | 7 | 8 | -------------------------------------------------------------------------------- /demo1/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /demo1/index.js: -------------------------------------------------------------------------------- 1 | var a = 1 2 | console.log(a) 3 | document.write('hello webpack') -------------------------------------------------------------------------------- /demo1/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo1", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "devDependencies": { 12 | "webpack": "^4.43.0", 13 | "webpack-cli": "^3.3.11" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /demo10/README.md: -------------------------------------------------------------------------------- 1 | # 动态链接DllPlugin -------------------------------------------------------------------------------- /demo10/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo10", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "webpack", 9 | "build:dll": "webpack --config=webpack.dll.js" 10 | }, 11 | "author": "", 12 | "license": "ISC", 13 | "devDependencies": { 14 | "@babel/core": "^7.10.5", 15 | "@babel/plugin-transform-runtime": "^7.10.5", 16 | "@babel/preset-env": "^7.10.4", 17 | "babel-loader": "^8.1.0", 18 | "copy-webpack-plugin": "^6.0.3", 19 | "html-webpack-plugin": "^4.3.0", 20 | "webpack-cli": "^3.3.12" 21 | }, 22 | "dependencies": { 23 | "@babel/runtime": "^7.10.5", 24 | "axios": "^0.19.2", 25 | "dayjs": "^1.8.30", 26 | "element-ui": "^2.13.2", 27 | "mint-ui": "^2.2.13", 28 | "qs": "^6.9.4", 29 | "vue": "^2.6.11", 30 | "vue-router": "^3.3.4", 31 | "vuex": "^3.5.1", 32 | "webpack": "^4.43.0" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /demo10/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 |
10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /demo10/src/index.js: -------------------------------------------------------------------------------- 1 | var Vue = require('vue') 2 | var Vuex = require('vuex') 3 | var VueRouter = require('vue-router') 4 | var dayjs = require('dayjs') 5 | var axios = require('axios') 6 | var MintUI = require('mint-ui') 7 | 8 | 9 | console.log(dayjs(), Vue) 10 | -------------------------------------------------------------------------------- /demo10/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | const CopyWebpackPlugin = require('copy-webpack-plugin'); 4 | const webpack = require('webpack') 5 | module.exports = { 6 | mode: "production", 7 | entry: "./src/index.js", 8 | output: { 9 | path: path.resolve(__dirname, "dist"), 10 | filename: "index.js", 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | test: /\.js/, 16 | use: [ 17 | { 18 | loader: "babel-loader", 19 | } 20 | ], 21 | }, 22 | ], 23 | }, 24 | plugins: [ 25 | new HtmlWebpackPlugin({ 26 | template: './public/index.html', 27 | filename: 'index.html', //打包后的文件名 28 | minify: { 29 | removeAttributeQuotes: false, 30 | collapseWhitespace: false, 31 | }, 32 | }), 33 | new CopyWebpackPlugin({ 34 | patterns: [ 35 | { 36 | from: 'public/vendor/*.js', 37 | to: path.resolve(__dirname, 'dist', 'vendor'), 38 | flatten: true, 39 | }, 40 | { 41 | from: 'public/vendor/*.json', 42 | to: path.resolve(__dirname, 'dist', 'vendor'), 43 | flatten: true, 44 | } 45 | ] 46 | }), 47 | new webpack.DllReferencePlugin({ 48 | context: path.join(__dirname), 49 | manifest: require('./public/vendor/vendor.manifest.json') 50 | }), 51 | new webpack.DllReferencePlugin({ 52 | context: path.join(__dirname), 53 | manifest: require('./public/vendor/vue.manifest.json') 54 | }), 55 | ] 56 | }; 57 | -------------------------------------------------------------------------------- /demo10/webpack.dll.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | 4 | module.exports = { 5 | mode: "production", 6 | entry: { 7 | vue: ["vue", "vuex", "vue-router"], 8 | vendor: ["dayjs", "axios", "mint-ui"], 9 | }, 10 | output: { 11 | path: path.resolve(__dirname, "public/vendor"), 12 | // 指定文件名 13 | filename: "[name].dll.js", 14 | library: "[name]_dll_lib", 15 | }, 16 | plugins: [ 17 | new webpack.DllPlugin({ 18 | path: path.join(__dirname, "public", "vendor", "[name].manifest.json"), 19 | name: "[name]_dll_lib", 20 | }), 21 | ], 22 | }; 23 | -------------------------------------------------------------------------------- /demo11/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ], 5 | "plugins": [ 6 | "@babel/plugin-transform-runtime" 7 | ] 8 | } -------------------------------------------------------------------------------- /demo11/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | rules: { 3 | "no-undef": "off", 4 | "no-unused-vars": "off", 5 | "no-inner-declarations": "off", 6 | "no-extra-boolean-cast": "off", 7 | }, 8 | parserOptions: { 9 | ecmaVersion: 7, 10 | sourceType: "module", 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /demo11/README.md: -------------------------------------------------------------------------------- 1 | # happypack -------------------------------------------------------------------------------- /demo11/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo9", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "dependencies": { 7 | "@babel/runtime": "^7.10.5", 8 | "moment": "^2.27.0", 9 | "vue": "^2.6.11" 10 | }, 11 | "devDependencies": { 12 | "@babel/core": "^7.10.5", 13 | "@babel/plugin-transform-runtime": "^7.10.5", 14 | "@babel/preset-env": "^7.10.4", 15 | "babel-loader": "^8.1.0", 16 | "css-loader": "^4.2.1", 17 | "eslint": "^7.5.0", 18 | "eslint-loader": "^4.0.2", 19 | "happypack": "^5.0.1", 20 | "less-loader": "^6.2.0", 21 | "mini-css-extract-plugin": "^0.9.0", 22 | "speed-measure-webpack-plugin": "^1.3.3", 23 | "ts-loader": "^8.0.1", 24 | "typescript": "^3.9.7", 25 | "webpack": "^4.43.0", 26 | "webpack-cli": "^3.3.12" 27 | }, 28 | "scripts": { 29 | "test": "echo \"Error: no test specified\" && exit 1", 30 | "build": "webpack", 31 | "build:happy": "webpack --config webpack.happy.js" 32 | }, 33 | "author": "", 34 | "license": "ISC" 35 | } 36 | -------------------------------------------------------------------------------- /demo11/src/adapters/xhr.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | import settle from './../core/settle'; 5 | import cookies from './../helpers/cookies'; 6 | import buildURL from './../helpers/buildURL'; 7 | import buildFullPath from '../core/buildFullPath'; 8 | import parseHeaders from './../helpers/parseHeaders'; 9 | import isURLSameOrigin from './../helpers/isURLSameOrigin'; 10 | import createError from '../core/createError'; 11 | 12 | export default function xhrAdapter(config) { 13 | return new Promise(function dispatchXhrRequest(resolve, reject) { 14 | var requestData = config.data; 15 | var requestHeaders = config.headers; 16 | 17 | if (utils.isFormData(requestData)) { 18 | delete requestHeaders['Content-Type']; // Let the browser set it 19 | } 20 | 21 | if ( 22 | (utils.isBlob(requestData) || utils.isFile(requestData)) && 23 | requestData.type 24 | ) { 25 | delete requestHeaders['Content-Type']; // Let the browser set it 26 | } 27 | 28 | var request = new XMLHttpRequest(); 29 | 30 | // HTTP basic authentication 31 | if (config.auth) { 32 | var username = config.auth.username || ''; 33 | var password = unescape(encodeURIComponent(config.auth.password)) || ''; 34 | requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); 35 | } 36 | 37 | var fullPath = buildFullPath(config.baseURL, config.url); 38 | request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); 39 | 40 | // Set the request timeout in MS 41 | request.timeout = config.timeout; 42 | 43 | // Listen for ready state 44 | request.onreadystatechange = function handleLoad() { 45 | if (!request || request.readyState !== 4) { 46 | return; 47 | } 48 | 49 | // The request errored out and we didn't get a response, this will be 50 | // handled by onerror instead 51 | // With one exception: request that using file: protocol, most browsers 52 | // will return status as 0 even though it's a successful request 53 | if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { 54 | return; 55 | } 56 | 57 | // Prepare the response 58 | var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; 59 | var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; 60 | var response = { 61 | data: responseData, 62 | status: request.status, 63 | statusText: request.statusText, 64 | headers: responseHeaders, 65 | config: config, 66 | request: request 67 | }; 68 | 69 | settle(resolve, reject, response); 70 | 71 | // Clean up request 72 | request = null; 73 | }; 74 | 75 | // Handle browser request cancellation (as opposed to a manual cancellation) 76 | request.onabort = function handleAbort() { 77 | if (!request) { 78 | return; 79 | } 80 | 81 | reject(createError('Request aborted', config, 'ECONNABORTED', request)); 82 | 83 | // Clean up request 84 | request = null; 85 | }; 86 | 87 | // Handle low level network errors 88 | request.onerror = function handleError() { 89 | // Real errors are hidden from us by the browser 90 | // onerror should only fire if it's a network error 91 | reject(createError('Network Error', config, null, request)); 92 | 93 | // Clean up request 94 | request = null; 95 | }; 96 | 97 | // Handle timeout 98 | request.ontimeout = function handleTimeout() { 99 | var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; 100 | if (config.timeoutErrorMessage) { 101 | timeoutErrorMessage = config.timeoutErrorMessage; 102 | } 103 | reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', 104 | request)); 105 | 106 | // Clean up request 107 | request = null; 108 | }; 109 | 110 | // Add xsrf header 111 | // This is only done if running in a standard browser environment. 112 | // Specifically not if we're in a web worker, or react-native. 113 | if (utils.isStandardBrowserEnv()) { 114 | // Add xsrf header 115 | var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? 116 | cookies.read(config.xsrfCookieName) : 117 | undefined; 118 | 119 | if (xsrfValue) { 120 | requestHeaders[config.xsrfHeaderName] = xsrfValue; 121 | } 122 | } 123 | 124 | // Add headers to the request 125 | if ('setRequestHeader' in request) { 126 | utils.forEach(requestHeaders, function setRequestHeader(val, key) { 127 | if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { 128 | // Remove Content-Type if data is undefined 129 | delete requestHeaders[key]; 130 | } else { 131 | // Otherwise add header to the request 132 | request.setRequestHeader(key, val); 133 | } 134 | }); 135 | } 136 | 137 | // Add withCredentials to request if needed 138 | if (!utils.isUndefined(config.withCredentials)) { 139 | request.withCredentials = !!config.withCredentials; 140 | } 141 | 142 | // Add responseType to request if needed 143 | if (config.responseType) { 144 | try { 145 | request.responseType = config.responseType; 146 | } catch (e) { 147 | // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. 148 | // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. 149 | if (config.responseType !== 'json') { 150 | throw e; 151 | } 152 | } 153 | } 154 | 155 | // Handle progress if needed 156 | if (typeof config.onDownloadProgress === 'function') { 157 | request.addEventListener('progress', config.onDownloadProgress); 158 | } 159 | 160 | // Not all browsers support upload events 161 | if (typeof config.onUploadProgress === 'function' && request.upload) { 162 | request.upload.addEventListener('progress', config.onUploadProgress); 163 | } 164 | 165 | if (config.cancelToken) { 166 | // Handle cancellation 167 | config.cancelToken.promise.then(function onCanceled(cancel) { 168 | if (!request) { 169 | return; 170 | } 171 | 172 | request.abort(); 173 | reject(cancel); 174 | // Clean up request 175 | request = null; 176 | }); 177 | } 178 | 179 | if (!requestData) { 180 | requestData = null; 181 | } 182 | 183 | // Send the request 184 | request.send(requestData); 185 | }); 186 | }; 187 | -------------------------------------------------------------------------------- /demo11/src/cancel/Cancel.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * A `Cancel` is an object that is thrown when an operation is canceled. 5 | * 6 | * @class 7 | * @param {string=} message The message. 8 | */ 9 | function Cancel(message) { 10 | this.message = message; 11 | } 12 | 13 | Cancel.prototype.toString = function toString() { 14 | return 'Cancel' + (this.message ? ': ' + this.message : ''); 15 | }; 16 | 17 | Cancel.prototype.__CANCEL__ = true; 18 | 19 | export default Cancel; 20 | -------------------------------------------------------------------------------- /demo11/src/cancel/CancelToken.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import Cancel from './Cancel'; 4 | 5 | /** 6 | * A `CancelToken` is an object that can be used to request cancellation of an operation. 7 | * 8 | * @class 9 | * @param {Function} executor The executor function. 10 | */ 11 | function CancelToken(executor) { 12 | if (typeof executor !== 'function') { 13 | throw new TypeError('executor must be a function.'); 14 | } 15 | 16 | var resolvePromise; 17 | this.promise = new Promise(function promiseExecutor(resolve) { 18 | resolvePromise = resolve; 19 | }); 20 | 21 | var token = this; 22 | executor(function cancel(message) { 23 | if (token.reason) { 24 | // Cancellation has already been requested 25 | return; 26 | } 27 | 28 | token.reason = new Cancel(message); 29 | resolvePromise(token.reason); 30 | }); 31 | } 32 | 33 | /** 34 | * Throws a `Cancel` if cancellation has been requested. 35 | */ 36 | CancelToken.prototype.throwIfRequested = function throwIfRequested() { 37 | if (this.reason) { 38 | throw this.reason; 39 | } 40 | }; 41 | 42 | /** 43 | * Returns an object that contains a new `CancelToken` and a function that, when called, 44 | * cancels the `CancelToken`. 45 | */ 46 | CancelToken.source = function source() { 47 | var cancel; 48 | var token = new CancelToken(function executor(c) { 49 | cancel = c; 50 | }); 51 | return { 52 | token: token, 53 | cancel: cancel 54 | }; 55 | }; 56 | 57 | export default CancelToken; 58 | -------------------------------------------------------------------------------- /demo11/src/cancel/isCancel.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export default function isCancel(value) { 4 | return !!(value && value.__CANCEL__); 5 | }; 6 | -------------------------------------------------------------------------------- /demo11/src/core/Axios.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | import buildURL from'../helpers/buildURL'; 5 | import InterceptorManager from './InterceptorManager'; 6 | import dispatchRequest from './dispatchRequest'; 7 | import mergeConfig from './mergeConfig'; 8 | 9 | /** 10 | * Create a new instance of Axios 11 | * 12 | * @param {Object} instanceConfig The default config for the instance 13 | */ 14 | function Axios(instanceConfig) { 15 | this.defaults = instanceConfig; 16 | this.interceptors = { 17 | request: new InterceptorManager(), 18 | response: new InterceptorManager() 19 | }; 20 | } 21 | 22 | /** 23 | * Dispatch a request 24 | * 25 | * @param {Object} config The config specific for this request (merged with this.defaults) 26 | */ 27 | Axios.prototype.request = function request(config) { 28 | /*eslint no-param-reassign:0*/ 29 | // Allow for axios('example/url'[, config]) a la fetch API 30 | if (typeof config === 'string') { 31 | config = arguments[1] || {}; 32 | config.url = arguments[0]; 33 | } else { 34 | config = config || {}; 35 | } 36 | 37 | config = mergeConfig(this.defaults, config); 38 | 39 | // Set config.method 40 | if (config.method) { 41 | config.method = config.method.toLowerCase(); 42 | } else if (this.defaults.method) { 43 | config.method = this.defaults.method.toLowerCase(); 44 | } else { 45 | config.method = 'get'; 46 | } 47 | 48 | // Hook up interceptors middleware 49 | var chain = [dispatchRequest, undefined]; 50 | var promise = Promise.resolve(config); 51 | 52 | this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { 53 | chain.unshift(interceptor.fulfilled, interceptor.rejected); 54 | }); 55 | 56 | this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { 57 | chain.push(interceptor.fulfilled, interceptor.rejected); 58 | }); 59 | 60 | while (chain.length) { 61 | promise = promise.then(chain.shift(), chain.shift()); 62 | } 63 | 64 | return promise; 65 | }; 66 | 67 | Axios.prototype.getUri = function getUri(config) { 68 | config = mergeConfig(this.defaults, config); 69 | return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); 70 | }; 71 | 72 | // Provide aliases for supported request methods 73 | utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { 74 | /*eslint func-names:0*/ 75 | Axios.prototype[method] = function(url, config) { 76 | return this.request(mergeConfig(config || {}, { 77 | method: method, 78 | url: url 79 | })); 80 | }; 81 | }); 82 | 83 | utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { 84 | /*eslint func-names:0*/ 85 | Axios.prototype[method] = function(url, data, config) { 86 | return this.request(mergeConfig(config || {}, { 87 | method: method, 88 | url: url, 89 | data: data 90 | })); 91 | }; 92 | }); 93 | 94 | export default Axios; 95 | -------------------------------------------------------------------------------- /demo11/src/core/InterceptorManager.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | function InterceptorManager() { 6 | this.handlers = []; 7 | } 8 | 9 | /** 10 | * Add a new interceptor to the stack 11 | * 12 | * @param {Function} fulfilled The function to handle `then` for a `Promise` 13 | * @param {Function} rejected The function to handle `reject` for a `Promise` 14 | * 15 | * @return {Number} An ID used to remove interceptor later 16 | */ 17 | InterceptorManager.prototype.use = function use(fulfilled, rejected) { 18 | this.handlers.push({ 19 | fulfilled: fulfilled, 20 | rejected: rejected 21 | }); 22 | return this.handlers.length - 1; 23 | }; 24 | 25 | /** 26 | * Remove an interceptor from the stack 27 | * 28 | * @param {Number} id The ID that was returned by `use` 29 | */ 30 | InterceptorManager.prototype.eject = function eject(id) { 31 | if (this.handlers[id]) { 32 | this.handlers[id] = null; 33 | } 34 | }; 35 | 36 | /** 37 | * Iterate over all the registered interceptors 38 | * 39 | * This method is particularly useful for skipping over any 40 | * interceptors that may have become `null` calling `eject`. 41 | * 42 | * @param {Function} fn The function to call for each interceptor 43 | */ 44 | InterceptorManager.prototype.forEach = function forEach(fn) { 45 | utils.forEach(this.handlers, function forEachHandler(h) { 46 | if (h !== null) { 47 | fn(h); 48 | } 49 | }); 50 | }; 51 | 52 | export default InterceptorManager; 53 | -------------------------------------------------------------------------------- /demo11/src/core/buildFullPath.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import isAbsoluteURL from '../helpers/isAbsoluteURL'; 4 | import combineURLs from '../helpers/combineURLs'; 5 | 6 | /** 7 | * Creates a new URL by combining the baseURL with the requestedURL, 8 | * only when the requestedURL is not already an absolute URL. 9 | * If the requestURL is absolute, this function returns the requestedURL untouched. 10 | * 11 | * @param {string} baseURL The base URL 12 | * @param {string} requestedURL Absolute or relative URL to combine 13 | * @returns {string} The combined full path 14 | */ 15 | export default function buildFullPath(baseURL, requestedURL) { 16 | if (baseURL && !isAbsoluteURL(requestedURL)) { 17 | return combineURLs(baseURL, requestedURL); 18 | } 19 | return requestedURL; 20 | }; 21 | -------------------------------------------------------------------------------- /demo11/src/core/createError.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import enhanceError from './enhanceError'; 4 | 5 | /** 6 | * Create an Error with the specified message, config, error code, request and response. 7 | * 8 | * @param {string} message The error message. 9 | * @param {Object} config The config. 10 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). 11 | * @param {Object} [request] The request. 12 | * @param {Object} [response] The response. 13 | * @returns {Error} The created error. 14 | */ 15 | export default function createError(message, config, code, request, response?) { 16 | var error = new Error(message); 17 | return enhanceError(error, config, code, request, response); 18 | }; 19 | -------------------------------------------------------------------------------- /demo11/src/core/dispatchRequest.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | import transformData from './transformData'; 5 | import isCancel from '../cancel/isCancel'; 6 | import defaults from '../defaults'; 7 | 8 | /** 9 | * Throws a `Cancel` if cancellation has been requested. 10 | */ 11 | function throwIfCancellationRequested(config) { 12 | if (config.cancelToken) { 13 | config.cancelToken.throwIfRequested(); 14 | } 15 | } 16 | 17 | /** 18 | * Dispatch a request to the server using the configured adapter. 19 | * 20 | * @param {object} config The config that is to be used for the request 21 | * @returns {Promise} The Promise to be fulfilled 22 | */ 23 | export default function dispatchRequest(config) { 24 | throwIfCancellationRequested(config); 25 | 26 | // Ensure headers exist 27 | config.headers = config.headers || {}; 28 | 29 | // Transform request data 30 | config.data = transformData( 31 | config.data, 32 | config.headers, 33 | config.transformRequest 34 | ); 35 | 36 | // Flatten headers 37 | config.headers = utils.merge( 38 | config.headers.common || {}, 39 | config.headers[config.method] || {}, 40 | config.headers 41 | ); 42 | 43 | utils.forEach( 44 | ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], 45 | function cleanHeaderConfig(method) { 46 | delete config.headers[method]; 47 | } 48 | ); 49 | 50 | var adapter = config.adapter || defaults.adapter; 51 | 52 | return adapter(config).then(function onAdapterResolution(response) { 53 | throwIfCancellationRequested(config); 54 | 55 | // Transform response data 56 | response.data = transformData( 57 | response.data, 58 | response.headers, 59 | config.transformResponse 60 | ); 61 | 62 | return response; 63 | }, function onAdapterRejection(reason) { 64 | if (!isCancel(reason)) { 65 | throwIfCancellationRequested(config); 66 | 67 | // Transform response data 68 | if (reason && reason.response) { 69 | reason.response.data = transformData( 70 | reason.response.data, 71 | reason.response.headers, 72 | config.transformResponse 73 | ); 74 | } 75 | } 76 | 77 | return Promise.reject(reason); 78 | }); 79 | }; 80 | -------------------------------------------------------------------------------- /demo11/src/core/enhanceError.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Update an Error with the specified config, error code, and response. 5 | * 6 | * @param {Error} error The error to update. 7 | * @param {Object} config The config. 8 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). 9 | * @param {Object} [request] The request. 10 | * @param {Object} [response] The response. 11 | * @returns {Error} The error. 12 | */ 13 | export default function enhanceError(error, config, code, request, response) { 14 | error.config = config; 15 | if (code) { 16 | error.code = code; 17 | } 18 | 19 | error.request = request; 20 | error.response = response; 21 | error.isAxiosError = true; 22 | 23 | error.toJSON = function toJSON() { 24 | return { 25 | // Standard 26 | message: this.message, 27 | name: this.name, 28 | // Microsoft 29 | description: this.description, 30 | number: this.number, 31 | // Mozilla 32 | fileName: this.fileName, 33 | lineNumber: this.lineNumber, 34 | columnNumber: this.columnNumber, 35 | stack: this.stack, 36 | // Axios 37 | config: this.config, 38 | code: this.code 39 | }; 40 | }; 41 | return error; 42 | }; 43 | -------------------------------------------------------------------------------- /demo11/src/core/mergeConfig.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from '../utils'; 4 | 5 | /** 6 | * Config-specific merge-function which creates a new config-object 7 | * by merging two configuration objects together. 8 | * 9 | * @param {Object} config1 10 | * @param {Object} config2 11 | * @returns {Object} New object resulting from merging config2 to config1 12 | */ 13 | export default function mergeConfig(config1, config2) { 14 | // eslint-disable-next-line no-param-reassign 15 | config2 = config2 || {}; 16 | var config = {}; 17 | 18 | var valueFromConfig2Keys = ['url', 'method', 'data']; 19 | var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; 20 | var defaultToConfig2Keys = [ 21 | 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 22 | 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 23 | 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 24 | 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 25 | 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' 26 | ]; 27 | var directMergeKeys = ['validateStatus']; 28 | 29 | function getMergedValue(target, source) { 30 | if (utils.isPlainObject(target) && utils.isPlainObject(source)) { 31 | return utils.merge(target, source); 32 | } else if (utils.isPlainObject(source)) { 33 | return utils.merge({}, source); 34 | } else if (utils.isArray(source)) { 35 | return source.slice(); 36 | } 37 | return source; 38 | } 39 | 40 | function mergeDeepProperties(prop) { 41 | if (!utils.isUndefined(config2[prop])) { 42 | config[prop] = getMergedValue(config1[prop], config2[prop]); 43 | } else if (!utils.isUndefined(config1[prop])) { 44 | config[prop] = getMergedValue(undefined, config1[prop]); 45 | } 46 | } 47 | 48 | utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { 49 | if (!utils.isUndefined(config2[prop])) { 50 | config[prop] = getMergedValue(undefined, config2[prop]); 51 | } 52 | }); 53 | 54 | utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); 55 | 56 | utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { 57 | if (!utils.isUndefined(config2[prop])) { 58 | config[prop] = getMergedValue(undefined, config2[prop]); 59 | } else if (!utils.isUndefined(config1[prop])) { 60 | config[prop] = getMergedValue(undefined, config1[prop]); 61 | } 62 | }); 63 | 64 | utils.forEach(directMergeKeys, function merge(prop) { 65 | if (prop in config2) { 66 | config[prop] = getMergedValue(config1[prop], config2[prop]); 67 | } else if (prop in config1) { 68 | config[prop] = getMergedValue(undefined, config1[prop]); 69 | } 70 | }); 71 | 72 | var axiosKeys = valueFromConfig2Keys 73 | .concat(mergeDeepPropertiesKeys) 74 | .concat(defaultToConfig2Keys) 75 | .concat(directMergeKeys); 76 | 77 | var otherKeys = Object 78 | .keys(config1) 79 | .concat(Object.keys(config2)) 80 | .filter(function filterAxiosKeys(key) { 81 | return axiosKeys.indexOf(key) === -1; 82 | }); 83 | 84 | utils.forEach(otherKeys, mergeDeepProperties); 85 | 86 | return config; 87 | }; 88 | -------------------------------------------------------------------------------- /demo11/src/core/settle.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import createError from './createError'; 4 | 5 | /** 6 | * Resolve or reject a Promise based on response status. 7 | * 8 | * @param {Function} resolve A function that resolves the promise. 9 | * @param {Function} reject A function that rejects the promise. 10 | * @param {object} response The response. 11 | */ 12 | export default function settle(resolve, reject, response) { 13 | var validateStatus = response.config.validateStatus; 14 | if (!response.status || !validateStatus || validateStatus(response.status)) { 15 | resolve(response); 16 | } else { 17 | reject(createError( 18 | 'Request failed with status code ' + response.status, 19 | response.config, 20 | null, 21 | response.request, 22 | response 23 | )); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /demo11/src/core/transformData.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | /** 6 | * Transform the data for a request or a response 7 | * 8 | * @param {Object|String} data The data to be transformed 9 | * @param {Array} headers The headers for the request or response 10 | * @param {Array|Function} fns A single function or Array of functions 11 | * @returns {*} The resulting transformed data 12 | */ 13 | export default function transformData(data, headers, fns) { 14 | /*eslint no-param-reassign:0*/ 15 | utils.forEach(fns, function transform(fn) { 16 | data = fn(data, headers); 17 | }); 18 | 19 | return data; 20 | }; 21 | -------------------------------------------------------------------------------- /demo11/src/defaults.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './utils'; 4 | import normalizeHeaderName from './helpers/normalizeHeaderName'; 5 | import xhr from './adapters/xhr' 6 | var DEFAULT_CONTENT_TYPE = { 7 | 'Content-Type': 'application/x-www-form-urlencoded' 8 | }; 9 | 10 | function setContentTypeIfUnset(headers, value) { 11 | if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { 12 | headers['Content-Type'] = value; 13 | } 14 | } 15 | 16 | function getDefaultAdapter() { 17 | var adapter = xhr 18 | return adapter; 19 | } 20 | 21 | var defaults:any = { 22 | adapter: getDefaultAdapter(), 23 | 24 | transformRequest: [function transformRequest(data, headers) { 25 | normalizeHeaderName(headers, 'Accept'); 26 | normalizeHeaderName(headers, 'Content-Type'); 27 | if (utils.isFormData(data) || 28 | utils.isArrayBuffer(data) || 29 | utils.isBuffer(data) || 30 | utils.isStream(data) || 31 | utils.isFile(data) || 32 | utils.isBlob(data) 33 | ) { 34 | return data; 35 | } 36 | if (utils.isArrayBufferView(data)) { 37 | return data.buffer; 38 | } 39 | if (utils.isURLSearchParams(data)) { 40 | setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); 41 | return data.toString(); 42 | } 43 | if (utils.isObject(data)) { 44 | setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); 45 | return JSON.stringify(data); 46 | } 47 | return data; 48 | }], 49 | 50 | transformResponse: [function transformResponse(data) { 51 | /*eslint no-param-reassign:0*/ 52 | if (typeof data === 'string') { 53 | try { 54 | data = JSON.parse(data); 55 | } catch (e) { /* Ignore */ } 56 | } 57 | return data; 58 | }], 59 | 60 | /** 61 | * A timeout in milliseconds to abort a request. If set to 0 (default) a 62 | * timeout is not created. 63 | */ 64 | timeout: 0, 65 | 66 | xsrfCookieName: 'XSRF-TOKEN', 67 | xsrfHeaderName: 'X-XSRF-TOKEN', 68 | 69 | maxContentLength: -1, 70 | maxBodyLength: -1, 71 | 72 | validateStatus: function validateStatus(status) { 73 | return status >= 200 && status < 300; 74 | } 75 | }; 76 | 77 | defaults.headers = { 78 | common: { 79 | 'Accept': 'application/json, text/plain, */*' 80 | } 81 | }; 82 | 83 | utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { 84 | defaults.headers[method] = {}; 85 | }); 86 | 87 | utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { 88 | defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); 89 | }); 90 | 91 | export default defaults; 92 | -------------------------------------------------------------------------------- /demo11/src/helpers/README.md: -------------------------------------------------------------------------------- 1 | # axios // helpers 2 | 3 | The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: 4 | 5 | - Browser polyfills 6 | - Managing cookies 7 | - Parsing HTTP headers 8 | -------------------------------------------------------------------------------- /demo11/src/helpers/bind.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | export default function bind(fn:any, thisArg:any) { 4 | return function wrap() { 5 | var args = new Array(arguments.length); 6 | for (var i = 0; i < args.length; i++) { 7 | args[i] = arguments[i]; 8 | } 9 | return fn.apply(thisArg, args); 10 | }; 11 | }; 12 | -------------------------------------------------------------------------------- /demo11/src/helpers/buildURL.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | function encode(val) { 6 | return encodeURIComponent(val). 7 | replace(/%3A/gi, ':'). 8 | replace(/%24/g, '$'). 9 | replace(/%2C/gi, ','). 10 | replace(/%20/g, '+'). 11 | replace(/%5B/gi, '['). 12 | replace(/%5D/gi, ']'); 13 | } 14 | 15 | /** 16 | * Build a URL by appending params to the end 17 | * 18 | * @param {string} url The base of the url (e.g., http://www.google.com) 19 | * @param {object} [params] The params to be appended 20 | * @returns {string} The formatted url 21 | */ 22 | export default function buildURL(url, params, paramsSerializer) { 23 | /*eslint no-param-reassign:0*/ 24 | if (!params) { 25 | return url; 26 | } 27 | 28 | var serializedParams; 29 | if (paramsSerializer) { 30 | serializedParams = paramsSerializer(params); 31 | } else if (utils.isURLSearchParams(params)) { 32 | serializedParams = params.toString(); 33 | } else { 34 | var parts = []; 35 | 36 | utils.forEach(params, function serialize(val, key) { 37 | if (val === null || typeof val === 'undefined') { 38 | return; 39 | } 40 | 41 | if (utils.isArray(val)) { 42 | key = key + '[]'; 43 | } else { 44 | val = [val]; 45 | } 46 | 47 | utils.forEach(val, function parseValue(v) { 48 | if (utils.isDate(v)) { 49 | v = v.toISOString(); 50 | } else if (utils.isObject(v)) { 51 | v = JSON.stringify(v); 52 | } 53 | parts.push(encode(key) + '=' + encode(v)); 54 | }); 55 | }); 56 | 57 | serializedParams = parts.join('&'); 58 | } 59 | 60 | if (serializedParams) { 61 | var hashmarkIndex = url.indexOf('#'); 62 | if (hashmarkIndex !== -1) { 63 | url = url.slice(0, hashmarkIndex); 64 | } 65 | 66 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; 67 | } 68 | 69 | return url; 70 | }; 71 | -------------------------------------------------------------------------------- /demo11/src/helpers/combineURLs.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Creates a new URL by combining the specified URLs 5 | * 6 | * @param {string} baseURL The base URL 7 | * @param {string} relativeURL The relative URL 8 | * @returns {string} The combined URL 9 | */ 10 | export default function combineURLs(baseURL, relativeURL) { 11 | return relativeURL 12 | ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') 13 | : baseURL; 14 | }; 15 | -------------------------------------------------------------------------------- /demo11/src/helpers/cookies.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | export default ( 6 | utils.isStandardBrowserEnv() ? 7 | 8 | // Standard browser envs support document.cookie 9 | (function standardBrowserEnv() { 10 | return { 11 | write: function write(name, value, expires, path, domain, secure) { 12 | var cookie = []; 13 | cookie.push(name + '=' + encodeURIComponent(value)); 14 | 15 | if (utils.isNumber(expires)) { 16 | cookie.push('expires=' + new Date(expires).toUTCString()); 17 | } 18 | 19 | if (utils.isString(path)) { 20 | cookie.push('path=' + path); 21 | } 22 | 23 | if (utils.isString(domain)) { 24 | cookie.push('domain=' + domain); 25 | } 26 | 27 | if (secure === true) { 28 | cookie.push('secure'); 29 | } 30 | 31 | document.cookie = cookie.join('; '); 32 | }, 33 | 34 | read: function read(name) { 35 | var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); 36 | return (match ? decodeURIComponent(match[3]) : null); 37 | }, 38 | 39 | remove: function remove(name) { 40 | this.write(name, '', Date.now() - 86400000); 41 | } 42 | }; 43 | })() : 44 | 45 | // Non standard browser env (web workers, react-native) lack needed support. 46 | (function nonStandardBrowserEnv() { 47 | return { 48 | write: function write() {}, 49 | read: function read() { return null; }, 50 | remove: function remove() {} 51 | }; 52 | })() 53 | ); 54 | -------------------------------------------------------------------------------- /demo11/src/helpers/deprecatedMethod.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /*eslint no-console:0*/ 4 | 5 | /** 6 | * Supply a warning to the developer that a method they are using 7 | * has been deprecated. 8 | * 9 | * @param {string} method The name of the deprecated method 10 | * @param {string} [instead] The alternate method to use if applicable 11 | * @param {string} [docs] The documentation URL to get further details 12 | */ 13 | export default function deprecatedMethod(method, instead, docs) { 14 | try { 15 | console.warn( 16 | 'DEPRECATED method `' + method + '`.' + 17 | (instead ? ' Use `' + instead + '` instead.' : '') + 18 | ' This method will be removed in a future release.'); 19 | 20 | if (docs) { 21 | console.warn('For more information about usage see ' + docs); 22 | } 23 | } catch (e) { /* Ignore */ } 24 | }; 25 | -------------------------------------------------------------------------------- /demo11/src/helpers/isAbsoluteURL.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Determines whether the specified URL is absolute 5 | * 6 | * @param {string} url The URL to test 7 | * @returns {boolean} True if the specified URL is absolute, otherwise false 8 | */ 9 | export default function isAbsoluteURL(url) { 10 | // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). 11 | // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed 12 | // by any combination of letters, digits, plus, period, or hyphen. 13 | return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); 14 | }; 15 | -------------------------------------------------------------------------------- /demo11/src/helpers/isURLSameOrigin.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | export default ( 6 | utils.isStandardBrowserEnv() ? 7 | 8 | // Standard browser envs have full support of the APIs needed to test 9 | // whether the request URL is of the same origin as current location. 10 | (function standardBrowserEnv() { 11 | var msie = /(msie|trident)/i.test(navigator.userAgent); 12 | var urlParsingNode = document.createElement('a'); 13 | var originURL; 14 | 15 | /** 16 | * Parse a URL to discover it's components 17 | * 18 | * @param {String} url The URL to be parsed 19 | * @returns {Object} 20 | */ 21 | function resolveURL(url) { 22 | var href = url; 23 | 24 | if (msie) { 25 | // IE needs attribute set twice to normalize properties 26 | urlParsingNode.setAttribute('href', href); 27 | href = urlParsingNode.href; 28 | } 29 | 30 | urlParsingNode.setAttribute('href', href); 31 | 32 | // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils 33 | return { 34 | href: urlParsingNode.href, 35 | protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', 36 | host: urlParsingNode.host, 37 | search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', 38 | hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', 39 | hostname: urlParsingNode.hostname, 40 | port: urlParsingNode.port, 41 | pathname: (urlParsingNode.pathname.charAt(0) === '/') ? 42 | urlParsingNode.pathname : 43 | '/' + urlParsingNode.pathname 44 | }; 45 | } 46 | 47 | originURL = resolveURL(window.location.href); 48 | 49 | /** 50 | * Determine if a URL shares the same origin as the current location 51 | * 52 | * @param {String} requestURL The URL to test 53 | * @returns {boolean} True if URL shares the same origin, otherwise false 54 | */ 55 | return function isURLSameOrigin(requestURL) { 56 | var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; 57 | return (parsed.protocol === originURL.protocol && 58 | parsed.host === originURL.host); 59 | }; 60 | })() : 61 | 62 | // Non standard browser envs (web workers, react-native) lack needed support. 63 | (function nonStandardBrowserEnv() { 64 | return function isURLSameOrigin() { 65 | return true; 66 | }; 67 | })() 68 | ); 69 | -------------------------------------------------------------------------------- /demo11/src/helpers/normalizeHeaderName.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from '../utils'; 4 | 5 | export default function normalizeHeaderName(headers, normalizedName) { 6 | utils.forEach(headers, function processHeader(value, name) { 7 | if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { 8 | headers[normalizedName] = value; 9 | delete headers[name]; 10 | } 11 | }); 12 | }; 13 | -------------------------------------------------------------------------------- /demo11/src/helpers/parseHeaders.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | // Headers whose duplicates are ignored by node 6 | // c.f. https://nodejs.org/api/http.html#http_message_headers 7 | var ignoreDuplicateOf = [ 8 | 'age', 'authorization', 'content-length', 'content-type', 'etag', 9 | 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 10 | 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 11 | 'referer', 'retry-after', 'user-agent' 12 | ]; 13 | 14 | /** 15 | * Parse headers into an object 16 | * 17 | * ``` 18 | * Date: Wed, 27 Aug 2014 08:58:49 GMT 19 | * Content-Type: application/json 20 | * Connection: keep-alive 21 | * Transfer-Encoding: chunked 22 | * ``` 23 | * 24 | * @param {String} headers Headers needing to be parsed 25 | * @returns {Object} Headers parsed into an object 26 | */ 27 | export default function parseHeaders(headers) { 28 | var parsed = {}; 29 | var key; 30 | var val; 31 | var i; 32 | 33 | if (!headers) { return parsed; } 34 | 35 | utils.forEach(headers.split('\n'), function parser(line) { 36 | i = line.indexOf(':'); 37 | key = utils.trim(line.substr(0, i)).toLowerCase(); 38 | val = utils.trim(line.substr(i + 1)); 39 | 40 | if (key) { 41 | if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { 42 | return; 43 | } 44 | if (key === 'set-cookie') { 45 | parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); 46 | } else { 47 | parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; 48 | } 49 | } 50 | }); 51 | 52 | return parsed; 53 | }; 54 | -------------------------------------------------------------------------------- /demo11/src/helpers/spread.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Syntactic sugar for invoking a function and expanding an array for arguments. 5 | * 6 | * Common use case would be to use `Function.prototype.apply`. 7 | * 8 | * ```js 9 | * function f(x, y, z) {} 10 | * var args = [1, 2, 3]; 11 | * f.apply(null, args); 12 | * ``` 13 | * 14 | * With `spread` this example can be re-written. 15 | * 16 | * ```js 17 | * spread(function(x, y, z) {})([1, 2, 3]); 18 | * ``` 19 | * 20 | * @param {Function} callback 21 | * @returns {Function} 22 | */ 23 | export default function spread(callback) { 24 | return function wrap(arr) { 25 | return callback.apply(null, arr); 26 | }; 27 | }; 28 | -------------------------------------------------------------------------------- /demo11/src/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var utils = require('./utils'); 4 | var bind = require('./helpers/bind.ts'); 5 | var Axios = require('./core/Axios'); 6 | var mergeConfig = require('./core/mergeConfig'); 7 | var defaults = require('./defaults'); 8 | var vue = require('vue') 9 | // var moemnt = require('moment') 10 | /** 11 | * Create an instance of Axios 12 | * 13 | * @param {Object} defaultConfig The default config for the instance 14 | * @return {Axios} A new instance of Axios 15 | */ 16 | function createInstance(defaultConfig) { 17 | var context = new Axios(defaultConfig); 18 | var instance = bind(Axios.prototype.request, context); 19 | 20 | // Copy axios.prototype to instance 21 | utils.extend(instance, Axios.prototype, context); 22 | 23 | // Copy context to instance 24 | utils.extend(instance, context); 25 | 26 | return instance; 27 | } 28 | 29 | // Create the default instance to be exported 30 | var axios = createInstance(defaults); 31 | 32 | // Expose Axios class to allow class inheritance 33 | axios.Axios = Axios; 34 | 35 | // Factory for creating new instances 36 | axios.create = function create(instanceConfig) { 37 | return createInstance(mergeConfig(axios.defaults, instanceConfig)); 38 | }; 39 | 40 | // Expose Cancel & CancelToken 41 | axios.Cancel = require('./cancel/Cancel'); 42 | axios.CancelToken = require('./cancel/CancelToken'); 43 | axios.isCancel = require('./cancel/isCancel'); 44 | 45 | // Expose all/spread 46 | axios.all = function all(promises) { 47 | return Promise.all(promises); 48 | }; 49 | axios.spread = require('./helpers/spread'); 50 | 51 | 52 | -------------------------------------------------------------------------------- /demo11/src/utils.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import bind from './helpers/bind'; 4 | 5 | /*global toString:true*/ 6 | 7 | // utils is a library of generic helper functions non-specific to axios 8 | 9 | var toString = Object.prototype.toString; 10 | 11 | /** 12 | * Determine if a value is an Array 13 | * 14 | * @param {Object} val The value to test 15 | * @returns {boolean} True if value is an Array, otherwise false 16 | */ 17 | function isArray(val) { 18 | return toString.call(val) === '[object Array]'; 19 | } 20 | 21 | /** 22 | * Determine if a value is undefined 23 | * 24 | * @param {Object} val The value to test 25 | * @returns {boolean} True if the value is undefined, otherwise false 26 | */ 27 | function isUndefined(val) { 28 | return typeof val === 'undefined'; 29 | } 30 | 31 | /** 32 | * Determine if a value is a Buffer 33 | * 34 | * @param {Object} val The value to test 35 | * @returns {boolean} True if value is a Buffer, otherwise false 36 | */ 37 | function isBuffer(val) { 38 | return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) 39 | && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); 40 | } 41 | 42 | /** 43 | * Determine if a value is an ArrayBuffer 44 | * 45 | * @param {Object} val The value to test 46 | * @returns {boolean} True if value is an ArrayBuffer, otherwise false 47 | */ 48 | function isArrayBuffer(val) { 49 | return toString.call(val) === '[object ArrayBuffer]'; 50 | } 51 | 52 | /** 53 | * Determine if a value is a FormData 54 | * 55 | * @param {Object} val The value to test 56 | * @returns {boolean} True if value is an FormData, otherwise false 57 | */ 58 | function isFormData(val) { 59 | return (typeof FormData !== 'undefined') && (val instanceof FormData); 60 | } 61 | 62 | /** 63 | * Determine if a value is a view on an ArrayBuffer 64 | * 65 | * @param {Object} val The value to test 66 | * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false 67 | */ 68 | function isArrayBufferView(val) { 69 | var result; 70 | if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { 71 | result = ArrayBuffer.isView(val); 72 | } else { 73 | result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); 74 | } 75 | return result; 76 | } 77 | 78 | /** 79 | * Determine if a value is a String 80 | * 81 | * @param {Object} val The value to test 82 | * @returns {boolean} True if value is a String, otherwise false 83 | */ 84 | function isString(val) { 85 | return typeof val === 'string'; 86 | } 87 | 88 | /** 89 | * Determine if a value is a Number 90 | * 91 | * @param {Object} val The value to test 92 | * @returns {boolean} True if value is a Number, otherwise false 93 | */ 94 | function isNumber(val) { 95 | return typeof val === 'number'; 96 | } 97 | 98 | /** 99 | * Determine if a value is an Object 100 | * 101 | * @param {Object} val The value to test 102 | * @returns {boolean} True if value is an Object, otherwise false 103 | */ 104 | function isObject(val) { 105 | return val !== null && typeof val === 'object'; 106 | } 107 | 108 | /** 109 | * Determine if a value is a plain Object 110 | * 111 | * @param {Object} val The value to test 112 | * @return {boolean} True if value is a plain Object, otherwise false 113 | */ 114 | function isPlainObject(val) { 115 | if (toString.call(val) !== '[object Object]') { 116 | return false; 117 | } 118 | 119 | var prototype = Object.getPrototypeOf(val); 120 | return prototype === null || prototype === Object.prototype; 121 | } 122 | 123 | /** 124 | * Determine if a value is a Date 125 | * 126 | * @param {Object} val The value to test 127 | * @returns {boolean} True if value is a Date, otherwise false 128 | */ 129 | function isDate(val) { 130 | return toString.call(val) === '[object Date]'; 131 | } 132 | 133 | /** 134 | * Determine if a value is a File 135 | * 136 | * @param {Object} val The value to test 137 | * @returns {boolean} True if value is a File, otherwise false 138 | */ 139 | function isFile(val) { 140 | return toString.call(val) === '[object File]'; 141 | } 142 | 143 | /** 144 | * Determine if a value is a Blob 145 | * 146 | * @param {Object} val The value to test 147 | * @returns {boolean} True if value is a Blob, otherwise false 148 | */ 149 | function isBlob(val) { 150 | return toString.call(val) === '[object Blob]'; 151 | } 152 | 153 | /** 154 | * Determine if a value is a Function 155 | * 156 | * @param {Object} val The value to test 157 | * @returns {boolean} True if value is a Function, otherwise false 158 | */ 159 | function isFunction(val) { 160 | return toString.call(val) === '[object Function]'; 161 | } 162 | 163 | /** 164 | * Determine if a value is a Stream 165 | * 166 | * @param {Object} val The value to test 167 | * @returns {boolean} True if value is a Stream, otherwise false 168 | */ 169 | function isStream(val) { 170 | return isObject(val) && isFunction(val.pipe); 171 | } 172 | 173 | /** 174 | * Determine if a value is a URLSearchParams object 175 | * 176 | * @param {Object} val The value to test 177 | * @returns {boolean} True if value is a URLSearchParams object, otherwise false 178 | */ 179 | function isURLSearchParams(val) { 180 | return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; 181 | } 182 | 183 | /** 184 | * Trim excess whitespace off the beginning and end of a string 185 | * 186 | * @param {String} str The String to trim 187 | * @returns {String} The String freed of excess whitespace 188 | */ 189 | function trim(str) { 190 | return str.replace(/^\s*/, '').replace(/\s*$/, ''); 191 | } 192 | 193 | /** 194 | * Determine if we're running in a standard browser environment 195 | * 196 | * This allows axios to run in a web worker, and react-native. 197 | * Both environments support XMLHttpRequest, but not fully standard globals. 198 | * 199 | * web workers: 200 | * typeof window -> undefined 201 | * typeof document -> undefined 202 | * 203 | * react-native: 204 | * navigator.product -> 'ReactNative' 205 | * nativescript 206 | * navigator.product -> 'NativeScript' or 'NS' 207 | */ 208 | function isStandardBrowserEnv() { 209 | if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || 210 | navigator.product === 'NativeScript' || 211 | navigator.product === 'NS')) { 212 | return false; 213 | } 214 | return ( 215 | typeof window !== 'undefined' && 216 | typeof document !== 'undefined' 217 | ); 218 | } 219 | 220 | /** 221 | * Iterate over an Array or an Object invoking a function for each item. 222 | * 223 | * If `obj` is an Array callback will be called passing 224 | * the value, index, and complete array for each item. 225 | * 226 | * If 'obj' is an Object callback will be called passing 227 | * the value, key, and complete object for each property. 228 | * 229 | * @param {Object|Array} obj The object to iterate 230 | * @param {Function} fn The callback to invoke for each item 231 | */ 232 | function forEach(obj, fn) { 233 | // Don't bother if no value provided 234 | if (obj === null || typeof obj === 'undefined') { 235 | return; 236 | } 237 | 238 | // Force an array if not already something iterable 239 | if (typeof obj !== 'object') { 240 | /*eslint no-param-reassign:0*/ 241 | obj = [obj]; 242 | } 243 | 244 | if (isArray(obj)) { 245 | // Iterate over array values 246 | for (var i = 0, l = obj.length; i < l; i++) { 247 | fn.call(null, obj[i], i, obj); 248 | } 249 | } else { 250 | // Iterate over object keys 251 | for (var key in obj) { 252 | if (Object.prototype.hasOwnProperty.call(obj, key)) { 253 | fn.call(null, obj[key], key, obj); 254 | } 255 | } 256 | } 257 | } 258 | 259 | /** 260 | * Accepts varargs expecting each argument to be an object, then 261 | * immutably merges the properties of each object and returns result. 262 | * 263 | * When multiple objects contain the same key the later object in 264 | * the arguments list will take precedence. 265 | * 266 | * Example: 267 | * 268 | * ```js 269 | * var result = merge({foo: 123}, {foo: 456}); 270 | * console.log(result.foo); // outputs 456 271 | * ``` 272 | * 273 | * @param {Object} obj1 Object to merge 274 | * @returns {Object} Result of all merge properties 275 | */ 276 | function merge(...result:any) { 277 | var result:any = {}; 278 | function assignValue(val, key) { 279 | if (isPlainObject(result[key]) && isPlainObject(val)) { 280 | result[key] = merge(result[key], val); 281 | } else if (isPlainObject(val)) { 282 | result[key] = merge({}, val); 283 | } else if (isArray(val)) { 284 | result[key] = val.slice(); 285 | } else { 286 | result[key] = val; 287 | } 288 | } 289 | 290 | for (var i = 0, l = arguments.length; i < l; i++) { 291 | forEach(arguments[i], assignValue); 292 | } 293 | return result; 294 | } 295 | 296 | /** 297 | * Extends object a by mutably adding to it the properties of object b. 298 | * 299 | * @param {Object} a The object to be extended 300 | * @param {Object} b The object to copy properties from 301 | * @param {Object} thisArg The object to bind function to 302 | * @return {Object} The resulting value of object a 303 | */ 304 | function extend(a, b, thisArg) { 305 | forEach(b, function assignValue(val, key) { 306 | if (thisArg && typeof val === 'function') { 307 | a[key] = bind(val, thisArg); 308 | } else { 309 | a[key] = val; 310 | } 311 | }); 312 | return a; 313 | } 314 | 315 | /** 316 | * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) 317 | * 318 | * @param {string} content with BOM 319 | * @return {string} content value without BOM 320 | */ 321 | function stripBOM(content) { 322 | if (content.charCodeAt(0) === 0xFEFF) { 323 | content = content.slice(1); 324 | } 325 | return content; 326 | } 327 | 328 | export default { 329 | isArray, 330 | isArrayBuffer, 331 | isBuffer, 332 | isFormData, 333 | isArrayBufferView, 334 | isString, 335 | isNumber, 336 | isObject, 337 | isPlainObject, 338 | isUndefined, 339 | isDate, 340 | isFile, 341 | isBlob, 342 | isFunction, 343 | isStream, 344 | isURLSearchParams, 345 | isStandardBrowserEnv, 346 | forEach, 347 | merge, 348 | extend, 349 | trim, 350 | stripBOM 351 | }; 352 | -------------------------------------------------------------------------------- /demo11/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "sourceMap": true, 4 | "target": "ES2016", 5 | }, 6 | "lib": ["dom", "scripthost", "es5", "es2015.promise", "es2015.core"] 7 | } -------------------------------------------------------------------------------- /demo11/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | //没有优化的config 3 | const SpeedMeasurePlugin = require("speed-measure-webpack-plugin"); 4 | const smp = new SpeedMeasurePlugin(); 5 | 6 | module.exports = smp.wrap({ 7 | mode: "development", 8 | entry: "./src/index.js", 9 | output: { 10 | path: path.resolve(__dirname, "dist"), 11 | filename: "index.js", 12 | }, 13 | module: { 14 | rules: [ 15 | { 16 | test: /\.js/, 17 | exclude: /node_modules/, 18 | use: [{ 19 | loader: "babel-loader", 20 | }, 21 | { 22 | loader: "eslint-loader", 23 | }, 24 | ], 25 | }, 26 | { 27 | test: /\.tsx?$/, 28 | use: [{ 29 | loader: "babel-loader", 30 | }, 31 | { 32 | loader: "eslint-loader", 33 | }, 34 | { 35 | loader: "ts-loader", 36 | }, 37 | ], 38 | }, 39 | ], 40 | }, 41 | plugins: [ 42 | ], 43 | resolve: { 44 | extensions: [".js", ".ts", ".json"], 45 | }, 46 | }); -------------------------------------------------------------------------------- /demo11/webpack.happy.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | //优化的config 3 | const SpeedMeasurePlugin = require("speed-measure-webpack-plugin"); 4 | const smp = new SpeedMeasurePlugin(); 5 | const happypack = require("happypack"); 6 | 7 | var happyThreadPool = happypack.ThreadPool({ 8 | size: 5 9 | }); 10 | module.exports = smp.wrap({ 11 | mode: "development", 12 | entry: "./src/index.js", 13 | output: { 14 | path: path.resolve(__dirname, "dist"), 15 | filename: "index.js", 16 | }, 17 | module: { 18 | rules: [ 19 | { 20 | test: /\.js/, 21 | exclude: /node_modules/, 22 | use: "happypack/loader?id=js", 23 | }, 24 | { 25 | test: /\.tsx?$/, 26 | use: ["happypack/loader?id=js", "ts-loader"], 27 | }, 28 | ], 29 | }, 30 | plugins: [ 31 | new happypack({ 32 | id: "js", 33 | threadPool: happyThreadPool, 34 | loaders: [{ 35 | loader: "babel-loader", 36 | }, 37 | { 38 | loader: "eslint-loader", 39 | }, 40 | ], 41 | }), 42 | 43 | ], 44 | resolve: { 45 | extensions: [".js", ".ts", ".json"], 46 | }, 47 | }); -------------------------------------------------------------------------------- /demo12/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false 7 | } 8 | ] 9 | ], 10 | "plugins": ["@babel/plugin-transform-runtime"] 11 | } 12 | -------------------------------------------------------------------------------- /demo12/README.md: -------------------------------------------------------------------------------- 1 | # Tree Shaking -------------------------------------------------------------------------------- /demo12/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo12", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.5", 14 | "@babel/plugin-transform-runtime": "^7.10.5", 15 | "@babel/preset-env": "^7.10.4", 16 | "babel-loader": "^8.1.0", 17 | "clean-webpack-plugin": "^3.0.0", 18 | "html-webpack-plugin": "^4.3.0", 19 | "terser-webpack-plugin": "^3.0.7", 20 | "webpack": "^4.43.0", 21 | "webpack-cli": "^3.3.12" 22 | }, 23 | "sideEffects": [ 24 | "./src/utils.js" 25 | ], 26 | "dependencies": { 27 | "@babel/runtime": "^7.10.5", 28 | "lodash": "^4.17.19", 29 | "lodash-es": "^4.17.15" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /demo12/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /demo12/src/index.js: -------------------------------------------------------------------------------- 1 | import { 2 | isArray 3 | } from './utils' 4 | 5 | isArray([]) 6 | console.log(isArray([])) 7 | 8 | 9 | import { chunk } from 'lodash-es' 10 | console.log(chunk([1,2,3,4], 2)) -------------------------------------------------------------------------------- /demo12/src/utils.js: -------------------------------------------------------------------------------- 1 | 2 | var toString = Object.prototype.toString; 3 | 4 | 5 | export function isArray(val) { 6 | return toString.call(val) === '[object Array]'; 7 | } 8 | 9 | 10 | export function isUndefined(val) { 11 | return typeof val === 'undefined'; 12 | } 13 | 14 | export function isBuffer(val) { 15 | return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) 16 | && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); 17 | } 18 | 19 | 20 | export function isArrayBuffer(val) { 21 | return toString.call(val) === '[object ArrayBuffer]'; 22 | } 23 | 24 | export function isFormData(val) { 25 | return (typeof FormData !== 'undefined') && (val instanceof FormData); 26 | } 27 | 28 | 29 | export function isArrayBufferView(val) { 30 | var result; 31 | if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { 32 | result = ArrayBuffer.isView(val); 33 | } else { 34 | result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); 35 | } 36 | return result; 37 | } 38 | 39 | 40 | export function isString(val) { 41 | return typeof val === 'string'; 42 | } 43 | 44 | 45 | export function isNumber(val) { 46 | return typeof val === 'number'; 47 | } 48 | 49 | 50 | export function isObject(val) { 51 | return val !== null && typeof val === 'object'; 52 | } 53 | 54 | 55 | export function isPlainObject(val) { 56 | if (toString.call(val) !== '[object Object]') { 57 | return false; 58 | } 59 | 60 | var prototype = Object.getPrototypeOf(val); 61 | return prototype === null || prototype === Object.prototype; 62 | } 63 | 64 | 65 | export function isDate(val) { 66 | return toString.call(val) === '[object Date]'; 67 | } 68 | 69 | 70 | export function isFile(val) { 71 | return toString.call(val) === '[object File]'; 72 | } 73 | 74 | export function isBlob(val) { 75 | return toString.call(val) === '[object Blob]'; 76 | } 77 | 78 | export function isFunction(val) { 79 | return toString.call(val) === '[object Function]'; 80 | } 81 | 82 | export function isStream(val) { 83 | return isObject(val) && isFunction(val.pipe); 84 | } 85 | 86 | 87 | export function isURLSearchParams(val) { 88 | return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; 89 | } 90 | 91 | 92 | export function trim(str) { 93 | return str.replace(/^\s*/, '').replace(/\s*$/, ''); 94 | } 95 | 96 | export function isStandardBrowserEnv() { 97 | if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || 98 | navigator.product === 'NativeScript' || 99 | navigator.product === 'NS')) { 100 | return false; 101 | } 102 | return ( 103 | typeof window !== 'undefined' && 104 | typeof document !== 'undefined' 105 | ); 106 | } 107 | 108 | 109 | export function forEach(obj, fn) { 110 | if (obj === null || typeof obj === 'undefined') { 111 | return; 112 | } 113 | 114 | if (typeof obj !== 'object') { 115 | obj = [obj]; 116 | } 117 | 118 | if (isArray(obj)) { 119 | for (var i = 0, l = obj.length; i < l; i++) { 120 | fn.call(null, obj[i], i, obj); 121 | } 122 | } else { 123 | for (var key in obj) { 124 | if (Object.prototype.hasOwnProperty.call(obj, key)) { 125 | fn.call(null, obj[key], key, obj); 126 | } 127 | } 128 | } 129 | } 130 | 131 | 132 | export function merge(/* obj1, obj2, obj3, ... */) { 133 | var result = {}; 134 | function assignValue(val, key) { 135 | if (isPlainObject(result[key]) && isPlainObject(val)) { 136 | result[key] = merge(result[key], val); 137 | } else if (isPlainObject(val)) { 138 | result[key] = merge({}, val); 139 | } else if (isArray(val)) { 140 | result[key] = val.slice(); 141 | } else { 142 | result[key] = val; 143 | } 144 | } 145 | 146 | for (var i = 0, l = arguments.length; i < l; i++) { 147 | forEach(arguments[i], assignValue); 148 | } 149 | return result; 150 | } 151 | 152 | export function stripBOM(content) { 153 | if (content.charCodeAt(0) === 0xFEFF) { 154 | content = content.slice(1); 155 | } 156 | return content; 157 | } 158 | 159 | 160 | -------------------------------------------------------------------------------- /demo12/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | const HtmlWebpackPlugin = require("html-webpack-plugin"); 4 | const TerserJSPlugin = require("terser-webpack-plugin"); 5 | const { 6 | CleanWebpackPlugin 7 | } = require("clean-webpack-plugin"); 8 | module.exports = { 9 | devtool: "cheap-source-map", 10 | mode: "development", 11 | entry: "./src/index.js", 12 | output: { 13 | path: path.resolve(__dirname, "dist"), 14 | filename: "index.js", 15 | }, 16 | module: { 17 | rules: [ 18 | { 19 | test: /\.js/, 20 | exclude: /node_modules/, 21 | use: [ 22 | { 23 | loader: "babel-loader", 24 | }, 25 | ], 26 | }, 27 | ], 28 | }, 29 | plugins: [ 30 | new CleanWebpackPlugin(), 31 | new HtmlWebpackPlugin({ 32 | template: "./public/index.html", 33 | filename: "index.html", 34 | }), 35 | ], 36 | optimization: { 37 | usedExports: true, 38 | sideEffects: true, 39 | // minimize: true, 40 | // minimizer: [ 41 | // new TerserJSPlugin({ 42 | // cache: true, 43 | // parallel: true, 44 | // sourceMap: false, 45 | // }), 46 | // ], 47 | }, 48 | }; 49 | -------------------------------------------------------------------------------- /demo13/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false 7 | } 8 | ] 9 | ], 10 | "plugins": ["@babel/plugin-transform-runtime"] 11 | } 12 | -------------------------------------------------------------------------------- /demo13/README.md: -------------------------------------------------------------------------------- 1 | # noParse -------------------------------------------------------------------------------- /demo13/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo13", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.5", 14 | "@babel/plugin-transform-runtime": "^7.10.5", 15 | "@babel/preset-env": "^7.10.4", 16 | "babel-loader": "^8.1.0", 17 | "webpack": "^4.44.0", 18 | "webpack-cli": "^3.3.12" 19 | }, 20 | "dependencies": { 21 | "@babel/runtime": "^7.10.5", 22 | "jquery": "^3.5.1", 23 | "jquery-ui": "^1.12.1", 24 | "lodash": "^4.17.19" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo13/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | 4 | //添加noParse 624ms 5 | //没有添加noParse 835ms 6 | 7 | module.exports = { 8 | mode: "development", 9 | entry: "./src/index.js", 10 | output: { 11 | path: path.resolve(__dirname, "dist"), 12 | filename: "index.js", 13 | }, 14 | module: { 15 | noParse: /jquery|lodash|jquery-ui/, 16 | rules: [ 17 | { 18 | test: /\.js/, 19 | exclude: /node_modules/, 20 | use: [ 21 | { 22 | loader: "babel-loader", 23 | }, 24 | ], 25 | }, 26 | ], 27 | }, 28 | }; 29 | -------------------------------------------------------------------------------- /demo14/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false 7 | } 8 | ] 9 | ], 10 | "plugins": [] 11 | } 12 | -------------------------------------------------------------------------------- /demo14/README.md: -------------------------------------------------------------------------------- 1 | # 提取公共代码 -------------------------------------------------------------------------------- /demo14/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo14", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.5", 14 | "@babel/plugin-transform-runtime": "^7.10.5", 15 | "@babel/preset-env": "^7.10.4", 16 | "babel-loader": "^8.1.0", 17 | "clean-webpack-plugin": "^3.0.0", 18 | "html-webpack-plugin": "^4.3.0", 19 | "webpack": "^4.44.1", 20 | "webpack-cli": "^3.3.12" 21 | }, 22 | "dependencies": { 23 | "@babel/runtime": "^7.10.5", 24 | "axios": "^0.19.2", 25 | "dayjs": "^1.8.31", 26 | "lodash": "^4.17.19", 27 | "vue": "^2.6.11", 28 | "vue-router": "^3.3.4", 29 | "vuex": "^3.5.1" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /demo14/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /demo14/src/async.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | console.log('i m async module') -------------------------------------------------------------------------------- /demo14/src/async_a.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | 3 | module.exports = () => { 4 | console.log('i m async a') 5 | } 6 | 7 | -------------------------------------------------------------------------------- /demo14/src/async_b.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | 3 | module.exports = ()=>{ 4 | console.log('i m async b') 5 | } 6 | 7 | -------------------------------------------------------------------------------- /demo14/src/detail.js: -------------------------------------------------------------------------------- 1 | const vue = require('vue') 2 | const vuex = require('vuex') 3 | const router = require('vue-router') 4 | 5 | const dayjs = require('dayjs') 6 | 7 | const utils = require('./utils') 8 | 9 | console.log(dayjs()) 10 | console.log(utils.trim('detail')) 11 | 12 | 13 | setTimeout(()=>{ 14 | let async_a = require('./async_a') 15 | async_a() 16 | }, 2000) 17 | -------------------------------------------------------------------------------- /demo14/src/home.js: -------------------------------------------------------------------------------- 1 | const vue = require('vue') 2 | const vuex = require('vuex') 3 | const router = require('vue-router') 4 | 5 | const axios = require('axios') 6 | const dayjs = require('dayjs') 7 | 8 | const utils = require('./utils') 9 | 10 | console.log(dayjs()) 11 | 12 | console.log(utils.trim('home')) 13 | 14 | setTimeout(()=>{ 15 | let async_a = require('./async_a') 16 | async_a() 17 | }, 2000) 18 | 19 | -------------------------------------------------------------------------------- /demo14/src/list.js: -------------------------------------------------------------------------------- 1 | const vue = require('vue') 2 | const vuex = require('vuex') 3 | const router = require('vue-router') 4 | 5 | const axios = require('axios') 6 | const dayjs = require('dayjs') 7 | 8 | const utils = require('./utils') 9 | 10 | console.log(dayjs()) 11 | 12 | console.log(utils.trim('list')) -------------------------------------------------------------------------------- /demo14/src/utils.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | /*global toString:true*/ 4 | 5 | // utils is a library of generic helper functions non-specific to axios 6 | 7 | var toString = Object.prototype.toString; 8 | 9 | /** 10 | * Determine if a value is an Array 11 | * 12 | * @param {Object} val The value to test 13 | * @returns {boolean} True if value is an Array, otherwise false 14 | */ 15 | function isArray(val) { 16 | return toString.call(val) === '[object Array]'; 17 | } 18 | 19 | /** 20 | * Determine if a value is undefined 21 | * 22 | * @param {Object} val The value to test 23 | * @returns {boolean} True if the value is undefined, otherwise false 24 | */ 25 | function isUndefined(val) { 26 | return typeof val === 'undefined'; 27 | } 28 | 29 | /** 30 | * Determine if a value is a Buffer 31 | * 32 | * @param {Object} val The value to test 33 | * @returns {boolean} True if value is a Buffer, otherwise false 34 | */ 35 | function isBuffer(val) { 36 | return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) 37 | && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); 38 | } 39 | 40 | /** 41 | * Determine if a value is an ArrayBuffer 42 | * 43 | * @param {Object} val The value to test 44 | * @returns {boolean} True if value is an ArrayBuffer, otherwise false 45 | */ 46 | function isArrayBuffer(val) { 47 | return toString.call(val) === '[object ArrayBuffer]'; 48 | } 49 | 50 | /** 51 | * Determine if a value is a FormData 52 | * 53 | * @param {Object} val The value to test 54 | * @returns {boolean} True if value is an FormData, otherwise false 55 | */ 56 | function isFormData(val) { 57 | return (typeof FormData !== 'undefined') && (val instanceof FormData); 58 | } 59 | 60 | /** 61 | * Determine if a value is a view on an ArrayBuffer 62 | * 63 | * @param {Object} val The value to test 64 | * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false 65 | */ 66 | function isArrayBufferView(val) { 67 | var result; 68 | if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { 69 | result = ArrayBuffer.isView(val); 70 | } else { 71 | result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); 72 | } 73 | return result; 74 | } 75 | 76 | /** 77 | * Determine if a value is a String 78 | * 79 | * @param {Object} val The value to test 80 | * @returns {boolean} True if value is a String, otherwise false 81 | */ 82 | function isString(val) { 83 | return typeof val === 'string'; 84 | } 85 | 86 | /** 87 | * Determine if a value is a Number 88 | * 89 | * @param {Object} val The value to test 90 | * @returns {boolean} True if value is a Number, otherwise false 91 | */ 92 | function isNumber(val) { 93 | return typeof val === 'number'; 94 | } 95 | 96 | /** 97 | * Determine if a value is an Object 98 | * 99 | * @param {Object} val The value to test 100 | * @returns {boolean} True if value is an Object, otherwise false 101 | */ 102 | function isObject(val) { 103 | return val !== null && typeof val === 'object'; 104 | } 105 | 106 | /** 107 | * Determine if a value is a plain Object 108 | * 109 | * @param {Object} val The value to test 110 | * @return {boolean} True if value is a plain Object, otherwise false 111 | */ 112 | function isPlainObject(val) { 113 | if (toString.call(val) !== '[object Object]') { 114 | return false; 115 | } 116 | 117 | var prototype = Object.getPrototypeOf(val); 118 | return prototype === null || prototype === Object.prototype; 119 | } 120 | 121 | /** 122 | * Determine if a value is a Date 123 | * 124 | * @param {Object} val The value to test 125 | * @returns {boolean} True if value is a Date, otherwise false 126 | */ 127 | function isDate(val) { 128 | return toString.call(val) === '[object Date]'; 129 | } 130 | 131 | /** 132 | * Determine if a value is a File 133 | * 134 | * @param {Object} val The value to test 135 | * @returns {boolean} True if value is a File, otherwise false 136 | */ 137 | function isFile(val) { 138 | return toString.call(val) === '[object File]'; 139 | } 140 | 141 | /** 142 | * Determine if a value is a Blob 143 | * 144 | * @param {Object} val The value to test 145 | * @returns {boolean} True if value is a Blob, otherwise false 146 | */ 147 | function isBlob(val) { 148 | return toString.call(val) === '[object Blob]'; 149 | } 150 | 151 | /** 152 | * Determine if a value is a Function 153 | * 154 | * @param {Object} val The value to test 155 | * @returns {boolean} True if value is a Function, otherwise false 156 | */ 157 | function isFunction(val) { 158 | return toString.call(val) === '[object Function]'; 159 | } 160 | 161 | /** 162 | * Determine if a value is a Stream 163 | * 164 | * @param {Object} val The value to test 165 | * @returns {boolean} True if value is a Stream, otherwise false 166 | */ 167 | function isStream(val) { 168 | return isObject(val) && isFunction(val.pipe); 169 | } 170 | 171 | /** 172 | * Determine if a value is a URLSearchParams object 173 | * 174 | * @param {Object} val The value to test 175 | * @returns {boolean} True if value is a URLSearchParams object, otherwise false 176 | */ 177 | function isURLSearchParams(val) { 178 | return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; 179 | } 180 | 181 | /** 182 | * Trim excess whitespace off the beginning and end of a string 183 | * 184 | * @param {String} str The String to trim 185 | * @returns {String} The String freed of excess whitespace 186 | */ 187 | function trim(str) { 188 | return str.replace(/^\s*/, '').replace(/\s*$/, ''); 189 | } 190 | 191 | /** 192 | * Determine if we're running in a standard browser environment 193 | * 194 | * This allows axios to run in a web worker, and react-native. 195 | * Both environments support XMLHttpRequest, but not fully standard globals. 196 | * 197 | * web workers: 198 | * typeof window -> undefined 199 | * typeof document -> undefined 200 | * 201 | * react-native: 202 | * navigator.product -> 'ReactNative' 203 | * nativescript 204 | * navigator.product -> 'NativeScript' or 'NS' 205 | */ 206 | function isStandardBrowserEnv() { 207 | if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || 208 | navigator.product === 'NativeScript' || 209 | navigator.product === 'NS')) { 210 | return false; 211 | } 212 | return ( 213 | typeof window !== 'undefined' && 214 | typeof document !== 'undefined' 215 | ); 216 | } 217 | 218 | /** 219 | * Iterate over an Array or an Object invoking a function for each item. 220 | * 221 | * If `obj` is an Array callback will be called passing 222 | * the value, index, and complete array for each item. 223 | * 224 | * If 'obj' is an Object callback will be called passing 225 | * the value, key, and complete object for each property. 226 | * 227 | * @param {Object|Array} obj The object to iterate 228 | * @param {Function} fn The callback to invoke for each item 229 | */ 230 | function forEach(obj, fn) { 231 | // Don't bother if no value provided 232 | if (obj === null || typeof obj === 'undefined') { 233 | return; 234 | } 235 | 236 | // Force an array if not already something iterable 237 | if (typeof obj !== 'object') { 238 | /*eslint no-param-reassign:0*/ 239 | obj = [obj]; 240 | } 241 | 242 | if (isArray(obj)) { 243 | // Iterate over array values 244 | for (var i = 0, l = obj.length; i < l; i++) { 245 | fn.call(null, obj[i], i, obj); 246 | } 247 | } else { 248 | // Iterate over object keys 249 | for (var key in obj) { 250 | if (Object.prototype.hasOwnProperty.call(obj, key)) { 251 | fn.call(null, obj[key], key, obj); 252 | } 253 | } 254 | } 255 | } 256 | 257 | /** 258 | * Accepts varargs expecting each argument to be an object, then 259 | * immutably merges the properties of each object and returns result. 260 | * 261 | * When multiple objects contain the same key the later object in 262 | * the arguments list will take precedence. 263 | * 264 | * Example: 265 | * 266 | * ```js 267 | * var result = merge({foo: 123}, {foo: 456}); 268 | * console.log(result.foo); // outputs 456 269 | * ``` 270 | * 271 | * @param {Object} obj1 Object to merge 272 | * @returns {Object} Result of all merge properties 273 | */ 274 | function merge(/* obj1, obj2, obj3, ... */) { 275 | var result = {}; 276 | function assignValue(val, key) { 277 | if (isPlainObject(result[key]) && isPlainObject(val)) { 278 | result[key] = merge(result[key], val); 279 | } else if (isPlainObject(val)) { 280 | result[key] = merge({}, val); 281 | } else if (isArray(val)) { 282 | result[key] = val.slice(); 283 | } else { 284 | result[key] = val; 285 | } 286 | } 287 | 288 | for (var i = 0, l = arguments.length; i < l; i++) { 289 | forEach(arguments[i], assignValue); 290 | } 291 | return result; 292 | } 293 | 294 | /** 295 | * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) 296 | * 297 | * @param {string} content with BOM 298 | * @return {string} content value without BOM 299 | */ 300 | function stripBOM(content) { 301 | if (content.charCodeAt(0) === 0xFEFF) { 302 | content = content.slice(1); 303 | } 304 | return content; 305 | } 306 | 307 | module.exports = { 308 | isArray: isArray, 309 | isArrayBuffer: isArrayBuffer, 310 | isBuffer: isBuffer, 311 | isFormData: isFormData, 312 | isArrayBufferView: isArrayBufferView, 313 | isString: isString, 314 | isNumber: isNumber, 315 | isObject: isObject, 316 | isPlainObject: isPlainObject, 317 | isUndefined: isUndefined, 318 | isDate: isDate, 319 | isFile: isFile, 320 | isBlob: isBlob, 321 | isFunction: isFunction, 322 | isStream: isStream, 323 | isURLSearchParams: isURLSearchParams, 324 | isStandardBrowserEnv: isStandardBrowserEnv, 325 | forEach: forEach, 326 | merge: merge, 327 | trim: trim, 328 | stripBOM: stripBOM 329 | }; 330 | -------------------------------------------------------------------------------- /demo14/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const { 3 | CleanWebpackPlugin 4 | } = require("clean-webpack-plugin"); 5 | const HtmlWebpackPlugin = require("html-webpack-plugin"); 6 | module.exports = { 7 | mode: "development", 8 | devtool: "none", 9 | output: { 10 | path: path.resolve(__dirname, "dist"), 11 | filename: "[name].bundle.js", 12 | }, 13 | entry: { 14 | home: "./src/home.js", 15 | list: "./src/list.js", 16 | detail: "./src/detail.js", 17 | }, 18 | plugins: [ 19 | new HtmlWebpackPlugin({ 20 | template: "./public/index.html", 21 | filename: "home.html", 22 | chunks: ["vue","vendors","common","async", "home" ], 23 | }), 24 | new CleanWebpackPlugin(), 25 | ], 26 | module: { 27 | rules: [{ 28 | test: /\.js/, 29 | exclude: /node_modules/, 30 | use: [{ 31 | loader: "babel-loader", 32 | }, ], 33 | }, ], 34 | }, 35 | resolve: { 36 | alias: { 37 | 'axios$': 'axios/dist/axios.min.js' 38 | } 39 | }, 40 | // optimization: { 41 | // splitChunks: { 42 | // cacheGroups: { 43 | // base: { 44 | // name: "base", 45 | // test: /[\\/]node_modules[\\/]/, 46 | // // test: (module) => { 47 | // // return /axios|dayjs/.test(module.context); 48 | // // }, 49 | // chunks: "all", 50 | // priority: 10, 51 | // minChunks: 2, 52 | // }, 53 | // common: { 54 | // chunks: "all", 55 | // test: /[\\/]src[\\/]/, 56 | // name: "common", 57 | // priority: 2, 58 | // minChunks: 2, 59 | // }, 60 | // }, 61 | // }, 62 | // }, 63 | 64 | optimization: { 65 | splitChunks: { 66 | chunks: 'initial', 67 | cacheGroups: { 68 | vue: { 69 | test: /[\\/]node_modules[\\/](vue|vuex|vue-router)/, 70 | priority: 10, 71 | name: 'vue' 72 | }, 73 | vendors: { 74 | test: /[\\/]node_modules[\\/]/, 75 | priority: 9, 76 | name: 'vendors' 77 | }, 78 | common: { 79 | test: /[\\/]src[\\/]/, 80 | priority: 5, 81 | name: 'common' 82 | }, 83 | async: { 84 | chunks: 'async', 85 | test: /[\\/]src[\\/]/, 86 | priority: 6, 87 | name: 'async' 88 | } 89 | } 90 | } 91 | } 92 | 93 | }; -------------------------------------------------------------------------------- /demo15/READMD.md: -------------------------------------------------------------------------------- 1 | # externals排除第三方模块 -------------------------------------------------------------------------------- /demo15/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo15", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "server": "webpack-dev-server", 8 | "build": "webpack", 9 | "test": "echo \"Error: no test specified\" && exit 1" 10 | }, 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "jquery": "^3.5.1" 15 | }, 16 | "devDependencies": { 17 | "html-webpack-plugin": "^4.3.0", 18 | "webpack": "^4.44.1", 19 | "webpack-cli": "^3.3.12", 20 | "webpack-dev-server": "^3.11.0" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo15/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /demo15/src/index.js: -------------------------------------------------------------------------------- 1 | import $ from 'jquery' 2 | 3 | console.log('asd') -------------------------------------------------------------------------------- /demo15/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | module.exports = { 4 | mode: "development", 5 | output: { 6 | path: path.resolve(__dirname, "dist"), 7 | filename: "[name].bundle.js", 8 | }, 9 | entry: "./src/index.js", 10 | devServer: { 11 | port: 9000, 12 | host: "0.0.0.0", 13 | hot: true, 14 | compress: true, 15 | open: false, 16 | contentBase: [path.join(__dirname, "public")], 17 | }, 18 | externals: { 19 | jquery: "jQuery", 20 | }, 21 | plugins: [ 22 | new HtmlWebpackPlugin({ 23 | template: './public/index.html', 24 | filename: 'index.html', 25 | }), 26 | ] 27 | }; 28 | -------------------------------------------------------------------------------- /demo16/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false 7 | } 8 | ] 9 | ], 10 | "plugins": ["@babel/plugin-transform-runtime"] 11 | } 12 | -------------------------------------------------------------------------------- /demo16/README.md: -------------------------------------------------------------------------------- 1 | # cache-loader -------------------------------------------------------------------------------- /demo16/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo16", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.5", 14 | "@babel/plugin-transform-runtime": "^7.10.5", 15 | "@babel/preset-env": "^7.10.4", 16 | "babel-loader": "^8.1.0", 17 | "cache-loader": "^4.1.0", 18 | "webpack": "^4.44.0", 19 | "webpack-cli": "^3.3.12" 20 | }, 21 | "dependencies": { 22 | "@babel/runtime": "^7.10.5", 23 | "jquery": "^3.5.1", 24 | "jquery-ui": "^1.12.1", 25 | "lodash": "^4.17.19" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /demo16/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | 4 | //没有cache-loader 5 | //第一次 1582ms 6 | //第二次 1533ms 7 | 8 | //有cache-loader 9 | //第一次 1651ms 10 | //第二次 542ms 11 | 12 | module.exports = { 13 | mode: "development", 14 | entry: "./src/index.js", 15 | output: { 16 | path: path.resolve(__dirname, "dist"), 17 | filename: "index.js", 18 | }, 19 | module: { 20 | rules: [{ 21 | test: /\.js/, 22 | exclude: /node_modules/, 23 | use: [{ 24 | loader: 'cache-loader' 25 | }, 26 | { 27 | loader: "babel-loader", 28 | options: { 29 | cacheDirectory: true 30 | } 31 | }, 32 | ], 33 | }, ], 34 | }, 35 | }; -------------------------------------------------------------------------------- /demo17/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false 7 | } 8 | ] 9 | ], 10 | "plugins": ["@babel/plugin-transform-runtime"] 11 | } 12 | -------------------------------------------------------------------------------- /demo17/README.md: -------------------------------------------------------------------------------- 1 | # hard-source-webpack-plugin -------------------------------------------------------------------------------- /demo17/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo17", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.5", 14 | "@babel/plugin-transform-runtime": "^7.10.5", 15 | "@babel/preset-env": "^7.10.4", 16 | "babel-loader": "^8.1.0", 17 | "cache-loader": "^4.1.0", 18 | "hard-source-webpack-plugin": "^0.13.1", 19 | "webpack": "^4.44.0", 20 | "webpack-cli": "^3.3.12" 21 | }, 22 | "dependencies": { 23 | "@babel/runtime": "^7.10.5", 24 | "jquery": "^3.5.1", 25 | "jquery-ui": "^1.12.1", 26 | "lodash": "^4.17.19" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /demo17/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | var HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); 4 | 5 | module.exports = { 6 | mode: "development", 7 | entry: "./src/index.js", 8 | output: { 9 | path: path.resolve(__dirname, "dist"), 10 | filename: "index.js", 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | test: /\.js/, 16 | exclude: /node_modules/, 17 | use: [ 18 | { 19 | loader: "babel-loader", 20 | }, 21 | ], 22 | }, 23 | ], 24 | }, 25 | plugins: [ 26 | new HardSourceWebpackPlugin({ 27 | configHash: function(webpackConfig) { 28 | // node-object-hash on npm can be used to build this. 29 | return new Date().getTime() + '' 30 | }, 31 | }) 32 | ] 33 | }; 34 | -------------------------------------------------------------------------------- /demo18/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "modules": false 7 | } 8 | ] 9 | ], 10 | "plugins": ["@babel/plugin-transform-runtime"] 11 | } 12 | -------------------------------------------------------------------------------- /demo18/README.md: -------------------------------------------------------------------------------- 1 | # thread-loader -------------------------------------------------------------------------------- /demo18/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo18", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.5", 14 | "@babel/plugin-transform-runtime": "^7.10.5", 15 | "@babel/preset-env": "^7.10.4", 16 | "babel-loader": "^8.1.0", 17 | "cache-loader": "^4.1.0", 18 | "thread-loader": "^2.1.3", 19 | "webpack": "^4.44.0", 20 | "webpack-cli": "^3.3.12" 21 | }, 22 | "dependencies": { 23 | "@babel/runtime": "^7.10.5", 24 | "jquery": "^3.5.1", 25 | "jquery-ui": "^1.12.1", 26 | "lodash": "^4.17.19" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /demo18/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | 4 | 5 | module.exports = { 6 | mode: "development", 7 | entry: "./src/index.js", 8 | output: { 9 | path: path.resolve(__dirname, "dist"), 10 | filename: "index.js", 11 | }, 12 | module: { 13 | rules: [{ 14 | test: /\.js/, 15 | exclude: /node_modules/, 16 | use: [{ 17 | loader: "thread-loader" 18 | }, { 19 | loader: "babel-loader", 20 | }] 21 | }] 22 | }, 23 | }; -------------------------------------------------------------------------------- /demo19/README.md: -------------------------------------------------------------------------------- 1 | # 手写loader -------------------------------------------------------------------------------- /demo19/loader/banner-loader.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const path = require("path"); 3 | const { getOptions } = require("loader-utils"); 4 | const { validate } = require("schema-utils"); 5 | 6 | module.exports = function (source) { 7 | this.cacheable && this.cacheable(true); 8 | 9 | 10 | const options = getOptions(this); 11 | const schema = { 12 | type: "object", 13 | properties: { 14 | text: { 15 | type: "string", 16 | }, 17 | filename: { 18 | type: "string", 19 | }, 20 | }, 21 | additionalProperties: false, 22 | }; 23 | validate(schema, options, { 24 | name: "banner-loader", 25 | baseDataPath: "options", 26 | }); 27 | 28 | if (options.filename) { 29 | let txt = ""; 30 | if (options.filename == "banner1") { 31 | this.addDependency(path.resolve(__dirname, "./banner1.txt")); 32 | txt = fs.readFileSync(path.resolve(__dirname, "./banner1.txt")); 33 | } else if (options.filename == "banner2") { 34 | this.addDependency(path.resolve(__dirname, "./banner1.txt")); 35 | txt = fs.readFileSync(path.resolve(__dirname, "./banner1.txt")); 36 | } 37 | return source + txt; 38 | } else if (options.text) { 39 | return source + `/* ${options.text} */`; 40 | } else { 41 | return source; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /demo19/loader/banner1.txt: -------------------------------------------------------------------------------- 1 | /* build from banner1 */ -------------------------------------------------------------------------------- /demo19/loader/banner2.txt: -------------------------------------------------------------------------------- 1 | /* build from banner2 */ -------------------------------------------------------------------------------- /demo19/loader/cleanlog-loader.js: -------------------------------------------------------------------------------- 1 | const { 2 | getOptions, 3 | parseQuery, 4 | stringifyRequest, 5 | urlToRequest, 6 | isUrlRequest, 7 | } = require("loader-utils"); 8 | 9 | const { validate } = require("schema-utils"); 10 | 11 | const schema = require("./schema.json"); 12 | 13 | module.exports = function (source) { 14 | const options = getOptions(this); 15 | 16 | const params = parseQuery("?param1=foo"); 17 | //转为相对路径 18 | console.log(stringifyRequest(this, "D:\\projects\\WebpackDemo\\.gitignore")); 19 | 20 | const file_url = "../src/index.js"; 21 | if (isUrlRequest(file_url)) { 22 | //将url转换成适合webpack环境的模块请求 23 | const request = urlToRequest(file_url); 24 | console.log(request, "request"); 25 | } 26 | console.log(params, options, "queryssss"); 27 | 28 | const configuration = { name: "cleanlog-loader", baseDataPath: "options" }; 29 | 30 | validate(schema, options, configuration); 31 | console.log(this.cacheable, "cacheable"); 32 | 33 | if (this.cacheable) { 34 | this.cacheable(true); 35 | } 36 | 37 | let result = source.replace(/console\.log\(.*\);?\n?/g, ""); 38 | // console.log(result, "result"); 39 | return result; 40 | }; 41 | -------------------------------------------------------------------------------- /demo19/loader/less-loader.js: -------------------------------------------------------------------------------- 1 | const less = require("less"); 2 | const { getOptions, stringifyRequest, parseQuery } = require("loader-utils"); 3 | const { validate } = require("schema-utils"); 4 | 5 | const schema = { 6 | type: "object", 7 | properties: { 8 | option: { 9 | type: "boolean", 10 | }, 11 | }, 12 | additionalProperties: false, 13 | }; 14 | 15 | function loader(source) { 16 | const options = getOptions(this); 17 | 18 | const callback = this.async(); 19 | 20 | const string_result = stringifyRequest(this, "./test.js"); 21 | const configuration = { name: "loader" }; 22 | 23 | // console.log( 24 | // parseQuery("?name=kev&age=14"), 25 | // "string_result", 26 | // options, 27 | // ); 28 | 29 | // console.log(this.sourceMap, "sourceMap"); 30 | // console.log(this.context, "context"); 31 | // console.log(this.resource, "resource"); 32 | 33 | // console.log(options, this.query, 'query') 34 | 35 | less.render(source, { sourceMap: {} }, function (err, c) { 36 | // 这是less插件提供的解析方法 37 | let { css, map } = c; 38 | callback(null, css, map); 39 | }); 40 | 41 | // return css; 42 | } 43 | module.exports = loader; 44 | -------------------------------------------------------------------------------- /demo19/loader/schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "option": { 5 | "description": "options", 6 | "type": "boolean" 7 | }, 8 | "limt": { 9 | "type": "string" 10 | }, 11 | "name": { 12 | "type": "string" 13 | }, 14 | "key": { 15 | "type": "string" 16 | } 17 | }, 18 | "additionalProperties": true 19 | } -------------------------------------------------------------------------------- /demo19/loader/style-loader.js: -------------------------------------------------------------------------------- 1 | function loader(source, map) { 2 | let style = ` 3 | let style = document.createElement('style'); 4 | style.innerHTML = ${JSON.stringify(source)}; // 将css文件的内容字符串化 5 | document.head.appendChild(style) 6 | `; 7 | // console.log(map, "mapssss"); 8 | return style; 9 | } 10 | module.exports = loader; 11 | -------------------------------------------------------------------------------- /demo19/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo19", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "./src/index.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "devDependencies": { 11 | "@babel/core": "^7.10.5", 12 | "@babel/plugin-transform-runtime": "^7.10.5", 13 | "@babel/preset-env": "^7.10.4", 14 | "babel-loader": "^8.1.0", 15 | "cache-loader": "^4.1.0", 16 | "html-webpack-plugin": "^4.5.0", 17 | "less": "^3.12.2", 18 | "loader-utils": "^2.0.0", 19 | "schema-utils": "^3.0.0", 20 | "thread-loader": "^2.1.3", 21 | "webpack": "^4.44.2", 22 | "webpack-cli": "^3.3.12" 23 | }, 24 | "dependencies": { 25 | "@babel/runtime": "^7.10.5", 26 | "jquery": "^3.5.1", 27 | "jquery-ui": "^1.12.1", 28 | "lodash": "^4.17.19" 29 | }, 30 | "author": "", 31 | "license": "ISC" 32 | } 33 | -------------------------------------------------------------------------------- /demo19/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /demo19/src/index.js: -------------------------------------------------------------------------------- 1 | import "./index.less"; 2 | const { a } = { 3 | a: 1, 4 | b: 2, 5 | }; 6 | 7 | const c = a + 1; 8 | console.log("11"); 9 | -------------------------------------------------------------------------------- /demo19/src/index.less: -------------------------------------------------------------------------------- 1 | *{ 2 | margin: 0; 3 | padding: 0; 4 | } 5 | @base: #fff; 6 | 7 | body{ 8 | background: #ccc; 9 | } 10 | .box{ 11 | display: flex; 12 | width: 200px; 13 | height: 200px; 14 | background: @base; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /demo19/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | const HtmlWebpackPlugin = require("html-webpack-plugin"); 4 | module.exports = { 5 | mode: "development", 6 | devtool: "source-map", 7 | entry: "./src/index.js", 8 | output: { 9 | path: path.resolve(__dirname, "dist"), 10 | filename: "[name].bundle.js", 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | test: /\.less/, 16 | use: [ 17 | { 18 | loader: "./loader/style-loader.js", 19 | options: { 20 | cache: true, 21 | }, 22 | }, 23 | { 24 | loader: path.resolve(__dirname, "loader", "less-loader"), 25 | // options: { 26 | // cache: true, 27 | // key: "qweasd", 28 | // }, 29 | }, 30 | ], 31 | }, 32 | { 33 | test: /\.js/, 34 | use: [ 35 | "babel-loader", 36 | "banner-loader?text=banner111", 37 | "cleanlog-loader?limt=1024&name=[hash:8].[ext]&option=true", 38 | ], 39 | }, 40 | ], 41 | }, 42 | plugins: [ 43 | new HtmlWebpackPlugin({ 44 | template: "./public/index.html", 45 | filename: "index.html", 46 | }), 47 | ], 48 | resolveLoader: { 49 | modules: [path.resolve(__dirname, "loader"), "node_modules"], 50 | }, 51 | }; 52 | -------------------------------------------------------------------------------- /demo2/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 | 13 |
14 | body 15 |
16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /demo2/src/header.js: -------------------------------------------------------------------------------- 1 | var header = document.getElementById('header') 2 | header.style.background = '#999' -------------------------------------------------------------------------------- /demo2/src/index.js: -------------------------------------------------------------------------------- 1 | console.log(222) 2 | 3 | var wrap = document.getElementById('body-wrap') 4 | wrap.style.background = '#666' 5 | -------------------------------------------------------------------------------- /demo2/webpack.config.js: -------------------------------------------------------------------------------- 1 | module.exports = function(env,args){ 2 | return { 3 | mode: 'development', 4 | entry: ['./src/index.js', './src/header.js'] 5 | } 6 | } 7 | 8 | 9 | -------------------------------------------------------------------------------- /demo20/README.md: -------------------------------------------------------------------------------- 1 | # 手写plugins -------------------------------------------------------------------------------- /demo20/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo20", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "./src/index.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "devDependencies": { 11 | "@babel/core": "^7.10.5", 12 | "@babel/plugin-transform-runtime": "^7.10.5", 13 | "@babel/preset-env": "^7.10.4", 14 | "babel-loader": "^8.1.0", 15 | "cache-loader": "^4.1.0", 16 | "html-webpack-plugin": "^4.5.0", 17 | "less": "^3.12.2", 18 | "loader-utils": "^2.0.0", 19 | "schema-utils": "^3.0.0", 20 | "thread-loader": "^2.1.3", 21 | "webpack": "^4.44.2", 22 | "webpack-cli": "^3.3.12" 23 | }, 24 | "dependencies": { 25 | "@babel/runtime": "^7.10.5", 26 | "jquery": "^3.5.1", 27 | "jquery-ui": "^1.12.1", 28 | "lodash": "^4.17.19" 29 | }, 30 | "author": "", 31 | "license": "ISC" 32 | } 33 | -------------------------------------------------------------------------------- /demo20/plugins/FileListPlugin.js: -------------------------------------------------------------------------------- 1 | class FileListPlugin { 2 | apply(compiler){ 3 | compiler.hooks.emit.tapAsync('FileListPlugin', (compilation, callback)=>{ 4 | var filelist = 'In this build:\n\n'; 5 | 6 | // 遍历所有编译过的资源文件, 7 | // 对于每个文件名称,都添加一行内容。 8 | for (var filename in compilation.assets) { 9 | filelist += '- ' + filename + '\n'; 10 | } 11 | 12 | // 将这个列表作为一个新的文件资源,插入到 webpack 构建中: 13 | compilation.assets['filelist.md'] = { 14 | source: function() { 15 | return filelist; 16 | }, 17 | size: function() { 18 | return filelist.length; 19 | } 20 | }; 21 | 22 | callback(); 23 | }) 24 | } 25 | } 26 | 27 | module.exports = FileListPlugin -------------------------------------------------------------------------------- /demo20/plugins/MyPlugin.js: -------------------------------------------------------------------------------- 1 | class MyPlugin { 2 | constructor(options) { 3 | console.log("Plugin被创建了"); 4 | console.log(options, 'options'); 5 | } 6 | apply(compiler) { 7 | // compiler.plugin("compilation", (compilation) => { 8 | // console.log("compilation"); 9 | // }); 10 | compiler.hooks.emit.tap("MyPlugin", (compilation) => { 11 | console.log("emit"); 12 | console.log(compilation.assets, 'assets') 13 | }); 14 | 15 | // compiler.plugin('emit', (compilation, callback)=>{ 16 | // console.log('生成资源到 output 目录之前。') 17 | // callback() 18 | // }) 19 | // compiler.hooks.emit.tapAsync('MyPlugin', function (name, cb) { 20 | // console.log('生成资源到 output 目录之前。') 21 | // cb() 22 | // }) 23 | 24 | // compiler.hooks.done.tap('MyPlugin', function (compilation) { 25 | // console.log('done') 26 | // }) 27 | } 28 | } 29 | module.exports = MyPlugin; 30 | -------------------------------------------------------------------------------- /demo20/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /demo20/src/index.js: -------------------------------------------------------------------------------- 1 | console.log('11') -------------------------------------------------------------------------------- /demo20/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | const HtmlWebpackPlugin = require("html-webpack-plugin"); 4 | const MyPlugin = require('./plugins/MyPlugin') 5 | const FileListPlugin = require('./plugins/FileListPlugin') 6 | module.exports = { 7 | mode: "development", 8 | entry: "./src/index.js", 9 | output: { 10 | path: path.resolve(__dirname, "dist"), 11 | filename: "[name].bundle.js", 12 | }, 13 | module: { 14 | rules: [ 15 | { 16 | test: /\.js/, 17 | use: ["babel-loader"], 18 | }, 19 | ], 20 | }, 21 | plugins: [ 22 | new HtmlWebpackPlugin({ 23 | template: "./public/index.html", 24 | filename: "index.html", 25 | }), 26 | new MyPlugin({ title: 'MyPlugin' }), 27 | new FileListPlugin() 28 | ], 29 | }; 30 | -------------------------------------------------------------------------------- /demo3/README.md: -------------------------------------------------------------------------------- 1 | # html-webpack-plugin 2 | 3 | ``` 4 | npm i 5 | 6 | webpack 7 | ``` -------------------------------------------------------------------------------- /demo3/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <%= htmlWebpackPlugin.options.title %> 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /demo3/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo3", 3 | "version": "1.0.0", 4 | "description": "```\r npm i", 5 | "main": "webpack.config.js", 6 | "dependencies": {}, 7 | "devDependencies": { 8 | "html-webpack-plugin": "^4.3.0", 9 | "webpack": "^4.43.0" 10 | }, 11 | "scripts": { 12 | "test": "echo \"Error: no test specified\" && exit 1" 13 | }, 14 | "author": "", 15 | "license": "ISC" 16 | } 17 | -------------------------------------------------------------------------------- /demo3/src/common.js: -------------------------------------------------------------------------------- 1 | console.log('common') -------------------------------------------------------------------------------- /demo3/src/detail.js: -------------------------------------------------------------------------------- 1 | console.log('detail') 2 | -------------------------------------------------------------------------------- /demo3/src/home.js: -------------------------------------------------------------------------------- 1 | console.log('home') 2 | 3 | -------------------------------------------------------------------------------- /demo3/src/list.js: -------------------------------------------------------------------------------- 1 | console.log('list') -------------------------------------------------------------------------------- /demo3/webpack.config.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | const path =require('path') 4 | const webpack = require('webpack') 5 | var HtmlWebpackPlugin = require('html-webpack-plugin'); 6 | 7 | module.exports = { 8 | mode: 'none', 9 | entry: { 10 | home: './src/home.js', 11 | list: './src/list.js', 12 | detail: ['./src/detail.js', './src/common.js'], 13 | }, 14 | output: { 15 | path: path.resolve(__dirname, 'dist'), 16 | filename: '[name].bundle.js', 17 | }, 18 | plugins: [ 19 | new HtmlWebpackPlugin({ 20 | template: './index.html', 21 | filename: 'all.html', 22 | title: 'title all', 23 | chunks: 'all', 24 | inject: true, 25 | hash: true, 26 | favicon: '', 27 | meta: { 28 | 'viewport': 'width=device-width, initial-scale=1.0' 29 | }, 30 | minify: { 31 | //清除script标签引号 32 | removeAttributeQuotes: true, 33 | //清除html中的注释 34 | removeComments: true, 35 | //清除html中的空格、换行符 36 | //html压缩成一行 37 | collapseWhitespace: false, 38 | //压缩html内的样式 39 | minifyCSS: true, 40 | //清除内容为空的元素(慎用) 41 | removeEmptyElements: false, 42 | //清除style和link标签的type属性 43 | removeStyleLinkTypeAttributes: false 44 | } 45 | }), 46 | new HtmlWebpackPlugin({ 47 | template: './index.html', 48 | filename: 'home.html', 49 | chunks: ['home'] 50 | }), 51 | new HtmlWebpackPlugin({ 52 | template: './index.html', 53 | filename: 'list.html', 54 | chunks: ['list'] 55 | }), 56 | new HtmlWebpackPlugin({ 57 | template: './index.html', 58 | filename: 'detail.html', 59 | chunks: ['detail'] 60 | }), 61 | ] 62 | } -------------------------------------------------------------------------------- /demo4/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ], 5 | "plugins": [ 6 | "@babel/plugin-transform-runtime" 7 | ] 8 | } -------------------------------------------------------------------------------- /demo4/.browserslistrc: -------------------------------------------------------------------------------- 1 | > 0.25% 2 | not dead 3 | -------------------------------------------------------------------------------- /demo4/READMD.md: -------------------------------------------------------------------------------- 1 | # loader处理 2 | 3 | ``` 4 | npm i 5 | npm run build 6 | static-server 7 | ``` -------------------------------------------------------------------------------- /demo4/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 |
head
11 |
12 | main 13 | 14 |
sass
15 |
less
16 | 17 | 18 |
19 |
foot
20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /demo4/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo4", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "webpack" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.2", 14 | "@babel/plugin-transform-runtime": "^7.10.1", 15 | "@babel/runtime": "^7.10.2", 16 | "autoprefixer": "^9.8.0", 17 | "babel-loader": "^8.1.0", 18 | "babel-preset-env": "^1.7.0", 19 | "css-loader": "^3.5.3", 20 | "cssnano": "^4.1.10", 21 | "file-loader": "^6.0.0", 22 | "html-webpack-plugin": "^4.3.0", 23 | "html-withimg-loader": "^0.1.16", 24 | "less-loader": "^6.1.0", 25 | "node-sass": "^4.14.1", 26 | "postcss-loader": "^3.0.0", 27 | "postcss-plugins-px2rem": "0.0.5", 28 | "sass-loader": "^8.0.2", 29 | "style-loader": "^1.2.1", 30 | "url-loader": "^4.1.0", 31 | "webpack": "^4.43.0", 32 | "webpack-cli": "^3.3.11" 33 | }, 34 | "dependencies": { 35 | "@babel/preset-env": "^7.10.2" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /demo4/postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [ 3 | require('autoprefixer'), 4 | require('postcss-plugins-px2rem')({ remUnit: 75 }), 5 | require('cssnano'), 6 | ] 7 | } -------------------------------------------------------------------------------- /demo4/src/bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/acexyf/WebpackDemo/752b2e7a775c0cd886c8ba58d09f5938b26157c2/demo4/src/bg.png -------------------------------------------------------------------------------- /demo4/src/bg1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/acexyf/WebpackDemo/752b2e7a775c0cd886c8ba58d09f5938b26157c2/demo4/src/bg1.png -------------------------------------------------------------------------------- /demo4/src/foot.css: -------------------------------------------------------------------------------- 1 | .foot{ 2 | background: #ccc; 3 | } -------------------------------------------------------------------------------- /demo4/src/head.css: -------------------------------------------------------------------------------- 1 | .head{ 2 | display: flex; 3 | background: #666; 4 | } -------------------------------------------------------------------------------- /demo4/src/index.css: -------------------------------------------------------------------------------- 1 | @import './head.css'; 2 | @import './foot.css'; 3 | 4 | body{ 5 | width: 100vw; 6 | height: 100vh; 7 | background: url(./bg1.png) no-repeat; 8 | background-size: 400px 400px; 9 | background-position: center center; 10 | } 11 | 12 | .wrap { 13 | display: flex; 14 | background: #999; 15 | } -------------------------------------------------------------------------------- /demo4/src/index.js: -------------------------------------------------------------------------------- 1 | import './index.css' 2 | import './left.scss' 3 | import './right.less' 4 | 5 | var img=new Image(); 6 | img.src=require('./bg.png') 7 | img.onload = function(){ 8 | 9 | } 10 | 11 | { 12 | 13 | let a = 10; 14 | let [a1, b, c] = [1, 2, 3]; 15 | console.log(` 16 | 20 | `) 21 | for (let codePoint of 'foo') { 22 | console.log(codePoint) 23 | } 24 | function Point(x = 0, y = 0) { 25 | this.x = x; 26 | this.y = y; 27 | } 28 | const p = new Point(); 29 | class Points { 30 | constructor(x, y) { 31 | this.x = x; 32 | this.y = y; 33 | } 34 | toString() { 35 | return '(' + this.x + ', ' + this.y + ')'; 36 | } 37 | } 38 | } 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /demo4/src/left.scss: -------------------------------------------------------------------------------- 1 | $bg: #F90; 2 | $wid: 300px; 3 | .sass-box{ 4 | width: $wid; 5 | background: $bg; 6 | border-radius: 4px; 7 | } -------------------------------------------------------------------------------- /demo4/src/right.less: -------------------------------------------------------------------------------- 1 | 2 | @bg: green; 3 | @wid: 350px; 4 | .less-box{ 5 | width: @wid; 6 | background: @bg; 7 | border-radius: 4px; 8 | } -------------------------------------------------------------------------------- /demo4/webpack.config.js: -------------------------------------------------------------------------------- 1 | 2 | const path = require('path') 3 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 4 | 5 | module.exports = { 6 | mode: 'development', 7 | entry: './src/index.js', 8 | output: { 9 | path: path.resolve(__dirname, 'dist'), 10 | filename: '[name].js' 11 | }, 12 | plugins: [ 13 | new HtmlWebpackPlugin({ 14 | template: './index.html', 15 | filename: 'index.html', 16 | }) 17 | ], 18 | module: { 19 | rules: [{ 20 | test: /\.css/, 21 | use: [{ 22 | loader: 'style-loader' 23 | }, { 24 | loader: 'css-loader' 25 | }, { 26 | loader: 'postcss-loader' 27 | }] 28 | },{ 29 | test: /\.scss/, 30 | use: [{ 31 | loader: 'style-loader' 32 | }, { 33 | loader: 'css-loader' 34 | }, { 35 | loader: 'postcss-loader' 36 | },{ 37 | loader: 'sass-loader' 38 | }] 39 | },{ 40 | test: /\.less/, 41 | use: [{ 42 | loader: 'style-loader' 43 | }, { 44 | loader: 'css-loader' 45 | }, { 46 | loader: 'postcss-loader' 47 | },{ 48 | loader: 'less-loader' 49 | }] 50 | },{ 51 | test: /\.js/, 52 | use: { 53 | loader: 'babel-loader' 54 | } 55 | },{ 56 | test: /\.(png|jpg|gif|jpeg|webp|svg|eot|ttf|woff|woff2)$/, 57 | use: { 58 | loader: 'url-loader', 59 | options: { 60 | //10k 61 | limit: 10240, 62 | name: '[name].[hash:8].[ext]', 63 | outputPath: 'imgs/', 64 | esModule: false 65 | } 66 | } 67 | }, { 68 | test: /\.(htm|html)$/, 69 | use: { 70 | loader: 'html-withimg-loader' 71 | } 72 | }] 73 | } 74 | } -------------------------------------------------------------------------------- /demo5/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env"], 3 | "plugins": [ 4 | [ 5 | "@babel/plugin-transform-runtime" 6 | ] 7 | ] 8 | } -------------------------------------------------------------------------------- /demo5/README.md: -------------------------------------------------------------------------------- 1 | webpack vue 2 | 3 | ``` 4 | npm i 5 | npm run build 6 | cd dist 7 | static-server 8 | ``` -------------------------------------------------------------------------------- /demo5/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo5", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "@babel/runtime": "^7.10.2", 14 | "vue": "^2.6.11", 15 | "webpack": "^4.43.0", 16 | "webpack-cli": "^3.3.11" 17 | }, 18 | "devDependencies": { 19 | "@babel/core": "^7.10.2", 20 | "@babel/plugin-transform-runtime": "^7.10.1", 21 | "@babel/preset-env": "^7.10.2", 22 | "babel-loader": "^8.1.0", 23 | "css-loader": "^3.5.3", 24 | "html-webpack-plugin": "^4.3.0", 25 | "style-loader": "^1.2.1", 26 | "vue-loader": "^15.9.2", 27 | "vue-style-loader": "^4.1.2", 28 | "vue-template-compiler": "^2.6.11" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /demo5/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 |
10 | 11 | -------------------------------------------------------------------------------- /demo5/src/App.vue: -------------------------------------------------------------------------------- 1 | 6 | 24 | 25 | 31 | -------------------------------------------------------------------------------- /demo5/src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import App from './App.vue' 3 | 4 | new Vue({ 5 | render: h => h(App) 6 | }).$mount('#app') -------------------------------------------------------------------------------- /demo5/webpack.config.js: -------------------------------------------------------------------------------- 1 | 2 | const VueLoaderPlugin = require('vue-loader/lib/plugin') 3 | const path = require('path') 4 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 5 | module.exports = { 6 | mode: 'development', 7 | entry: './src/main.js', 8 | output: { 9 | path: path.resolve(__dirname, 'dist'), 10 | filename: '[name].js' 11 | }, 12 | module: { 13 | rules: [{ 14 | test: /\.vue$/, 15 | loader: 'vue-loader' 16 | },{ 17 | test: /\.js/, 18 | use: { 19 | loader: 'babel-loader' 20 | } 21 | },{ 22 | test: /\.css$/, 23 | use: [ 24 | 'vue-style-loader', 25 | 'css-loader' 26 | ] 27 | }] 28 | }, 29 | plugins: [ 30 | new VueLoaderPlugin(), 31 | new HtmlWebpackPlugin({ 32 | template: './public/index.html', 33 | filename: 'index.html', 34 | }) 35 | ] 36 | } -------------------------------------------------------------------------------- /demo6/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ], 5 | "plugins": [ 6 | "@babel/plugin-transform-runtime" 7 | ] 8 | } -------------------------------------------------------------------------------- /demo6/README.md: -------------------------------------------------------------------------------- 1 | webpack-dev-server 2 | 3 | ``` 4 | npm i 5 | npm run dev 6 | ``` 7 | -------------------------------------------------------------------------------- /demo6/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo6", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev": "webpack-dev-server --config webpack.dev.config.js", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.2", 14 | "@babel/plugin-transform-runtime": "^7.10.1", 15 | "@babel/preset-env": "^7.10.2", 16 | "babel-loader": "^8.1.0", 17 | "css-loader": "^3.5.3", 18 | "html-webpack-plugin": "^4.3.0", 19 | "style-loader": "^1.2.1", 20 | "webpack": "^4.43.0", 21 | "webpack-cli": "^3.3.11", 22 | "webpack-dev-server": "^3.11.0" 23 | }, 24 | "dependencies": { 25 | "@babel/runtime": "^7.10.2" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /demo6/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 |
这是dev-server启动的服务器
10 | 11 | 12 | -------------------------------------------------------------------------------- /demo6/public/js/js.cookie.min.js: -------------------------------------------------------------------------------- 1 | /*! js-cookie v3.0.0-rc.0 | MIT */ 2 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,function(){var r=e.Cookies,n=e.Cookies=t();n.noConflict=function(){return e.Cookies=r,n}}())}(this,function(){"use strict";function e(e){for(var t=1;t 0.25% 2 | last 2 versions 3 | -------------------------------------------------------------------------------- /demo7/README.md: -------------------------------------------------------------------------------- 1 | # webpack plugins -------------------------------------------------------------------------------- /demo7/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo7", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.2", 14 | "@babel/plugin-transform-runtime": "^7.10.1", 15 | "@babel/preset-env": "^7.10.2", 16 | "autoprefixer": "^9.8.0", 17 | "babel-loader": "^8.1.0", 18 | "clean-webpack-plugin": "^3.0.0", 19 | "copy-webpack-plugin": "^6.0.2", 20 | "html-webpack-plugin": "^4.3.0", 21 | "jquery": "^3.5.1", 22 | "mini-css-extract-plugin": "^0.9.0", 23 | "optimize-css-assets-webpack-plugin": "^5.0.3", 24 | "postcss-loader": "^3.0.0", 25 | "webpack": "^4.43.0", 26 | "webpack-cli": "^3.3.11" 27 | }, 28 | "dependencies": { 29 | "@babel/runtime": "^7.10.2", 30 | "css-loader": "^3.5.3", 31 | "less-loader": "^6.1.0" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /demo7/postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [ 3 | require('autoprefixer')() 4 | ] 5 | } -------------------------------------------------------------------------------- /demo7/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |
11 | 12 | 13 | -------------------------------------------------------------------------------- /demo7/public/js/js.cookie.min.js: -------------------------------------------------------------------------------- 1 | /*! js-cookie v3.0.0-rc.0 | MIT */ 2 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,function(){var r=e.Cookies,n=e.Cookies=t();n.noConflict=function(){return e.Cookies=r,n}}())}(this,function(){"use strict";function e(e){for(var t=1;t 0.25% 2 | not dead 3 | -------------------------------------------------------------------------------- /demo8/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "no-undef": "off", 4 | "no-unused-vars": "off", 5 | "no-inner-declarations": "off", 6 | "no-extra-boolean-cast": "off" 7 | }, 8 | "parserOptions": { 9 | "ecmaVersion": 7, 10 | "sourceType": "module" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /demo8/READMD.md: -------------------------------------------------------------------------------- 1 | # Eslint代码检查 2 | 3 | ``` 4 | npm i 5 | npm run build 6 | ``` -------------------------------------------------------------------------------- /demo8/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Document 7 | 8 | 9 | 10 |
head
11 |
12 | main 13 | 14 |
sass
15 |
less
16 | 17 | 18 |
19 |
foot
20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /demo8/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo4", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "webpack" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "devDependencies": { 13 | "@babel/core": "^7.10.2", 14 | "@babel/plugin-transform-runtime": "^7.10.1", 15 | "@babel/runtime": "^7.10.2", 16 | "autoprefixer": "^9.8.0", 17 | "babel-loader": "^8.1.0", 18 | "babel-preset-env": "^1.7.0", 19 | "css-loader": "^3.5.3", 20 | "cssnano": "^4.1.10", 21 | "eslint": "^7.3.1", 22 | "eslint-loader": "^4.0.2", 23 | "file-loader": "^6.0.0", 24 | "html-webpack-plugin": "^4.3.0", 25 | "html-withimg-loader": "^0.1.16", 26 | "less-loader": "^6.1.0", 27 | "node-sass": "^4.14.1", 28 | "postcss-loader": "^3.0.0", 29 | "postcss-plugins-px2rem": "0.0.5", 30 | "sass-loader": "^8.0.2", 31 | "style-loader": "^1.2.1", 32 | "url-loader": "^4.1.0", 33 | "webpack": "^4.43.0", 34 | "webpack-cli": "^3.3.11" 35 | }, 36 | "dependencies": { 37 | "@babel/preset-env": "^7.10.2" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /demo8/postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [ 3 | require('autoprefixer'), 4 | require('postcss-plugins-px2rem')({ remUnit: 75 }), 5 | require('cssnano'), 6 | ] 7 | } -------------------------------------------------------------------------------- /demo8/src/bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/acexyf/WebpackDemo/752b2e7a775c0cd886c8ba58d09f5938b26157c2/demo8/src/bg.png -------------------------------------------------------------------------------- /demo8/src/bg1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/acexyf/WebpackDemo/752b2e7a775c0cd886c8ba58d09f5938b26157c2/demo8/src/bg1.png -------------------------------------------------------------------------------- /demo8/src/foot.css: -------------------------------------------------------------------------------- 1 | .foot{ 2 | background: #ccc; 3 | } -------------------------------------------------------------------------------- /demo8/src/head.css: -------------------------------------------------------------------------------- 1 | .head{ 2 | display: flex; 3 | background: #666; 4 | } -------------------------------------------------------------------------------- /demo8/src/index.css: -------------------------------------------------------------------------------- 1 | @import './head.css'; 2 | @import './foot.css'; 3 | 4 | body{ 5 | width: 100vw; 6 | height: 100vh; 7 | background: url(./bg1.png) no-repeat; 8 | background-size: 400px 400px; 9 | background-position: center center; 10 | } 11 | 12 | .wrap { 13 | display: flex; 14 | background: #999; 15 | } -------------------------------------------------------------------------------- /demo8/src/index.js: -------------------------------------------------------------------------------- 1 | import './index.css' 2 | import './left.scss' 3 | import './right.less' 4 | 5 | var img=new Image(); 6 | img.src=require('./bg.png') 7 | img.onload = function(){ 8 | 9 | } 10 | 11 | { 12 | 13 | let a = 10; 14 | let [a1, b, c] = [1, 2, 3]; 15 | console.log(` 16 |
    17 |
  • 1
  • 18 |
  • 2
  • 19 |
20 | `) 21 | for (let codePoint of 'foo') { 22 | console.log(codePoint) 23 | } 24 | function Point(x = 0, y = 0) { 25 | this.x = x; 26 | this.y = y; 27 | } 28 | const p = new Point(); 29 | class Points { 30 | constructor(x, y) { 31 | this.x = x; 32 | this.y = y; 33 | } 34 | toString() { 35 | return '(' + this.x + ', ' + this.y + ')'; 36 | } 37 | } 38 | 39 | } 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /demo8/src/left.scss: -------------------------------------------------------------------------------- 1 | $bg: #F90; 2 | $wid: 300px; 3 | .sass-box{ 4 | width: $wid; 5 | background: $bg; 6 | border-radius: 4px; 7 | } -------------------------------------------------------------------------------- /demo8/src/right.less: -------------------------------------------------------------------------------- 1 | 2 | @bg: green; 3 | @wid: 350px; 4 | .less-box{ 5 | width: @wid; 6 | background: @bg; 7 | border-radius: 4px; 8 | } -------------------------------------------------------------------------------- /demo8/webpack.config.js: -------------------------------------------------------------------------------- 1 | 2 | const path = require('path') 3 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 4 | 5 | module.exports = { 6 | mode: 'development', 7 | entry: './src/index.js', 8 | output: { 9 | path: path.resolve(__dirname, 'dist'), 10 | filename: '[name].js' 11 | }, 12 | plugins: [ 13 | new HtmlWebpackPlugin({ 14 | template: './index.html', 15 | filename: 'index.html', 16 | }) 17 | ], 18 | module: { 19 | rules: [{ 20 | test: /\.css/, 21 | use: [{ 22 | loader: 'style-loader' 23 | }, { 24 | loader: 'css-loader' 25 | }, { 26 | loader: 'postcss-loader' 27 | }] 28 | },{ 29 | test: /\.scss/, 30 | use: [{ 31 | loader: 'style-loader' 32 | }, { 33 | loader: 'css-loader' 34 | }, { 35 | loader: 'postcss-loader' 36 | },{ 37 | loader: 'sass-loader' 38 | }] 39 | },{ 40 | test: /\.less/, 41 | use: [{ 42 | loader: 'style-loader' 43 | }, { 44 | loader: 'css-loader' 45 | }, { 46 | loader: 'postcss-loader' 47 | },{ 48 | loader: 'less-loader' 49 | }] 50 | },{ 51 | test: /\.js/, 52 | include: path.resolve(__dirname, 'src'), 53 | use: [{ 54 | loader: 'babel-loader', 55 | },{ 56 | loader: 'eslint-loader', 57 | }] 58 | },{ 59 | test: /\.(png|jpg|gif|jpeg|webp|svg|eot|ttf|woff|woff2)$/, 60 | use: { 61 | loader: 'url-loader', 62 | options: { 63 | //10k 64 | limit: 10240, 65 | name: '[name].[hash:8].[ext]', 66 | outputPath: 'imgs/', 67 | esModule: false 68 | } 69 | } 70 | }, { 71 | test: /\.(htm|html)$/, 72 | use: { 73 | loader: 'html-withimg-loader' 74 | } 75 | }] 76 | } 77 | } -------------------------------------------------------------------------------- /demo9/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ], 5 | "plugins": [ 6 | "@babel/plugin-transform-runtime" 7 | ] 8 | } -------------------------------------------------------------------------------- /demo9/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | rules: { 3 | "no-undef": "off", 4 | "no-unused-vars": "off", 5 | "no-inner-declarations": "off", 6 | "no-extra-boolean-cast": "off", 7 | }, 8 | parserOptions: { 9 | ecmaVersion: 7, 10 | sourceType: "module", 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /demo9/README.md: -------------------------------------------------------------------------------- 1 | # 缩小文件搜索范围 2 | 3 | 4 | babel-loader默认的缓存目录``node_modules/.cache/babel-loader`` 5 | -------------------------------------------------------------------------------- /demo9/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo9", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "webpack.config.js", 6 | "dependencies": { 7 | "@babel/runtime": "^7.10.5", 8 | "moment": "^2.27.0", 9 | "vue": "^2.6.11" 10 | }, 11 | "devDependencies": { 12 | "@babel/core": "^7.10.5", 13 | "@babel/plugin-transform-runtime": "^7.10.5", 14 | "@babel/preset-env": "^7.10.4", 15 | "babel-loader": "^8.1.0", 16 | "eslint": "^7.5.0", 17 | "eslint-loader": "^4.0.2", 18 | "ts-loader": "^8.0.1", 19 | "typescript": "^3.9.7" 20 | }, 21 | "scripts": { 22 | "test": "echo \"Error: no test specified\" && exit 1", 23 | "build": "webpack", 24 | "optimize": "webpack --config webpack.config.optimize.js" 25 | }, 26 | "author": "", 27 | "license": "ISC" 28 | } 29 | -------------------------------------------------------------------------------- /demo9/src/adapters/xhr.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | import settle from './../core/settle'; 5 | import cookies from './../helpers/cookies'; 6 | import buildURL from './../helpers/buildURL'; 7 | import buildFullPath from '../core/buildFullPath'; 8 | import parseHeaders from './../helpers/parseHeaders'; 9 | import isURLSameOrigin from './../helpers/isURLSameOrigin'; 10 | import createError from '../core/createError'; 11 | 12 | export default function xhrAdapter(config) { 13 | return new Promise(function dispatchXhrRequest(resolve, reject) { 14 | var requestData = config.data; 15 | var requestHeaders = config.headers; 16 | 17 | if (utils.isFormData(requestData)) { 18 | delete requestHeaders['Content-Type']; // Let the browser set it 19 | } 20 | 21 | if ( 22 | (utils.isBlob(requestData) || utils.isFile(requestData)) && 23 | requestData.type 24 | ) { 25 | delete requestHeaders['Content-Type']; // Let the browser set it 26 | } 27 | 28 | var request = new XMLHttpRequest(); 29 | 30 | // HTTP basic authentication 31 | if (config.auth) { 32 | var username = config.auth.username || ''; 33 | var password = unescape(encodeURIComponent(config.auth.password)) || ''; 34 | requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); 35 | } 36 | 37 | var fullPath = buildFullPath(config.baseURL, config.url); 38 | request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); 39 | 40 | // Set the request timeout in MS 41 | request.timeout = config.timeout; 42 | 43 | // Listen for ready state 44 | request.onreadystatechange = function handleLoad() { 45 | if (!request || request.readyState !== 4) { 46 | return; 47 | } 48 | 49 | // The request errored out and we didn't get a response, this will be 50 | // handled by onerror instead 51 | // With one exception: request that using file: protocol, most browsers 52 | // will return status as 0 even though it's a successful request 53 | if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { 54 | return; 55 | } 56 | 57 | // Prepare the response 58 | var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; 59 | var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; 60 | var response = { 61 | data: responseData, 62 | status: request.status, 63 | statusText: request.statusText, 64 | headers: responseHeaders, 65 | config: config, 66 | request: request 67 | }; 68 | 69 | settle(resolve, reject, response); 70 | 71 | // Clean up request 72 | request = null; 73 | }; 74 | 75 | // Handle browser request cancellation (as opposed to a manual cancellation) 76 | request.onabort = function handleAbort() { 77 | if (!request) { 78 | return; 79 | } 80 | 81 | reject(createError('Request aborted', config, 'ECONNABORTED', request)); 82 | 83 | // Clean up request 84 | request = null; 85 | }; 86 | 87 | // Handle low level network errors 88 | request.onerror = function handleError() { 89 | // Real errors are hidden from us by the browser 90 | // onerror should only fire if it's a network error 91 | reject(createError('Network Error', config, null, request)); 92 | 93 | // Clean up request 94 | request = null; 95 | }; 96 | 97 | // Handle timeout 98 | request.ontimeout = function handleTimeout() { 99 | var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; 100 | if (config.timeoutErrorMessage) { 101 | timeoutErrorMessage = config.timeoutErrorMessage; 102 | } 103 | reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', 104 | request)); 105 | 106 | // Clean up request 107 | request = null; 108 | }; 109 | 110 | // Add xsrf header 111 | // This is only done if running in a standard browser environment. 112 | // Specifically not if we're in a web worker, or react-native. 113 | if (utils.isStandardBrowserEnv()) { 114 | // Add xsrf header 115 | var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? 116 | cookies.read(config.xsrfCookieName) : 117 | undefined; 118 | 119 | if (xsrfValue) { 120 | requestHeaders[config.xsrfHeaderName] = xsrfValue; 121 | } 122 | } 123 | 124 | // Add headers to the request 125 | if ('setRequestHeader' in request) { 126 | utils.forEach(requestHeaders, function setRequestHeader(val, key) { 127 | if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { 128 | // Remove Content-Type if data is undefined 129 | delete requestHeaders[key]; 130 | } else { 131 | // Otherwise add header to the request 132 | request.setRequestHeader(key, val); 133 | } 134 | }); 135 | } 136 | 137 | // Add withCredentials to request if needed 138 | if (!utils.isUndefined(config.withCredentials)) { 139 | request.withCredentials = !!config.withCredentials; 140 | } 141 | 142 | // Add responseType to request if needed 143 | if (config.responseType) { 144 | try { 145 | request.responseType = config.responseType; 146 | } catch (e) { 147 | // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. 148 | // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. 149 | if (config.responseType !== 'json') { 150 | throw e; 151 | } 152 | } 153 | } 154 | 155 | // Handle progress if needed 156 | if (typeof config.onDownloadProgress === 'function') { 157 | request.addEventListener('progress', config.onDownloadProgress); 158 | } 159 | 160 | // Not all browsers support upload events 161 | if (typeof config.onUploadProgress === 'function' && request.upload) { 162 | request.upload.addEventListener('progress', config.onUploadProgress); 163 | } 164 | 165 | if (config.cancelToken) { 166 | // Handle cancellation 167 | config.cancelToken.promise.then(function onCanceled(cancel) { 168 | if (!request) { 169 | return; 170 | } 171 | 172 | request.abort(); 173 | reject(cancel); 174 | // Clean up request 175 | request = null; 176 | }); 177 | } 178 | 179 | if (!requestData) { 180 | requestData = null; 181 | } 182 | 183 | // Send the request 184 | request.send(requestData); 185 | }); 186 | }; 187 | -------------------------------------------------------------------------------- /demo9/src/axios.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from 'utils'; 4 | import bind from 'helpers/bind'; 5 | import Axios from 'core/Axios'; 6 | import mergeConfig from 'core/mergeConfig'; 7 | import defaults from './defaults'; 8 | // var moemnt = require('moment') 9 | /** 10 | * Create an instance of Axios 11 | * 12 | * @param {Object} defaultConfig The default config for the instance 13 | * @return {Axios} A new instance of Axios 14 | */ 15 | function createInstance(defaultConfig) { 16 | var context = new Axios(defaultConfig); 17 | var instance = bind(Axios.prototype.request, context); 18 | 19 | // Copy axios.prototype to instance 20 | utils.extend(instance, Axios.prototype, context); 21 | 22 | // Copy context to instance 23 | utils.extend(instance, context, null); 24 | 25 | return instance; 26 | } 27 | 28 | // Create the default instance to be exported 29 | var axios:any = createInstance(defaults); 30 | 31 | // Expose Axios class to allow class inheritance 32 | axios.Axios = Axios; 33 | 34 | // Factory for creating new instances 35 | axios.create = function create(instanceConfig) { 36 | return createInstance(mergeConfig(axios.defaults, instanceConfig)); 37 | }; 38 | 39 | // Expose Cancel & CancelToken 40 | import Cancel from 'cancel/Cancel' 41 | import CancelToken from 'cancel/CancelToken' 42 | import isCancel from 'cancel/isCancel' 43 | axios.Cancel = Cancel; 44 | axios.CancelToken = CancelToken; 45 | axios.isCancel = isCancel; 46 | 47 | // Expose all/spread 48 | axios.all = function all(promises) { 49 | return Promise.all(promises); 50 | }; 51 | import spread from 'helpers/spread' 52 | axios.spread = spread; 53 | 54 | 55 | export default axios -------------------------------------------------------------------------------- /demo9/src/cancel/Cancel.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * A `Cancel` is an object that is thrown when an operation is canceled. 5 | * 6 | * @class 7 | * @param {string=} message The message. 8 | */ 9 | function Cancel(message) { 10 | this.message = message; 11 | } 12 | 13 | Cancel.prototype.toString = function toString() { 14 | return 'Cancel' + (this.message ? ': ' + this.message : ''); 15 | }; 16 | 17 | Cancel.prototype.__CANCEL__ = true; 18 | 19 | export default Cancel; 20 | -------------------------------------------------------------------------------- /demo9/src/cancel/CancelToken.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import Cancel from './Cancel'; 4 | 5 | /** 6 | * A `CancelToken` is an object that can be used to request cancellation of an operation. 7 | * 8 | * @class 9 | * @param {Function} executor The executor function. 10 | */ 11 | function CancelToken(executor) { 12 | if (typeof executor !== 'function') { 13 | throw new TypeError('executor must be a function.'); 14 | } 15 | 16 | var resolvePromise; 17 | this.promise = new Promise(function promiseExecutor(resolve) { 18 | resolvePromise = resolve; 19 | }); 20 | 21 | var token = this; 22 | executor(function cancel(message) { 23 | if (token.reason) { 24 | // Cancellation has already been requested 25 | return; 26 | } 27 | 28 | token.reason = new Cancel(message); 29 | resolvePromise(token.reason); 30 | }); 31 | } 32 | 33 | /** 34 | * Throws a `Cancel` if cancellation has been requested. 35 | */ 36 | CancelToken.prototype.throwIfRequested = function throwIfRequested() { 37 | if (this.reason) { 38 | throw this.reason; 39 | } 40 | }; 41 | 42 | /** 43 | * Returns an object that contains a new `CancelToken` and a function that, when called, 44 | * cancels the `CancelToken`. 45 | */ 46 | CancelToken.source = function source() { 47 | var cancel; 48 | var token = new CancelToken(function executor(c) { 49 | cancel = c; 50 | }); 51 | return { 52 | token: token, 53 | cancel: cancel 54 | }; 55 | }; 56 | 57 | export default CancelToken; 58 | -------------------------------------------------------------------------------- /demo9/src/cancel/isCancel.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | export default function isCancel(value) { 4 | return !!(value && value.__CANCEL__); 5 | }; 6 | -------------------------------------------------------------------------------- /demo9/src/core/Axios.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | import buildURL from'../helpers/buildURL'; 5 | import InterceptorManager from './InterceptorManager'; 6 | import dispatchRequest from './dispatchRequest'; 7 | import mergeConfig from './mergeConfig'; 8 | 9 | /** 10 | * Create a new instance of Axios 11 | * 12 | * @param {Object} instanceConfig The default config for the instance 13 | */ 14 | function Axios(instanceConfig) { 15 | this.defaults = instanceConfig; 16 | this.interceptors = { 17 | request: new InterceptorManager(), 18 | response: new InterceptorManager() 19 | }; 20 | } 21 | 22 | /** 23 | * Dispatch a request 24 | * 25 | * @param {Object} config The config specific for this request (merged with this.defaults) 26 | */ 27 | Axios.prototype.request = function request(config) { 28 | /*eslint no-param-reassign:0*/ 29 | // Allow for axios('example/url'[, config]) a la fetch API 30 | if (typeof config === 'string') { 31 | config = arguments[1] || {}; 32 | config.url = arguments[0]; 33 | } else { 34 | config = config || {}; 35 | } 36 | 37 | config = mergeConfig(this.defaults, config); 38 | 39 | // Set config.method 40 | if (config.method) { 41 | config.method = config.method.toLowerCase(); 42 | } else if (this.defaults.method) { 43 | config.method = this.defaults.method.toLowerCase(); 44 | } else { 45 | config.method = 'get'; 46 | } 47 | 48 | // Hook up interceptors middleware 49 | var chain = [dispatchRequest, undefined]; 50 | var promise = Promise.resolve(config); 51 | 52 | this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { 53 | chain.unshift(interceptor.fulfilled, interceptor.rejected); 54 | }); 55 | 56 | this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { 57 | chain.push(interceptor.fulfilled, interceptor.rejected); 58 | }); 59 | 60 | while (chain.length) { 61 | promise = promise.then(chain.shift(), chain.shift()); 62 | } 63 | 64 | return promise; 65 | }; 66 | 67 | Axios.prototype.getUri = function getUri(config) { 68 | config = mergeConfig(this.defaults, config); 69 | return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); 70 | }; 71 | 72 | // Provide aliases for supported request methods 73 | utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { 74 | /*eslint func-names:0*/ 75 | Axios.prototype[method] = function(url, config) { 76 | return this.request(mergeConfig(config || {}, { 77 | method: method, 78 | url: url 79 | })); 80 | }; 81 | }); 82 | 83 | utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { 84 | /*eslint func-names:0*/ 85 | Axios.prototype[method] = function(url, data, config) { 86 | return this.request(mergeConfig(config || {}, { 87 | method: method, 88 | url: url, 89 | data: data 90 | })); 91 | }; 92 | }); 93 | 94 | export default Axios; 95 | -------------------------------------------------------------------------------- /demo9/src/core/InterceptorManager.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | function InterceptorManager() { 6 | this.handlers = []; 7 | } 8 | 9 | /** 10 | * Add a new interceptor to the stack 11 | * 12 | * @param {Function} fulfilled The function to handle `then` for a `Promise` 13 | * @param {Function} rejected The function to handle `reject` for a `Promise` 14 | * 15 | * @return {Number} An ID used to remove interceptor later 16 | */ 17 | InterceptorManager.prototype.use = function use(fulfilled, rejected) { 18 | this.handlers.push({ 19 | fulfilled: fulfilled, 20 | rejected: rejected 21 | }); 22 | return this.handlers.length - 1; 23 | }; 24 | 25 | /** 26 | * Remove an interceptor from the stack 27 | * 28 | * @param {Number} id The ID that was returned by `use` 29 | */ 30 | InterceptorManager.prototype.eject = function eject(id) { 31 | if (this.handlers[id]) { 32 | this.handlers[id] = null; 33 | } 34 | }; 35 | 36 | /** 37 | * Iterate over all the registered interceptors 38 | * 39 | * This method is particularly useful for skipping over any 40 | * interceptors that may have become `null` calling `eject`. 41 | * 42 | * @param {Function} fn The function to call for each interceptor 43 | */ 44 | InterceptorManager.prototype.forEach = function forEach(fn) { 45 | utils.forEach(this.handlers, function forEachHandler(h) { 46 | if (h !== null) { 47 | fn(h); 48 | } 49 | }); 50 | }; 51 | 52 | export default InterceptorManager; 53 | -------------------------------------------------------------------------------- /demo9/src/core/buildFullPath.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import isAbsoluteURL from '../helpers/isAbsoluteURL'; 4 | import combineURLs from '../helpers/combineURLs'; 5 | 6 | /** 7 | * Creates a new URL by combining the baseURL with the requestedURL, 8 | * only when the requestedURL is not already an absolute URL. 9 | * If the requestURL is absolute, this function returns the requestedURL untouched. 10 | * 11 | * @param {string} baseURL The base URL 12 | * @param {string} requestedURL Absolute or relative URL to combine 13 | * @returns {string} The combined full path 14 | */ 15 | export default function buildFullPath(baseURL, requestedURL) { 16 | if (baseURL && !isAbsoluteURL(requestedURL)) { 17 | return combineURLs(baseURL, requestedURL); 18 | } 19 | return requestedURL; 20 | }; 21 | -------------------------------------------------------------------------------- /demo9/src/core/createError.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import enhanceError from './enhanceError'; 4 | 5 | /** 6 | * Create an Error with the specified message, config, error code, request and response. 7 | * 8 | * @param {string} message The error message. 9 | * @param {Object} config The config. 10 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). 11 | * @param {Object} [request] The request. 12 | * @param {Object} [response] The response. 13 | * @returns {Error} The created error. 14 | */ 15 | export default function createError(message, config, code, request, response?) { 16 | var error = new Error(message); 17 | return enhanceError(error, config, code, request, response); 18 | }; 19 | -------------------------------------------------------------------------------- /demo9/src/core/dispatchRequest.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | import transformData from './transformData'; 5 | import isCancel from '../cancel/isCancel'; 6 | import defaults from '../defaults'; 7 | 8 | /** 9 | * Throws a `Cancel` if cancellation has been requested. 10 | */ 11 | function throwIfCancellationRequested(config) { 12 | if (config.cancelToken) { 13 | config.cancelToken.throwIfRequested(); 14 | } 15 | } 16 | 17 | /** 18 | * Dispatch a request to the server using the configured adapter. 19 | * 20 | * @param {object} config The config that is to be used for the request 21 | * @returns {Promise} The Promise to be fulfilled 22 | */ 23 | export default function dispatchRequest(config) { 24 | throwIfCancellationRequested(config); 25 | 26 | // Ensure headers exist 27 | config.headers = config.headers || {}; 28 | 29 | // Transform request data 30 | config.data = transformData( 31 | config.data, 32 | config.headers, 33 | config.transformRequest 34 | ); 35 | 36 | // Flatten headers 37 | config.headers = utils.merge( 38 | config.headers.common || {}, 39 | config.headers[config.method] || {}, 40 | config.headers 41 | ); 42 | 43 | utils.forEach( 44 | ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], 45 | function cleanHeaderConfig(method) { 46 | delete config.headers[method]; 47 | } 48 | ); 49 | 50 | var adapter = config.adapter || defaults.adapter; 51 | 52 | return adapter(config).then(function onAdapterResolution(response) { 53 | throwIfCancellationRequested(config); 54 | 55 | // Transform response data 56 | response.data = transformData( 57 | response.data, 58 | response.headers, 59 | config.transformResponse 60 | ); 61 | 62 | return response; 63 | }, function onAdapterRejection(reason) { 64 | if (!isCancel(reason)) { 65 | throwIfCancellationRequested(config); 66 | 67 | // Transform response data 68 | if (reason && reason.response) { 69 | reason.response.data = transformData( 70 | reason.response.data, 71 | reason.response.headers, 72 | config.transformResponse 73 | ); 74 | } 75 | } 76 | 77 | return Promise.reject(reason); 78 | }); 79 | }; 80 | -------------------------------------------------------------------------------- /demo9/src/core/enhanceError.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Update an Error with the specified config, error code, and response. 5 | * 6 | * @param {Error} error The error to update. 7 | * @param {Object} config The config. 8 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). 9 | * @param {Object} [request] The request. 10 | * @param {Object} [response] The response. 11 | * @returns {Error} The error. 12 | */ 13 | export default function enhanceError(error, config, code, request, response) { 14 | error.config = config; 15 | if (code) { 16 | error.code = code; 17 | } 18 | 19 | error.request = request; 20 | error.response = response; 21 | error.isAxiosError = true; 22 | 23 | error.toJSON = function toJSON() { 24 | return { 25 | // Standard 26 | message: this.message, 27 | name: this.name, 28 | // Microsoft 29 | description: this.description, 30 | number: this.number, 31 | // Mozilla 32 | fileName: this.fileName, 33 | lineNumber: this.lineNumber, 34 | columnNumber: this.columnNumber, 35 | stack: this.stack, 36 | // Axios 37 | config: this.config, 38 | code: this.code 39 | }; 40 | }; 41 | return error; 42 | }; 43 | -------------------------------------------------------------------------------- /demo9/src/core/mergeConfig.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from '../utils'; 4 | 5 | /** 6 | * Config-specific merge-function which creates a new config-object 7 | * by merging two configuration objects together. 8 | * 9 | * @param {Object} config1 10 | * @param {Object} config2 11 | * @returns {Object} New object resulting from merging config2 to config1 12 | */ 13 | export default function mergeConfig(config1, config2) { 14 | // eslint-disable-next-line no-param-reassign 15 | config2 = config2 || {}; 16 | var config = {}; 17 | 18 | var valueFromConfig2Keys = ['url', 'method', 'data']; 19 | var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; 20 | var defaultToConfig2Keys = [ 21 | 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 22 | 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 23 | 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 24 | 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 25 | 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' 26 | ]; 27 | var directMergeKeys = ['validateStatus']; 28 | 29 | function getMergedValue(target, source) { 30 | if (utils.isPlainObject(target) && utils.isPlainObject(source)) { 31 | return utils.merge(target, source); 32 | } else if (utils.isPlainObject(source)) { 33 | return utils.merge({}, source); 34 | } else if (utils.isArray(source)) { 35 | return source.slice(); 36 | } 37 | return source; 38 | } 39 | 40 | function mergeDeepProperties(prop) { 41 | if (!utils.isUndefined(config2[prop])) { 42 | config[prop] = getMergedValue(config1[prop], config2[prop]); 43 | } else if (!utils.isUndefined(config1[prop])) { 44 | config[prop] = getMergedValue(undefined, config1[prop]); 45 | } 46 | } 47 | 48 | utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { 49 | if (!utils.isUndefined(config2[prop])) { 50 | config[prop] = getMergedValue(undefined, config2[prop]); 51 | } 52 | }); 53 | 54 | utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); 55 | 56 | utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { 57 | if (!utils.isUndefined(config2[prop])) { 58 | config[prop] = getMergedValue(undefined, config2[prop]); 59 | } else if (!utils.isUndefined(config1[prop])) { 60 | config[prop] = getMergedValue(undefined, config1[prop]); 61 | } 62 | }); 63 | 64 | utils.forEach(directMergeKeys, function merge(prop) { 65 | if (prop in config2) { 66 | config[prop] = getMergedValue(config1[prop], config2[prop]); 67 | } else if (prop in config1) { 68 | config[prop] = getMergedValue(undefined, config1[prop]); 69 | } 70 | }); 71 | 72 | var axiosKeys = valueFromConfig2Keys 73 | .concat(mergeDeepPropertiesKeys) 74 | .concat(defaultToConfig2Keys) 75 | .concat(directMergeKeys); 76 | 77 | var otherKeys = Object 78 | .keys(config1) 79 | .concat(Object.keys(config2)) 80 | .filter(function filterAxiosKeys(key) { 81 | return axiosKeys.indexOf(key) === -1; 82 | }); 83 | 84 | utils.forEach(otherKeys, mergeDeepProperties); 85 | 86 | return config; 87 | }; 88 | -------------------------------------------------------------------------------- /demo9/src/core/settle.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import createError from './createError'; 4 | 5 | /** 6 | * Resolve or reject a Promise based on response status. 7 | * 8 | * @param {Function} resolve A function that resolves the promise. 9 | * @param {Function} reject A function that rejects the promise. 10 | * @param {object} response The response. 11 | */ 12 | export default function settle(resolve, reject, response) { 13 | var validateStatus = response.config.validateStatus; 14 | if (!response.status || !validateStatus || validateStatus(response.status)) { 15 | resolve(response); 16 | } else { 17 | reject(createError( 18 | 'Request failed with status code ' + response.status, 19 | response.config, 20 | null, 21 | response.request, 22 | response 23 | )); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /demo9/src/core/transformData.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | /** 6 | * Transform the data for a request or a response 7 | * 8 | * @param {Object|String} data The data to be transformed 9 | * @param {Array} headers The headers for the request or response 10 | * @param {Array|Function} fns A single function or Array of functions 11 | * @returns {*} The resulting transformed data 12 | */ 13 | export default function transformData(data, headers, fns) { 14 | /*eslint no-param-reassign:0*/ 15 | utils.forEach(fns, function transform(fn) { 16 | data = fn(data, headers); 17 | }); 18 | 19 | return data; 20 | }; 21 | -------------------------------------------------------------------------------- /demo9/src/defaults.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './utils'; 4 | import normalizeHeaderName from './helpers/normalizeHeaderName'; 5 | import xhr from './adapters/xhr' 6 | var DEFAULT_CONTENT_TYPE = { 7 | 'Content-Type': 'application/x-www-form-urlencoded' 8 | }; 9 | 10 | function setContentTypeIfUnset(headers, value) { 11 | if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { 12 | headers['Content-Type'] = value; 13 | } 14 | } 15 | 16 | function getDefaultAdapter() { 17 | var adapter = xhr 18 | return adapter; 19 | } 20 | 21 | var defaults:any = { 22 | adapter: getDefaultAdapter(), 23 | 24 | transformRequest: [function transformRequest(data, headers) { 25 | normalizeHeaderName(headers, 'Accept'); 26 | normalizeHeaderName(headers, 'Content-Type'); 27 | if (utils.isFormData(data) || 28 | utils.isArrayBuffer(data) || 29 | utils.isBuffer(data) || 30 | utils.isStream(data) || 31 | utils.isFile(data) || 32 | utils.isBlob(data) 33 | ) { 34 | return data; 35 | } 36 | if (utils.isArrayBufferView(data)) { 37 | return data.buffer; 38 | } 39 | if (utils.isURLSearchParams(data)) { 40 | setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); 41 | return data.toString(); 42 | } 43 | if (utils.isObject(data)) { 44 | setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); 45 | return JSON.stringify(data); 46 | } 47 | return data; 48 | }], 49 | 50 | transformResponse: [function transformResponse(data) { 51 | /*eslint no-param-reassign:0*/ 52 | if (typeof data === 'string') { 53 | try { 54 | data = JSON.parse(data); 55 | } catch (e) { /* Ignore */ } 56 | } 57 | return data; 58 | }], 59 | 60 | /** 61 | * A timeout in milliseconds to abort a request. If set to 0 (default) a 62 | * timeout is not created. 63 | */ 64 | timeout: 0, 65 | 66 | xsrfCookieName: 'XSRF-TOKEN', 67 | xsrfHeaderName: 'X-XSRF-TOKEN', 68 | 69 | maxContentLength: -1, 70 | maxBodyLength: -1, 71 | 72 | validateStatus: function validateStatus(status) { 73 | return status >= 200 && status < 300; 74 | } 75 | }; 76 | 77 | defaults.headers = { 78 | common: { 79 | 'Accept': 'application/json, text/plain, */*' 80 | } 81 | }; 82 | 83 | utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { 84 | defaults.headers[method] = {}; 85 | }); 86 | 87 | utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { 88 | defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); 89 | }); 90 | 91 | export default defaults; 92 | -------------------------------------------------------------------------------- /demo9/src/helpers/README.md: -------------------------------------------------------------------------------- 1 | # axios // helpers 2 | 3 | The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: 4 | 5 | - Browser polyfills 6 | - Managing cookies 7 | - Parsing HTTP headers 8 | -------------------------------------------------------------------------------- /demo9/src/helpers/bind.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | export default function bind(fn:any, thisArg:any) { 4 | return function wrap() { 5 | var args = new Array(arguments.length); 6 | for (var i = 0; i < args.length; i++) { 7 | args[i] = arguments[i]; 8 | } 9 | return fn.apply(thisArg, args); 10 | }; 11 | }; 12 | -------------------------------------------------------------------------------- /demo9/src/helpers/buildURL.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | function encode(val) { 6 | return encodeURIComponent(val). 7 | replace(/%3A/gi, ':'). 8 | replace(/%24/g, '$'). 9 | replace(/%2C/gi, ','). 10 | replace(/%20/g, '+'). 11 | replace(/%5B/gi, '['). 12 | replace(/%5D/gi, ']'); 13 | } 14 | 15 | /** 16 | * Build a URL by appending params to the end 17 | * 18 | * @param {string} url The base of the url (e.g., http://www.google.com) 19 | * @param {object} [params] The params to be appended 20 | * @returns {string} The formatted url 21 | */ 22 | export default function buildURL(url, params, paramsSerializer) { 23 | /*eslint no-param-reassign:0*/ 24 | if (!params) { 25 | return url; 26 | } 27 | 28 | var serializedParams; 29 | if (paramsSerializer) { 30 | serializedParams = paramsSerializer(params); 31 | } else if (utils.isURLSearchParams(params)) { 32 | serializedParams = params.toString(); 33 | } else { 34 | var parts = []; 35 | 36 | utils.forEach(params, function serialize(val, key) { 37 | if (val === null || typeof val === 'undefined') { 38 | return; 39 | } 40 | 41 | if (utils.isArray(val)) { 42 | key = key + '[]'; 43 | } else { 44 | val = [val]; 45 | } 46 | 47 | utils.forEach(val, function parseValue(v) { 48 | if (utils.isDate(v)) { 49 | v = v.toISOString(); 50 | } else if (utils.isObject(v)) { 51 | v = JSON.stringify(v); 52 | } 53 | parts.push(encode(key) + '=' + encode(v)); 54 | }); 55 | }); 56 | 57 | serializedParams = parts.join('&'); 58 | } 59 | 60 | if (serializedParams) { 61 | var hashmarkIndex = url.indexOf('#'); 62 | if (hashmarkIndex !== -1) { 63 | url = url.slice(0, hashmarkIndex); 64 | } 65 | 66 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; 67 | } 68 | 69 | return url; 70 | }; 71 | -------------------------------------------------------------------------------- /demo9/src/helpers/combineURLs.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Creates a new URL by combining the specified URLs 5 | * 6 | * @param {string} baseURL The base URL 7 | * @param {string} relativeURL The relative URL 8 | * @returns {string} The combined URL 9 | */ 10 | export default function combineURLs(baseURL, relativeURL) { 11 | return relativeURL 12 | ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') 13 | : baseURL; 14 | }; 15 | -------------------------------------------------------------------------------- /demo9/src/helpers/cookies.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | export default ( 6 | utils.isStandardBrowserEnv() ? 7 | 8 | // Standard browser envs support document.cookie 9 | (function standardBrowserEnv() { 10 | return { 11 | write: function write(name, value, expires, path, domain, secure) { 12 | var cookie = []; 13 | cookie.push(name + '=' + encodeURIComponent(value)); 14 | 15 | if (utils.isNumber(expires)) { 16 | cookie.push('expires=' + new Date(expires).toUTCString()); 17 | } 18 | 19 | if (utils.isString(path)) { 20 | cookie.push('path=' + path); 21 | } 22 | 23 | if (utils.isString(domain)) { 24 | cookie.push('domain=' + domain); 25 | } 26 | 27 | if (secure === true) { 28 | cookie.push('secure'); 29 | } 30 | 31 | document.cookie = cookie.join('; '); 32 | }, 33 | 34 | read: function read(name) { 35 | var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); 36 | return (match ? decodeURIComponent(match[3]) : null); 37 | }, 38 | 39 | remove: function remove(name) { 40 | this.write(name, '', Date.now() - 86400000); 41 | } 42 | }; 43 | })() : 44 | 45 | // Non standard browser env (web workers, react-native) lack needed support. 46 | (function nonStandardBrowserEnv() { 47 | return { 48 | write: function write() {}, 49 | read: function read() { return null; }, 50 | remove: function remove() {} 51 | }; 52 | })() 53 | ); 54 | -------------------------------------------------------------------------------- /demo9/src/helpers/deprecatedMethod.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /*eslint no-console:0*/ 4 | 5 | /** 6 | * Supply a warning to the developer that a method they are using 7 | * has been deprecated. 8 | * 9 | * @param {string} method The name of the deprecated method 10 | * @param {string} [instead] The alternate method to use if applicable 11 | * @param {string} [docs] The documentation URL to get further details 12 | */ 13 | export default function deprecatedMethod(method, instead, docs) { 14 | try { 15 | console.warn( 16 | 'DEPRECATED method `' + method + '`.' + 17 | (instead ? ' Use `' + instead + '` instead.' : '') + 18 | ' This method will be removed in a future release.'); 19 | 20 | if (docs) { 21 | console.warn('For more information about usage see ' + docs); 22 | } 23 | } catch (e) { /* Ignore */ } 24 | }; 25 | -------------------------------------------------------------------------------- /demo9/src/helpers/isAbsoluteURL.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Determines whether the specified URL is absolute 5 | * 6 | * @param {string} url The URL to test 7 | * @returns {boolean} True if the specified URL is absolute, otherwise false 8 | */ 9 | export default function isAbsoluteURL(url) { 10 | // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). 11 | // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed 12 | // by any combination of letters, digits, plus, period, or hyphen. 13 | return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); 14 | }; 15 | -------------------------------------------------------------------------------- /demo9/src/helpers/isURLSameOrigin.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | export default ( 6 | utils.isStandardBrowserEnv() ? 7 | 8 | // Standard browser envs have full support of the APIs needed to test 9 | // whether the request URL is of the same origin as current location. 10 | (function standardBrowserEnv() { 11 | var msie = /(msie|trident)/i.test(navigator.userAgent); 12 | var urlParsingNode = document.createElement('a'); 13 | var originURL; 14 | 15 | /** 16 | * Parse a URL to discover it's components 17 | * 18 | * @param {String} url The URL to be parsed 19 | * @returns {Object} 20 | */ 21 | function resolveURL(url) { 22 | var href = url; 23 | 24 | if (msie) { 25 | // IE needs attribute set twice to normalize properties 26 | urlParsingNode.setAttribute('href', href); 27 | href = urlParsingNode.href; 28 | } 29 | 30 | urlParsingNode.setAttribute('href', href); 31 | 32 | // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils 33 | return { 34 | href: urlParsingNode.href, 35 | protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', 36 | host: urlParsingNode.host, 37 | search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', 38 | hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', 39 | hostname: urlParsingNode.hostname, 40 | port: urlParsingNode.port, 41 | pathname: (urlParsingNode.pathname.charAt(0) === '/') ? 42 | urlParsingNode.pathname : 43 | '/' + urlParsingNode.pathname 44 | }; 45 | } 46 | 47 | originURL = resolveURL(window.location.href); 48 | 49 | /** 50 | * Determine if a URL shares the same origin as the current location 51 | * 52 | * @param {String} requestURL The URL to test 53 | * @returns {boolean} True if URL shares the same origin, otherwise false 54 | */ 55 | return function isURLSameOrigin(requestURL) { 56 | var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; 57 | return (parsed.protocol === originURL.protocol && 58 | parsed.host === originURL.host); 59 | }; 60 | })() : 61 | 62 | // Non standard browser envs (web workers, react-native) lack needed support. 63 | (function nonStandardBrowserEnv() { 64 | return function isURLSameOrigin() { 65 | return true; 66 | }; 67 | })() 68 | ); 69 | -------------------------------------------------------------------------------- /demo9/src/helpers/normalizeHeaderName.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from '../utils'; 4 | 5 | export default function normalizeHeaderName(headers, normalizedName) { 6 | utils.forEach(headers, function processHeader(value, name) { 7 | if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { 8 | headers[normalizedName] = value; 9 | delete headers[name]; 10 | } 11 | }); 12 | }; 13 | -------------------------------------------------------------------------------- /demo9/src/helpers/parseHeaders.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import utils from './../utils'; 4 | 5 | // Headers whose duplicates are ignored by node 6 | // c.f. https://nodejs.org/api/http.html#http_message_headers 7 | var ignoreDuplicateOf = [ 8 | 'age', 'authorization', 'content-length', 'content-type', 'etag', 9 | 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 10 | 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 11 | 'referer', 'retry-after', 'user-agent' 12 | ]; 13 | 14 | /** 15 | * Parse headers into an object 16 | * 17 | * ``` 18 | * Date: Wed, 27 Aug 2014 08:58:49 GMT 19 | * Content-Type: application/json 20 | * Connection: keep-alive 21 | * Transfer-Encoding: chunked 22 | * ``` 23 | * 24 | * @param {String} headers Headers needing to be parsed 25 | * @returns {Object} Headers parsed into an object 26 | */ 27 | export default function parseHeaders(headers) { 28 | var parsed = {}; 29 | var key; 30 | var val; 31 | var i; 32 | 33 | if (!headers) { return parsed; } 34 | 35 | utils.forEach(headers.split('\n'), function parser(line) { 36 | i = line.indexOf(':'); 37 | key = utils.trim(line.substr(0, i)).toLowerCase(); 38 | val = utils.trim(line.substr(i + 1)); 39 | 40 | if (key) { 41 | if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { 42 | return; 43 | } 44 | if (key === 'set-cookie') { 45 | parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); 46 | } else { 47 | parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; 48 | } 49 | } 50 | }); 51 | 52 | return parsed; 53 | }; 54 | -------------------------------------------------------------------------------- /demo9/src/helpers/spread.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Syntactic sugar for invoking a function and expanding an array for arguments. 5 | * 6 | * Common use case would be to use `Function.prototype.apply`. 7 | * 8 | * ```js 9 | * function f(x, y, z) {} 10 | * var args = [1, 2, 3]; 11 | * f.apply(null, args); 12 | * ``` 13 | * 14 | * With `spread` this example can be re-written. 15 | * 16 | * ```js 17 | * spread(function(x, y, z) {})([1, 2, 3]); 18 | * ``` 19 | * 20 | * @param {Function} callback 21 | * @returns {Function} 22 | */ 23 | export default function spread(callback) { 24 | return function wrap(arr) { 25 | return callback.apply(null, arr); 26 | }; 27 | }; 28 | -------------------------------------------------------------------------------- /demo9/src/index.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | import axios from './axios' 4 | 5 | axios.get('/api/get') 6 | 7 | -------------------------------------------------------------------------------- /demo9/src/utils.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import bind from './helpers/bind'; 4 | 5 | /*global toString:true*/ 6 | 7 | // utils is a library of generic helper functions non-specific to axios 8 | 9 | var toString = Object.prototype.toString; 10 | 11 | /** 12 | * Determine if a value is an Array 13 | * 14 | * @param {Object} val The value to test 15 | * @returns {boolean} True if value is an Array, otherwise false 16 | */ 17 | function isArray(val) { 18 | return toString.call(val) === '[object Array]'; 19 | } 20 | 21 | /** 22 | * Determine if a value is undefined 23 | * 24 | * @param {Object} val The value to test 25 | * @returns {boolean} True if the value is undefined, otherwise false 26 | */ 27 | function isUndefined(val) { 28 | return typeof val === 'undefined'; 29 | } 30 | 31 | /** 32 | * Determine if a value is a Buffer 33 | * 34 | * @param {Object} val The value to test 35 | * @returns {boolean} True if value is a Buffer, otherwise false 36 | */ 37 | function isBuffer(val) { 38 | return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) 39 | && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); 40 | } 41 | 42 | /** 43 | * Determine if a value is an ArrayBuffer 44 | * 45 | * @param {Object} val The value to test 46 | * @returns {boolean} True if value is an ArrayBuffer, otherwise false 47 | */ 48 | function isArrayBuffer(val) { 49 | return toString.call(val) === '[object ArrayBuffer]'; 50 | } 51 | 52 | /** 53 | * Determine if a value is a FormData 54 | * 55 | * @param {Object} val The value to test 56 | * @returns {boolean} True if value is an FormData, otherwise false 57 | */ 58 | function isFormData(val) { 59 | return (typeof FormData !== 'undefined') && (val instanceof FormData); 60 | } 61 | 62 | /** 63 | * Determine if a value is a view on an ArrayBuffer 64 | * 65 | * @param {Object} val The value to test 66 | * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false 67 | */ 68 | function isArrayBufferView(val) { 69 | var result; 70 | if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { 71 | result = ArrayBuffer.isView(val); 72 | } else { 73 | result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); 74 | } 75 | return result; 76 | } 77 | 78 | /** 79 | * Determine if a value is a String 80 | * 81 | * @param {Object} val The value to test 82 | * @returns {boolean} True if value is a String, otherwise false 83 | */ 84 | function isString(val) { 85 | return typeof val === 'string'; 86 | } 87 | 88 | /** 89 | * Determine if a value is a Number 90 | * 91 | * @param {Object} val The value to test 92 | * @returns {boolean} True if value is a Number, otherwise false 93 | */ 94 | function isNumber(val) { 95 | return typeof val === 'number'; 96 | } 97 | 98 | /** 99 | * Determine if a value is an Object 100 | * 101 | * @param {Object} val The value to test 102 | * @returns {boolean} True if value is an Object, otherwise false 103 | */ 104 | function isObject(val) { 105 | return val !== null && typeof val === 'object'; 106 | } 107 | 108 | /** 109 | * Determine if a value is a plain Object 110 | * 111 | * @param {Object} val The value to test 112 | * @return {boolean} True if value is a plain Object, otherwise false 113 | */ 114 | function isPlainObject(val) { 115 | if (toString.call(val) !== '[object Object]') { 116 | return false; 117 | } 118 | 119 | var prototype = Object.getPrototypeOf(val); 120 | return prototype === null || prototype === Object.prototype; 121 | } 122 | 123 | /** 124 | * Determine if a value is a Date 125 | * 126 | * @param {Object} val The value to test 127 | * @returns {boolean} True if value is a Date, otherwise false 128 | */ 129 | function isDate(val) { 130 | return toString.call(val) === '[object Date]'; 131 | } 132 | 133 | /** 134 | * Determine if a value is a File 135 | * 136 | * @param {Object} val The value to test 137 | * @returns {boolean} True if value is a File, otherwise false 138 | */ 139 | function isFile(val) { 140 | return toString.call(val) === '[object File]'; 141 | } 142 | 143 | /** 144 | * Determine if a value is a Blob 145 | * 146 | * @param {Object} val The value to test 147 | * @returns {boolean} True if value is a Blob, otherwise false 148 | */ 149 | function isBlob(val) { 150 | return toString.call(val) === '[object Blob]'; 151 | } 152 | 153 | /** 154 | * Determine if a value is a Function 155 | * 156 | * @param {Object} val The value to test 157 | * @returns {boolean} True if value is a Function, otherwise false 158 | */ 159 | function isFunction(val) { 160 | return toString.call(val) === '[object Function]'; 161 | } 162 | 163 | /** 164 | * Determine if a value is a Stream 165 | * 166 | * @param {Object} val The value to test 167 | * @returns {boolean} True if value is a Stream, otherwise false 168 | */ 169 | function isStream(val) { 170 | return isObject(val) && isFunction(val.pipe); 171 | } 172 | 173 | /** 174 | * Determine if a value is a URLSearchParams object 175 | * 176 | * @param {Object} val The value to test 177 | * @returns {boolean} True if value is a URLSearchParams object, otherwise false 178 | */ 179 | function isURLSearchParams(val) { 180 | return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; 181 | } 182 | 183 | /** 184 | * Trim excess whitespace off the beginning and end of a string 185 | * 186 | * @param {String} str The String to trim 187 | * @returns {String} The String freed of excess whitespace 188 | */ 189 | function trim(str) { 190 | return str.replace(/^\s*/, '').replace(/\s*$/, ''); 191 | } 192 | 193 | /** 194 | * Determine if we're running in a standard browser environment 195 | * 196 | * This allows axios to run in a web worker, and react-native. 197 | * Both environments support XMLHttpRequest, but not fully standard globals. 198 | * 199 | * web workers: 200 | * typeof window -> undefined 201 | * typeof document -> undefined 202 | * 203 | * react-native: 204 | * navigator.product -> 'ReactNative' 205 | * nativescript 206 | * navigator.product -> 'NativeScript' or 'NS' 207 | */ 208 | function isStandardBrowserEnv() { 209 | if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || 210 | navigator.product === 'NativeScript' || 211 | navigator.product === 'NS')) { 212 | return false; 213 | } 214 | return ( 215 | typeof window !== 'undefined' && 216 | typeof document !== 'undefined' 217 | ); 218 | } 219 | 220 | /** 221 | * Iterate over an Array or an Object invoking a function for each item. 222 | * 223 | * If `obj` is an Array callback will be called passing 224 | * the value, index, and complete array for each item. 225 | * 226 | * If 'obj' is an Object callback will be called passing 227 | * the value, key, and complete object for each property. 228 | * 229 | * @param {Object|Array} obj The object to iterate 230 | * @param {Function} fn The callback to invoke for each item 231 | */ 232 | function forEach(obj, fn) { 233 | // Don't bother if no value provided 234 | if (obj === null || typeof obj === 'undefined') { 235 | return; 236 | } 237 | 238 | // Force an array if not already something iterable 239 | if (typeof obj !== 'object') { 240 | /*eslint no-param-reassign:0*/ 241 | obj = [obj]; 242 | } 243 | 244 | if (isArray(obj)) { 245 | // Iterate over array values 246 | for (var i = 0, l = obj.length; i < l; i++) { 247 | fn.call(null, obj[i], i, obj); 248 | } 249 | } else { 250 | // Iterate over object keys 251 | for (var key in obj) { 252 | if (Object.prototype.hasOwnProperty.call(obj, key)) { 253 | fn.call(null, obj[key], key, obj); 254 | } 255 | } 256 | } 257 | } 258 | 259 | /** 260 | * Accepts varargs expecting each argument to be an object, then 261 | * immutably merges the properties of each object and returns result. 262 | * 263 | * When multiple objects contain the same key the later object in 264 | * the arguments list will take precedence. 265 | * 266 | * Example: 267 | * 268 | * ```js 269 | * var result = merge({foo: 123}, {foo: 456}); 270 | * console.log(result.foo); // outputs 456 271 | * ``` 272 | * 273 | * @param {Object} obj1 Object to merge 274 | * @returns {Object} Result of all merge properties 275 | */ 276 | function merge(...result:any) { 277 | var result:any = {}; 278 | function assignValue(val, key) { 279 | if (isPlainObject(result[key]) && isPlainObject(val)) { 280 | result[key] = merge(result[key], val); 281 | } else if (isPlainObject(val)) { 282 | result[key] = merge({}, val); 283 | } else if (isArray(val)) { 284 | result[key] = val.slice(); 285 | } else { 286 | result[key] = val; 287 | } 288 | } 289 | 290 | for (var i = 0, l = arguments.length; i < l; i++) { 291 | forEach(arguments[i], assignValue); 292 | } 293 | return result; 294 | } 295 | 296 | /** 297 | * Extends object a by mutably adding to it the properties of object b. 298 | * 299 | * @param {Object} a The object to be extended 300 | * @param {Object} b The object to copy properties from 301 | * @param {Object} thisArg The object to bind function to 302 | * @return {Object} The resulting value of object a 303 | */ 304 | function extend(a, b, thisArg) { 305 | forEach(b, function assignValue(val, key) { 306 | if (thisArg && typeof val === 'function') { 307 | a[key] = bind(val, thisArg); 308 | } else { 309 | a[key] = val; 310 | } 311 | }); 312 | return a; 313 | } 314 | 315 | /** 316 | * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) 317 | * 318 | * @param {string} content with BOM 319 | * @return {string} content value without BOM 320 | */ 321 | function stripBOM(content) { 322 | if (content.charCodeAt(0) === 0xFEFF) { 323 | content = content.slice(1); 324 | } 325 | return content; 326 | } 327 | 328 | export default { 329 | isArray, 330 | isArrayBuffer, 331 | isBuffer, 332 | isFormData, 333 | isArrayBufferView, 334 | isString, 335 | isNumber, 336 | isObject, 337 | isPlainObject, 338 | isUndefined, 339 | isDate, 340 | isFile, 341 | isBlob, 342 | isFunction, 343 | isStream, 344 | isURLSearchParams, 345 | isStandardBrowserEnv, 346 | forEach, 347 | merge, 348 | extend, 349 | trim, 350 | stripBOM 351 | }; 352 | -------------------------------------------------------------------------------- /demo9/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "sourceMap": true, 4 | "moduleResolution": "Node", 5 | "target": "ES2016", 6 | }, 7 | "lib": ["dom", "scripthost", "es5", "es2015.promise", "es2015.core"] 8 | } -------------------------------------------------------------------------------- /demo9/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | //没有优化的config 3 | //Time: 2819ms //第一次 4 | //Time: 2488ms //第二次 5 | module.exports = { 6 | mode: "production", 7 | entry: "./src/index.ts", 8 | output: { 9 | path: path.resolve(__dirname, "dist"), 10 | filename: "index.js", 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | test: /\.js/, 16 | exclude: /node_modules/, 17 | use: [ 18 | { 19 | loader: "babel-loader", 20 | }, 21 | { 22 | loader: "eslint-loader", 23 | }, 24 | ], 25 | }, 26 | { 27 | test: /\.tsx?$/, 28 | exclude: /node_modules/, 29 | use: [ 30 | { 31 | loader: "babel-loader", 32 | }, 33 | { 34 | loader: "eslint-loader", 35 | }, 36 | { 37 | loader: "ts-loader", 38 | }, 39 | ], 40 | }, 41 | ], 42 | }, 43 | resolve: { 44 | extensions: [".js", ".ts", ".json"], 45 | modules: [ 46 | path.resolve(__dirname, "src"), 47 | path.resolve(__dirname, "node_modules"), 48 | "node_modules", 49 | ], 50 | }, 51 | }; 52 | -------------------------------------------------------------------------------- /demo9/webpack.config.optimize.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | //优化后的config 3 | //Time: 2455ms 第一次 4 | //Time: 2337ms 第二次 5 | module.exports = { 6 | mode: "production", 7 | entry: "./src/index.ts", 8 | output: { 9 | path: path.resolve(__dirname, "dist"), 10 | filename: "index.js", 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | test: /\.js/, 16 | include: path.resolve(__dirname, "src"), 17 | use: [ 18 | { 19 | loader: "babel-loader", 20 | }, 21 | { 22 | loader: "eslint-loader", 23 | }, 24 | ], 25 | }, 26 | { 27 | test: /\.tsx?$/, 28 | include: path.resolve(__dirname, "src"), 29 | use: [ 30 | { 31 | loader: "babel-loader", 32 | }, 33 | { 34 | loader: "eslint-loader", 35 | }, 36 | { 37 | loader: "ts-loader", 38 | }, 39 | ], 40 | }, 41 | ], 42 | }, 43 | resolve: { 44 | mainFields: ["main"], 45 | extensions: [".ts", ".js"], 46 | alias: { 47 | vue: path.resolve( 48 | __dirname, 49 | "./node_modules/vue/dist/vue.runtime.common.js" 50 | ), 51 | }, 52 | //解析模块时应该搜索的目录 53 | modules: [ 54 | path.resolve(__dirname, "src"), 55 | path.resolve(__dirname, "node_modules"), 56 | "node_modules", 57 | ], 58 | }, 59 | }; 60 | --------------------------------------------------------------------------------