Preface:
Can go to mineGithub/blogRead on and if you can help, go to star😊
If, like me, you’ve followed the WebPack tutorial and have no idea how to use it, this series of articles will give you some experience setting up the WebPack + React scaffolding. This series of articles is written to help you review your own configuration requirements in the future, and to strengthen your understanding of WebPack. I will explain this scaffold configuration step by step in detail as much as possible, and I will also remind you of some points that need to be paid attention to, hoping to help you
Premise:
- Make sure you have the latest version of Node.js installed and type it in the console
node -v
View the current version, if not installed or not the latest version, provided hereNode. Js’s official websiteIn order to download - If you are a webpack veteran, please close this article. Your time is worth a lot.
- The writing of the current article is based on the MAC OS environment, if Windows, and I do the same operation but can not get the result, please Google
- Be patient. I will break this article into sections to prevent fatigue from too much concentration. You can take a break to read one section.
Let’s go!
Create an empty folder
Let’s create an empty folder on the desktop called webpkk-react-scaffold and open it using your editor. Drag this folder to your terminal and execute:
npm init -y
Copy the code
The above command generates a package.json file in your root directory that defines the various modules needed for the project, as well as the project’s configuration information (such as name, version, license, and other metadata). Based on this configuration file, the NPM install command automatically downloads the required modules, that is, the runtime and development environment required to configure the project.
Install webpack
Since we are using the WebPack 4+ version, we also need to install webpack-CLI by executing the following command:
npm install --save-dev webpack webpack-cli
Copy the code
Once installed, you’ll notice a devDependencies property in package.josn as a result of installing the save-dev dependencies, which represent development-time dependencies. After that, we will install the dependencies using just –save, which represents the runtime dependencies.
Let’s make sure that the file structure in the root directory is as follows:
webpack-react-scaffold
|- node_modules
|- package.json
Copy the code
Create a.js file called webpack.common.config.js and type in the following code:
const path = require('path');
module.exports = {
entry: {
app: './src/app.js',},output: {
filename: 'js/bundle.js'.path: path.resolve(__dirname, '.. /dist')}}Copy the code
The WebPack configuration is the standard CommonJS module of Node.js, which imports other modules through require, exports modules through module.exports, which are parsed by WebPack according to the properties defined by the object.
The entry attribute defines the entry file path, and output defines the file name and path after compilation and packaging. This tells WebPack that the entry file is the app.js file in the SRC directory. The packaged output file is called bundle.js and is stored in the dist folder in the previous directory.
Create a folder named SRC and create a new js file named app.js. Now our directory structure looks like this:
webpack-react-scaffold
+ |- config
+ |- webpack.common.config.js
|- node_modules
+ |- src
+ |- app.js
|- package.json
Copy the code
So how do we pack it? Configure the following properties in package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "start": "webpack --config ./config/webpack.common.config.js"
},
Copy the code
Okay, let’s try packaging, even though you don’t have any code in app.js. Enter the following code in the console:
npm run start
Copy the code
You can see why the “start” –config option specifies the configuration file. After execution, you will notice that the root directory has an additional folder: dist/js, which contains a JS file: bundle.js, so we have successfully compiled and packaged a JS file: app.js.
Use webpack – merge
We will use a tool called Webpack-Merge. With “generic” configurations, we don’t have to repeat code in environment-specific configurations. To put it simply, the configuration to be given varies from production environment to production environment, but a common configuration can be shared.
Let’s start by installing webpack-Merge:
npm install --save-dev webpack-merge
Copy the code
After the installation, we create two new files in the config folder: webpack.prod.config.js and webpack.dev.config.js, which correspond to the configuration of the production and development environments respectively.
Directory structure now:
webpack-react-scaffold
|- config
|- webpack.common.config.js
+ |- webpack.prod.config.js
+ |- webpack.dev.config.js
|- node_modules
|- src
|- app.js
|- package.json
Copy the code
Enter the following code in webpack.prod.config.js:
const merge = require('webpack-merge');
const common = require('./webpack.common.config.js');
module.exports = merge(common, {
mode: 'production'});Copy the code
Go back to the app.js file we created earlier and enter the code:
var root =document.getElementById('root');
root.innerHTML = 'hello, webpack! ';
Copy the code
Create a folder named “public” in the root directory and create an HTML file named “index.html” with the following contents:
<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>Configure webPack4 + React scaffolding from zero</title>
</head>
<body>
<div id="root"></div>
<script src=".. /dist/js/bundle.js"></script>
</body>
</html>
Copy the code
The current directory structure looks like this (the bundle.js to be imported does not, as long as it is not compiled and packaged) :
webpack-react-scaffold
|- config
|- webpack.common.config.js
|- webpack.prod.config.js
|- webpack.dev.config.js
|- node_modules
+ |- public
+ |- index.html
|- src
|- app.js
|- package.json
Copy the code
Before packaging, we modify package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
- "start": "webpack --config ./config/webpack.common.config.js",
+ "build": "webpack --config ./config/webpack.prod.config.js"
},
Copy the code
Ok, let’s try compiling and packaging next! The console executes the following code:
npm run build
Copy the code
We can see that webpack compiled afresh, this and implement webpack – config config/webpack prod. Conf., js is the same effect. Now you can open the browser public/index.html and see if there is anything ~ ~
Install the React
Enter the following code on the console:
npm install --save react react-dom
Copy the code
Once installed, we can write the React JSX syntax.
Create a new js file, index.js, in the SRC folder to render the root component.
Enter the following code in index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
Copy the code
Rewrite app.js with JSX syntax:
import React from 'react';
function App() {
return (
<div className="App">Hello World</div>
);
}
export default App;
Copy the code
Modify the entry in the webpack.common.config.js file because we now want to compile the package should be index.js:
const path = require('path');
module.exports = {
entry: {
- app: './src/app.js',
+ index: './src/index.js',}, output: { filename: 'js/bundle.js', path: path.resolve(__dirname, '.. /dist') } }Copy the code
Now try re-running the NPM run build and you will find that the packaging failed. Why? Then see…
Use the Babel 7
Why do we write that JSX will not pack, because WebPack does not recognize JSX syntax, so what to do? Use loader to preprocess the file. One such preprocessing plug-in, babel-Loader, loads ES2015+ code and translates it into ES5 using Babel. Start configuring it!
Start by installing the babel-related modules:
npm install --save-dev babel-loader @babel/preset-react @babel/preset-env @babel/core
Copy the code
- **babel-loader: ** Use Babel and webpack to translate JavaScript files.
- **@babel/preset- React: ** Paraphrase react JSX
- **@babel/preset-env: ** Paraphrase ES2015+ syntax
- **@babel/core: ** The core module of Babel
In theory we can configure “options” directly in webpack.common.config.js, but preferably in the current root directory. Create a new configuration file. Babelrc to configure the associated “presets” :
{"presets": [["@babel/preset-env", {"targets": {// Preset -env" edge": 17, "Firefox ": 60," Chrome ": 67, "Safari ": 11.1}, // Import methods according to ES6+ syntax used in code logic, not all import "useBuiltIns": "usage"}], "@babel/preset-react"]}Copy the code
The configuration of Bebel can be found on the official website.
Modify webpack.common.config.js and add the following code:
const path = require('path');
module.exports = {
entry: {
index: './src/index.js',},output: {
filename: 'js/bundle.js'.path: path.resolve(__dirname, '.. /dist')},module: {
rules: [{test: /\.(js|jsx)$/.use: 'babel-loader'.exclude: /node_modules/,}]}}Copy the code
Use is a mandatory attribute to use babel-loader. Exclude tells us that we do not need to translate “node_modules” files.
The following:
npm run build
Copy the code
Is it possible to pack successfully? Go back to your HTML page and see if “Hello Webpack” has been printed!
Let’s make a final confirmation of our catalogue:
webpack-react-scaffold
|- config
|- webpack.common.config.js
|- webpack.prod.config.js
|- webpack.dev.config.js
|- node_modules
|- public
|- index.html
|- src
+ |- index.js
|- app.js
+ |- .babelrc
|- package.json
Copy the code
This section ends here, you will find that there are many features that are still not implemented, such as automatic HTML file generation, real-time page refresh, etc. In the next section we will gradually improve our configuration!