webpack指南

tech2022-07-05  258

webpack指南

Nowadays, we’re forced to use many accessory tools to facilitate, speed up and optimize our web development workflow. Often though, such tools add an extra layer of complexity into the stack. As a result, we need to utilize additional time and effort to learn, understand and use these tools correctly. The same is true for webpack.

如今,我们被迫使用许多附件工具来简化,加快和优化我们的Web开发工作流程。 但是,此类工具通常会在堆栈中增加一层额外的复杂性。 结果,我们需要花费更多的时间和精力来正确地学习,理解和使用这些工具。 webpack也是如此。

When using webpack for the first time, it can be difficult to understand how it works and how it should be used. Although it has good documentation, it can be daunting for novices, and it has a steep learning curve. However, webpack is worth learning and can save considerable time and effort in the long run. In this tutorial, I’ll introduce all the core concepts to help you get started.

首次使用webpack时,可能很难理解它的工作方式和使用方式。 尽管它具有良好的文档记录,但对于新手来说可能会令人望而生畏,而且学习曲线也很陡。 但是,webpack值得学习,从长远来看可以节省大量时间和精力。 在本教程中,我将介绍所有核心概念以帮助您入门。

Note: in this tutorial I’ve used webpack 4.30.

注意:在本教程中,我使用了webpack 4.30。

SitePoint Premium gives you an entire collection of books covering developer essentials like Pug, Gulp, Git and more. Join now.

SitePoint Premium为您提供了一整套书籍,涵盖了Pug,Gulp,Git等开发人员的必备知识。 现在加入 。

什么是Webpack? (What Is Webpack?)

As its core, webpack is a static module bundler. In a particular project, webpack treats all files and assets as modules. Under the hood, it relies on a dependency graph. A dependency graph describes how modules relate to each other using the references (require and import statements) between files. In this way, webpack statically traverses all modules to build the graph, and uses it to generate a single bundle (or several bundles) — a JavaScript file containing the code from all modules combined in the correct order. “Statically” means that, when webpack builds its dependency graph, it doesn’t execute the source code but stitches modules and their dependencies together into a bundle. This can then be included in your HTML files.

作为其核心,webpack是一个静态模块捆绑器。 在特定项目中,webpack将所有文件和资产视为模块。 在后台,它依赖于依赖图。 依赖图描述了模块之间如何使用文件之间的引用( require和import语句)相互关联。 这样,webpack会静态遍历所有模块以构建图,并使用它生成单个捆绑包(或多个捆绑包)-一个JavaScript文件,其中包含所有模块以正确顺序组合而成的代码。 “静态”表示,当webpack构建其依赖关系图时,它不执行源代码,而是将模块及其依赖关系缝合在一起。 然后可以将其包含在HTML文件中。

Now, to expand the above cursory overview, let’s explore the main concepts webpack uses.

现在,为了扩展上面的粗略概述,让我们探索webpack所使用的主要概念。

Webpack主要概念 (Webpack Main Concepts)

Webpack has some main concepts which we need to understand clearly before digging in its practical implementation. Let’s examine them one by one:

Webpack有一些主要概念,在深入研究其实际实现之前,我们需要清楚地理解这些概念。 让我们一一检查它们:

Entry. The entry point is the module, which webpack uses to start building its internal dependency graph. From there, it determines which other modules and libraries that entry point depends on (directly and indirectly) and includes them in the graph until no dependency is left. By default, the entry property is set to ./src/index.js, but we can specify a different module (or even multiple modules) in the webpack configuration file.

条目。 入口点是模块,webpack使用该模块开始构建其内部依赖关系图。 从那里,它确定入口点直接(或间接)依赖于其他哪些模块和库,并将它们包括在图中,直到没有依赖性为止。 默认情况下,entry属性设置为./src/index.js ,但是我们可以在webpack配置文件中指定一个不同的模块(甚至多个模块)。

Output. The output property instructs webpack where to emit the bundle(s) and what name to use for that file(s). The default value for this property is ./dist/main.js for the main bundle and ./dist for other generated files — such as images, for example. Of course, we can specify different values in the configuration depending on our needs.

输出。 output属性指示webpack在何处发出分发包以及该文件使用什么名称。 对于主捆绑包,此属性的默认值为./dist对于其他生成的文件(例如,图像),默认值为./dist/main.js 。 当然,我们可以根据需要在配置中指定不同的值。

Loaders. By default, webpack only understands JavaScript and JSON files. To process other types of files and convert them into valid modules, webpack uses loaders. Loaders transform the source code of non-JavaScript modules, allowing us to preprocess those files before they’re added to the dependency graph. For example, a loader can transform files from a CoffeeScript language to JavaScript or inline images to data URLs. With loaders we can even import CSS files directly from our JavaScript modules.

装载机。 默认情况下,webpack仅理解JavaScript和JSON文件。 为了处理其他类型的文件并将其转换为有效的模块,webpack使用加载程序。 加载程序会转换非JavaScript模块的源代码,使我们能够在将这些文件添加到依赖关系图之前对其进行预处理。 例如,加载程序可以将文件从CoffeeScript语言转换为JavaScript,或者将内联图像转换为数据URL。 使用加载程序,我们甚至可以直接从JavaScript模块导入CSS文件。

Plugins. Plugins are used for any other task that loaders can’t do. They provide us with a wide range of solutions about asset management, bundle minimization and optimization, and so on.

插件。 插件用于装载程序无法执行的任何其他任务。 他们为我们提供了有关资产管理,捆绑包最小化和优化等方面的广泛解决方案。

Mode. Typically, when we develop our application we work with two types of source code — one for the development build and one for the production build. Webpack allows us to set which one we want to be produced by changing the mode parameter to development, production or none. This allows webpack to use built-in optimizations corresponding to each environment. The default value is production. The none mode means that there won’t be used any default optimization options. To learn more about the options webpack uses in development and production mode, visit the mode configuration page.

模式。 通常,在开发应用程序时,我们使用两种类型的源代码-一种用于开发版本,另一种用于生产版本。 Webpack允许我们通过将mode参数更改为development , production或none来设置要生产的产品 。 这允许webpack使用与每个环境相对应的内置优化。 默认值为production 。 none模式意味着将不使用任何默认优化选项。 要了解有关Webpack在开发和生产模式下使用的选项的更多信息,请访问模式配置页面 。

Webpack如何工作 (How Webpack Works)

In this section we’ll examine how webpack works. Even a simple project contains HTML, CSS and JavaScript files. Also, it can contains assets such as fonts, images, and so on. So, a typical webpack workflow would include setting up an index.html file with the appropriate CSS and JS links, and the necessary assets. Also, if you have many CSS and JS modules which depend on each other, they need to be optimized and properly combined in one unit ready for production.

在本节中,我们将研究webpack的工作方式。 甚至一个简单的项目也包含HTML,CSS和JavaScript文件。 而且,它可以包含字体,图像等资产。 因此,典型的webpack工作流程将包括使用适当CSS和JS链接以及必要的资产来设置index.html文件。 另外,如果您有许多相互依赖CSS和JS模块,则需要对其进行优化并将其正确组合到一个单元中,以进行生产。

To do all this, webpack relies on configuration. Although webpack 4 comes with reasonable defaults, for any non-trivial project you’ll need to provide a special configuration file webpack.config.js, which describes how the files and assets should be transformed and what kind of output should be generated. This file can quickly become quite monolithic, which makes it hard to understand how webpack does its job unless you know the main concepts behind its working.

为此,webpack依赖于配置。 尽管webpack 4带有合理的默认值,但对于任何不重要的项目,您都需要提供一个特殊的配置文件webpack.config.js ,该文件描述了应如何转换文件和资产以及应生成什么样的输出。 该文件很快就会变得非常单一,这使得很难理解webpack如何完成其​​工作,除非您知道其工作背后的主要概念。

Based on the provided configuration, webpack starts from the entry points and resolves each module it encounters while constructing the dependency graph. If a module contains dependencies, the process is performed recursively against each dependency until the traversal has completed. Then webpack bundles all project’s modules into a small number of bundles — usually, just one — to be loaded by the browser.

基于提供的配置,webpack从入口点开始,并解析在构造依赖关系图时遇到的每个模块。 如果模块包含依赖项,则针对每个依赖项递归执行该过程,直到遍历完成。 然后,webpack将所有项目的模块捆绑为少数捆绑软件(通常只有一个),以供浏览器加载。

入门 (Getting Started)

Note: you can find the files for our project in the GitHub repo.

注意:您可以在GitHub repo中找到我们项目的文件。

Now that we have solid theoretical foundation, let’s implement it in practice.

现在我们已经有了扎实的理论基础,让我们在实践中加以实施。

To start, we’ll create a new directory and switch to it. Then we’ll initialize a new project:

首先,我们将创建一个新目录并切换到该目录。 然后,我们将初始化一个新项目:

mkdir learn-webpack cd learn-webpack npm init -y

Next, we need to install webpack and webpack CLI locally:

接下来,我们需要在本地安装webpack和webpack CLI:

npm install webpack webpack-cli --save-dev

Now, the content of the generated package.json should be similar to the following:

现在,生成的package.json的内容应类似于以下内容:

{ "name": "learn_webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.30.0", "webpack-cli": "^3.3.0" } }

Besides bundling modules, webpack can be used as a simple task runner. We can create webpack tasks by including the name of our task followed by its instructions in the scripts section of the package,json file. Let’s try this now. Open package.json and change the scripts object to the following:

除了捆绑模块外,webpack还可以用作简单的任务运行器。 我们可以通过包括我们的任务,随后其在说明的名字创建的WebPack任务scripts中的部分package,json文件。 让我们现在尝试一下。 打开package.json并将scripts对象更改为以下内容:

"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode development", "build": "webpack --mode production" },

Within the scripts property, webpack allows us to reference locally installed npm packages by their names. We use that and the --mode flag to define dev and build tasks, which will run webpack in development (npm run dev) and production (npm run build) mode respectively.

在scripts属性中,webpack允许我们通过名称来引用本地安装的npm软件包。 我们使用它和--mode标志来定义dev和build任务,这将分别在开发( npm run dev )和生产( npm run build )模式下运行webpack。

Before we test the tasks we’ve just created, let’s create a src directory and put an index.js file in it so that it contains console.log("Hello webpack");. Now we can already to run the dev task to start webpack in development mode:

在测试刚刚创建的任务之前,让我们创建一个src目录,并在其中放置一个index.js文件,使其包含console.log("Hello webpack"); 。 现在我们已经可以运行dev任务以在开发模式下启动webpack了:

$ npm run dev > learn_webpack@1.0.0 dev C:\Users\User\Webpack\learn_webpack > webpack --mode development Hash: 5bb3bdc1efd7b7f4b627 Version: webpack 4.30.0 Time: 226ms Built at: 2019-04-16 17:48:32 Asset Size Chunks Chunk Names main.js 3.8 KiB main [emitted] main Entrypoint main = main.js [./src/index.js] 27 bytes {main} [built]

Great! It works as expected. But to verify that we get the correct output, we need to display the result in the browser. To do that, let’s create an index.html file in the dist directory:

大! 它按预期工作。 但是要验证我们是否获得正确的输出,我们需要在浏览器中显示结果。 为此,让我们在dist目录中创建一个index.html文件:

<!doctype html> <html> <head> <title>Getting Started</title> </head> <body> <script src="main.js"></script> </body> </html>

Now, if we open the file in the browser, we should see the Hello webpack message in the console.

现在,如果我们在浏览器中打开文件,则应该在控制台中看到Hello webpack消息。

So far, so good. But writing our index.html file manually can be problematic in some cases. For example, if we change the name of our entry point, the generated bundle will be renamed, but our index.html file will still reference the old name. So, we’ll need to update our HTML file manually every time we rename an entry point or add new one. Fortunately, we can easily fix that with the html-webpack-plugin. Let’s install it now:

到目前为止,一切都很好。 但是在某些情况下,手动编写index.html文件可能会出现问题。 例如,如果我们更改入口点的名称,则将重命名生成的包,但是我们的index.html文件仍将引用旧名称。 因此,每次重命名入口点或添加新入口点时,我们都需要手动更新HTML文件。 幸运的是,我们可以使用html-webpack-plugin轻松修复该问题。 现在安装它:

npm install html-webpack-plugin --save-dev

At this point, to activate the plugin, we need to create a webpack.config.js file in the root directory with the following content:

此时,要激活插件,我们需要在根目录中创建一个webpack.config.js文件,其内容如下:

const HtmlWebpackPlugin = require("html-webpack-plugin"); const path = require('path'); module.exports = { plugins: [ new HtmlWebpackPlugin({ title: "Webpack Output", }), ], };

As you can see, to activate a webpack plugin, we need to include it and then add it to the plugins array. If needed, we also pass options to the plugin.

如您所见,要激活一个webpack插件,我们需要将其包含进来,然后将其添加到plugins数组中。 如果需要,我们还将选项传递给插件。

Let’s run our build now to see what will happen:

现在运行我们的构建,看看会发生什么:

$ npm run build > learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack > webpack --mode production Hash: e56a796f5ccfebcc8270 Version: webpack 4.30.0 Time: 1088ms Built at: 2019-04-16 20:44:47 Asset Size Chunks Chunk Names index.html 183 bytes [emitted] main.js 956 bytes 0 [emitted] main Entrypoint main = main.js [0] ./src/index.js 27 bytes {0} [built] Child html-webpack-plugin for "index.html": 1 asset Entrypoint undefined = index.html [2] (webpack)/buildin/global.js 472 bytes {0} [built] [3] (webpack)/buildin/module.js 497 bytes {0} [built] + 2 hidden modules

Let’s open the index.html. As we can see, the plugin automatically creates an updated index.html file for us which uses the title option from the configuration:

让我们打开index.html 。 如我们所见,该插件会自动为我们创建一个更新的index.html文件,该文件使用配置中的title选项:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Webpack Output</title> </head> <body> <script type="text/javascript" src="main.js"></script></body> </html>

Let’s now expand our project and specify custom names for the entry and output properties. In webpack.config.js we add the following before the plugins property:

现在让我们扩展项目,并为entry和output属性指定自定义名称。 在webpack.config.js我们在plugins属性之前添加以下内容:

entry: './src/app.js', output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') },

Now, we’ll create an src/component.js file:

现在,我们将创建一个src/component.js文件:

export default (text = "Hello webpack") => { const element = document.createElement("p"); element.innerHTML = text; return element; };

Next, we rename index.js to app.js to reflect our changes, and swap its content with the following:

接下来,我们将index.js重命名为app.js以反映我们的更改,并用以下内容交换其内容:

import component from "./component"; document.body.appendChild(component());

Now, let’s run webpack in production mode:

现在,让我们在生产模式下运行webpack:

$ npm run build > learn_webpack@1.0.0 build C:\Users\User\Webpack\learn_webpack > webpack --mode production Hash: 9f78936f8a2a21061f0b Version: webpack 4.30.0 Time: 1689ms Built at: 2019-04-17 23:43:40 Asset Size Chunks Chunk Names index.html 190 bytes [emitted] main.bundle.js 1.04 KiB 0 [emitted] main Entrypoint main = main.bundle.js [0] ./src/app.js + 1 modules 227 bytes {0} [built] | ./src/app.js 79 bytes [built] | ./src/component.js 148 bytes [built] Child html-webpack-plugin for "index.html": 1 asset Entrypoint undefined = index.html [2] (webpack)/buildin/global.js 472 bytes {0} [built] [3] (webpack)/buildin/module.js 497 bytes {0} [built] + 2 hidden modules

Let’s examine and clarify the information from the webpack output. Beginning from the top, we see the hash of the build, webpack version, and the time it took to execute the build. Next, we see the files generated in the dist directory (index.html and main.bundle.js). Below them, we see the entry module (app.js) and its dependency (component.js). The output after Child html-webpack-plugin for "index.html": is related to the internal work of the html-webpack-plugin and we can safely ignore it.

让我们检查并澄清来自webpack输出的信息。 从顶部开始,我们看到了构建的哈希值,webpack版本以及执行构建所花费的时间。 接下来,我们将在dist目录中生成文件( index.html和main.bundle.js )。 在它们下面,我们看到输入模块( app.js )及其依赖项( component.js )。 后输出的Child html-webpack-plugin for "index.html":关系到内部工作html-webpack-plugin ,我们可以放心地忽略它。

So now, in the dist folder, we have the newly generated bundle file main.bundle.js. If we open index.html in the browser, we should see Hello webpack displayed on the page. Also, if we check the source of index.html, we’ll see that the value of the src property in the script tag is updated to main.bundle.js.

因此,现在在dist文件夹中,我们有了新生成的捆绑文件main.bundle.js 。 如果在浏览器中打开index.html ,则应该在页面上看到Hello Webpack 。 另外,如果我们检查index.html的源,我们将看到script标记中src属性的值已更新为main.bundle.js 。

使用脚本 (Working with Scripts)

In this section, we’ll discover how ES6 can be transpiled to ES5-compliant code which works in all browsers. Let’s start by running the following command:

在本节中,我们将发现如何将ES6转换为可在所有浏览器中使用的ES5兼容代码。 让我们从运行以下命令开始:

npm run dev -- --devtools false

Next, let’s open main.bundle.js:

接下来,让我们打开main.bundle.js :

/***/ "./src/component.js": /*!**************************!*\ !*** ./src/component.js ***! \**************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = ((text = "Hello webpack") => { const element = document.createElement("p"); element.innerHTML = text; return element; }); /***/ })

As you can see, the modern ES6 features (the arrow function and the const declaration) from component.js module are not transformed to ES5-compliant code by default. To make our code work in older browsers, we must add the Babel loader:

如您所见,默认情况下, component.js模块中的现代ES6功能(箭头功能和const声明)未转换为ES5兼容代码。 为了使我们的代码在较旧的浏览器中运行,我们必须添加Babel加载器:

npm install babel-loader @babel/core @babel/preset-env --save-dev

Then, in webpack.config.js add module after the output property:

然后,在webpack.config.js ,在output属性之后添加module :

module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] },

When we define rules for a webpack loader, there are usually three main properties we need to define:

当我们为webpack加载器定义规则时,通常需要定义三个主要属性:

test, which describes what kind of files should be transformed.

test ,它描述了应转换的文件类型。

exclude, which defines the files which should not be processed from the loader(s), if we have such.

exclude ,它定义了不应从加载程序处理的文件(如果有)。

use, which tells which loader(s) should be used against the matched modules.

use ,它指示应针对匹配的模块使用哪个加载器。

Run the following command again:

再次运行以下命令:

npm run dev -- --devtools false

This time, the code in main.bundle.js is compiled:

这次,对main.bundle.js的代码进行了编译:

/***/ "./src/component.js": /*!**************************!*\ !*** ./src/component.js ***! \**************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = (function () { var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "Hello webpack"; var element = document.createElement("p"); element.innerHTML = text; return element; }); /***/ })

Perfect. Now we can use the modern JS features, and webpack will transform our code so it can be executed by older browsers.

完善。 现在我们可以使用现代的JS功能,并且webpack将转换我们的代码,以便可以由较旧的浏览器执行。

处理样式 (Working with Styles)

In this section, we’ll see how we can add some styles to our project. To do this, we need to install two loaders:

在本节中,我们将看到如何为项目添加一些样式。 为此,我们需要安装两个加载程序:

npm install css-loader style-loader --save-dev

css-loader parses the CSS into JavaScript and resolves any dependencies, style-loader outputs our CSS into a <style> tag in the HTML document.

css-loader将CSS解析为JavaScript并解决所有依赖关系, style-loader将CSS输出到HTML文档中的<style>标记中。

Let’s add the necessary configuration in webpack.config.js:

让我们在webpack.config.js添加必要的配置:

{ test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader' }], },

Here, the order of loaders is important. They’re evaluated in reverse order — that is, from right to left and from bottom to top.

在此,装载机的顺序很重要。 他们的评估顺序相反-从右到左,从下到上。

Now, let’s create a file src/style.css:

现在,让我们创建一个文件src/style.css :

p { color: red; }

Then we import it into app.js:

然后我们将其导入app.js :

import './style.css'

When we run webpack and then open the index.html, we should see the Hello webpack message in red.

当我们运行webpack然后打开index.html ,我们应该看到红色的Hello Webpack消息。

资产管理 (Asset Management)

Most often your project will contain assets such as images, fonts, and so on. Here we’ll explore an example with images. First, we’ll need to install a file loader:

大多数情况下,您的项目将包含图像,字体等资产。 在这里,我们将探讨图像示例。 首先,我们需要安装文件加载器:

npm install file-loader --save-dev

Next, we’ll add new rule in the webpack.config.js:

接下来,我们将在webpack.config.js添加新规则:

{ test: /\.(png|jpg|gif)$/, use: [ { loader: 'file-loader' }, ], },

Now, to test the loader we’ll create an image-component.js file, in the src directory, with the following content:

现在,为了测试加载器,我们将在src目录中创建一个image-component.js文件,其内容如下:

import image from "./image.png" const img = document.createElement("img") img.src = image document.body.appendChild(img)

Here, we import our image as a module and use it to create an <img/> tag. We need to put that image in the src directory.

在这里,我们将图像导入为模块,并使用它来创建<img/>标签。 我们需要将该图像放在src目录中。

The next thing is to import our image component in app.js:

接下来是将图像组件导入app.js :

import './image-component'

And voila. Now, when we run webpack and open the page, we should see the image above the Hello webpack message.

和瞧。 现在,当我们运行webpack并打开页面时,我们应该看到Hello webpack消息上方的图像。

使用webpack-dev-server加快开发过程 (Speed Up the Development Process with webpack-dev-server)

Currently, we need to rebuild our code every time we make a change. Fortunately, webpack offers a live-reloading web server which automatically builds and refreshes the page. To install it:

当前,每次进行更改时,我们都需要重建代码。 幸运的是,webpack提供了一个实时重载的Web服务器,该服务器可以自动构建和刷新页面。 要安装它:

npm install webpack-dev-server --save-dev

We need to update our dev script, in package.json, to use the server:

我们需要更新package.json dev脚本以使用服务器:

"dev": "webpack-dev-server --mode development"

Now let’s configure the server in webpack.config.js by adding the following property:

现在,通过添加以下属性,在webpack.config.js配置服务器:

devServer: { contentBase: './dist', open: true },

This tells webpack-dev-server to serve the files from the dist directory and to open the entry page automatically.

这告诉webpack-dev-server从dist目录提供文件并自动打开条目页面。

Now, if we run webpack (npm run dev), we should see how the page is automatically opened in the browser on localhost:8080:

现在,如果我们运行webpack( npm run dev ),我们应该看到如何在localhost:8080的浏览器中自动打开页面:

i 「wds」: Project is running at http://localhost:8080/ i 「wds」: webpack output is served from / i 「wds」: Content not from webpack is served from ./dist

If we now change any of the source files and save them, the web server will automatically reload the page after the code has been compiled. Try to change the color property in our CSS file to green, for example, and you should see how the color is updated appropriately in the page.

如果现在更改任何源文件并保存它们,则在代码编译后,Web服务器将自动重新加载页面。 例如,尝试将我们CSS文件中的color属性更改为绿色,然后您应该在页面中看到如何正确更新颜色。

清理输出 (Clean Up the Output)

As our project progress, the dist folder might become quite cluttered. On every build, webpack will generate the bundles and put them in the dist folder, but it doesn’t keep track of which files are actually in use by your project. So it’s good practice to clean the dist folder before each build, so that only the files in use will be generated. To do this, we need to install and configure the clean-webpack-plugin:

随着我们项目的进展, dist文件夹可能变得很混乱。 在每次构建时,webpack都会生成捆绑包并将其放置在dist文件夹中,但不会跟踪项目实际使用的文件。 因此,在每次构建之前清理dist文件夹是一个好习惯,这样只会生成正在使用的文件。 为此,我们需要安装和配置clean-webpack-plugin :

npm install --save-dev clean-webpack-plugin

In webpack.config.js:

在webpack.config.js :

const CleanWebpackPlugin = require('clean-webpack-plugin'); ... plugins: [ ... new CleanWebpackPlugin() ],

Now, run webpack (npm run build) and inspect the dist folder. You should now only see the files generated from the build without old and unused files. In our case, the file which should be deleted is main.js.

现在,运行webpack( npm run build )并检查dist文件夹。 现在,您应该只看到从生成生成的文件,而没有旧的和未使用的文件。 在我们的例子中,应该删除的文件是main.js

结论 (Conclusion)

Webpack is a useful and powerful tool. This tutorial introduces only the core concepts, but webpack offers many more features, plugins, and different techniques to apply them, which you can adopt as your knowledge grows. Here’s a list of resources I suggest for further exploration of webpack’s capabilities:

Webpack是一个有用而强大的工具。 本教程仅介绍核心概念,但是webpack提供了更多功能,插件和不同的技术来应用它们,您可以随着知识的增长而采用它们。 以下是我建议进一步探索webpack功能的资源列表:

Official webpack Documentation. The documentation offers you structured information about webpack’s main concepts and configuration; plugins and loaders you can use in your project; basic guides and API references.

官方webpack文档 。 该文档为您提供有关Webpack的主要概念和配置的结构化信息。 您可以在项目中使用的插件和加载器; 基本指南和API参考。

Webpack: From Apprentice to Master. A complete manual which dives deeply into each webpack aspect. Written by Juho Vepsäläinen, a core developer of webpack.

Webpack:从学徒到大师 。 完整的手册深入探讨了Webpack的各个方面。 由webpack的核心开发人员JuhoVepsäläinen撰写。

A Tale of webpack 4 and How to Finally Configure It in the Right Way. A detailed tutorial with solutions to most common issues you can encounter when working with webpack.

webpack 4的故事以及如何正确地最终配置它 。 有关使用webpack时可能遇到的最常见问题的解决方案的详细教程。

Webpack 4 Tutorial: from 0 Conf to Production Mode. A good introductory tutorial with examples for React and Vue.

Webpack 4教程:从0 Conf到生产模式 。 一个很好的入门教程,其中包含React和Vue的示例。

Configuring webpack from scratch for Tailwind CSS with React. A tutorial that explores how to configure webpack for use with React and Tailwind CSS.

使用React从零开始为Tailwind CSS配置webpack 。 本教程探讨了如何配置Webpack以与React和Tailwind CSS一起使用。

How to use webpack with React: an in-depth tutorial. An advanced tutorial about using Webpack with React.

如何将Webpack与React结合使用:深入的教程 。 有关将Webpack与React结合使用的高级教程。

Webpack: The Core Concepts. A great introductory video course by Sean Larkin, one of the webpack’s maintainers.

Webpack:核心概念 。 webpack的维护者之一Sean Larkin的精彩介绍性视频课程。

翻译自: https://www.sitepoint.com/webpack-beginner-guide/

webpack指南

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)