Webpack初学者介绍

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 mode

    Webpack在生产模式下工作

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值