If you don’t already know how to package your projects using Webpack, it’s time to catch up!

Knock on the blackboard: Hey, let’s explain how to use Webpack to package a project with zero configuration.

The first step is to initialize the project

First, create the project in a directory on your computer. I will create a local folder called myApp, open the command prompt, go to the folder and execute:

# initialization
npm init -y
Copy the code

The above command automatically creates a package.json configuration file in the myapp folder with the default configuration information.

Then install webpack and webpack-CLI into the development environment and execute the following command:

cnpm i webpack webpack-cli -D
Copy the code

Json configuration file, you can see the devDependencies configuration item:

{
    / /...
    "devDependencies": {
        "webpack": "^ 4.42.1"."webpack-cli": "^ 3.3.11." "}}Copy the code

At this point, project initialization is complete!

Step 2 Create a directory

This is just a demonstration of the webpack packaging process, so it’s not that complicated. Now create a SRC directory under myapp and create three.js files under SRC. The structure is as follows:

| __ the SRC | -- hello. Js | -- world. Js | __ index. JsCopy the code

The effect is shown below:

Hello.js file contents:

module.exports = 'hello';
Copy the code

World.js file contents:

module.exports = 'world';
Copy the code

Index.js file contents:

const hello = require('./hello');
const world = require('./world');

console.log(`${hello} ${world}`);
Copy the code

Step 3 use Webpack to package the project

1. Optimize the packaging command

After the above code is written, we can execute the webpack command for packaging. To facilitate the following packaging command execution, we need to configure a script field in the package.json file:

"scripts": {
    "build": "webpack"
}
Copy the code

PS: After “scripts” is configured, running NPM run build on the console is equivalent to executing webpack.

NPM run build = NPM run build = NPM run build

After successful execution, the dist directory is automatically created in the MyApp project directory to store the packaged files.

In the dist directory, a main.js file is generated, which is the generated package file. We can run this file in the myApp project root directory:

node dist/main
Copy the code

Execution Result:

If hello World is displayed, we have already packaged the project.

At this point, the index.js file is packed into the dis folder. But there is a warning in the console results:

Production mode is used by default. Open the dist/main.js file and all the code in the file is compressed, which indicates that the production environment is packaged.

Just add two configurations to the scripts run script to resolve this warning:

"scripts": {
  "dev": "webpack --mode development"."build": "webpack --mode production"
}
Copy the code

After the configuration is complete, run the NPM run dev command and the package result is as follows:

Now when you open dist/main.js, there is no compression, and the console is no longer warning.

PS: There are two packaging environments for Webpack, production and development, which correspond to production environment and development environment respectively. Production environment means that the project has been deployed online and started to formally provide external services, so there will be code compression. If we were in the development phase, we would have chosen the development environment package, that is, development.

2. Modify the package output directory

In the packing process above, you can see that WebPack automatically packages files in the SRC directory, because the default entry for WebPack is SRC /index.js and the default exit is dist/main.js.

If you want to change the default output directory of webpack, you need to use the webpack command –output.

"scripts": {
  "dev": "webpack --mode development --output ./output/main.js"."build": "webpack --mode production --output ./output/main.js"
}
Copy the code

NPM run dev will output the package file to ‘output/main.js’.

Extension: Use Babel to convert ES6 syntax

The previous code used CommonJS ‘module.exports syntax to export variables. Now let’s try using ES6’s Module export default syntax to implement packaging. Because the ES6 syntax is not supported in normal browsers, errors are reported, so use the loader to package the project.

So the question is, why are we refactoring code using ES6 syntax and packaging it again?

This is because many component-based development frameworks, such as React and Vue, use ES6 syntax, so in order to package these projects smoothly, we have to learn to use Babel to convert ES6 syntax.

SRC rewrites the previous code as follows:

// hello.js
export default 'hello';

// world.js
export default 'world';

// index.js
import hello from './hello';
import world from './world';

console.log(`${hello} ${world}`);
Copy the code

In this case, if we execute the package command directly, although it can be successfully packaged, but in some older browsers or mobile browsers will report an error, which needs to use Babel to convert ES6 syntax.

Having said that, I will review two concepts for you:

  • Babel is a JavaScript compiler that translates ES6+ syntax into ES5 syntax to ensure browser compatibility.
  • Loader is an important concept of Webpack. Loader can do some operations related to file attributes. If ES6 syntax conversion is done here, it is usedbabel-loaderThis Loader depends on@babel/core@babel/preset-env.

Start by executing the installation command:

cnpm i @babel/core babel-loader @babel/preset-env -D
Copy the code

Then create a configuration file for Babel in the root directory of the project. Babelrc with the following contents:

{
    "presets": ["@babel/preset-env"]}Copy the code

If the file name is.babelrc, you need to set the file name to.babelrc. I’ll just add one more point.

With babel-loader, you can use the webpack command –module-bind to specify how the corresponding files should be handled by the loader, so continue to modify NPM scripts:

"scripts": {
    "build": "webpack --mode production --module-bind js=babel-loader"."dev": "webpack --mode development --module-bind js=babel-loader"
  }
Copy the code

After adding, execute NPM run build and take a look at the dist/main.js file to see what the converted ES5 syntax looks like.

Finally, a few tips for webpack-CLI:

  1. Webpack takes longer to compile as your project grows larger or is packaged in a production environment. You can use parameters to make compiled output with progress and colors: Webpack –progress –colors;
  2. The configuration of Webpack is complex, and it is easy to tolerate errors. If something goes wrong, some simple error messages will be printed. We can also print error details by using the parameter –display-error-details: Webpack –display-error-details; 3. If you don’t want to recompile every time you modify a module, you can enable the listening mode. After enabling the listening mode, the module that does not change will be cached in memory after compilation, rather than recompile every time, so the overall speed of listening mode is very fast: webpack –watch;
  3. Webpack-cli supports two shortcut options: -d and -p, which represent packaging for some common development and production environments, respectively.

In addition, webpack-cli command has a lot of options, you can refer to the webpack-cli document for details. Here we summarize the most common options:

  • – config: specifies the path to a Webpack configuration file.
  • – mode: specifies the mode of the packaging environment. The value can be development and production, corresponding to the development environment and production environment respectively.
  • -json: Output mode to the Webpack result. You can use Webpack –json > stats.json to output the package result to the specified file.
  • – progress: displays the Webpack packaging progress.
  • – Watch, -w: package in watch mode. The package starts again after monitoring file changes.
  • –color, –colors/ –no-color, –no-colors: Whether the console output is colored;
  • – Hot: Enables the Hot Module Replacement mode, which is described in details later.
  • – Profile: displays the time (time) of each link in detail, facilitating troubleshooting of packaging speed bottlenecks.