Foreword – Read the webpack book in practice

directory

  • Installation and use
  • Loader
  • Plugin
  • Devserver

Source reference

Installation and use

# NPM install --save-dev NPM I -d webpack@<version> # Install NPM i-d webpack@beta # Install NPM i-g webpack globallyCopy the code

Let’s build a CommonJS modularized project using Webpack to display Hello Webpack in a web page using JavaScript compiled by Webpack.

Create an HTML

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <! -- Import Webpack output JavaScript file named bundle.js -->
  <script src="./dist/bundle.js"></script>
</head>

<body>
  <div id="app"></div>
</body>

</html>
Copy the code

Create an execution entry file main.js

var showText = require("./utils.js");
showText('Webpack');
Copy the code

In the commonJs module specification, a JS file is equivalent to a module, followed by calls to functions in that module. Ok, so at this point I need to create this module file utils.js

Create utils. Js

// Manipulate the DOM element to display the content on the web page
function showText(content) {
  window.document.getElementById('app').innerText = 'Hello,' + content;
}
// Export the show function from the CommonJS specification
module.exports = showText;
Copy the code

The content is simply a function called showText. The body of the function displays a piece of text on the page, followed by the export function.

Now that we have the entry file and the actions to perform, we need a WebPack configuration file. Next, we create a webpack.config.js file

Create a webpack. Config. Js

const path = require('path');
module.exports = {
  entry: './main.js'.// The entry file, which is important, runs webPack to build a uniquely executed file
  output: {
    // Combine all dependent modules into a bundle.js file
    filename: 'bundle.js'.// Put the output files in the dist directory
    // __dirname only points to the directory currently
    path: path.resolve(__dirname, './dist'),}};Copy the code

The path module is based on the node module, which is basically the path (as the name implies), and then exports an object, which contains the entry file and the exit file configuration. The details are explained in the code comments.

Up to this point, our preparation files are ready, the directory is as follows for the time being:

webpack // Project directory
	index.html
	main.js
	utils.js
	webpack.config.js
Copy the code

Package. json file, so let’s initialize it, okaynpm installYou will find that the command line will ask you to fill in some things, such as webPack project name, author, version, entry file, etc. We just need to make sure of everything.Json file, we need to add an execute command to the scripts object to execute our Webpack configuration file, i.ewebpack.config.jsfile

{
  "name": "webpack-demo"."version": "1.0.0"."description": "HiSen"."main": "main.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1".// Add the command
    "build":"webpack --config webpack.config.js"
  },
  "author": ""."license": "ISC"
}

Copy the code

Ready to go, let’s install WebPacknpm install -D webpackThen execute our WebPack build commandnpm run buildIt’s actually execution"webpack --config webpack.config.js"Look at the scripts object above. The result is not satisfactory ah (as shown below), but also let us installwebpack-cliSince the reason is provided as a separate package, well, follow it.There is an episode here, I chose yes to install it, but there is an error. I did not check the reason, I just ordered to install it myselfOk, so all the files are ready, so our directory andpackage.jsonThe files have all changed a little bit; As follows:

webpack  // Project directory
	index.html
	main.js
	utils.js
	webpack.config.js
	package.json
	node_modules
Copy the code

Directory will automatically generate a dependency file when you install WebPack,node_modules package.jsonfiledevDependenciesObject also adds to our installedwebpackwebpack-cli

Finally, let’s try building the package:npm run build Congratulations, the results are obvious, we have simply implemented an example of a WebPack build package.

Code structure directory

webpack  // Project directory
	dist // Build the build directory
	   bundle.js
	index.html
	main.js
	utils.js
	webpack.config.js
	package.json
	node_modules
Copy the code

If you open the local HTML, you can see that our page may encounter a small error Cannot set property 'innerText' of nullBecause when JavaScript runs, the div element with id=”app” may not be parsed and loaded yet, just move the whole thing to the front, like this:Final result:

Loader

Next we can create a CSS file main.css and import it in our entry file main.js. The result is as follows:

Main. CSS file content

#app{
  text-align: center;
  color:red;
}
Copy the code

The main js import

require("./main.css"); // Import main. CSS
var showText = require("./utils.js");
showText('Webpack');
Copy the code

Obviously, if you build directly, Webpack builds will report errors, because Webpack does not natively support parsing CSS files. To support files that are not JavaScript types, you need to use Webpack’s Loader mechanism. So we modify the webpack.config.js file and add Loader configuration (Loader is a file parser that parses CSS, less, SCSS, etc.)

module.exports = {

  entry: './main.js'.// Import file
  output: {
    // Combine all dependent modules into a bundle.js file
    filename: 'bundle.js'.// Put the output files in the dist directory
    // __dirname only points to the directory currently
    path: path.resolve(__dirname, './dist'),},// Add the following configuration
  module: {
    rules: [{test: /\.css$/.// Use the re to match the CSS file to be converted with this loader
        use: ['style-loader'.'css-loader'] // Make sure the order is correct}}};Copy the code

There’s another way to write user, which is as an array object

use: [
 'style-loader', 
  {
    loader:'css-loader'.options: {minimize:true.Minimize tells csS-Loader to turn on CSS compression.}}]Copy the code

The module.rules array in the configuration configurs a set of rules that tell Webpack which loaders to use to load and transform which files it encounters.

This configuration tells Webpack to use the CSS-Loader to read the CSS file when it encounters a.css ending file, and then hand it over to the style-Loader to inject the CSS content into the JavaScript.

Note: The value of the use attribute needs to be an array of Loader names that are executed from last to first; Each Loader can pass in parameters in the form of a URL QueryString (or array object).

Ok, let’s try this out. Before we build it, we need to install Loader first. In this case, we use style-loader, CSs-Loader

npm i -D style-loader css-loader
Copy the code

package.jsonThe file will be displayed, follow up everyone please pay attention to themselves, I will not tile.Results the following

Instead of generating an extra CSS file, you’ll notice that the bundle.js file has been updated to inject the CSS written in main. CSS. But when you refresh the index.html page, you will find that Hello, the Webpack is centered and the style is in effect! You may be surprised to see CSS written in JavaScript for the first time! This is all thanks to the style-loader, which probably works by storing CSS content as strings in JavaScript, The HTML style tag is dynamically inserted into the HTML head tag by DOM manipulation while the page is executing JavaScript. Maybe you think this will make the JavaScript file bigger and take longer to load the page, and you want Webpack to output the CSS file separately. Then look down

Plugin

First we need to download the extract-text-webpack-plugin

npm i -D extract-text-webpack-plugin
Copy the code

Then look directly at the webpack.config.js configuration file and do the following configuration:

  1. The introduction of extract-text-webpack-pluginA plugin that extracts CSS from JavaScript code into a separate file
  2. The plugin array is added to the module and the plugin filename property is used to tell the plugin that the CSS filename output is approved[name]_[contenthash:8].cssString template, where [name] represents the file name and [contenthash:8] represents the 8-bit hash value calculated based on the file contents.
  3. In the rules, there is no useExtractTextPluginPlugins convert csS-Loader, where style-loader parsing is no longer required.
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin'); // Insert plugin

module.exports = {

  entry: './main.js'.// Import file
  output: {
    // Combine all dependent modules into a bundle.js file
    filename: 'bundle.js'.// Put the output files in the dist directory
    // __dirname only points to the directory currently
    path: path.resolve(__dirname, './dist'),},// Add the following configuration
  module: {
    rules: [{// Use the re to match the CSS file to be converted with this loader
        test: /\.css$/.// use: ['style-loader', 'css-loader'],
        use: ExtractTextPlugin.extract({
          // Convert the.css file to the required Loader
          use: ['css-loader']}),}]},plugins: [
    new ExtractTextPlugin({
      // The name of the.css file extracted from the.js file
      filename: `[name]_[contenthash:8].css`,})]};Copy the code

After the above modifications are completed, we start to build, soga, the successful build is out, if any error is found, please check whether the WebPack version matches the ExtractTextPlugin version.

The constructed dist directory is as follows:

dist
	bundle.js // There is no CSS style code in js
	main_69bba57c.css // The CSS file is our main.css file
Copy the code

DevServer

The first few sections just get Webpack up and running, but in real life you might need:

  1. Provide HTTP services instead of using local file previews;
  2. Monitor file changes and automatically refresh the web page, real-time preview;
  3. Support Source Map for debugging.

The DevServer will start an HTTP server to serve web requests. It will also help start WebPack, receive file changes from WebPack, and automatically refresh web pages for real-time previews via WebSocket.

Install webpack-dev-server: install webpack-dev-server: install webpack-dev-server: install webpack-dev-server: install webpack-dev-server

npm i -D webpack-dev-server
Copy the code

Run the commandwebpack-dev-serveThe following runs successfully, at this point there is a place, notice, line 3, line 4This means that the DevServer starts the HTTP server listening onhttp://localhost:8081/, the DevServer will stay running in the background after starting.

/dist/bundle.js is loaded with 404; /dist/bundle.js is loaded with 404. The reason is that DevServer keeps webpack-built files in memory, and when accessing the output files, you must access them through the HTTP service. Since DevServer does not care about the output.path property configured in webpack.config.js, the correct index.html should be changed to:

<link rel="stylesheet" href="main_69bba57c.css">
<script src="bundle.js"></script>
Copy the code

Then you try to modify any file and find that, like a hot update, the terminal and the web page refresh as you modify it. Well, that’s all for chapter one, and I’ll see you in the next chapter.

You can also package a vue file or a JSX file, but you need a Bebal-Loader compile and some Loader parse

A link to the

  • Front-end visualization platform implementation scheme
  • Getting started with WebPack is a must
  • Webpack core knowledge