Webpack is a tool that lets you compile JavaScript modules. It’s also known as a module bundler.

Webpack是使您可以编译JavaScript模块的工具。 也称为模块捆绑器

Given a large number of files, it generates a single file (or a few files) that run your app.

给定大量文件,它将生成一个(或几个文件)运行您的应用程序的文件。

It can perform many operations:

它可以执行许多操作:

  • helps you bundle your resources.帮助您捆绑资源。
  • watches for changes and re-runs the tasks.监视更改并重新运行任务。
  • can run Babel transpilation to ES5, allowing you to use the latest JavaScript features without worrying about browser support.

    可以将Babel转换运行到ES5,从而使您可以使用最新的JavaScript功能,而不必担心浏览器支持。

  • can transpile CoffeeScript to JavaScript可以将CoffeeScript转换为JavaScript
  • can convert inline images to data URIs.可以将嵌入式图像转换为数据URI。
  • allows you to use require() for CSS files.允许您将require()用于CSS文件。
  • can run a development webserver.可以运行开发Web服务器。
  • can handle hot module replacement.可以处理热模块更换。
  • can split the output files into multiple files to avoid having a huge JS file to load in the first page hit.可以将输出文件分为多个文件,以避免在首页命中时加载巨大的JS文件。
  • can perform tree shaking.

    可以摇树 。

Webpack is not limited to being used on the front-end, but is useful in backend Node.js development as well.

Webpack不仅限于在前端使用,在后端Node.js开发中也很有用。

There are many predecessors of Webpack and lots of similarities in what those tools and Webpack do. The main difference is that those tools are known as task runners, while Webpack was born as a module bundler.

Webpack的前身很多,并且这些工具和Webpack的功能有很多相似之处。 主要区别在于这些工具被称为任务运行器 ,而Webpack则是模块捆绑器。

Webpack is a more focused tool. You just need to specify an entry point to your app (it could even be an HTML file with script tags) and webpack analyzes the files and bundles them in a single JavaScript output file that includes everything you need to run the app.

Webpack是更集中的工具。 您只需要指定应用程序的入口点(它甚至可以是带有脚本标签HTML文件),然后webpack会分析这些文件并将它们捆绑在一个JavaScript输出文件中,该文件包含您运行该应用程序所需的一切。

安装Webpack (Installing Webpack)

Webpack can be installed globally or locally for each project.

Webpack可以在每个项目的全局或本地安装。

全局安装 (Global install)

Here’s how to install it globally with Yarn:

这是使用Yarn全局安装的方法:

yarn global add webpack webpack-cli

with npm:

与npm :

npm i -g webpack webpack-cli

once this is done, you should be able to run

完成此操作后,您应该可以运行

webpack-cli

本地安装 (Local Install)

Webpack can be installed locally as well. It’s the recommended setup, because Webpack can be updated per-project, and you have less resistance in using the latest features just for a small project rather than updating all the projects you have that use Webpack.

Webpack也可以在本地安装。 这是推荐的设置,因为Webpack可以按项目进行更新,并且您对仅针对小型项目使用最新功能的阻力较小,而不必更新拥有Webpack的所有项目。

With Yarn:

带纱 :

yarn add webpack webpack-cli -D

with npm:

与npm :

npm i webpack webpack-cli --save-dev

Once this is done, add this to your package.json file:

完成后,将其添加到package.json文件:

{   //...   "scripts": {     "build": "webpack"   } }

Once this is done, you can run Webpack by typing

完成此操作后,您可以通过键入以下内容来运行Webpack:

yarn build

in the project root.

在项目根目录中。

Webpack配置 (Webpack configuration)

By default, Webpack (starting from version 4) does not require any config if you respect these conventions:

默认情况下,如果遵守以下约定,Webpack(从版本4开始)不需要任何配置:

  • the entry point of your app is ./src/index.js

    您的应用程序的入口点./src/index.js

  • the output is put in ./dist/main.js.

    输出放在./dist/main.js

  • Webpack works in production modeWebpack在生产模式下工作

You can customize every little bit of Webpack of course, when you need. The Webpack configuration is stored in the webpack.config.js file, in the project root folder.

当然,您可以根据需要自定义Webpack的每一个细节。 Webpack配置存储在项目根文件夹中的webpack.config.js文件中。

入口点 (The entry point)

By default the entry point is ./src/index.js This simple example uses the ./index.js file as a starting point:

默认情况下,入口点是./src/index.js这个简单的示例使用./index.js文件作为起点:

module.exports = {  /*...*/  entry: './index.js'  /*...*/}

输出 (The output)

By default the output is generated in ./dist/main.js. This example puts the output bundle into app.js:

默认情况下,输出是在./dist/main.js生成的。 此示例将输出包放入app.js

module.exports = {  /*...*/  output: {    path: path.resolve(__dirname, 'dist'),    filename: 'app.js'  }  /*...*/}

Using Webpack allows you to use import or require statements in your JavaScript code not just to include other JavaScript, but any kind of file (for example CSS).

使用Webpack允许您在JavaScript代码中使用importrequire语句,不仅包括其他JavaScript,还包括任何类型的文件(例如CSS)。

Webpack aims to handle all our dependencies, not just JavaScript, and loaders are one way to do that.

Webpack旨在处理我们所有的依赖关系,而不仅仅是JavaScript,而加载程序是做到这一点的一种方法。

For example, in your code you can use:

例如,在您的代码中,您可以使用:

import 'style.css'

by using this loader configuration:

通过使用此加载程序配置:

module.exports = {  /*...*/  module: {    rules: [      { test: /\.css$/, use: 'css-loader' },    }]  }  /*...*/}

The regular expression targets any CSS file.

正则表达式以任何CSS文件为目标。

A loader can have options:

装载机可以有以下选择:

module.exports = {  /*...*/  module: {    rules: [      {        test: /\.css$/,        use: [          {            loader: 'css-loader',            options: {              modules: true            }          }        ]      }    ]  }  /*...*/}

You can require multiple loaders for each rule:

您可以为每个规则要求多个加载程序:

module.exports = {  /*...*/  module: {    rules: [      {        test: /\.css$/,        use:          [            'style-loader',            'css-loader',          ]      }    ]  }  /*...*/}

In this example, css-loader interprets the import 'style.css' directive in the CSS. style-loader is then responsible for injecting that CSS in the DOM, using a <style> tag.

在此示例中, css-loader解释css-loader import 'style.css'指令。 然后, style-loader负责使用<sty le>标签将CSS注入DOM中。

The order matters, and it’s reversed (the last is executed first).

顺序很重要,并且顺序相反(最后执行的是第一个)。

What kind of loaders are there? Many! You can find the full list here.

那里有什么装载机? 许多! 您可以在此处找到完整列表 。

A commonly used loader is Babel, which is used to transpile modern JavaScript to ES5 code:

常用的加载器是Babel ,用于将现代JavaScript转换为ES5代码:

module.exports = {  /*...*/  module: {    rules: [      {        test: /\.js$/,        exclude: /(node_modules|bower_components)/,        use: {          loader: 'babel-loader',          options: {            presets: ['@babel/preset-env']          }        }      }    ]  }  /*...*/}

This example makes Babel preprocess all our React/JSX files:

这个例子使Babel预处理我们所有的React / JSX文件:

module.exports = {  /*...*/  module: {    rules: [      {        test: /\.(js|jsx)$/,        exclude: /node_modules/,        use: 'babel-loader'      }    ]  },  resolve: {    extensions: [      '.js',      '.jsx'    ]  }  /*...*/}

See the babel-loader options here.

在此处查看babel-loader选项。

外挂程式 (Plugins)

Plugins are like loaders, but on steroids. They can do things that loaders can’t do, and they are the main building blocks of Webpack.

插件就像加载程序一样,但是在类固醇上。 他们可以完成加载程序无法完成的工作,它们是Webpack的主要组成部分。

Take this example:

举个例子:

module.exports = {  /*...*/  plugins: [    new HTMLWebpackPlugin()  ]  /*...*/}

The HTMLWebpackPlugin plugin does the job of automatically creating an HTML file and adding the output JS bundle path, so the JavaScript is ready to be served.

HTMLWebpackPlugin插件可以自动创建HTML文件并添加输出JS包路径,因此可以随时使用JavaScript。

There are lots of plugins available.

有很多可用的插件 。

One useful plugin, CleanWebpackPlugin, can be used to clear the dist/ folder before creating any output, so you don’t leave files around when you change the names of the output files:

一个有用的插件CleanWebpackPlugin可以用于在创建任何输出之前清除dist/文件夹,因此在更改输出文件的名称时,您不会留下文件:

module.exports = {  /*...*/  plugins: [    new CleanWebpackPlugin(['dist']),  ]  /*...*/}

Webpack模式 (The Webpack mode)

This mode (introduced in Webpack 4) sets the environment on which Webpack works. It can be set to development or production (defaults to production, so you only set it when moving to development).

此模式(在Webpack 4中引入)设置了Webpack工作的环境。 可以将其设置为developmentproduction (默认为生产,因此仅在进行开发时进行设置)。

module.exports = {  entry: './index.js',  mode: 'development',  output: {    path: path.resolve(__dirname, 'dist'),    filename: 'app.js'  }}

Development mode:

开发方式:

  • builds very fast建立非常快
  • is less optimized than production没有比生产优化
  • does not remove comments不删除评论
  • provides more detailed error messages and suggestions提供更详细的错误消息和建议
  • provides a better debugging experience提供更好的调试体验

Production mode is slower to build, since it needs to generate a more optimized bundle. The resulting JavaScript file is smaller in size, as it removes many things that are not needed in production.

生产模式的构建速度较慢,因为它需要生成更优化的捆绑包。 生成JavaScript文件较小,因为它删除了生产中不需要的许多东西。

I made a sample app that just prints a console.log statement.

我制作了一个示例应用程序,仅打印console.log语句。

Here’s the production bundle:

这是产品包:

Here’s the development bundle:

这是开发包:

运行Webpack (Running Webpack)

Webpack can be run from the command line manually if installed globally. But generally you write a script inside the package.json file, which is then run using npm or yarn.

如果Webpack已全局安装,则可以从命令行手动运行。 但是通常您会在package.json文件中编写一个脚本,然后使用npmyarn运行该脚本。

For example this package.json scripts definition we used before:

例如,我们之前使用的以下package.json脚本定义:

"scripts": {  "build": "webpack"}

allows us to run webpack by running

允许我们通过运行来运行webpack

npm run build

or

要么

yarn run build

or simply

或简单地

yarn build

观察变化 (Watching changes)

Webpack can automatically rebuild the bundle when a change in your app happens, and it keeps listening for the next change.

当您的应用程序发生更改时,Webpack可以自动重建捆绑包,并且它会一直在监听下一个更改。

Just add this script:

只需添加以下脚本:

"scripts": {  "watch": "webpack --watch"}

and run

并运行

npm run watch

or

要么

yarn run watch

or simply

或简单地

yarn watch

One nice feature of the watch mode is that the bundle is only changed if the build has no errors. If there are errors, watch will keep listening for changes, and try to rebuild the bundle, but the current, working bundle is not affected by those problematic builds.

监视模式的一个不错的功能是,仅当构建没有错误时才更改捆绑软件。 如果有错误, watch将继续侦听更改,并尝试重建捆绑软件,但是当前有效的捆绑软件不受那些有问题的构建的影响。

处理图像 (Handling images)

Webpack allows you to use images in a very convenient way, using the file-loader loader.

Webpack允许您使用file-loaderfile-loader器以非常方便的方式使用图像。

This simple configuration:

这个简单的配置:

module.exports = {  /*...*/  module: {    rules: [      {        test: /\.(png|svg|jpg|gif)$/,        use: [          'file-loader'        ]      }    ]  }  /*...*/}

Allows you to import images in your JavaScript:

允许您在JavaScript中导入图像:

import Icon from './icon.png'const img = new Image()img.src = Iconelement.appendChild(img)

Where img is an HTMLImageElement. Check out the Image docs.

其中img是HTMLImageElement。 查看Image文档 。

file-loader can handle other asset types as well, like fonts, CSV files, XML, and more.

file-loader还可以处理其他资产类型,例如字体,CSV文件,XML等。

Another nice tool to work with images is the url-loader loader.

另一个处理图像的好工具是url-loader loader。

This example loads any PNG file smaller than 8KB as a data URL.

本示例将小于8KB的任何PNG文件加载为数据URL 。

module.exports = {  /*...*/  module: {    rules: [      {        test: /\.png$/,        use: [          {            loader: 'url-loader',            options: {              limit: 8192            }          }        ]      }    ]  }  /*...*/}

处理您的SASS代码并将其转换为CSS (Process your SASS code and transform it to CSS)

Using sass-loader, css-loader and style-loader:

使用sass-loadercss-loaderstyle-loader

module.exports = {  /*...*/  module: {    rules: [      {        test: /\.scss$/,        use: [          'style-loader',          'css-loader',          'sass-loader'        ]      }    ]  }  /*...*/}

生成源地图 (Generate Source Maps)

Since Webpack bundles the code, Source Maps are mandatory to get a reference to the original file that raised an error. For example:

由于Webpack捆绑了代码,因此必须使用“源映射”才能获得对引发错误的原始文件的引用。 例如:

You tell Webpack to generate source maps using the devtool property of the configuration:

您告诉Webpack使用配置的devtool属性生成源映射:

module.exports = {  /*...*/  devtool: 'inline-source-map',  /*...*/}

devtool has many possible values, the most used probably are:

devtool有许多可能的值 ,最常用的是:

  • none: adds no source maps

    none :不添加源地图

  • source-map: ideal for production, provides a separate source map that can be minimized, and adds a reference into the bundle, so development tools know that the source map is available. Of course you should configure the server to avoid shipping this, and just use it for debugging purposes

    source-map :非常适合生产,提供可以最小化的单独的源映射,并在捆绑包中添加引用,因此开发工具知道该源映射可用。 当然,您应该配置服务器以避免运送它,而仅将其用于调试目的

  • inline-source-map: ideal for development, inlines the source map as a Data URL

    inline-source-map :非常适合开发,将源映射作为数据URL内联

I publish 1 free programming tutorial per day on flaviocopes.com, check it out!

我每天在flaviocopes.com上发布1个免费的编程教程,请查看!

Originally published at flaviocopes.com.

最初发布于flaviocopes.com 。

翻译自: https://www.freecodecamp.org/news/a-beginners-introduction-to-webpack-2620415e46b3/

Webpack初学者介绍相关推荐

  1. React with Webpack -1: 介绍Helloworld

    React with Webpack -1: 介绍&Helloworld node.js 开发之react 学习1 context:node.js 开发的工具和lib发展的很快,in othe ...

  2. 透视前端工程化之 Webpack 基本介绍【文末有彩蛋~】

    1 Webpack 的特点 图片来源于网络 Webpack 是一款强大的打包工具.在 Webpack 中一切皆模块.Webpack 官网的 Banner 图完美地诠释了这一理念.Webpack 从一个 ...

  3. webpack笔记一:webpack的介绍,安装,加载css、图片、字体等

    写在前面的话: 在当前grunt.gulp.webpack成为日常工具的情况下,如果你还只是熟练的使用html.css和激块瑞的话,已经远远不能满足项目的需求,所以你得变强,你需要懂得更多.现在前端不 ...

  4. linux命令之tee,技术|为初学者介绍的 Linux tee 命令(6 个例子)

    有时候,你会想手动跟踪命令的输出内容,同时又想将输出的内容写入文件,确保之后可以用来参考.如果你想寻找这相关的工具,那么恭喜你,Linux 已经有了一个叫做 tee 的命令可以帮助你. 本教程中,我们 ...

  5. webpack — 概述介绍

    webpack概述 webpack是一个流行的前端项目构建工具(打包工具),可以解决当前web 开发中所面临的困境. webpack提供了友好的模块化支持,以及代码压缩混淆.处理js兼容问题.性能优化 ...

  6. 为初学者介绍10个最常被问到的Javascript问题

    在本文中,我收集了关于Javascript 最常被问到的 10 个问题及其答案. 它们大多涉及 Javascript 的基础知识,所以如果你刚刚开始学习 JS,最好理解并掌握它们并. 这个 10 问题 ...

  7. webpack初学者第一版

    webpack的配置信息 nrm的使用 npm i nrm -g 全局安装nrm(提供常用的下载包地址,真正使用的装包工具还是npm) nrm ls 查看清单列表(查看镜像地址,所谓镜像地址,就是从[ ...

  8. 给Angular初学者介绍一个非常方便的例子学习网站

    网址:https://angular.io/generated/live-examples/getting-started-v0/stackblitz.html 这个网站打开后,是一个已经开发好的An ...

  9. 前端学习(2137):webpack的介绍和安装

最新文章

  1. MYSQL5 表列更名删除等操作测试(更新中...)
  2. P03: 多重背包问题
  3. 在Windows IoT上使用网络摄像头
  4. jquery常见的选择器
  5. dvwa如何打开_一篇文章让你搭建自己的Web安全测试平台(Dvwa)
  6. linux top p 乱码,将Linux top命令输入到指定文件时的乱码问题
  7. Win10上rabbitmq 安装
  8. docker mysql总是退出_docker 安装 mysql
  9. 谷歌这波操作,预警了什么信号??
  10. JavaScript实现斐波那契数列(Febonacci Array)
  11. JavaScript中的try...catch...finally
  12. 小升初数学计算机考试题,重点中学小升初数学分班考试模拟试卷试题及解析总结计划-20210513100212.docx-原创力文档...
  13. Clear Type技术
  14. 1688商品类目API接口-(item_cat_get-获得1688商品类目接口)
  15. 同一局域网内怎样获取新来美眉QQ号码!((*^__^*) 嘻嘻……)
  16. 微信记录删了,怎么恢复找回来?5种攻略推荐
  17. 计算机发展趋势 网络化,计算机的发展趋势表现在多极化网络化等几个方面
  18. 健身记录--每日更新
  19. IMX.6ULL_Linux_基础篇(6) soc资源介绍
  20. 2020-4-22 深度学习笔记20 - 深度生成模型 5 (有向生成网络--sigmoid信念网络/可微生成器网络/变分自编码器VAE/生产对抗网络GAN/生成矩匹配网络)

热门文章

  1. 【面试总结】java测试工程师培训
  2. 从草根到百万年薪程序员的十年风雨之路,使用指南
  3. 在线视频常见加密方式及安全性透析
  4. STM32F013 十元板
  5. 1、Linux命令随笔
  6. 命令行窗口常用的一些小技巧
  7. 推荐几款热门的敏捷开发工具
  8. HDU 5102 The K-th Distance
  9. 11个JavaScript颜色选择器插件
  10. 项目进行JVM调优 Jconsole