In the previous tutorial, we learned how to set up a Webpack project and how to use a loader to handle JavaScript. Where Webpack really shines, though, is its ability to bundle other types of static resources (such as CSS and images) and include them in our projects only when needed. Let's start by adding some styling to the page.
Style Loader
First, create a normal CSS file in the styles directory. Call main.css
and add style rules for the title element.
h2 { background: blue; color: yellow; }
So how do we put this stylesheet into our page? Well, like most things with Webpack, we need another loader. There are actually two: css-loader and style-loader. The first one reads all the styles from our CSS file, while the other injects said styles into our HTML page. Install them like this:
npm install style-loader css-loader
Next, we tell Webpack how to use them. In webpack.config.js
we need to add another object to the loaders array. In it, we're going to add a test to match only CSS files and specify the loader to use.
{ test: /\.css$/, exclude: /node_modules/, loader: 'style!css' }
The interesting part of this code snippet is the 'style!css'
line. The loader reads from right to left, so this tells Webpack to first read the styles of any file ending with .css
and then inject those styles into our page.
Because we have updated the configuration file, we need to restart the development server for the changes to take effect. Use ctrl c
to stop the server and use webpack-dev-server
to restart the server.
All we need to do now is get the stylesheet from the main.js
file. We do this the same way as any other JavaScript module:
const sayHello = require('./say-hello'); require('./styles/main.css'); sayHello('Guybrush', document.querySelector('h2'));
Note that we haven't even touched index.html
. Open the browser and you will see a page with the style h2
. Changing the color of the header in the stylesheet updates immediately without refreshing. cute.
You have to yell at it
"But no one uses CSS these days, Grandpa! It's all about Sass." Of course. Luckily, Webpack has a loader that does just that. Install it along with the node version of Sass using the following command:
npm install sass-loader node-sass
Then update webpack.config.js
:
{ test: /\.scss$/, exclude: /node_modules/, loader: 'style!css!sass' }
Now what this means is that for any file ending in .scss
, convert Sass to plain CSS, read the styles from the CSS, and then insert the styles into the page. Remember to rename main.css
to main.scss
and require the newly named file. First some Sass:
$background: blue; h2 { background: $background; color: yellow; }
Then main.js:
require('./styles/main.scss');
super. It's that simple. No need to convert and save files or even look at folders. We just need to enter the Sass style directly.
picture
"So I bet the same goes for images and loaders?" Of course! For images, we're going to use url-loader. This loader gets the relative URL of the image and updates the path so that it is included correctly in your package. as usual:
npm install url-loader
Now, let's try something different in webpack.config.js
. Add another entry to the loaders array in the usual way, but this time we want the regular expression to match images with different file extensions:
{ test: /\.(jpg|png|gif)$/, include: /images/, loader: 'url' }
Please note another difference here. We are not using the exclude
key. Instead, we use include
. This is more efficient because it tells webpack to ignore anything that doesn't match a folder named "images".
Normally you would use some kind of templating system to create HTML views, but we're going to keep it basic and create the image markup in JavaScript the old-fashioned way. First create an image element, set the required image to the src attribute, and then add the element to the page.
var imgElement = document.createElement('img'); imgElement.src = require('./images/my-image.jpg'); document.body.appendChild(imgElement);
Return to the browser and your image will appear in front of you!
Preloader
Another task often performed during development is linting. Linting is a method of finding potential errors in your code and checking that you are following certain coding conventions. What you might want to look for is "Did I use a variable without declaring it first?" or "Did I forget the semicolon at the end of the line?" By enforcing these rules, we can weed out silly mistakes early on.
JSHint 是一种流行的 linting 工具。这会检查我们的代码并突出显示我们所犯的潜在错误。 JSHint 可以在命令行手动运行,但这很快就会成为开发过程中的一件苦差事。理想情况下,我们希望它在每次保存文件时自动运行。我们的 Webpack 服务器已经在留意变化,所以是的,你猜对了——另一个加载器。
按照通常的方式安装jshint-loader:
npm install jshint-loader
我们必须再次将其添加到我们的 webpack.config.js
中来告诉 Webpack 使用它。然而,这个加载器略有不同。它实际上并没有转换任何代码——只是看看。我们也不希望所有较重的代码修改加载器仅仅因为忘记了分号而运行并失败。这就是预加载器的用武之地。预加载器是我们指定在主要任务之前运行的任何加载器。它们以与加载器类似的方式添加到我们的 webpack.conf.js
中。
module: { preLoaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'jshint' } ], loaders: [ ... ] }
现在,如果检测到问题,我们的 linting 过程会立即运行并失败。在重新启动 Web 服务器之前,我们需要告诉 JSHint 我们正在使用 ES6,否则当它看到我们正在使用的 const
关键字时将会失败。
在配置中的模块键之后,添加另一个名为“jshint”的条目和一行来指定 JavaScript 的版本。
module: { preLoaders: [ ... ], loaders: [ ... ] }, jshint: { esversion: 6 }
保存文件并重新启动webpack-dev-server
。运行还好吗?伟大的。这意味着您的代码不包含错误。让我们通过删除这一行中的分号来介绍一个:
var imgElement = document.createElement('img')
再次保存文件并查看终端。现在我们得到了这个:
WARNING in ./main.js jshint results in errors Missing semicolon. @ line 7 char 47
谢谢,JSHint!
准备生产
现在我们很高兴我们的代码已经成型并且它完成了我们想要的一切,我们需要为现实世界做好准备。上线代码时最常见的事情之一就是缩小代码,将所有文件连接成一个,然后将其压缩到尽可能小的文件中。在继续之前,请查看您当前的 bundle.js
。它可读,有大量空白,大小为 32kb。
“等等!别告诉我。另一个装载机,对吧?”没有!在这种罕见的情况下,我们不需要装载机。 Webpack 内置了缩小功能。一旦您对代码感到满意,只需运行以下命令:
webpack -p
-p
标志告诉 Webpack 让我们的代码为生产做好准备。当它生成捆绑包时,它会尽可能地进行优化。运行此命令后,打开 bundle.js
,您会看到它全部被压缩在一起,即使使用如此少量的代码,我们也节省了 10kb。
摘要
我希望这个由两部分组成的教程能让您有足够的信心在自己的项目中使用 Webpack。请记住,如果您想在构建过程中执行某些操作,那么 Webpack 很可能有一个加载器。所有加载器都是通过 npm 安装的,因此请查看那里是否有人已经制作了您需要的内容。
玩得开心!
The above is the detailed content of Deepening your understanding of Webpack: Part 2. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.