The preparatory work
Make sure nodeJS is installed locally, as webPack is built on top of it. To download the latest LTS, long Term maintenance, press next as you would any other software installation, and then open the command line tool, CMD.
node -v
npm -v
Copy the code
Note: NPM is the package management tool for Node.
The installation
There are two common scenarios for installing WebPack: global and local working directories. The difference is that webpack commands can be executed from any directory on your computer through a globally installed Webpack, while the latter can only be executed from the current working directory.
During installation, we usually install two packages: Webpack, which is the main wepack package, and webpack-CLI, which can execute webpack commands from the command line.
Global installation
Let’s start installing webPack globally
npm install webpack webpack-cli --global
Copy the code
Above is the complete command line code, also available through the shorthand mode below.
npm i -g webpack webpack-cli
Copy the code
If you’re a MAC user, make sure you put sudo in front of it.
sudo npm i -g webpack webpack-cli
Copy the code
Enter your computer’s login password as prompted.
After the installation is complete, use webpack -v to view related information.
At this point, the global installation of WebPack is complete, but in practice this is not recommended, as it will lock all your projects into one version of WebPack and will cause your build to fail running projects with different versions of WebPack.
In order to be more flexible and avoid some unnecessary errors, it is recommended to install in the current working directory in practice, so that there will be no problem even if you change computers.
Local working directory installation
To start, you need to create a working directory and initialize a Node configuration file, known as package.json.
npm init -y
Copy the code
This will automatically create a package.json file in the project root directory.
Next, execute the following command in the current directory:
NPM install webpack webpack-cli --save-dev // NPM I -d webpack webpack-cliCopy the code
At this point, the local installation is complete and we can execute the webpack command in our current directory.
run
To test the simple WebPack package, let’s create two JS files.
src/c1.js
In c1.js, we export an add function by default.
export default function add (a, b) {
console.log(`a+b=${a + b}`);
}
Copy the code
src/index.js
In index.js, we import the c1.js exported add function and make a call.
import add from './c1.js'
add(3.4)
Copy the code
By executing the webpack command in the current directory, a dist directory is automatically created that contains main.js, which is the JS code webPack packaged for us.
If you think about it, it looks like we didn’t configure anything. We just installed the two dependency packages that WebPack must have.
webpack --stats detailed
Copy the code
By executing the above command, we can see the detailed WebPack packaging information.
Consider: is the webpack command executed on the command line global or in the current directory?
To test the results, let’s uninstall the global Webpack.
npm uninstall --global webpack webpack-cli
Copy the code
Then, we execute the webpack directive again in the working directory. We find that the Webpack directive is not found, which indicates that the directive we just executed is a global directive.
If we didn’t have the global Webpack, wouldn’t the project be built? No, at this point we can use NPX to execute the webpack command.
npx webpack
Copy the code
At this point, we can pack normally again.
What exactly is NPX? There is such magic, then where is he using the Webpack?
NPX is a command issued after NPM5.2. We can use NPX to execute various commands. By default, NPX will search for webpack in the current directory. NPX will execute the webpack in the current directory.
At this point, webPack preparations and how to run them are covered, but we’re not going to control how WebPack builds according to our needs, for example, which file I use as my entry point, where I put the package files, and so on. Let’s walk through the webPack configuration file step by step.
configuration
Webpack provides two configuration forms by default: terminal commands and configuration files.
Terminal command
Webpack provides us with a wealth of command line instructions to view through webpack –help.
Next, let’s take a quick look at some common command line commands.
For example, we specify the entry as SRC /index.js and the mode as production.
npx webpack --entry ./src/index.js --mode production
Copy the code
If we want to customize the directory and the generated file name, we need to configure other parameters. As a result, our command will become very long, which is definitely not the best solution. Webpack also gives us another configuration solution. This packaging information is configured via webpack.config.js.
The configuration file
First, create a webpack.config.js file in the project root directory (the file name cannot be changed). The default configuration file uses commonJS syntax, exports a configuration object through module.exports, and WebPack automatically reads the configuration file.
const path = require('path')
module.exports = {
entry: './src/index.js'.output: {
filename: 'bundle.js'.path: path.resolve(__dirname, './dist') // You must use path to handle the path, otherwise an error is reported.
},
mode: 'none' // Specify the development mode to avoid console errors.
}
Copy the code
This is a basic Webpack configuration file, specifying the entry, exit, and development environment. When we execute: NPX webpack again, dist/bundle.js will also be generated.
Is that all Webpack can do? Let’s start looking at webPack plug-ins, which will simplify our development process.
The plug-in
We can imagine Webpack as a production line, and the entry files as raw materials, which will go through various processes to produce the finished products we need, and this process may use a variety of tools to assist, we can imagine the plug-ins of Webpack as these tools.
Let’s take a look at some of the most common plug-ins you can use at work.
HtmlWebpackPlugin
In the actual work, we certainly not only in order to generate a JS file so simple, we also need to generate js files automatically into HTML is perfect, or every time to manually introduce, a little attention will also be wrong, this plug-in is to solve our problem.
First, of course, is installing the plug-in:
npm i -D html-webpack-plugin
Copy the code
Once installed, we will of course configure the plug-in in webpack.config.js.
.const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
...
plugins: [
new HtmlWebpackPlugin()
]
}
Copy the code
NPX webpack: there is not only bundle.js in dist, but also an index. HTML, and it automatically introduces the js file that we generated. Open the HTML file in the browser and js will work fine.
We opened the generated index.html and found that the code in it was automatically generated by the plugin. The damn control desire can’t tolerate uncontrolled code. Can we ask it to generate the file according to the HTML format we provided? Of course it can!
new HtmlWebpackPlugin({
template: 'index.html'.// Template file
filename: 'app.html'.// The name of the generated HTML file
inject: 'body' // The position where js is inserted, default is head.
})
Copy the code
That way, we can do whatever we want.
Open the dist directory again, except for the previous HTML file, and generate a new app.html for us, the previous HTML file is naturally useless, we can’t manually delete it every time, of course not, the few files are ok, in case there are dozens or hundreds of useless files, let alone hand trembling.
Clean up the dist
To clean up the old files before each package, simply configure the clean property in output.
output: { ... .clean: true
}
Copy the code
Use the source map
At this point, we deliberately write the wrong syntax,
Modify the SRC/index. Js
. cosole.log('hhh');
Copy the code
Change the mode in the webpack.config.js configuration file to development, execute again: NPX webpack, and open dist/app.html in your browser.
We can see that it does not point to errors in our source code, which is too difficult for us to develop and debug.
Next, we modify webpack.config.js, configure devtool to: inline-source-map, and perform packaging again, and refresh the browser.
module.exports = { ... .devtool: 'inline-source-map'
}
Copy the code
This time I have correctly pointed out the location of the wrong syntax.
Thinking: I don’t know if you have noticed, we need to manually execute NPX webpack every time we need to change, which is not front-end automation, this is not different from the construction site to move bricks, then how can once and for all, very simple, execute: NPX webpack –watch, add a supervisor to the webpack, so that whenever our project has a file change, it will automatically perform packaging.
Auto-packaging worked, but we still had to manually refresh the browser every time to see the latest results, which was clearly not what we expected.
Setting up the development environment
Webpack-dev-server is a solution to our last pain point, with the ability to start a server locally and refresh in real time.
Webpack – dev – server installation
npm i -D webpack-dev-server
Copy the code
Modify the webpack. Config. Js
module.exports = { ... .devServer: {
static: './dist'}}Copy the code
Executing NPX webpack-dev-server will automatically start a server.
Open in your browser: http://localhost:8080
Fact: Webpack-dev-server does not need the dist directory files, but reads them directly from memory, so we can still access them even if we delete the dist directory.
Resource module
Can Webpack pack other files besides our JS files? Such as: Fonts, images, etc. Before this, we used gulp or Grunt to handle our resource files and move the resources to Dist or Build. The best thing about WebPack is that in addition to introducing JS, it can also use the built-in asset modules to import any other type of resources.
There are four types of resource modules:
Asset/Resource: Sends a separate file and exports the URI
Asset /inline: Data URI of the exported resource
Asset /source: Exports the source code of the resource
Asset: Automatically selects between exporting a URI and sending a separate file