By yugasun from yugasun.com/post/you-ma… This article can be reproduced in full, but the original author and source need to be retained.

The development environment

Since it is actual combat, how can not leave the project development environment? First, I would like to recommend my personal development environment:

Hardware: Mac OSX Compiler: Visual Studio Code command line tool: iTerm2 Debugging tool: Chrome Dev tool + vue-devtools Version management: Git

The operation interface of the tool and how to use it are not shown here. Use search engine search casually, it is relevant introduction. You can choose your development environment according to your personal preference.

Modular development

The use of Vue in the previous article is to directly introduce source code to use, but the actual development of the project is generally very complex, and will involve a lot of page templates, it is impossible to write all functions in the same JS file, and then through the script tag introduction, so that the project will be more and more difficult to maintain, So the project needs modular development.

For more information about what modularity is and how to build modular architecture for our project, we recommend reading JavaScript Modularity primer I: Understanding Modules and JavaScript Modularity Primer II: Module Packaging and Building.

As the project code grows and our module files grow, we need tools to help us manage and package these modules better, so that we can focus on modular development rather than trivial things. There are a lot of tools like WebPack that have their own advantages, such as rollup, parcel… .

All the examples in future articles will use version 3.x of WebPack to complete development work in conjunction with Vue.

The initial webpack

I have to say that many of my friends start their Vue projects with vuE-CLI scaffolding tools, even though they can quickly build project templates without worrying about initial configuration. But I don’t recommend doing this, because it starts with vuejs + webpack + ES6 + Babel + ESLint… Before anyone knows what they are, they start using them. When something goes wrong, you don’t know what to do. Although with the help of search engines can help us solve 80% of the problem, but still need to spend a lot of energy to search queries, continuous attempts, and so on to solve the problem, a day passed, outweight the loss ah.

So I suggest starting with learning how to use WebPack and introducing it step by step to make it easier to accept. After all, most people in this world are not geniuses. You have to walk before you can run.

Although the current society is impetuous, but have a quiet heart, down to earth, is the way to success

Well, without further ado, let’s get straight to the main topic of today, happy Vuejs project development using Webpack.

Before reading the code below, familiarize yourself with the use of the NodeJS module, including the basics of installing module dependencies through NPM and how to introduce third-party module use, which is covered here but not explained in detail.

Let’s create a new project folder and create index.html under the root directory as follows:


      
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Vue webpack demo</title>
</head>
<body>
  <div id="app"></div>
  <script src="./build.js"></script>
</body>
</html>
Copy the code

Json file will appear in the root directory of the project. For details on the contents of package.json file, please read this article: Package. json file). Then install the vUE library we need via NPM:

# Add --save parameter to add vUE dependencies to package.json file
npm install vue --save
Copy the code

Create an app.js entry file in the SRC directory with the following code:

// Modularize the import of vUE and assign it to vUE variables
var Vue = require('vue')

new Vue({
  el: "#app".template: "<h1>{{ msg }}</h1>",
  data () {
    return {
      msg: 'Hello Vue.js'}}})Copy the code

Of course require function browser is not recognized, this is the need to use Webpack to help us achieve compilation and packaging work, into the mainstream browser but other ES5 code.

Install the webPack dependencies first:

# Add the --save-dev parameter to add the WebPack development dependencies to package.json file
npm install webpack --save-dev
Copy the code

Then create the webpack.config.js file in the project root directory as follows:

module.exports = {
  // Import file
  entry: './src/app.js'.// Compile the output file
  output: {
    filename: 'build.js'
  },
  resolve: {
    alias: {
      / / because we here is introduced the require of it, so you should use vue.com mon. Js/vue js/vue. Min. Js
      'vue$': 'vue/dist/vue.common.js'}}}Copy the code

Since index.html above introduces the compiled build.js file, to see the development effect, you need to run the webpack command manually:

./node_modules/.bin/webpack
Copy the code

If you want to run webpack directly, you need to install webpack globally on your computer. You can run NPM install webpack -g command to install webpack globally.

You should then see the following output:

$ webpack
Hash: 8a61c2605578f38f46cd
Version: webpack 3.10.0
Time: 386ms
   Asset    Size  Chunks             Chunk Names
build.js  104 kB       0  [emitted]  main
   [0] (webpack)/buildin/global.js 509 bytes {0} [built]
   [1] ./src/app.js 148 bytes {0} [built]
    + 4 hidden modules
Copy the code

At this point, the build.js file will appear in the root directory, and we will open the index.html file through the browser, and the familiar screen will appear: Hello vue.js.

A simple project based on Vue + Webpack has been built, isn’t it very simple, can’t wait to try it yourself? Of course, Webpack features far more than this more detailed features, please read the official documentation, a comprehensive understanding of the power of Webpack.

Live reloading

Another problem with the above example is that every time we update the code, we have to repackage and compile it, and manually refresh the browser to see the effect of our changes, which is just too much trouble. The webpack authors also took this issue into account and developed the webpack-dev-server tool to help us implement live reloading, which means that when we update code, the browser will refresh in real time to show the updated effect.

Use it quickly ~ install the dependency first:

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

Then modify the webpack.config.js configuration file as follows:

module.exports = {
  // Import file
  entry: './src/app.js'.// Compile the output file
  output: {
    filename: 'build.js'
  },
  resolve: {
    alias: {
      / / because we here is introduced the require of it, so you should use vue.com mon. Js/vue js/vue. Min. Js
      'vue$': 'vue/dist/vue.common.js'}},// Add the webpack-dev-server configuration
  devServer: {
    // Define the root directory of the Web service enabled by webpack-dev-server
    contentBase: '/'}}Copy the code

Then execute the command:

./node_modules/.bin/webpack-dev-server
Copy the code

The console will print the following:

$ ./node_modules/.bin/webpack-dev-server Project is running at http://localhost:8080/ webpack output is served from / Content not from webpack is served from./ Hash: D33155F6797f2C78C448 Version: webpack 3.10.0 Time: 903ms Asset Size Chunks Chunk Names build.js 627 kB 0 [emitted] [big] main [0] (webpack)/buildin/global.js 509 bytes {0}  [built] [3] multi (webpack)-dev-server/client? http://localhost:8080./ SRC /app.js 40 bytes {0} [built] [4] (webpack)-dev-server/client?http://localhost:8080 7.91 kB {0} [built] ... [28]./node_modules/timers-browserify/main.js 1.9 kB {0} [built] + 15 hidden Modules webpack: Compiled successfully.Copy the code

Open the browser, visit: http://localhost:8080, at this time we are familiar with the screen again, O(∩_∩)O~~. If we try to modify the MSG content in app.js, the content of the browser will also change, isn’t it cool? Let’s try it.

Use the NPM script

For the packing commands./node_modules/.bin/webpack and the real-time development commands./node_modules/.bin/webpack-dev-server, you can quickly copy and paste input from the command line, but you can’t avoid typing it the first time. How can a lazy programmer accept typing so many extra characters? The scripts field in the package.json file can help us solve this problem.

Let’s take a look at the introduction:

Scripts are used to specify the NPM command line abbreviations for running script commands. For example, start specifies the commands to be executed when running NPM run start.

Ok, now that we know what it does, let’s try to rewrite the package.json file and change the scripts field to something like this:

"scripts": {
  "dev": "webpack-dev-server",
  "build": "webpack"
}
Copy the code

Then, on the command line, type:

npm run dev
Copy the code

You’ll find the same effect as executing./node_modules/.bin/webpack-dev-server.

Note: Here, the webpack-dev-server command is specified in scripts, leaving out the command path, because when NPM executes scripts, the command in the current directory./node_modules/.bin/ will be executed by default, and if it cannot be found, the global command will be executed.

Similarly, to execute NPM run build is to package and output the build.js file we want.

CSS preprocessor

CSS is powerful enough, but in the eyes of programmers, it has always been a cumbersome thing, it has no variables, no conditional statements, just a simple line of description, very cumbersome to write. So a variety of CSS preprocessors emerged, one of my favorite is SASS, using SASS syntax to write our style files, will greatly improve our development efficiency, making CSS engineering become a lot easier.

Next, how to integrate into our project.

For Webpack, everything is module, all files form dependencies through module introduction, and for each module introduction or preprocessing, are implemented by loader. Since our SASS syntax browser is not recognized, we need to use the relevant loader to pre-process its input and convert it into the corresponding CSS. Although CSS browsers recognize it, WebPack is essentially a static module wrapper for a javascript application, where all file content is processed as javascript and then processed later. Therefore, in addition to pre-processing the LOADER of SASS, we also need to load the loader of CSS. Finally, we need to convert the style-loader to dynamically create the style tag in the index.html through JS.

With this in mind, we know what to do: first install the required loader:

# Since 'sass-loader' needs to rely on 'node-sass', install it as well
npm install style-loader css-loader sass-loader node-sass --save-dev
Copy the code

Modify the webpack.config.js configuration file and add the relevant loader configuration:

module.exports = {
  / /...
  module: {
    // This is used to configure the loader used to process files with different suffixes
    rules: [
      {
        test: /\.scss$/.use: [{loader: 'style-loader'
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'sass-loader'}]}}Copy the code

Webpack loader supports chained transfer, which can use pipline processing for resources. A group of chained Loaders will be processed in reverse order. Here is the processing flow: sass-loader -> css-loader => style-loader

With that configured, let’s test it by creating an app. SCSS file in the SRC directory with the following contents:

$red: rgb(218.42.42);

h1 {
  color: $red;
}
Copy the code

Then in the SRC /app.js file introduce:

require('./app.scss');

var Vue = require('vue');

new Vue({
  el: "#app".template: "<h1>{{ msg }}</h1>",
  data () {
    return {
      msg: 'Hello Vue.js'}}});Copy the code

Run NPM run dev again and you’ll notice that our h1 tag has changed color. App.scss: app.scss: app.scss: app.scss: app.scss: app.scss: app.scss: app.scss: app.scss: app.scss

h1 {
  color: #da2a2a;
}
Copy the code

If you are not familiar with the use of SASS, you are advised to check out this basic introduction document: The SASS Usage Guide

Image to load

Now that we’re talking about CSS static resources, it’s natural to load images. As mentioned above, in WebPack, everything is modular, and images are of course introduced as modules. Since it is a module, it is inevitable to introduce the relevant loader, here we use the image to introduce the urL-loader, first install:

npm install url-loader --save-dev
Copy the code

Add url-loader configuration:

module.exports = {
  // ...
  module: {
    // This is used to configure the loader used to process files with different suffixes
    rules: [
      // ...
      {
        test: /\.(jpe? g|gif|png)$/.use: 'url-loader'}}}]Copy the code

Then add to app.js:

require('./app.scss');

var Vue = require('vue');
var logoSrc =  require('./logo.jpg')

new Vue({
  el: "#app",
  data () {
    return {
      msg: 'Hello Vue.js'
    }
  },
  render (h) {
    return (
      h('div', [
        h('img', {
          domProps: {
            src: logoSrc,
            alt: 'logo'.className: 'logo'
          }
        }),
        h('h1'.this.msg)
      ])
    )
  }
});
Copy the code

Here we use the render function to customize our node, which contains the default h argument, which is just another name for the createElement argument we talked about in the fancy render target element, for simplicity of writing. The first argument to the h function is the DOM name, the second argument is the creation configuration object, and domProps is used to add dom related property values. Here we assign the logoSrc we introduced to its SRC property.

Then re-run NPM run Dev and the desired logo image appears on the page.

conclusion

Know yourself and know your enemy, one hundred battles are not dangerous, we only really understand the use of Webpack skills, in the actual development, we will be more handy. Not to be scared by a silly mistake. Programmers have three treasures: learn more, write more, summarize more, we will continue to improve programming skills.

The source code in this

Project directory

You-May-Not-Know-Vuejs