Article content output source: pull hook big front-end high salary training camp

– Load the resource module

- WebPack is not just a JS module packaging tool, it can be said to be a modular packaging tool for the entire front-end project or front-end engineering - that is, We can also use webpack to import any type of file we have in the front-end project - try to pack our project CSS file with Webpack - add file: main.css - body {margin: 0 auto, padding: 0 20px, max-width: 800px, background: #f4f8fb,Copy the code

}

- const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.css // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, no relative path path: path.join(__dirname,’output’)}}

- Package - YARN webpack - Error: Module parse failed: Unexpected Token - Cause: Webpack only handles JS files by default. In other words, WebPack will parse all the files encountered during the packaging process as JS files, while it is dealing with CSS files, which contain CSS code, so it will naturally report errors. Webpack also gives a prompt after the error. - Corresponding tips: you may need an appropriate loader to handle this file type, Currently no loaders are configured to process this file. - 解决 - install CSS loader - yarn add css-loader --dev - - const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.css // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’)}, module: Rules: [// Each rule object needs to be configured with two properties: test and use {// Regular expressions that match the file path test we encountered during the packaging process: /.css$/, // Use: ‘css-loader’}]}

- Pack - YARN webpack - OK~ -serve. - Style does not take effect - Cause: Install style loader - yarn add style-loader --dev - -const path = require ('path') -webpack.config.jsCopy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.css // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’)}, module: Rules: [// Each rule object needs to be configured with two properties: test and use {// Regular expressions that match the file path test we encountered during the packaging process: Use: [‘style-loader’, ‘css-loader’]}]}} use: [‘style-loader’, ‘css-loader’]}}

- YARN webpack -ok ~ -serve. -ok ~ -loader is the core of webpack to realize the front-end modularization. - Use loader to load any type of resourcesCopy the code

– Import a resource module

- Through the above exploration, we can really use CSS files as a packaging entry point. JS - const path = require - main.js - const path = require - main.js - const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’)}, module: Rules: [// Each rule object needs to be configured with two properties: test and use {// Regular expressions that match the file path test we encountered during the packaging process: Use: [‘style-loader’, ‘css-loader’]}]}} use: [‘style-loader’, ‘css-loader’]}}

-import createHeading from './heading. Js'Copy the code

import ‘./main.css’ const heading= createHeading()

document.body.append(heading)

- package - yarn webpack -ok ~ - Start the application: serve. -ok: the style works normally. Style file heading. CSS -. Heading {padding: 20px, background: #343a40, color: # FFFCopy the code

}

- Import heading. CSS file in heading. Js - import './heading. CSS 'Copy the code

Export default () ⥤ {const element = document.createElement(‘h2’)

element.textContent='hello world' element.classList.add('heading') element.addEventListener('click', () ⥤ {alert('Hello webpack')}) return elementCopy the code

} – packaged

- yarn webpack -ok ~ -Start the application: serve. -ok: the style works normally. - Webpack suggests that we load CSS in JS - reason - actually Webpack doesn't just suggest that we introduce CSS in JS - it suggests that we introduce any resource files that you need for your current code in the process of writing it. - Because what really needs resources is not the application but the code you are writing at the moment - Webpack philosophy - dynamically importing resources according to the needs of the code - it is the code in your JS that needs resources to work properly - the JS code itself is responsible for completing the page application, and in a larger sense, JS drives the whole front-end application. - A series of resource files such as styles, fonts or images may be required to implement business functions. If this dependency is established, it is logical that JS does need these resources. Second, to ensure that online resources are not missing, are necessary. - Thinking outside the box 🤔 - Actually learning a new thing does not mean that you can improve by learning all its uses, because these things can be documented by anyone. - The point is: the idea of something new is the breakthrough. - Being able to figure out why these new things are designed the way they are is basically the beginning.Copy the code

– Resource loader :loader

- There are so many resource loaders available in the WebPack community - basically every reasonable need you can think of has a loader - try some very representative loaders - file resource loaders - most loaders are similar to CSS-Loaders, Are all about resource module conversion into JS code implementation way to work. - But there are some resource files we often use, such as images and fonts in our project, so these files cannot be represented by THE WAY of JS. For this kind of resources, we need to use file resource loader, also known as file-loader. - add an image icon. PNG to the SRC directory - we assume that this image is the resource we need to implement a feature. - According to Webpack idea, we should import the image by import where we use the resource and let WebPack handle the loading of our resource. -import createHeading from './heading. Js'Copy the code

import ‘./main.css’ import icon from ‘./icon.lng’ const heading= createHeading()

document.body.append(heading)

const img = new Image() omg.src = icon

document.body.append(img)

- Install file-loader-yarn add file-loader -- dev-package-yarn webpack -ok ~ - Start the application: serve. -ok: The style can work properly. - const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’)}, module: Rules: [// Each rule object needs to be configured with two properties: test and use {// Regular expressions that match the file path test we encountered during the packaging process: /.css/, // Specifies the loader to be used by the file matched by test. If multiple Loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: PNG /, // Specifies the loader to be used for the file matched by test. If multiple loaders are configured, run them from the back to the front. Use: ‘file-loader’}]}} – Package

-yarn webpack -ok ~ -start the application: serve. -ok: There will be an additional image in the dist directory - this image is the one we imported in the code, but the file name has been changed. File name changes, however, will be covered later. - How is this image represented in bundle.js? - Look at the last module - expanding this module, we find that it is also very simple, it just exported the name of the file we just generated - and then back to our entry module, the first module, which uses the exported file path directly, there is nothing complicated about it. - Problem: the image is not loading properly at this point - don't panic here, the normal reaction is to open the developer tools and have a look. - According to the display of the development tool, we found that it directly loaded the image file in our root directory, but our website root directory does not have this file. This file should be in the dist directory at the root of the site. - The problem is that when I demonstrate here, our index.html is not generated in the dist directory, but in the project root directory, so I use the project root directory as the root of the site, and WebPack assumes by default that all of its packaged results will be placed in the site root directory. So that's the problem. - const path = require ('path') - configuration file tells Webpack where your packed file ends up on our siteCopy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’) // the default value is an empty string: represents the root directory of the website. PublicPath: ‘dist/’,}, module: {// Configuration of load rules for other resource modules rules: [// Each rule object requires two properties: Test and use {// Regular expressions are used to match the file path encountered in the packaging process test: /.css/, // Are used to specify the loader used by the file matched by test. When multiple loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: PNG /, // Specifies the loader used by the file matched by test. If multiple loaders are configured, the loader is executed from the back to the front. Use: ‘file-loader’}]}}

- package - yarn webpack - OK~ - Start the application: serve. - OK: the service works normally. - Take a closer look at the bundle.js file - find the module where the image resides, so here the file name is preceded by a variable p, which is provided by the code inside webpack. The value of this variable is the publicPath we just set. - This also explains why the final slash of publicPath can't be omitted - serve. - refresh the page - load the image successfully - Summarize how the file loader works - Webpack encounters our resource file when packaging - and then according to the configuration in the configuration file, The corresponding file loader is matched, and the file loader starts working. - First copy our imported file to the output directory, and then copy our file to the output directory as the return value of the current module. This resource is published for our application. We can also get the access path of this file through the module's export member. -Data URLS and URl-loader - In addition to file-loader, which processes file resources by copying physical files, there is another way to represent files through Data URLS. Data URL is a special URL protocol that can be used to directly represent a file. Our traditional URL requires that there is a corresponding file on the server. It then requests that address to get the corresponding file on the server. - Data URL is a way to represent the contents of the file directly with the current URL. -data :[<mediatype>][;base64],<data> protocol, mediatype and encoding, data-instance-data :text/ HTML; Charset =UTF-8,<h1> HTML content</h1> The base64 encoded result is a string to represent the file content - instance-data :image/ PNG; base64,iVBOw0KGoAAAANSUhE... SuQmCC - represents a PNG file - base64 is usually longer, But the browser can also parse the file - the text in the URL already contains the content of the file - so it doesn't send any HTTP requests when using this URL - we can do this when webpack packs static resources - with the Data URL, Url-loader-yarn add url-loader --dev -- modify the configuration file webpack.config.js  - const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’) // the default value is an empty string: represents the root directory of the website. PublicPath: ‘dist/’,}, module: {// Configuration of load rules for other resource modules rules: [// Each rule object requires two properties: Test and use {// Regular expressions are used to match the file path encountered in the packaging process test: /.css/, // Are used to specify the loader used by the file matched by test. When multiple loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: /.png/, // Specifies the loader used by the file matched by test. If multiple loaders are configured, the loader is executed from the back to the front. Use: ‘url-loader’}]}}

- bundle - yarn webpack - OK~ - now no separate image file is generated in dist directory - look at bundle.js - also locate the last module in the file - now this module is not exported as a file path, It is a complete Data URL - since this Data URL already contains the contents of the file - so we do not need a separate physical file - copy Data URL - browser access - OK~ -serve. -ok ~ -data The URL approach works well for the smaller resources in our project - because if they are too large, our packaging results will be very large. This results in our speed - best practice - use Data URLs for small files, reduce the number of requests - use URL-loader - store large files separately, - const path = require ('path') webpack.config.js - const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’) // the default value is an empty string: represents the root directory of the website. PublicPath: ‘dist/’,}, module: {// Configuration of load rules for other resource modules rules: [// Each rule object requires two properties: Test and use {// Regular expressions are used to match the file path encountered in the packaging process test: /.css/, // Are used to specify the loader used by the file matched by test. When multiple loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: Use: {loader: ‘url-loader’, options: {limit: 10 * 1024, // 10KB, url-loader will only convert files smaller than 10KB to Data URL form, and file larger than this size will still be sent to file-loader to complete loading}}}]}}

- Package - YARN webpack - OK~ - Files larger than 10KB are stored separately - files smaller than 10KB are converted into Data URLs embedded in the code - special note - to implement this best practice, you must install file-loader. Although it is not configured in the configuration file webpack.config.js. - Because the url-loader implementation uses file-loader internally - the resource loader in WebPack is a bit like the production shop in our daily life - it is used to process and process the resource files we encounter during the packaging process - in addition to the loader described above, There are many other loaders in the community - we will use most of the common loaders in the future - but before that, to better understand them, They can be roughly divided into three categories - three types of loader - compiler conversion class loaders - this type of loader will load the resource module into JS code - for example - CSS -loader - CSS code to work in JS CSS module - file operation type loaders - Usually file operation type loaders will copy the loaded resource module to the output directory - and export the access path of this file- such as -file-loader - is very typical file operation type loaders - code quality check loader - This type of loader does not modify production code - for example, es-loader. This type of loader does not modify production code - for example, es-loaderCopy the code

– handle ES2015

- Since WebPack handles import and export in code by default, one would expect WebPack to automatically compile ES6 code. - No, webpack is just a package of modules. - That's why Webpack does some translation of import and export in the code - in addition, Webpack does not convert other ES6 features in the code - try - package - yarn webpack - OK~ - find bundle.js - fold the code to find the module - New ES6 features such as const and arrow functions used in modules are not handled extra by WebPack - if we need WebPack to handle the transformation of other new ES6 features during the packaging process - we need to configure an extra compiled Loader for JS files - For example, the most common one is babel-loader - install dependency -yarn add babel-loader @babel/ core@babel /preset-env --dev - Modify the configuration file webpack.config.js - -const path = require ('path') -const path = require ('path') -const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’) // the default value is an empty string: represents the root directory of the website. PublicPath: ‘dist/’,}, module: {// Configuration of load rules for other resource modules rules: [// Each rule object requires two properties: Test and use {// Regular expressions are used to match the file path encountered during the packaging process test: /.js/, and // Are used to specify the loader to be used for the file matched by test. When multiple loaders are configured, use: ‘babel-loader’}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test that we encountered during the packaging process: /.css/, // Specifies the loader to be used by the file matched by test. If multiple Loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: PNG $/, // Specifies the loader used by the file matched by test. If multiple loaders are configured, run them from the back to the front. Use: ‘url-loader’}]}} -yarn webpack

- OK~ - go back to bundle.js - Collapse code to find module - Find new ES6 features still not converted - Not converted cause: Const path = require ('path') const path = require ('path') const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’) // the default value is an empty string: represents the root directory of the website. PublicPath: ‘dist/’,}, module: {// Configuration of load rules for other resource modules rules: [// Each rule object requires two properties: Test and use {// Regular expressions are used to match the file path encountered during the packaging process test: /.js/, and // Are used to specify the loader to be used for the file matched by test. When multiple loaders are configured, use: {loader: ‘babel-loader’, options: {presets: [‘@babel/preset-env’]},}}, // Two properties need to be configured for each rule object: Test and use {// Regular expressions are used to match the file path encountered in the packaging process test: /.css/, // Are used to specify the loader used by the file matched by test. When multiple loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: PNG $/, // Specifies the loader to be used for the file matched by test. If multiple loaders are configured, run them from the back to the front. Use: ‘url-loader’}]}} – Repack: YARN webpack

-ok: Find the generated code again. Now the code for the new ES2015 feature has been successfully converted. - Summary - Webpack is just a packaging tool and will not deal with the new ES6+ feature code - the loader can be used to compile the transformation codeCopy the code

– Module loading mode

-Import createHeading from './heading. Js' -import createHeading from './heading.Copy the code

import ‘./main.css’ const heading= createHeading()

document.body.append(heading)

- const createHeading = require('./heading. Js ')Copy the code

require( ‘./main.css’) const heading= createHeading()

Document.body. append(heading) – if an ES Modules module is loaded by require

-const createHeading = require('./heading. Js ').defaultCopy the code

require( ‘./main.css’) const heading= createHeading()

document.body.append(heading)

Define (['./heading. Js ','./icon.png', './main.css'], (createHeading, Icon)⥤{const heading = createHeading. Default () const img = new Image() img.src = icon document.body.append(heading) document.body.append(img)Copy the code

})

Require ([‘. / heading. Js’, ‘. / icon PNG ‘, *./main.css’],(createHeading,icon)⥤ {const heading = createHeading. Default () const img = new Image() img.src = icon document.body.append(heading) document.body.append(img) })

- In addition to the above three module loading standards, there are also some independent loaders Loader will handle some imported modules in the resources we load - such as CSS - Loader load CSS files, @import directive and URL function in such files - SRC attribute of image tag in HTML code - experiment - Import resource module in style file - main.js - import createHeading from './heading. Js'Copy the code

import ‘./main.css’ const heading= createHeading()

document.body.append(heading)

				- main.css

					- body {
min-height: 100vh,
background: #f4f8fb,
background-image: url(background.png),
background-size: cover,
Copy the code

}

-yarn webpack -ok ~ -serve. -ok ~ -reset. CSS - * {margin: 0, padding: 0,Copy the code

}

- Modify main.css - import url(reset.css)Copy the code

body { min-height: 100vh, background: #f4f8fb, background-image: url(background.png), background-size: cover, }

- yarn webpack - OK~ -serve. -ok ~ -footer. HTML - <footer>Copy the code

-import createHeading from './heading. Js'Copy the code

import ‘./main.css’ import footerHtml from ‘./footer.html’ const heading= createHeading()

document.body.append(heading) document.write(footerHtml)

						- 

				- yarn add html-loader --dev
				- const path = require ('path')
Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’) // the default value is an empty string: represents the root directory of the website. PublicPath: ‘dist/’,}, module: {// Configuration of load rules for other resource modules rules: [// Each rule object requires two properties: Test and use {// Regular expressions are used to match the file path encountered in the packaging process test: /.css/, // Are used to specify the loader used by the file matched by test. When multiple loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: Use: {loader: ‘url-loader’, options: {limit: 10 * 1024, // 10KB, url-loader will only convert files smaller than 10KB into Data URL form, and file loader will still load files larger than this size}}}, // Each rule object needs to be configured with two attributes: Test and use {// regular expressions are used to match the file path encountered during the packaging process test: /.html$/, // Are used to specify the loader used by the file matched by test. {loader: ‘html-loader’}}]}} – Package

-yarn webpack -ok ~ -serve. -ok ~ -modify footer. HTML - <footer>Copy the code

down load png

-yarn webpack -ok ~ -serve. -const path = require ('path') -yarn webpack -ok ~ -serve. -const path = require ('path')Copy the code

Module. exports = {mode: ‘none’, // set the path to webpack./ SRC /main.js // set the path to webpack. {// set the output filename filename: ‘bundle.js’, // specify the output file directory, the relative path cannot be used path: path.join(__dirname,’output’) // the default value is an empty string: represents the root directory of the website. PublicPath: ‘dist/’,}, module: {// Configuration of load rules for other resource modules rules: [// Each rule object requires two properties: Test and use {// Regular expressions are used to match the file path encountered in the packaging process test: /.css/, // Are used to specify the loader used by the file matched by test. When multiple loaders are configured, use: [‘style-loader’, ‘css-loader’]}, // Each rule object needs to be configured with two properties: test and use {// regular expressions that match the file path test encountered during the packaging process: Use: {loader: ‘url-loader’, options: {limit: 10 * 1024, // 10KB, url-loader will only convert files smaller than 10KB into Data URL form, and file loader will still load files larger than this size}}}, // Each rule object needs to be configured with two attributes: Test and use {// regular expressions are used to match the file path encountered during the packaging process test: /.html$/, // Are used to specify the loader used by the file matched by test. {loader: ‘HTML – loader, the options: {attrs: [‘ img: SRC’, ‘a: href’]}}}]}} – packaging

-YARN webpack -ok ~ -serve. -ok ~ -experience - In other words Webpack is compatible with multiple modular standards, but you should definitely not mix them in your project unless you have to. - If mixed, the maintainability of the project will be greatly reduced - each project will only need to use a single standardCopy the code