Webpack4 Tutorial: Part I, portals, inputs, and ES6 modules

Source: Internet
Author: User
Tags new set xquery

Please specify the Source: Grape City website, Grape City for developers to provide professional development tools, solutions and services, empowering developers.

Original source: wanago.io/2018/07/16/webpack-4-course-part-one-entry-output-and-es6-modules/

How are you doing! Today we will start a Webpack 4 introductory tutorial. We will start with the basic concept of webpack, as the tutorial progresses. This time, we will learn the basics of modularity with ES6 modules. Webpack 4 provides a default configuration, and we'll step through it. Let's get started!

Webpack 4 Tutorial Start-Wait, what is Webpack?

Before considering using any tool, you need to ask yourself a very important question: This tool solves your problem. Webpack is a module wrapper. This means that it is intended to merge a set of modules (depending on their dependencies). Its output may be one or more files. In addition to packaging modules, Webpack can do a variety of things with your files: For example, convert Scss to CSS, or convert typescript to JavaScript. It can even compress all your image files! But why do you really want to pack them?

The purpose of packaging

Long ago, in addition to using <script> tags, there was no other way to split the JavaScript used by the browser into multiple files. We need to put each JavaScript source file link in the HTML code. This is not convenient. The community has found some workarounds: CommonJS (implemented in node. js) and AMD. Here is an article about their introduction. In the end, ES6 introduced a new set of Import/export grammars.

ES6 Modules

The syntax of the module is defined in ES6. Thanks to it, we finally have the standard module form, which becomes part of the JavaScript language specification. This does not mean that browsers have a good support for this, but these are improving. Even with native support for the ES6 module, you might want to package multiple modules into fewer files. The purpose of this tutorial is to provide you with all the knowledge you need to get started with webpack, so let's simply look at the syntax of the ES6 module.

Export

export syntax is used to create JavaScript modules. You can use it to export objects (including functions) and original values (primitive value). It is important to note that the exported module uses strict mode. There are two types of exports:named and default.

Named Export

In a module, you can have multiple named exports.

// lib.jsexport function sum(a, b) { return a + b;}export function substract(a, b) { return a - b;}function divide(a, b) { return a / b;}export { divide };

Notice that if you want to export after the declaration, you need to wrap it up in curly braces, just like the function in the example above divide .

Default Export

A module that can have only one default export.

// dog.jsexport default class Dog { bark() { console.log('bark!'); }}
Import

Import statements are used for importing other modules.

Entire Import
// index.jsimport * as lib from './lib.js';console.log(lib.sum(1,2));console.log(lib.substract(3,1));console.log(lib.divide(6,3));

You can set any name for the exported module. If you import a module that contains the default export, the default export will be placed on a default property of the imported object.

// index.jsimport * as Dog from './dog.js';const dog = new Dog.default();dog.bark();
Import one or more named exports
// index.jsimport { sum, substract, divide } from './lib';console.log(sum(1,2));console.log(substract(3,1));console.log(divide(6,3));

It is important to note that the corresponding import and export names must match.

Import a default export
// index.jsimport Dog from './dog.js';const dog = new Dog();dog.bark(); // 'bark!'

Note that Defualt export can use any name when importing. So we can do this:

import Cat from './dog.js';const dog = new Cat();dog.bark(); // 'bark!'

The ES6 module also supports dynamic import, which we'll discuss in a future section.

You can view the MDN about the exported and imported documents.

The basic concept of webpack

Starting with version 4, Webpack does not require any configuration or can be used. It has a default set of values. If you want to create a configuration file, you can name it webpack.config.js . Let's now follow its default configuration and explain the basic concepts related to Webpack.

Webpack.config.js

Note that we use the node. JS environment to write the Webpack configuration file, so it uses the Commonjs type of module.

webpack.config.jsExports a separate object. If you run Webpack by command, it will go to find and use this file.

Entry

Webpack requires an entry starting point (entry points). It indicates which module the webpack starts packing from. Its default value is as follows:

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

It means that Webpack will find './src/index.js' this file and start packing from it. index.jsany imports you use in, Webpack will process them.

You can have more than one entry starting point, but for a single page applications, it usually has only one entry.

Output

Output is used to configure where the Webpack the output of your package. It is exported by default to './dist/main.js' .

// webpack.config.jsconst path = require('path');module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'main.js' }};
Run Webpack

In the previous section, we created the index.js function in which it was imported lib.js . Finally let's run Webpack! Remember to put these files in a src folder so that they match the default settings.

The first thing to do is to install Webpack. I'll use NPM to do it. Open your terminal and enter:

npm init -ynppm install webpack webpack-cli
Translator Note: As of translation, the Webpack version is 4.17.1. The original text did not add the webpack-cli behind. However, when you run Webpack for the first time, you will still be prompted to install WEBPACK-CLI or Webpack-command. All here select Webpack-cli to install in advance. The effect is the same as the previous installation.

This creates the Node_modules folder, which contains the webpack. There are also two files package.json and package-lock.json .

If you want to know more about the dependencies in Package-lock.json and NPM, you can view keeping you dependencies in the order when using NPM.

Now open the package.json file and modify it:

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

As a result of the above changes, the run npm run build will use node_modules the Webpack under the folder.

As you can see, a main.js file dist is created under the folder. It contains all the index.js code from and lib.js .

Multiple Entry Beginnings

Without any configuration, you can implement the features described above. If you want to do more, now is the time to create the configuration file.

Entries

The entry property in the configuration file must not necessarily be a string. If you want to have multiple portals, you can use an object:

// webpack.config.jsmodule.exports = {  entry: {    first: './src/one.js', second: './src/two.js' }}

Using the above code, we created two entry beginnings. If you are developing a multi-page application (multi-page application), you can need it.

Outputs

This has a problem: By default, only one output is specified. We can easily modify it by:

// webpack.config.jsmodule.exports = {  entry: {    first: './src/one.js', second: './src/two.js', }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }}

In the above code, we show that we can have an extra output file. Now, all the output files will have their own unique name, in this case, first.bundle.js and second.bundle.js , just like our entry starting point.

If you run Webpack as you did before, it will look for webpack.config.js the file and use the configuration inside.

The business value of Webpack

So far, can keep up with ES6 and webpack footsteps of the product is not much, I know Spreadjs, WIJMO, etc., if you know other, you can leave a message under the article.

Summarize

Today we learned the basics of using Webpack to package ES6 modules. WEBPACK4 provides a default configuration, and we explain some of these when we discuss the entry and output concepts. Of course, Webpack can do far more than that. In the next tutorial, we will be dealing with loaders, and even we write one ourselves. Please look forward to!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.