This article’s Webpack code sample is based on WebPack 2.7.0 and runs on Mac.

Last year’s article “What’s It Like to Learn JavaScript in 2016?” Frightened a lot of new students who want to enter the line and old drivers who have been in the line for a long time, feel that the front-end world has been unable to understand, do a page to be so troublesome? Of course, if you just want a simple static page, this is a terrible trick. But if you are going to develop a Web App, and then you will continue to iterate, it is extremely important to have a comfortable development environment, so what kind of environment will be comfortable and pleasant?

Wouldn’t it be nice to have an environment where resource dependencies can be installed and referenced in a modular way, you can use cool ES6 syntax, you can write CSS using SASS preprocessors, and your code can be updated in real time instead of having to manually refresh the page over and over again? Ok, let’s configure an environment like this!

Based on the environment

First, you need node.js, and then NPM is installed with Node.js.

What is NPM? Simply put, NPM is a manager for downloading third-party toolkits that install Node.js. Of course, you can now install packages that are used in the browser as well. Bower has always been a front-end library management tool. Initially, NPM could only publish and install Node.js packages, so Bower became very popular. With the popularity of CommonJS and the rise of UMD specifications, It made it possible for NPM to install front-end browser JS packages. As the NPM ecosystem matured, Bower was slowly forgotten

After node. js is installed, run the following command to verify the installation:

$ node -v
v6.11.0

$ npm -v
3.10.10
Copy the code

Don’t worry, node.js is not finished yet, the official source of NPM installation in China seems to be very slow, often have to wait for a long time, how to solve? We can install an NRM! NRM is the NPM Registry management tool, you can freely switch the NPM Registry, and then the command is still used by NPM. There are many mirrors of NPM in China, such as TAOBAO’S CNPM, but many companies have set up their own private libraries. What is private storage? A private library is an NPM package that can only be accessed on the Intranet of the company and cannot be published to the NPM sharing platform. For example, the name of Registry of our large company’s private library is HNPM. Without going into details, let’s try one first:

$ npm install -g nrm
Copy the code

Then according to the official tutorial, we will first cut a domestic registry, such as taobao’s:

$ nrm use cnpm
Copy the code

Then install anything with NPM and see how fast it works. Is not soon ^_^

Wait, node.js has more. Some development dependencies come with node.js versions. We know that the functionality of Node.js varies from one version to another, but we’re not going to uninstall and install it again and again. It feels so stupid! Well, of course we can install NVM. NVM? Looks like NRM! NVM is a node.js version management tool that allows you to switch between and run different Versions of Node.js on multiple terminals. See installation tutorials here. NVM doesn’t work on Windows, but there are several alternatives: NVM-Window, GNVM.

Again, we verify the installation by executing the following command:

$ nvm --version
0.33.0
Copy the code

Project initialization

With the tools above we are ready to start creating a project. We execute the following command to start a project:

mkdir my-app
cd my-app
npm init
Copy the code

After executing NPM init you will see that you need to enter some information about your project, press Enter to confirm when you are done, and NPM will create a file called package.json in the root directory, where any dependencies you install later via –save or –save-dev will appear.

Anyway, create a SRC directory under the root directory, and then create index.js, index.html… Well, you can create a new file as follows:

.├ ─ package.json ├─ SRC ├─ index.html ├─ index.pdfCopy the code

Enter the code in the following file:

Index. Js:

var el = document.createElement('div'),
  text = document.createTextNode('My App');

el.appendChild(text);
document.body.appendChild(el);
Copy the code

Index.html:


      
<html>
<head>
  <meta charset="utf-8" />
  <title>My App</title>
</head>
<body>
</body>
</html>
Copy the code

We need to figure out a way to make this page run, what?? Is it that simple? Add JS to index.html and you’re done. Of course it’s not that simple. We’re building something big!

Ha ~ off topic, let’s continue.

First we need to install something called WebPack, which is a module packer, also known as a build tool. Grunt, Gulp are also build tools, but webpack is popular these days! As a joke, WebPack’s extensibility and plugability, as well as the concept of treating any file as a module, are universally respected by the front-end community, and the efficiency of packaging and splitting files on demand can’t be compared with other build tools. Of course, WebPack configuration is too flexible, and the official documentation is too difficult to understand. Also led to a lot of beginners don’t know how to start.

Now let’s match this amazing tool.

An automated build

Let’s start by installing webPack:

npm install --save-dev webpack
Copy the code

Then create a new webpack.config.js file in the root directory and enter the following code:

let path = require('path');

module.exports = {
  entry: {
    app: path.resolve(__dirname, 'src'.'index.js')},output: {
    filename: '[name].js'.path: path.resolve(__dirname, 'dist')}};Copy the code

You need a local server to access it in your browser, so you can install webpack-dev-server:

npm install --save-dev webpack-dev-server
Copy the code

Let’s add NPM scripts to package.json:

"scripts": {
  "start": "webpack-dev-server --port 3003"
},
Copy the code

Ok! Let’s run NPM start and go to http://localhost:3003 in the browser. Ah? There seems to be something wrong! Yeah, you have to tell WebPack which HTML template your bundle is going to plug into, and as I said webPack is plug-in, it opens up a lot of functionality to a third party to implement, he’s just there to assemble it, okay, Now we need to install an HTML-webpack-plugin:

npm install --save-dev html-webpack-plugin
Copy the code

Modify webpack-config.js:

let HtmlWebpackPlugin = require('html-webpack-plugin'),
  path = require('path');

module.exports = {
  entry: {... },... plugins: [new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'src'.'index.html')]}})Copy the code

Run NPM start again and the page can be accessed normally.

However, this seems a bit low, so let’s add a new file utils. Js to do some ES6 syntax:

.├ ── package.json ├─ SRC ├─ index.css ├─ index.html ├─ index.js+   └── utils
+ └ ─ ─ utils. Js
Copy the code

utils.js:

export function wordsToSentence(. words) {
  return words.join(' ');
}
Copy the code

Modified index. Js

+ import { wordsToSentence } from './utils/utils';

let el = document.createElement('div'),
- text = document.createTextNode('My App');
+ text = document.createTextNode(
+ wordsToSentence('Welcome', 'to', 'my', 'app! ')
+);

el.appendChild(text);
document.body.appendChild(el);
Copy the code

Nothing seems to be wrong when you refresh the page (you must be using Chrome!). Take a closer look at the console source code snippet for app.js (your bundle) :

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = wordsToSentence;
function wordsToSentence(. words) {
  return words.join(' ');
}
Copy the code

It’s worth noting that you need to consider older browsers that don’t support ES6 when using ES6, and while there are no problems with Chrome or other advanced browsers, it’s not guaranteed to work in other browsers. To be sure, we need to convert ES6 to ES5, or JS code converters, which Babel is the best tool in the world:

npm install --save-dev babel-loader babel-core
Copy the code

If you install Babel, you need to get presets:

npm install --save-dev babel-preset-env
Copy the code

Create a new.babelrc file in the root directory and enter the configuration:

{
  "presets": ["env"]}Copy the code

Modify webpack.config.js to add Babel support:

. module.exports = { ... module: {rules: [{test: /\.js$/.loader: 'babel-loader'.include: path.resolve(__dirname, 'src'}]},... };Copy the code

Execute NPM start to find the app.js code snippet under console source:

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.wordsToSentence = wordsToSentence;
function wordsToSentence() {
  for (var _len = arguments.length, words = Array(_len), _key = 0; _key < _len; _key++) {
    words[_key] = arguments[_key];
  }

  return words.join(' ');
}
Copy the code

It has been successfully converted to ES5 code. However, ES6 Modules are currently handled by Babel, and you can compare the previous and second code snippets of module output. Now, WebPack 2 has built-in CONVERSION of ES6 Modules, which is said to be more efficient and performance than Babel! ^_^ not verified, let’s try first, turn Babel module conversion off:

.babelrc

{
  "presets": [["env", {
      "modules": false}}]]Copy the code

Execute NPM start to see the output app.js code snippet again:

-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.wordsToSentence = wordsToSentence;
+/* harmony export (immutable) */ __webpack_exports__["a"] = wordsToSentence;
function wordsToSentence() {
  ...
}
Copy the code

Module output goes back to the code before using Babel.

The js environment seems to be ready, but CSS is not. Let’s modify index.css:

#app {
  color: #57af09;
}
Copy the code

At the same time, import the CSS into the bundle portal and modify index.js:

import './index.css';
import { wordsToSentence } from './utils/utils';

let el = document.createElement('div'),... el.id ='app'; .Copy the code

Webpack also needs a loader to handle CSS modules:

npm i --save-dev style-loader css-loader
Copy the code

Modify webpack.config.js:

. module.exports = { ... module: {rules: [{...test: /\.css$/.loader: ['style-loader'.'css-loader'].include: path.resolve(__dirname, 'src'}]},... };Copy the code

Execute NPM start and you can now see that the page is styled. But we said we wanted to use an advanced weapon: SASS. Let’s modify index.css:

$app-color: #57af09;

#app {
  color: $app-color;
}
Copy the code

Modify the file suffix again:

.├ ── package.json ├─ SRC- ├ ─ ─ index. The CSS
+ ├ ─ ─ index. SCSS.Copy the code

Modify the entry to index.js:

-import './index.css';
+import './index.scss';
Copy the code

Since the file (module) type has changed, we also need a SASS Webpack loader:

npm install --save-dev sass-loader node-sass
Copy the code

Modify webpack.config.js again:

. module.exports = { ... module: { rules: [ ... {- test: /\.css$/,
+ test: /\.scss$/,
- loader: ['style-loader', 'css-loader'],
+ loader: ['style-loader', 'css-loader', 'sass-loader'],
        include: path.resolve(__dirname, 'src')
      }
    ]
  },
  ...
};
Copy the code

NPM start, webpack compilation without error, the page shows everything is normal!

Automatic code updates (hot updates)

If you try to change the style of index. SCSS, have you noticed a problem: the page will refresh automatically. But sometimes when you’re developing a module, like a Dialog, the refresh will result in you having to iterate on the page to see the style update for that dialog. Is there a way to see code updates without refreshing the page?

NPM scripts for package.json:

"scripts": {
  "start": "webpack-dev-server --hot --inline --port 3003"
},
Copy the code

Noting the code above, we added –hot –inline to give the development environment the ability to hot update. We re-execute NPM start, place your browser and editor side by side, and then repeatedly modify index. SCSS. You will see that the page does not refresh, but the style is automatically pushed to update, which is the hot update.

conclusion

At this point, you’ve got the basics of a simple, modern front-end development environment, but this article is not a webPack guide or ES6 syntax tutorial, but hopefully you’ll get a sense of the engineering side of front-end development.

IKcamp’s original new book “Mobile Web Front-end Efficient Development Combat” has been sold on Amazon, JD.com and Dangdang.

>> Hujiang Web Front-end Shanghai team recruiting [Web front-end architect], interested candidates resume to: [email protected] <<


In 2019, iKcamp’s original new book Koa and Node.js Development Actual Combat has been sold on JD.com, Tmall, Amazon and Dangdang!