A beginner's Guide on Webpack2 and Module packaging (Part One)

Source: Internet
Author: User

Webpack has become one of the most important tools in modern web development. It is a module-wrapping tool for JavaScript, but it can also transform all of the front-end resources, such as HTML and CSS, and even pictures. It gives you more control over the number of HTTP requests generated by your application, features that allow you to use other resources (such as Jade, sass, and ES6). Webpack also allows you to easily download packages from NPM.

This article focuses on those who have just contacted Webpack, and will introduce the initial setup and configuration, modules, loaders, plug-ins, code splitting, and hot module replacements.

Before you continue learning the following, you need to make sure that node. JS is already installed on your PC.

Initial configuration

Use NPM to initialize a new project and install Webpack:

mkdir webpack-democd webpack-demonpm init -ynpm install [email protected] --save-devmkdir srctouch index.html src/app.js webpack.config.js

Write the following files:

<!-- index.html --><!DOCTYPE html>
// src/app.jsconst root = document.querySelector(‘#root‘)root.innerHTML = `<p>Hello webpack.</p>`
// webpack.config.jsconst webpack = require(‘webpack‘)const path = require(‘path‘)const config = { context: path.resolve(__dirname, ‘src‘), entry: ‘./app.js‘, output: { path: path.resolve(__dirname, ‘dist‘), filename: ‘bundle.js‘ }, module: { rules: [{ test: /\.js$/, include: path.resolve(__dirname, ‘src‘), use: [{ loader: ‘babel-loader‘, options: { presets: [ [‘es2015‘, { modules: false }] ] } }] }] }}module.exports = config

The above configuration is a common starting point, which informs Webpack to compile the import file into a src/app.js file /dist/bundle.js , and use Babel to convert all the .js files from ES2015 to ES5.

To make it possible to convert the JS file into the ES5 format, we need to install three packages: babel-core , Webpack loader babel-loader and presets babel-preset-es2015 . Use { modules: false } let tree Shaking remove unused export entries (exports) from packaged files to reduce file size.

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

Finally, replace package.json the section with the following scripts :

"scripts": { "start": "webpack --watch", "build": "webpack -p"},

Running on the command line npm start will start webpack in watch mode, and src it will recompile bundle.js when the file in the directory .js changes. The output in the console shows the information for the packaged file, and it is important to note the number and size of the packaged files.

Now you'll see "Hello webpack." When you load the index.html page in a browser.

open index.html

Open the dist/bundle.js file to see what Webpack has done, the top is the Webpack module boot code, the bottom is our module. So far, you may not have a deep impression of this. But now that you can start writing the ES6 module, Webpack will generate a packaged file for all browsers.

Use Ctrl + C stop Webpack, run npm run build in production mode to compile our bundle.js .

Note that the size of the packaged file has been reduced from 2.61 KB to 585 bytes . Looking at the dist/bundle.js file again, you'll see a lot of code that's hard to understand because we used UGLIFYJS to compress it. In this case, we can use less code to achieve the same effect as before.

Module

Excellent webpack know how to use the various formats of the JavaScript module, the most famous of the two are:

    • ES2015 import Statements
    • CommonJS require() Statements

We can test the modules of these formats by installing and importing Lodash.

npm install lodash --save
// src/app.jsimport {groupBy} from ‘lodash/collection‘const people = [{  manager: ‘Jen‘,  name: ‘Bob‘}, {  manager: ‘Jen‘,  name: ‘Sue‘}, {  manager: ‘Bob‘,  name: ‘Shirley‘}, {  manager: ‘Bob‘,  name: ‘Terrence‘}]const managerGroups = groupBy(people, ‘manager‘)const root = document.querySelector(‘#root‘)root.innerHTML = `<pre>${JSON.stringify(managerGroups, null, 2)}</pre>`

Run npm start start Webpack and Refresh index.html, you can see an array that is grouped by the manager.

Let's move this array to its own module people.js .

// src/people.jsconst people = [{  manager: ‘Jen‘,  name: ‘Bob‘}, {  manager: ‘Jen‘,  name: ‘Sue‘}, {  manager: ‘Bob‘,  name: ‘Shirley‘}, {  manager: ‘Bob‘,  name: ‘Terrence‘}]export default people

We can app.js easily import it using relative paths in.

// src/app.jsimport {groupBy} from ‘lodash/collection‘import people from ‘./people‘const managerGroups = groupBy(people, ‘manager‘)const root = document.querySelector(‘#root‘)root.innerHTML = `<pre>${JSON.stringify(managerGroups, null, 2)}</pre>`

Note : lodash/collection There are no relative paths like this import is imported installed in /node_modules the module, your own module needs a similar ./people relative path, you can distinguish them by this.

Loading device

As we've already covered, you can babel-loader tell webpack what to do when you encounter an import of different file types by configuring a loader like this. You can combine multiple loaders to apply to many file transformations. Importing files in JS .sass is a very good example.

Sass

This conversion involves three separate loaders and node-sass libraries:

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

Add a new rule to the file in the configuration file .scss .

// webpack.config.jsrules: [{  test: /\.scss$/,  use: [    ‘style-loader‘,    ‘css-loader‘,    ‘sass-loader‘  ]}, {  // ...}]

Note: any webpack.config.js one of the load rules in the change will need to use Ctrl + C and npm start restart the build.

The loader sequence is processed in reverse order: first sass-loader convert the sass to CSS, then css-loader parse the CSS into JavaScript and parse all dependencies, and finally style-loader output our CSS to the document

A beginner's Guide on Webpack2 and Module packaging (Part One)

Related Article

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.