Home >Web Front-end >JS Tutorial >Summary of issues related to webpack2 and module packaging

Summary of issues related to webpack2 and module packaging

巴扎黑
巴扎黑Original
2017-08-11 10:49:141125browse

This article mainly introduces the novice guide (summary) about webpack2 and module packaging. It has certain reference value and interested friends can refer to it.

Webpack has become one of the most important tools in modern web development. It is a module packaging tool for JavaScript, but it can also convert all front-end resources, such as HTML and CSS, and even images. It gives you greater control over the number of HTTP requests your application makes, and allows you to use features from other resources (such as Jade, Sass, and ES6). webpack also lets you easily download packages from npm.

This article is mainly aimed at students who are new to webpack and will introduce initial setup and configuration, modules, loaders, plug-ins, code splitting and hot module replacement.

Before continuing to study the following content, you need to make sure that Node.js has been installed on your computer.

Initial configuration

Use npm to initialize a new project and install webpack:


mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack@beta --save-dev
mkdir src
touch index.html src/app.js webpack.config.js

Written The following files:


<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Hello webpack</title>
 </head>
 <body>
  <p id="root"></p>
  <script src="dist/bundle.js"></script>
 </body>
</html>


// src/app.js
const root = document.querySelector(&#39;#root&#39;)
root.innerHTML = `<p>Hello webpack.</p>`


// webpack.config.js
const webpack = require(&#39;webpack&#39;)
const path = require(&#39;path&#39;)

const config = {
 context: path.resolve(__dirname, &#39;src&#39;),
 entry: &#39;./app.js&#39;,
 output: {
  path: path.resolve(__dirname, &#39;dist&#39;),
  filename: &#39;bundle.js&#39;
 },
 module: {
  rules: [{
   test: /\.js$/,
   include: path.resolve(__dirname, &#39;src&#39;),
   use: [{
    loader: &#39;babel-loader&#39;,
    options: {
     presets: [
      [&#39;es2015&#39;, { modules: false }]
     ]
    }
   }]
  }]
 }
}

module.exports = config

The above configuration is an ordinary Starting point, it notifies webpack to compile and output the entry file src/app.js to the file /dist/bundle.js, and use babel to compile all .js File converted from ES2015 to ES5.

In order to convert it to ES5 format JS files, we need to install three packages: babel-core, webpack loader babel-loader and presets babel-preset-es2015. Use { modules: false } to have Tree Shaking remove unused exports from the packaged file to reduce file size.


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

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


##

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

Running npm start in the command line will start webpack in monitor mode, which will recompile bundle.js when the .js file in the src directory changes. The output in the console shows the information of the packaged files. It is important to pay attention to the number and size of the packaged files.

Now when you load the index.html page in your browser you will see "Hello webpack."

open index.html

Open the

dist/bundle.js file to see what webpack has done. The top is the module guide of webpack Code, at the bottom is our module. So far, you may not have a deep impression of this. But now you can start writing ES6 modules and webpack will generate bundled files that work in all browsers.

Use

Ctrl + C to stop webpack and run npm run build to compile our bundle.js in production mode.

Note that the size of the packed file has been reduced from 2.61 kB to 585 bytes. Take another look at the

dist/bundle.js file and you will see a lot of unreadable code because we used UglifyJS to minify it. This way, we can use less code to achieve the same effect as before.

Modules

Good webpackers know how to use JavaScript modules in various formats, the two most famous are:

  • ES2015 import statement

  • CommonJS require() statement

We can test modules in these formats by installing and importing lodash.



npm install lodash --save


// src/app.js
import {groupBy} from &#39;lodash/collection&#39;

const people = [{
 manager: &#39;Jen&#39;,
 name: &#39;Bob&#39;
}, {
 manager: &#39;Jen&#39;,
 name: &#39;Sue&#39;
}, {
 manager: &#39;Bob&#39;,
 name: &#39;Shirley&#39;
}, {
 manager: &#39;Bob&#39;,
 name: &#39;Terrence&#39;
}]
const managerGroups = groupBy(people, &#39;manager&#39;)

const root = document.querySelector(&#39;#root&#39;)
root.innerHTML = `<pre class="brush:php;toolbar:false">${JSON.stringify(managerGroups, null, 2)}
`

Run

npm startStart webpack and refresh index.html, you can see An array grouped by manager.

Let's move this array into its own module

people.js.


// src/people.js
const people = [{
 manager: &#39;Jen&#39;,
 name: &#39;Bob&#39;
}, {
 manager: &#39;Jen&#39;,
 name: &#39;Sue&#39;
}, {
 manager: &#39;Bob&#39;,
 name: &#39;Shirley&#39;
}, {
 manager: &#39;Bob&#39;,
 name: &#39;Terrence&#39;
}]

export default people

We can easily import it using relative paths in

app.js.


// src/app.js
import {groupBy} from &#39;lodash/collection&#39;
import people from &#39;./people&#39;

const managerGroups = groupBy(people, &#39;manager&#39;)

const root = document.querySelector(&#39;#root&#39;)
root.innerHTML = `<pre class="brush:php;toolbar:false">${JSON.stringify(managerGroups, null, 2)}
`

Note: Imports without relative paths like

lodash/collection are imported and installed in /node_modules Modules, your own modules need a relative path like ./people, you can use this to distinguish them.

Loader

We have already introduced that you can configure a loader like

babel-loader to tell webpack when encountering different What to do when importing file types. You can combine multiple loaders together and apply them to many file conversions. Importing .sass files in JS 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 new rules for .scss files in the configuration file.



// webpack.config.js
rules: [{
 test: /\.scss$/,
 use: [
  &#39;style-loader&#39;,
  &#39;css-loader&#39;,
  &#39;sass-loader&#39;
 ]
}, {
 // ...
}]

Note: Any time you change any loading rule in

webpack.config.js you need to use Ctrl + C and npm start Restart the build.

The loader sequence is processed in reverse order:

  • sass-loader Converts Sass to CSS.

  • css-loader Parses CSS into JavaScript and resolves all dependencies.

  • style-loader outputs our CSS to

in the document

The above is the detailed content of Summary of issues related to webpack2 and module packaging. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn