diff --git a/11-前端模块化开发/04-webpack_Loader使用/dist/result.js b/11-前端模块化开发/04-webpack_Loader使用/dist/result.js index b742930..f9b457d 100644 --- a/11-前端模块化开发/04-webpack_Loader使用/dist/result.js +++ b/11-前端模块化开发/04-webpack_Loader使用/dist/result.js @@ -73,7 +73,7 @@ Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); console.log(__WEBPACK_IMPORTED_MODULE_0__js_mathTools_js__["a" /* add */](33,44)); console.log(__WEBPACK_IMPORTED_MODULE_0__js_mathTools_js__["b" /* remove */](323,111)); -__webpack_require__(2) +__webpack_require__(2); /***/ }), /* 1 */ @@ -94,17 +94,40 @@ function remove(num1,num2){ /* 2 */ /***/ (function(module, exports, __webpack_require__) { +var content = __webpack_require__(3); +content = content.__esModule ? content.default : content; + +if (typeof content === 'string') { + content = [[module.i, content, '']]; +} + +var options = {} + +options.insert = "head"; +options.singleton = false; + +var update = __webpack_require__(5)(content, options); + +if (content.locals) { + module.exports = content.locals; +} + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + // Imports -var ___CSS_LOADER_API_IMPORT___ = __webpack_require__(3); +var ___CSS_LOADER_API_IMPORT___ = __webpack_require__(4); exports = ___CSS_LOADER_API_IMPORT___(false); // Module -exports.push([module.i, "body{\r\n background-color: antiquewhite;\r\n}\r\n", ""]); +exports.push([module.i, "body{\r\n background-color: #f00;\r\n}\r\n", ""]); // Exports module.exports = exports; /***/ }), -/* 3 */ +/* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -203,5 +226,293 @@ function toComment(sourceMap) { return "/*# ".concat(data, " */"); } +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var stylesInDom = {}; + +var isOldIE = function isOldIE() { + var memo; + return function memorize() { + if (typeof memo === 'undefined') { + // Test for IE <= 9 as proposed by Browserhacks + // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 + // Tests for existence of standard globals is to allow style-loader + // to operate correctly into non-standard environments + // @see https://github.com/webpack-contrib/style-loader/issues/177 + memo = Boolean(window && document && document.all && !window.atob); + } + + return memo; + }; +}(); + +var getTarget = function getTarget() { + var memo = {}; + return function memorize(target) { + if (typeof memo[target] === 'undefined') { + var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself + + if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) { + try { + // This will throw an exception if access to iframe is blocked + // due to cross-origin restrictions + styleTarget = styleTarget.contentDocument.head; + } catch (e) { + // istanbul ignore next + styleTarget = null; + } + } + + memo[target] = styleTarget; + } + + return memo[target]; + }; +}(); + +function listToStyles(list, options) { + var styles = []; + var newStyles = {}; + + for (var i = 0; i < list.length; i++) { + var item = list[i]; + var id = options.base ? item[0] + options.base : item[0]; + var css = item[1]; + var media = item[2]; + var sourceMap = item[3]; + var part = { + css: css, + media: media, + sourceMap: sourceMap + }; + + if (!newStyles[id]) { + styles.push(newStyles[id] = { + id: id, + parts: [part] + }); + } else { + newStyles[id].parts.push(part); + } + } + + return styles; +} + +function addStylesToDom(styles, options) { + for (var i = 0; i < styles.length; i++) { + var item = styles[i]; + var domStyle = stylesInDom[item.id]; + var j = 0; + + if (domStyle) { + domStyle.refs++; + + for (; j < domStyle.parts.length; j++) { + domStyle.parts[j](item.parts[j]); + } + + for (; j < item.parts.length; j++) { + domStyle.parts.push(addStyle(item.parts[j], options)); + } + } else { + var parts = []; + + for (; j < item.parts.length; j++) { + parts.push(addStyle(item.parts[j], options)); + } + + stylesInDom[item.id] = { + id: item.id, + refs: 1, + parts: parts + }; + } + } +} + +function insertStyleElement(options) { + var style = document.createElement('style'); + + if (typeof options.attributes.nonce === 'undefined') { + var nonce = true ? __webpack_require__.nc : null; + + if (nonce) { + options.attributes.nonce = nonce; + } + } + + Object.keys(options.attributes).forEach(function (key) { + style.setAttribute(key, options.attributes[key]); + }); + + if (typeof options.insert === 'function') { + options.insert(style); + } else { + var target = getTarget(options.insert || 'head'); + + if (!target) { + throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid."); + } + + target.appendChild(style); + } + + return style; +} + +function removeStyleElement(style) { + // istanbul ignore if + if (style.parentNode === null) { + return false; + } + + style.parentNode.removeChild(style); +} +/* istanbul ignore next */ + + +var replaceText = function replaceText() { + var textStore = []; + return function replace(index, replacement) { + textStore[index] = replacement; + return textStore.filter(Boolean).join('\n'); + }; +}(); + +function applyToSingletonTag(style, index, remove, obj) { + var css = remove ? '' : obj.css; // For old IE + + /* istanbul ignore if */ + + if (style.styleSheet) { + style.styleSheet.cssText = replaceText(index, css); + } else { + var cssNode = document.createTextNode(css); + var childNodes = style.childNodes; + + if (childNodes[index]) { + style.removeChild(childNodes[index]); + } + + if (childNodes.length) { + style.insertBefore(cssNode, childNodes[index]); + } else { + style.appendChild(cssNode); + } + } +} + +function applyToTag(style, options, obj) { + var css = obj.css; + var media = obj.media; + var sourceMap = obj.sourceMap; + + if (media) { + style.setAttribute('media', media); + } + + if (sourceMap && btoa) { + css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */"); + } // For old IE + + /* istanbul ignore if */ + + + if (style.styleSheet) { + style.styleSheet.cssText = css; + } else { + while (style.firstChild) { + style.removeChild(style.firstChild); + } + + style.appendChild(document.createTextNode(css)); + } +} + +var singleton = null; +var singletonCounter = 0; + +function addStyle(obj, options) { + var style; + var update; + var remove; + + if (options.singleton) { + var styleIndex = singletonCounter++; + style = singleton || (singleton = insertStyleElement(options)); + update = applyToSingletonTag.bind(null, style, styleIndex, false); + remove = applyToSingletonTag.bind(null, style, styleIndex, true); + } else { + style = insertStyleElement(options); + update = applyToTag.bind(null, style, options); + + remove = function remove() { + removeStyleElement(style); + }; + } + + update(obj); + return function updateStyle(newObj) { + if (newObj) { + if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) { + return; + } + + update(obj = newObj); + } else { + remove(); + } + }; +} + +module.exports = function (list, options) { + options = options || {}; + options.attributes = typeof options.attributes === 'object' ? options.attributes : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of `. It is **default** behaviour. + +**component.js** + +```js +import './styles.css'; +``` + +Example with c Locals (CSS Modules): + +**component-with-css-modules.js** + +```js +import styles from './styles.css'; + +const divElement = document.createElement('div'); +divElement.className = styles['my-class']; +``` + +All locals (class names) stored in imported object. + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + use: [ + // The `injectType` option can be avoided because it is default behaviour + { loader: 'style-loader', options: { injectType: 'styleTag' } }, + 'css-loader', + ], + }, + ], + }, +}; +``` + +The loader inject styles like: + +```html + + +``` + +#### `singletonStyleTag` + +Automatically injects styles into the DOM using one ``. + +> ⚠ Source maps do not work. + +**component.js** + +```js +import './styles.css'; +``` + +**component-with-css-modules.js** + +```js +import styles from './styles.css'; + +const divElement = document.createElement('div'); +divElement.className = styles['my-class']; +``` + +All locals (class names) stored in imported object. + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + use: [ + { + loader: 'style-loader', + options: { injectType: 'singletonStyleTag' }, + }, + 'css-loader', + ], + }, + ], + }, +}; +``` + +The loader inject styles like: + +```html + +``` + +#### `lazyStyleTag` + +Injects styles into the DOM using multiple `` on demand. +We recommend following `.lazy.css` naming convention for lazy styles and the `.css` for basic `style-loader` usage (similar to other file types, i.e. `.lazy.less` and `.less`). +When you `lazyStyleTag` value the `style-loader` injects the styles lazily making them useable on-demand via `style.use()` / `style.unuse()`. + +> ⚠️ Behavior is undefined when `unuse` is called more often than `use`. Don't do that. + +**component.js** + +```js +import styles from './styles.lazy.css'; + +styles.use(); +// For removing styles you can use +// styles.unuse(); +``` + +**component-with-css-modules.js** + +```js +import styles from './styles.lazy.css'; + +styles.use(); + +const divElement = document.createElement('div'); +divElement.className = styles.locals['my-class']; +``` + +All locals (class names) stored in `locals` property of imported object. + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + exclude: /\.lazy\.css$/i, + use: ['style-loader', 'css-loader'], + }, + { + test: /\.lazy\.css$/i, + use: [ + { loader: 'style-loader', options: { injectType: 'lazyStyleTag' } }, + 'css-loader', + ], + }, + ], + }, +}; +``` + +The loader inject styles like: + +```html + + +``` + +#### `lazySingletonStyleTag` + +Injects styles into the DOM using one `` on demand. +We recommend following `.lazy.css` naming convention for lazy styles and the `.css` for basic `style-loader` usage (similar to other file types, i.e. `.lazy.less` and `.less`). +When you `lazySingletonStyleTag` value the `style-loader` injects the styles lazily making them useable on-demand via `style.use()` / `style.unuse()`. + +> ⚠️ Source maps do not work. + +> ⚠️ Behavior is undefined when `unuse` is called more often than `use`. Don't do that. + +**component.js** + +```js +import styles from './styles.css'; + +styles.use(); +// For removing styles you can use +// styles.unuse(); +``` + +**component-with-css-modules.js** + +```js +import styles from './styles.lazy.css'; + +styles.use(); + +const divElement = document.createElement('div'); +divElement.className = styles.locals['my-class']; +``` + +All locals (class names) stored in `locals` property of imported object. + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + exclude: /\.lazy\.css$/i, + use: ['style-loader', 'css-loader'], + }, + { + test: /\.lazy\.css$/i, + use: [ + { loader: 'style-loader', options: { injectType: 'lazyStyleTag' } }, + 'css-loader', + ], + }, + ], + }, +}; +``` + +The loader generate this: + +```html + +``` + +#### `linkTag` + +Injects styles into the DOM using multiple `` . + +> ℹ️ The loader will dynamically insert the `` tag at runtime via JavaScript. You should use [MiniCssExtractPlugin](https://webpack.js.org/plugins/mini-css-extract-plugin/) if you want to include a static ``. + +```js +import './styles.css'; +import './other-styles.css'; +``` + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.link\.css$/i, + use: [ + { loader: 'style-loader', options: { injectType: 'linkTag' } }, + { loader: 'file-loader' }, + ], + }, + ], + }, +}; +``` + +The loader generate this: + +```html + + +``` + +### `attributes` + +Type: `Object` +Default: `{}` + +If defined, the `style-loader` will attach given attributes with their values on ` +``` + +### `insert` + +Type: `String|Function` +Default: `head` + +By default, the `style-loader` appends ` +``` + +#### `__webpack_nonce__` + +**create-nonce.js** + +```js +__webpack_nonce__ = '12345678'; +``` + +**component.js** + +```js +import './create-nonce.js'; +import './style.css'; +``` + +Alternative example for `require`: + +**component.js** + +```js +__webpack_nonce__ = '12345678'; + +require('./style.css'); +``` + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + use: ['style-loader', 'css-loader'], + }, + ], + }, +}; +``` + +The loader generate: + +```html + +``` + +#### Insert styles at top + +Inserts styles at top of `head` tag. + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + use: [ + { + loader: 'style-loader', + options: { + insert: function insertAtTop(element) { + var parent = document.querySelector('head'); + var lastInsertedElement = + window._lastElementInsertedByStyleLoader; + + if (!lastInsertedElement) { + parent.insertBefore(element, parent.firstChild); + } else if (lastInsertedElement.nextSibling) { + parent.insertBefore(element, lastInsertedElement.nextSibling); + } else { + parent.appendChild(element); + } + + window._lastElementInsertedByStyleLoader = element; + }, + }, + }, + 'css-loader', + ], + }, + ], + }, +}; +``` + +#### Insert styles before target element + +Inserts styles before `#id` element. + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + use: [ + { + loader: 'style-loader', + options: { + insert: function insertBeforeAt(element) { + const parent = document.querySelector('head'); + const target = document.querySelector('#id'); + + const lastInsertedElement = + window._lastElementInsertedByStyleLoader; + + if (!lastInsertedElement) { + parent.insertBefore(element, target); + } else if (lastInsertedElement.nextSibling) { + parent.insertBefore(element, lastInsertedElement.nextSibling); + } else { + parent.appendChild(element); + } + + window._lastElementInsertedByStyleLoader = element; + }, + }, + }, + 'css-loader', + ], + }, + ], + }, +}; +``` + +## Contributing + +Please take a moment to read our contributing guidelines if you haven't yet done so. + +[CONTRIBUTING](./.github/CONTRIBUTING.md) + +## License + +[MIT](./LICENSE) + +[npm]: https://img.shields.io/npm/v/style-loader.svg +[npm-url]: https://npmjs.com/package/style-loader +[node]: https://img.shields.io/node/v/style-loader.svg +[node-url]: https://nodejs.org +[deps]: https://david-dm.org/webpack-contrib/style-loader.svg +[deps-url]: https://david-dm.org/webpack-contrib/style-loader +[tests]: https://dev.azure.com/webpack-contrib/style-loader/_apis/build/status/webpack-contrib.style-loader?branchName=master +[tests-url]: https://dev.azure.com/webpack-contrib/style-loader/_build/latest?definitionId=18&branchName=master +[cover]: https://codecov.io/gh/webpack-contrib/style-loader/branch/master/graph/badge.svg +[cover-url]: https://codecov.io/gh/webpack-contrib/style-loader +[chat]: https://badges.gitter.im/webpack/webpack.svg +[chat-url]: https://gitter.im/webpack/webpack +[size]: https://packagephobia.now.sh/badge?p=style-loader +[size-url]: https://packagephobia.now.sh/result?p=style-loader diff --git a/11-前端模块化开发/04-webpack_Loader使用/node_modules/style-loader/dist/index.js b/11-前端模块化开发/04-webpack_Loader使用/node_modules/style-loader/dist/index.js new file mode 100644 index 0000000..5034adb --- /dev/null +++ b/11-前端模块化开发/04-webpack_Loader使用/node_modules/style-loader/dist/index.js @@ -0,0 +1,165 @@ +"use strict"; + +var _path = _interopRequireDefault(require("path")); + +var _loaderUtils = _interopRequireDefault(require("loader-utils")); + +var _schemaUtils = _interopRequireDefault(require("schema-utils")); + +var _options = _interopRequireDefault(require("./options.json")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = () => {}; + +module.exports.pitch = function loader(request) { + const options = _loaderUtils.default.getOptions(this) || {}; + (0, _schemaUtils.default)(_options.default, options, { + name: 'Style Loader', + baseDataPath: 'options' + }); + const insert = typeof options.insert === 'undefined' ? '"head"' : typeof options.insert === 'string' ? JSON.stringify(options.insert) : options.insert.toString(); + const injectType = options.injectType || 'styleTag'; + + switch (injectType) { + case 'linkTag': + { + const hmrCode = this.hot ? ` +if (module.hot) { + module.hot.accept( + ${_loaderUtils.default.stringifyRequest(this, `!!${request}`)}, + function() { + var newContent = require(${_loaderUtils.default.stringifyRequest(this, `!!${request}`)}); + newContent = newContent.__esModule ? newContent.default : newContent; + + update(newContent); + } + ); + + module.hot.dispose(function() { + update(); + }); +}` : ''; + return `var options = ${JSON.stringify(options)}; + +options.insert = ${insert}; + +var content = require(${_loaderUtils.default.stringifyRequest(this, `!!${request}`)}); +content = content.__esModule ? content.default : content; + +var update = require(${_loaderUtils.default.stringifyRequest(this, `!${_path.default.join(__dirname, 'runtime/injectStylesIntoLinkTag.js')}`)})(content, options); +${hmrCode}`; + } + + case 'lazyStyleTag': + case 'lazySingletonStyleTag': + { + const isSingleton = injectType === 'lazySingletonStyleTag'; + const hmrCode = this.hot ? ` +if (module.hot) { + var lastRefs = module.hot.data && module.hot.data.refs || 0; + + if (lastRefs) { + exports.use(); + + if (!content.locals) { + refs = lastRefs; + } + } + + if (!content.locals) { + module.hot.accept(); + } + + module.hot.dispose(function(data) { + data.refs = content.locals ? 0 : refs; + + if (dispose) { + dispose(); + } + }); +}` : ''; + return `var refs = 0; +var dispose; +var content = require(${_loaderUtils.default.stringifyRequest(this, `!!${request}`)}); +content = content.__esModule ? content.default : content; + +var options = ${JSON.stringify(options)}; + +options.insert = ${insert}; +options.singleton = ${isSingleton}; + +if (typeof content === 'string') { + content = [[module.id, content, '']]; +} + +if (content.locals) { + exports.locals = content.locals; +} + +exports.use = function() { + if (!(refs++)) { + dispose = require(${_loaderUtils.default.stringifyRequest(this, `!${_path.default.join(__dirname, 'runtime/injectStylesIntoStyleTag.js')}`)})(content, options); + } + + return exports; +}; + +exports.unuse = function() { + if (refs > 0 && !--refs) { + dispose(); + dispose = null; + } +}; +${hmrCode} +`; + } + + case 'styleTag': + case 'singletonStyleTag': + default: + { + const isSingleton = injectType === 'singletonStyleTag'; + const hmrCode = this.hot ? ` +if (module.hot) { + if (!content.locals) { + module.hot.accept( + ${_loaderUtils.default.stringifyRequest(this, `!!${request}`)}, + function () { + var newContent = require(${_loaderUtils.default.stringifyRequest(this, `!!${request}`)}); + newContent = newContent.__esModule ? newContent.default : newContent; + + if (typeof newContent === 'string') { + newContent = [[module.id, newContent, '']]; + } + + update(newContent); + } + ) + } + + module.hot.dispose(function() { + update(); + }); +}` : ''; + return `var content = require(${_loaderUtils.default.stringifyRequest(this, `!!${request}`)}); +content = content.__esModule ? content.default : content; + +if (typeof content === 'string') { + content = [[module.id, content, '']]; +} + +var options = ${JSON.stringify(options)} + +options.insert = ${insert}; +options.singleton = ${isSingleton}; + +var update = require(${_loaderUtils.default.stringifyRequest(this, `!${_path.default.join(__dirname, 'runtime/injectStylesIntoStyleTag.js')}`)})(content, options); + +if (content.locals) { + module.exports = content.locals; +} +${hmrCode}`; + } + } +}; \ No newline at end of file diff --git a/11-前端模块化开发/04-webpack_Loader使用/node_modules/style-loader/dist/options.json b/11-前端模块化开发/04-webpack_Loader使用/node_modules/style-loader/dist/options.json new file mode 100644 index 0000000..c68ad61 --- /dev/null +++ b/11-前端模块化开发/04-webpack_Loader使用/node_modules/style-loader/dist/options.json @@ -0,0 +1,35 @@ +{ + "type": "object", + "properties": { + "injectType": { + "description": "Allows to setup how styles will be injected into DOM (https://github.com/webpack-contrib/style-loader#injecttype).", + "enum": [ + "styleTag", + "singletonStyleTag", + "lazyStyleTag", + "lazySingletonStyleTag", + "linkTag" + ] + }, + "attributes": { + "description": "Adds custom attributes to tag (https://github.com/webpack-contrib/style-loader#attributes).", + "type": "object" + }, + "insert": { + "description": "Inserts `