webpack 4 is out!

The popular module bundler gets a massive update.

webpack 4, what’s new? A massive performance improvement, zero configuration and sane defaults.

This is a living, breathing introduction to webpack 4. Constantly updated.

You’ll build a working webpack 4 environment by following each section in order. But feel free to jump over the tutorial!

Table of Contents

webpack 4 as a zero configuration module bundler

webpack is powerful and has a lot of unique features but one of its pain point is the configuration file.

Providing a configuration for webpack is not a big deal in medium to bigger projects. You can’t live without one. Yet, for smaller ones it’s kind of annoying, especially when you want to kickstart some toy app.

That’s why Parcel gained a lot of traction.

Here’s the breaking news now: webpack 4 doesn’t need a configuration file by default!

Let’s try that out.

webpack 4: getting started with zero conf

Create a new directory and move into it:

  1. mkdir webpack-4-quickstart && cd $_

Initialize a package.json by running:

  1. npm init -y

and pull webpack 4 in:

  1. npm i webpack --save-dev

We need webpack-cli also, which lives as a separate package:

  1. npm i webpack-cli --save-dev

Now open up package.json and add a build script:

  1. "scripts": {
  2. "build": "webpack"
  3. }

Close the file and save it.

Try to run:

  1. npm run build

and see what happens:

  1. ERROR in Entry module not found: Error: Can't resolve './src' in '~/webpack-4-quickstart'

webpack 4 is looking for an entry point in ./src! If you don’t know what that means go check out my previous article on switching from Gulp to webpack.

In brief: the entry point is the file webpack looks for to start building your Javascript bundle.

In the previous version of webpack the entry point has to be defined inside a configuration file named webpack.config.js.

But starting from webpack 4 there is no need to define the entry point: it will take ./src/index.js as the default!

Testing the new feature is easy. Create ./src/index.js:

  1. console.log(`I'm a silly entry point`);

and run the build again:

  1. npm run build

You will get the bundle in ~/webpack-4-quickstart/dist/main.js.

What? Wait a moment. There is no need to define the output file? Exactly.

In webpack 4 there is no need to define neither the entry point, nor the output file.

webpack’s main strength is code splitting. But trust me, having a zero configuration tool speeds things up.

So here is the first news: webpack 4 doesn’t need a configuration file.

It will look in ./src/index.js as the default entry point. Moreover, it will spit out the bundle in ./dist/main.js.

In the next section we’ll see another nice feature of webpack 4: production and development mode.

webpack 4: production and development mode

Having 2 configuration files is a common pattern in webpack.

A tipical project may have:

  • a configuration file for development, for defining webpack dev server and other stuff
  • a configuration file for production, for defining UglifyJSPlugin, sourcemaps and so on

While bigger projects may still need 2 files, in webpack 4 you can get by without a single line of configuration.

How so?

webpack 4 introduces production and development mode.

In fact if you pay attention at the output of npm run buildyou’ll see a nice warning:

The ‘mode’ option has not been set. Set ‘mode’ option to ‘development’ or ‘production’ to enable defaults for this environment.

What does that mean? Let’s see.

Open up package.json and fill the script section like the following:

  1. "scripts": {
  2. "dev": "webpack --mode development",
  3. "build": "webpack --mode production"
  4. }

Now try to run:

  1. npm run dev

and take a look at ./dist/main.js. What do you see? Yes, I know, a boring bundle… not minified!

Now try to run:

  1. npm run build

and take a look at ./dist/main.js. What do you see now? A minified bundle!

Yes!

Production mode enables all sorts of optimizations out of the box. Including minification, scope hoisting, tree-shaking and more.

Development mode on the other hand is optimized for speed and does nothing more than providing an un-minified bundle.

So here is the second news: webpack 4 introduces production and development mode.

In webpack 4 you can get by without a single line of configuration! Just define the --modeflag and you get everything for free!

webpack 4: overriding the defaults entry/output

I love webpack 4 zero conf but how about overriding the default entry point? And the default output?

Configure them in package.json!

Here’s an example:

  1. "scripts": {
  2. "dev": "webpack --mode development ./foo/src/js/index.js --output ./foo/main.js",
  3. "build": "webpack --mode production ./foo/src/js/index.js --output ./foo/main.js"
  4. }

webpack 4: transpiling Javascript ES6 with Babel

Modern Javascript is mostly written in ES6.

But not every browser know how to deal with ES6. We need some kind of transformation.

This transformation step is called transpiling. Transpiling is the act of taking ES6 and making it understandable by older browsers.

Webpack doesn’t know how to make the transformation but has loaders: think of them as of transformers.

babel-loader is the webpack loader for transpiling ES6 and above, down to ES5.

To start using the loader we need to install a bunch of dependencies. In particular:

  • babel-core
  • babel-loader
  • babel-preset-env for compiling Javascript ES6 code down to ES5

Let’s do it:

  1. npm i babel-core babel-loader babel-preset-env --save-dev

Next up configure Babel by creating a new file named .babelrc inside the project folder:

  1. {
  2. "presets": [
  3. "env"
  4. ]
  5. }

At this point we have 2 options for configuring babel-loader:

  • using a configuration file for webpack
  • using --module-bindin your npm scripts

Yes, I know what you’re thinking. webpack 4 markets itself as a zero configuration tool. Why would you write a configuration file again?

The concept of zero configuration in webpack 4 applies to:

  • the entry point. Default to ./src/index.js
  • the output. Default to ./dist/main.js
  • production and development mode (no need to create 2 separate confs for production and development)

And it’s enough. But for using loaders in webpack 4 you still have to create a configuration file.

I’ve asked Sean about this. Will loaders in webpack 4 work the same as webpack 3? Is there any plan to provide 0 conf for common loaders like babel-loader?

His response:

“For the future (after v4, maybe 4.x or 5.0), we have already started the exploration of how a preset or addon system will help define this. What we don’t want: To try and shove a bunch of things into core as defaults What we do want: Allow other to extend”

For now you must still rely on webpack.config.js. Let’s take a look…

webpack 4: using babel-loader with a configuration file

Give webpack a configuration file for using babel-loader in the most classical way.

Create a new file named webpack.config.jsand configure the loader:

  1. module.exports = {
  2. module: {
  3. rules: [
  4. {
  5. test: /\.js$/,
  6. exclude: /node_modules/,
  7. use: {
  8. loader: "babel-loader"
  9. }
  10. }
  11. ]
  12. }
  13. };

There is no need to specify the entry point unless you want to customize it.

Next up open ./src/index.js and write some ES6:

  1. const arr = [1, 2, 3];
  2. const iAmJavascriptES6 = () => console.log(...arr);
  3. window.iAmJavascriptES6 = iAmJavascriptES6;

Finally create the bundle with:

  1. npm run build

Now take a look at ./dist/main.js to see the transpiled code.

webpack 4: using babel-loader without a configuration file

There is another method for using webpack loaders.

The --module-bindflag lets you specify loaders from the command line. Thank you Cezar for pointing this out.

The flag is not webpack 4 specific. It was there since version 3.

To use babel-loader without a configuration file configure your npm scripts in package.json like so:

  1. "scripts": {
  2. "dev": "webpack --mode development --module-bind js=babel-loader",
  3. "build": "webpack --mode production --module-bind js=babel-loader"
  4. }

And you’re ready to run the build.

I’m not a fan of this method (I don’t like fat npm scripts) but it is interesting nonetheless.

webpack 4: setting up webpack 4 with React

That’s easy once you’ve installed and configured babel.

Install React with:

  1. npm i react react-dom --save-dev

Next up add babel-preset-react:

  1. npm i babel-preset-react --save-dev

Configure the preset in .babelrc:

  1. {
  2. "presets": ["env", "react"]
  3. }

and you’re good to go!

To test things out you can create a dummy React component in ./src/App.js:

  1. import React from "react";
  2. import ReactDOM from "react-dom";
  3. const App = () => {
  4. return (
  5. <div>
  6. <p>React here!</p>
  7. </div>
  8. );
  9. };
  10. export default App;
  11. ReactDOM.render(<App />, document.getElementById("app"));

Next up import the component in ./src/index.js:

  1. import App from "./App";

and run the build again.

webpack 4: the HTML webpack plugin

webpack needs two additional components for processing HTML: html-webpack-plugin and html-loader.

Add the dependencies with:

  1. npm i html-webpack-plugin html-loader --save-dev

Then update the webpack configuration:

  1. const HtmlWebPackPlugin = require("html-webpack-plugin");
  2. module.exports = {
  3. module: {
  4. rules: [
  5. {
  6. test: /\.js$/,
  7. exclude: /node_modules/,
  8. use: {
  9. loader: "babel-loader"
  10. }
  11. },
  12. {
  13. test: /\.html$/,
  14. use: [
  15. {
  16. loader: "html-loader",
  17. options: { minimize: true }
  18. }
  19. ]
  20. }
  21. ]
  22. },
  23. plugins: [
  24. new HtmlWebPackPlugin({
  25. template: "./src/index.html",
  26. filename: "./index.html"
  27. })
  28. ]
  29. };

Next up create an HTML file into ./src/index.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>webpack 4 quickstart</title>
  6. </head>
  7. <body>
  8. <div id="app">
  9. </div>
  10. </body>
  11. </html>

run the build with:

  1. npm run build

and take a look at the ./distfolder. You should see the resulting HTML.

There’s no need to include your Javascript inside the HTML file: the bundle will be automatically injected.

Open up ./dist/index.htmlin your browser: you should see the React component working!

As you can see nothing has changed in regards of handling HTML.

webpack 4 is still a module bundler aiming at Javascript.

But there are plans for adding HTML as a module (HTML as an entry point).

webpack 4: extracting CSS to a file

webpack doesn’t know to extract CSS to a file.

In the past it was a job for extract-text-webpack-plugin.

Unfortunately said plugin does not play well with webpack 4.

According to Michael Ciniawsky:

extract-text-webpack-plugin reached a point where maintaining it become too much of a burden and it’s not the first time upgrading a major webpack version was complicated and cumbersome due to issues with it

mini-css-extract-plugin is here to overcome those issues.

NOTE: Make sure to update webpack to version 4.2.0. Otherwise mini-css-extract-plugin won’t work!

Install the plugin and css-loader with:

  1. npm i mini-css-extract-plugin css-loader --save-dev

Next up create a CSS file for testing things out:

  1. /* */
  2. /* CREATE THIS FILE IN ./src/main.css */
  3. /* */
  4. body {
  5. line-height: 2;
  6. }

Configure both the plugin and the loader:

  1. const HtmlWebPackPlugin = require("html-webpack-plugin");
  2. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  3. module.exports = {
  4. module: {
  5. rules: [
  6. {
  7. test: /\.js$/,
  8. exclude: /node_modules/,
  9. use: {
  10. loader: "babel-loader"
  11. }
  12. },
  13. {
  14. test: /\.html$/,
  15. use: [
  16. {
  17. loader: "html-loader",
  18. options: { minimize: true }
  19. }
  20. ]
  21. },
  22. {
  23. test: /\.css$/,
  24. use: [MiniCssExtractPlugin.loader, "css-loader"]
  25. }
  26. ]
  27. },
  28. plugins: [
  29. new HtmlWebPackPlugin({
  30. template: "./src/index.html",
  31. filename: "./index.html"
  32. }),
  33. new MiniCssExtractPlugin({
  34. filename: "[name].css",
  35. chunkFilename: "[id].css"
  36. })
  37. ]
  38. };

Finally import the CSS in the entry point:

  1. //
  2. // PATH OF THIS FILE: ./src/index.js
  3. //
  4. import style from "./main.css";

run the build:

  1. npm run build

and take a look in the ./dist folder. You should see the resulting CSS!

To recap: extract-text-webpack-plugin does not work with webpack 4. Use mini-css-extract-plugin instead.

webpack 4 : the webpack dev server

Running npm run devwhenever you make changes to your code? Far from ideal.

It takes just a minute to configure a development server with webpack.

Once configured webpack dev server will launch your application inside a browser.

It will automagically refresh the browser’s window as well, every time you change a file.

To set up webpack dev server install the package with:

  1. npm i webpack-dev-server --save-dev

Next up open package.jsonand adjust the scripts like the following:

  1. "scripts": {
  2. "start": "webpack-dev-server --mode development --open",
  3. "build": "webpack --mode production"
  4. }

Save and close the file.

Now, by running:

  1. npm run start

you’ll see webpack dev server launching your application inside the browser.

webpack dev server is great for development. (And it makes React Dev Tools work properly in your browser).

Stay tuned! More coming soon…

Webpack 4 Tutorial: from 0 Conf to Production Mode的更多相关文章

  1. webpack 4 :从0配置到项目搭建

    webpack4发布以来,我写项目都是用脚手架,即使再简单的项目,真的是really shame..虽然道听途说了很多 webpack4 的特性,却没有尝试过,因为它给人的感觉就是,em...很难.但 ...

  2. nginx: [emerg] unknown directive "聽" in D:\software03\GitSpace\cms\nginx-1.14.0/conf/nginx.conf:36

    nginx: [emerg] unknown directive "聽" in D:\software03\GitSpace\cms\nginx-1.14.0/conf/nginx ...

  3. webpack前端构建angular1.0!!!

    webpack前端构建angular1.0 Webpack最近很热,用webapcak构建react,vue,angular2.0的文章很多,但是webpack构建angualr1.0的文章找来找去也 ...

  4. unknown directive "" in E:\canteen\nginx-1.16.0/conf/nginx.conf:3-------文本编辑器修改nginx配置文件的坑

    nignx小白一个,今天在配置nginx的时候,理所当然的用了文本编辑器编辑并保存了一下nginx的nginx.conf配置文件,一不小心就折腾了几个钟. 保存之后就nginx -s reload一下 ...

  5. Caused by: org.xml.sax.SAXParseException; systemId: file:/home/hadoop/hive-0.12.0/conf/hive-site.xml; lineNumber: 5; columnNumber: 2; The markup in the document following the root element must be well

    1:Hive安装的过程(Hive启动的时候报的错误),贴一下错误,和为什么错,以及解决方法: [root@master bin]# ./hive // :: INFO Configuration.de ...

  6. Windows环境下执行hadoop命令出现Error: JAVA_HOME is incorrectly set Please update D:\SoftWare\hadoop-2.6.0\conf\hadoop-env.cmd错误的解决办法(图文详解)

    不多说,直接上干货! 导读   win下安装hadoop 大家,别小看win下的安装大数据组件和使用  玩过dubbo和disconf的朋友们,都知道,在win下安装zookeeper是经常的事   ...

  7. 从0开始搭建vue+webpack脚手架(四)

    之前1-3部分是webpack最基本的配置, 接下来会把项目结构和配置文件重新设计,可以扩充更多的功能模块. 一.重构webpack的配置项 1. 新建目录build,存放webpack不同的配置文件 ...

  8. webpack@3.6.0(1) -- 快速开始

    本篇内容 前言 配置入口和输出 热更新 loader配置 js代码压缩 html的打包与发布 前言 //全局安装 npm install -g webpack(3.6.0) npm init //安装 ...

  9. webpack入门级 - 从0开始搭建单页项目配置

    前言 webpack 作为前端最知名的打包工具,能够把散落的模块打包成一个完整的应用,大多数的知名框架 cli 都是基于 webpack 来编写.这些 cli 为使用者预设好各种处理配置,使用多了就会 ...

随机推荐

  1. 真正理解拉格朗日乘子法和 KKT 条件

        这篇博文中直观上讲解了拉格朗日乘子法和 KKT 条件,对偶问题等内容.     首先从无约束的优化问题讲起,一般就是要使一个表达式取到最小值: \[min \quad f(x)\]     如 ...

  2. linux系统下的SVN安装

    1.直接安装 # sudo apt-get install subversion 2. 创建版本库 # sudo mkdir /home/svn # sudo svnadmin create /hom ...

  3. 参加Java培训到底靠不靠谱?

    导读 科技越发展,社会越进步,人们越便利,便衍生出更多的人从事程序员这个高大上的职业,可哈尔滨Java培训学校这么多,到底靠不靠谱,会不会处处是陷阱,爱尚实训帮你擦亮眼 随着时代的发展,越来越多的人对 ...

  4. 网络流入门-POJ1459PowerNetwork-Dinic模板

    (我有什么错误或者你有什么意见,欢迎留言或私聊!谢谢!) (Ps:以前听说过网络流,想着以后再学,这次中南多校赛也碰到有关网络流的题目,想着这两天试着学学这个吧~~ 这是本人网络流入门第二题,不知道怎 ...

  5. 关于Goldwell平台推出赠金及手数奖励

    关于Goldwell平台推出赠金及手数奖励 Goldwell平台是一家拥有30多年现货黄金经验平台,平台位于柬埔寨金边,是一家国际衍生品的经纪公司.Goldwell平台它对柬埔寨金融市场和客户绝对的承 ...

  6. WebRTC 音频采样算法 附完整C++示例代码

    之前有大概介绍了音频采样相关的思路,详情见<简洁明了的插值音频重采样算法例子 (附完整C代码)>. 音频方面的开源项目很多很多. 最知名的莫过于谷歌开源的WebRTC, 其中的音频模块就包 ...

  7. [CQOI 2015]选数

    Description 我们知道,从区间[L,H](L和H为整数)中选取N个整数,总共有(H-L+1)^N种方案.小z很好奇这样选出的数的最大公约数的规律,他决定对每种方案选出的N个整数都求一次最大公 ...

  8. [HNOI 2001]产品加工

    Description 某加工厂有A.B两台机器,来加工的产品可以由其中任何一台机器完成,或者两台机器共同完成.由于受到机器性能和产品特性的限制,不同的机器加工同一产品所需的时间会不同,若同时由两台机 ...

  9. 【模板】KMP字符串匹配

    题目描述 如题,给出两个字符串s1和s2,其中s2为s1的子串,求出s2在s1中所有出现的位置. 为了减少骗分的情况,接下来还要输出子串的前缀数组next. (如果你不知道这是什么意思也不要问,去百度 ...

  10. 例10-11 uva11181

    题意:n个人去逛超市,第i个人买东西的概率是pi,,计算每个人实际买了东西的概率 思路: 搜索标处理所以的情况,得出所有概率和all(开始天真的以为是1 - -,就说怎么案例看着怪怪的),用tt[i] ...