webpack 入门

During application development, building parts of your application as modules helps improve reusability, and readability. With the rise of frontend frameworks like React, Angular 2, and Vue that hit on the point of building modules, compiling these modules has become quite essential too.

在应用程序开发过程中,将应用程序的各个部分构建为模块有助于提高可重用性和可读性。 随着诸如React,Angular 2和Vue之类的前端框架的兴起,人们纷纷开始构建模块,编译这些模块也变得至关重要。

什么是Webpack? ( What is Webpack? )

Webpack in it's simplest form is a module bundler. This means that webpack takes modules with dependencies and generates static assets representing those modules.

最简单形式的Webpack是模块捆绑器。 这意味着webpack会获取具有依赖性的模块,并生成代表这些模块的静态资产。

Still on the topic of bundling, here on Scotch, Peleke wrote an article on browserify — another module bundler.

还是关于捆绑的话题,在这里苏格兰, Peleke写了一篇文章browserify -另一个模块捆绑。

What makes webpack so different from other module bundlers is the fact that it has watched other module bundlers and seen areas that needed improvements.

使webpack与其他模块捆绑软件如此不同的原因在于,它已经观察了其他模块捆绑软件并看到了需要改进的地方。

Webpack understands that CSS and images are also dependencies and treats them as such. To that end, WebPack is not just another module bundler — but offers a plethora of features we use as developers.

Webpack了解CSS和图像也是依赖项,因此将它们视为依赖项。 为此,WebPack不仅是另一个模块捆绑器,而且还提供了我们用作开发人员的大量功能。

Webpack的目标 (Goals of Webpack)

As stated from the main webpack site, the main goals of creating another module bundler are the abilities to:

正如从主要webpack网站所说的那样,创建另一个模块捆绑器的主要目标是能够:

  • Split the dependency tree into chunks loaded on demand将依赖关系树拆分为按需加载的块
  • Keep initial loading time low保持较低的初始加载时间
  • Every static asset should be able to be a module每个静态资产都应该能够成为一个模块
  • Ability to integrate 3rd-party libraries as modules能够将第三方库集成为模块
  • Ability to customize nearly every part of the module bundler能够自定义模块捆绑器的几乎每个部分
  • Suited for big projects适合大型项目

安装Webpack ( Installing Webpack )

As an npm dependency, we can install webpack using npm. So from the command line install webpack using this command.

作为npm依赖性,我们可以使用npm安装webpack。 因此,从命令行使用此命令安装webpack。

@media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }} @media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }}

npm install -g webpack

This will install webpack on your command line and make it available anywhere. To test if webpack was successfully installed, open a terminal and type webpack. You should get something like this.

这将在您的命令行上安装webpack并使其在任何地方都可用。 要测试是否成功安装了webpack,请打开终端并输入webpack 。 你应该得到这样的东西。

webpack 1.13.2
Usage: https://webpack.github.io/docs/cli.html

首次使用Webpack运行 ( First run with Webpack )

Let's create a working directory named webpack. In our project folder, we create an index.html and add this little boilerplate.

让我们创建一个名为webpack的工作目录。 在我们的项目文件夹中,我们创建一个index.html并添加这个小样板。

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Getting Started with Webpack</title>
</head>
<body><h1>WebPack is fun</h1>
</body>
</html>

Next, we create a main.js file, and we can add a simple console.log statement to our newly created file.

接下来,我们创建一个main.js文件,并且可以向我们新创建的文件中添加一个简单的console.log语句。

console.log('Hello from Webpack');

From the root of our working directory, run.

从工作目录的根目录运行。

webpack main.js bundle.js

When it is done, you should see a message like this in the command line.

完成后,您应该在命令行中看到类似这样的消息。

Hash: b882f8dcc15e61b5124e
Version: webpack 1.13.2
Time: 75msAsset     Size  Chunks             Chunk Names
bundle.js  1.42 kB       0[emitted]  main[0] ./main.js 34 bytes {0} [built]

If you check out the newly created bundle.js, you will see that webpack has created some wrapper around our own code. Because of this inclusion, we can use AMD syntax or requirejs to load javascript files.

如果您检出新创建的bundle.js ,则会看到webpack已围绕我们自己的代码创建了一些包装器。 由于包含了这些内容,因此我们可以使用AMD语法或requirejs加载javascript文件。

定义配置文件 ( Defining a Config File )

While we could go ahead and keep running things from the command line, our builds are going to become more and more complex. As we bring in more JS modules, CSS, and things like TypeScript/ES6 and Sass, we'll want a more robust way of running Webpack.

虽然我们可以继续并从命令行继续运行,但是我们的构建将变得越来越复杂。 随着我们引入更多的JS模块,CSS以及诸如TypeScript / ES6和Sass之类的东西,我们将需要一种更健壮的方式来运行Webpack。

This is where a config file comes into play.

这是配置文件起作用的地方。

Before we create a config file, you need to understand that webpack operates on the principle of an entry point and an output location, just like the command we ran above.

在创建配置文件之前,您需要了解webpack会根据入口点和输出位置的原理进行操作 ,就像上面运行的命令一样。

The webpack command line option takes in two params: the entry and the output.

webpack命令行选项接受两个参数: entryoutput

To create a config file, in the root of our working directory, we create a webpack.config.js. This file exports our project's webpack configuration object.

要创建配置文件,请在工作目录的根目录中创建一个webpack.config.js 。 该文件导出我们项目的webpack配置对象。

module.exports = {entry: './main.js',output: {filename: './bundle.js'}
};

Now from the root of our application, we can just run webpack and still have the same result.

现在,从应用程序的根目录开始,我们可以运行webpack并保持相同的结果。

留意变化 ( Watching For Changes )

One thing we developers hate is to do the same task over and over again. So, we tend to create shortcuts for ourselves. Instead of typing webpack in the command line whenever we bundle our code, we can instead watch for changes. This allows us to change a piece of code in our editor and automatically have it compiled.

开发人员讨厌的一件事是一遍又一遍地执行相同的任务。 因此,我们倾向于为自己创建快捷方式。 无需在捆绑代码时在命令行中键入webpack ,而是可以监视更改。 这使我们可以在编辑器中更改一段代码并自动对其进行编译。

Webpack provides two methods for watching for a file change. The first one is using the command line.

Webpack提供了两种监视文件更改的方法。 第一个是使用命令行。

webpack --watch

Or

要么

webpack -w

As soon as you run this command, webpack will watch your project for any change, and when a change happens it basically reruns the webpack command.

一旦运行此命令,webpack就会监视您的项目是否有任何更改,并且当发生更改时,它基本上会重新运行webpack命令。

配置“监视模式” (Configuring "watchmode")

This is the second method that tells webpack to watch for the code for change. You can configure webpack to automatically watch the project directory whenever webpack is run. To do this, open your configuration file and set a new config attribute named watch to true.

这是第二种告诉webpack监视更改代码的方法。 您可以配置的WebPack自动腕表只要项目目录webpack运行。 为此,请打开您的配置文件,并将名为watch的新配置属性设置为true。

module.exports = {entry: './main.js',output: {filename: './bundle.js'},watch: true
};

装载机 ( Loaders )

Out of the box, webpack only knows how to read and understand .js files. Since webpack only knows how to speak .js, we need loaders to teach webpack some new tricks.

开箱即用,webpack只知道如何阅读和理解.js文件。 由于webpack只会说.js ,因此我们需要加载程序来教webpack一些新技巧。

Loaders teach webpack how to load files for bundling. Let me explain, if you use a preprocessor like SASS, webpack needs to be taught how to convert SASS code to CSS, and this is where a loader comes in. We'll also need a loader for CSS.

加载程序教webpack如何加载文件进行捆绑。 让我解释一下,如果您使用像SASS这样的预处理器,则需要教webpack如何将SASS代码转换为CSS,这就是装入程序的来源。我们还需要CSS装入程序。

This also allows for a lot of flexibility in webpack, as we can also create our own loaders. The community has already gone ahead and created a long list of loaders.

由于我们还可以创建自己的加载程序,因此这也为webpack提供了很大的灵活性。 该社区已经取得了进展,并创建了很多装载机 。

Since loaders are not added to webpack by default as it will make webpack bloated with a lot of dependencies, we need to npm install any loader required by our project.

由于默认情况下未将加载程序添加到webpack,因为它将使webpack膨胀,并具有很多依赖关系,因此我们需要npm install项目所需的任何加载程序。

NOTE: Make sure your project has a package.json file, if you don't have one or don't know how to create one, just run npm init from the root of the project.

注意:确保您的项目有一个package.json文件,如果您没有一个文件或不知道如何创建一个文件,只需从项目的根目录运行npm init

加载JavaScript (Loading JavaScript)

Nowadays, a lot of people are beginning to write javascript using es6 standard(ES2015). Since browser support is still low, we use third party transpiler like babel to convert our code to old JavaScript syntax.

如今,许多人开始使用es6标准(ES2015)编写javascript。 由于浏览器支持仍然很低,我们使用像babel这样的第三方编译器将代码转换为旧JavaScript语法。

So for us to be able to use webpack to convert our code, we need to install babel-loader. In this case, the babel loader depends on babel-core. Finally, since we want to convert from ES2015 or es6 to plain old es5 we need to tell babel what preset to use. For this, we also need a babel-preset-2015.

因此,要使我们能够使用webpack转换代码,我们需要安装babel-loader 。 在这种情况下,babel加载程序取决于babel-core 。 最后,由于我们想从ES2015或es6转换为普通的旧es5,我们需要告诉babel使用什么预设。 为此,我们还需要babel-preset-2015

So we can install these dependencies using:

因此,我们可以使用以下命令安装这些依赖项:

npm install --save-dev babel-loader babel-core babel-preset-es2015

Now in our webpack config file, we can add our module loader.

现在,在我们的webpack配置文件中,我们可以添加模块加载器。

module.exports = {// ...module: {loaders: [{test: /\.js$/,exclude: /node_modules/,loader: 'babel',query: {presets: ['es2015']}}],}
};

As you can see, the module/loaders is an array of objects that test for a particular file and runs it through a loader. In this case, we checked for any file that ends with .js, we excluded any file in node_modules directory, any matched file should be run through the babel loader, and finally, tell babel to use es2015 preset.

如您所见, 模块/加载器是一组对象,用于测试特定文件并通过加载器运行它。 在这种情况下,我们检查了以.js结尾的任何文件,排除了node_modules目录中的任何文件,任何匹配的文件都应通过babel loader运行,最后,告诉babel使用es2015预设。

So, we can change our main.js file to look like this:

因此,我们可以将main.js文件更改为如下所示:

const name = 'Scotch.io';setTimeout(() => alert(`Hello there from ${name}`), 300);

Then we run our webpack command again. After running this command, we link to the bundle.js file in our index.html. We open our index file in the browser, and after 300ms, we get an alert with the message "Hello there from Scotch.io".

然后,我们再次运行webpack命令。 运行此命令后,我们链接到index.html中bundle.js文件。 我们在浏览器中打开索引文件,并在300毫秒后收到一条消息“您好,来自Scotch.io”的警报。

载入CSS (Loading CSS)

Loaders can be chained. This means we can use more than one loader on a particular file. There are two ways we can chain webpack loaders: the first is using an exclamation mark to separate loaders, while the other method is passing an array of loaders.

装载机可以链接 。 这意味着我们可以在一个特定文件上使用多个加载程序。 我们可以使用两种方法链接Webpack加载程序:第一种方法是使用感叹号分隔加载程序,而第二种方法则传递一组加载程序。

NOTE: Loaders are processed RTL (right to left).

注意:加载程序是经过处理的RTL(从右到左)。

Using webpack to load CSS requires two loaders: css-loader and style-loader. The first loader loads the content of a CSS file, whilst the second loader injects the CSS into the page.

使用webpack加载CSS需要两个加载器: css-loader和style-loader 。 第一个加载器加载CSS文件的内容,而第二个加载器将CSS注入页面。

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

After installing the loaders, we can then tell webpack to process our css file like this.

安装加载程序后,我们可以告诉webpack这样处理css文件。

module.exports = {// ...module: {loaders: [{test: /\.css$/,exclude: /node_modules/,loader: 'style!css'}],}
};

As usual, any file that ends with .css and is not in node_modules directory should be processed. To actually get our css to the page, we need to require it.

像往常一样,应处理任何以.css结尾但不在node_modules目录中的文件。 要真正得到我们CSS页面,我们需要require它。

Our CSS main.css file looks like this.

我们CSS main.css文件如下所示。

h1 {color: red;
}

Edit main.js to look like this.

编辑main.js看起来像这样。

require('./main.css');const name = 'Scotch.io';setTimeout(() => console.log(`Hello there from ${name}`), 300);

From the root of our project, run webpack, and it should compile without any error.

从项目的根目录运行webpack ,它应该可以正确编译。

NOTE: css-loader can go as far as to get the content from css files in @import statements.

注意: css-loader可以从@import语句中的css文件中获取内容。

开发服务器 ( Development Server )

Similar to browsersync's live reload, webpack creates a dev server to easily check our code. The server listens for any change in your project and then injects that change into the browser. No more ctrl+r.

类似于browsersync的实时重新加载,webpack会创建一个开发服务器来轻松检查我们的代码。 服务器侦听项目中的任何更改,然后将更改注入浏览器。 没有更多的ctrl+r

To install the server, from the terminal execute:

要安装服务器,请从终端执行:

npm install webpack-dev-server -g

Now that it is installed, go to your project directory and run webpack-dev-server command.

现在已经安装了,转到您的项目目录并运行webpack-dev-server命令。

You should notice that the command doesn't stop running, it creates a buffer that waits for a user to change a piece of code. Also, the project will be available at http://localhost:8080/webpack-dev-server/.

您应该注意到该命令不会停止运行,它会创建一个缓冲区,等待用户更改一段代码。 此外,该项目将在http:// localhost:8080 / webpack-dev-server /上提供 。

优化Webpack输出 ( Optimizing Webpack Output )

Our final webpack bundle is not suitable for production, it has a lot of gunk comments and spaces. We all know that minification is good for getting scripts and styles ready for production. Don't worry, we won' t be installing another loader. For this particular reason, it makes more sense to use a webpack command to make our bundles production ready. Webpack went ahead and did just that. To get our bundle ready for production, from the root of our project, we can run:

我们最终的Webpack捆绑包不适合生产,它有很多乱七八糟的注释和空格。 我们都知道,缩小有助于使脚本和样式准备就绪。 不用担心,我们不会安装其他装载机。 由于这个特殊原因,使用webpack命令使我们的捆绑包生产准备就绪更为有意义。 Webpack继续这样做。 为了使我们的捆绑包准备好投入生产,从我们项目的根源开始,我们可以运行:

webpack -p

This command is short for webpack --optimize-minimize. After running this command, all our bundles will be minified.

该命令是webpack --optimize-minimize 。 运行此命令后,我们所有的捆绑包都会缩小。

WebPack的问题 ( Problems with WebPack )

IMHO, the only problem I see with webpack is the fact that trying to change your module bundler will definitely break your code. You will have to go into your project and change each place where you required a module.

恕我直言,我看到的webpack唯一的问题是,试图更改模块捆绑程序肯定会破坏您的代码。 您将必须进入项目并更改需要模块的每个位置。

This is not a big issue, more like a flimsy excuse as there is hardly any reason you might want to change an existing project's module bundler.

这不是一个大问题,更像是一个脆弱的借口,因为您几乎没有理由要更改现有项目的模块捆绑器。

结论 ( Conclusion )

Is webpack a replacement for module bundlers? The answer is yes and no. As we always say, "it boils down to personal preference". Use the right tool for the right job, if you prefer other module bundlers to webpack, stick with that.

webpack是否可以替代模块捆绑器? 答案是肯定的。 正如我们常说的,“归结为个人喜好”。 使用正确的工具完成正确的工作,如果您更喜欢其他模块捆绑工具来打包,请坚持使用。

If you want to automatically load CSS in addition to JS, have code splitting features, and an easy to setup config file, Webpack may be the right tool for your job.

如果您想除JS之外自动加载CSS,具有代码拆分功能以及易于设置的配置文件,Webpack可能是适合您的工作的工具。

翻译自: https://scotch.io/tutorials/getting-started-with-webpack-module-bundling-magic

webpack 入门

webpack 入门_Webpack入门:模块捆绑魔术相关推荐

  1. git 创建webpack项目_Webpack入门:从安装到配置

    文档 webpack 用于编译 JavaScript 模块. 一旦完成安装,你就可以通过 webpack 的 CLI 或 API 与其配合交互. 这里以入门者的角度(中文)介绍 webpack 的常用 ...

  2. webpack打包测试_webpack入门笔记(一)

    webpack 是一个现代 JavaScript 应用程序的静态模块打包器(module bundler).当 webpack 处理应用程序时,它会递归地构建一个依赖关系图(dependency gr ...

  3. vue(vue-cli+vue-router)+babel+webpack项目搭建入门(三)

    vue(vue-cli+vue-router)+babel+webpack项目搭建入门<三> 本系列文章将介绍基于vue+webpack的前端项目的构建过程.文章分为四章内容,第一章介绍开 ...

  4. vue(vue-cli+vue-router)+babel+webpack项目搭建入门 (第一步)

    vue(vue-cli+vue-router)+babel+webpack项目搭建入门<一> 本系列文章将介绍基于vue+webpack的前端项目的构建过程.文章分为四章内容,第一章介绍开 ...

  5. Webpack实战:入门、进阶与调优(第2版)

    你是否经常听到项目组的同事抱怨:"为什么Webpack这么慢?""为什么Webpack又出错了?" "发布到线上的代码为什么不能正常工作?" ...

  6. 新书推荐 |《Webpack实战:入门、进阶与调优》

    新书推荐 <Webpack实战:入门.进阶与调优> 长按二维码 了解及购买 资深前端工程师.Webpack技术专家.知名开源项目YKit主导者/核心开发者,从功能特性.工作原理.应用实践. ...

  7. spring 定时器设置停止_单片机MSP430入门-理论⑦--定时器模块-定时器A②

    单片机MSP430入门-理论⑦--定时器模块-定时器A② 上期大概给大家汇总介绍了,定时器模块中比较重要并且常用的定时器A,大概说了下定时器A的两种常用模式,比较模式和捕获模式 本期将继续介绍定时器A ...

  8. vue(vue-cli+vue-router)+babel+webpack项目搭建入门(四)

    vue(vue-cli+vue-router)+babel+webpack项目搭建入门<四> 本系列文章将介绍基于vue+webpack的前端项目的构建过程.文章分为四章内容,第一章介绍开 ...

  9. vue(vue-cli+vue-router)+babel+webpack项目搭建入门 (第二步)

    vue(vue-cli+vue-router)+babel+webpack项目搭建入门<二> 本系列文章将介绍基于vue+webpack的前端项目的构建过程.文章分为四章内容,第一章介绍开 ...

最新文章

  1. StringBuilder与 StringBuffer
  2. 3.4.3 后退N帧协议(GBN)
  3. Application 类 简介
  4. SVN项目,快速查看项目的当前版本号
  5. python把数据写入excel_Python读取和写入Excel文件(转)
  6. 【机器视觉】 dev_set_part算子
  7. 通过configuration隐藏product overview page上某些区域
  8. Laravel中的Blade模版
  9. 关于@Alias注解的几个问题
  10. [转]HSPICE软件的应用及常见问题解决
  11. linux下shell脚本编程2
  12. Node.js meitulu图片批量下载爬虫1.01版
  13. 通过时间序列分析预测未来广州的空气质量指数变化
  14. 本周开课 | 10年运营专家亲授,掌握9类运营的核心技能,强化运营实力
  15. 电容屏物体识别_触摸屏物体识别到底是怎么实现的
  16. 软件定制开发怎么收费
  17. 用vue实现打印页面的几种方法
  18. win10键盘全变成快捷键_(安卓)全键盘快捷键
  19. php 图片抠图,php 图像处理 抠图,生成背景透明png 图片
  20. 通过迅雷下载谷歌浏览器下载的内容

热门文章

  1. jQuery.prototype的含义。
  2. jsp网上图书销售管理系统ssh论文
  3. 有些话经典到让人受不了
  4. python 年月日转标准日期格式
  5. pandas数据的合并与拼接的实现
  6. 机器学习与R语言 多元线性回归insurance.R:保险费
  7. mac 语音召唤siri_如何让Siri在Mac上为您阅读文章
  8. html 去除li标签样式,CSS如何更改li标签样式?附源码!
  9. web 垂直对齐方式 vertical-align属性
  10. C++中对象和对象指针的区别