Always feel SSR is a very troublesome thing, involved in the scope of knowledge is quite large, especially with vue-CLI tools, shielding many configuration details. But in the use of SSR, not nuxt.js when to do SSR, or very difficult to get started, simply take a good look at the relevant knowledge in this area, summed up a series of articles. As a supplement to SSR document, I hope to help you.

The target

The main purpose of this article is to explain how a simple Vue-WebPack is built and what each plug-in does. Complete a client-only vuE-Webpack development environment with the following functions:

  • Process vUE single file components
  • Compile ES6
  • Compile Less or Sass
  • Loading pictures
  • Development server
  • Thermal loading
  • Defining environment variables
  • Can compress according to production environment

If you are familiar with this configuration, you can turn it off.

Add basic features

Starting with this section, I will post the step-by-step implementation code, trying to restore the entire configuration in detail.

Creating project files

$ mkdir simple-webpack && cd simple-webpack
$ npm initCopy the code

Then create a new file according to the following directory structure.

. ├ ─ ─ index. The HTML ├ ─ ─ package. The json ├ ─ ─ the SRC │ ├ ─ ─ App. Vue │ ├ ─ ─ App. Js │ └ ─ ─ assets └ ─ ─ webpack. Config. JsCopy the code

Installing dependencies

The dependencies required to install WebPack are:

  • webpack
  • vue-loader
  • babel-core
  • css-loader
  • babel-loader
  • file-loader
  • sass-loader
  • node-sass

When installing sequentially, save the installation dependencies to package.json so that they can be quickly installed the next time they are used in a different environment.

Add Vue code

index.html


      
<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>simple - webpack</title>
</head>
<body>
    <div id="app"></div>
  <script src="/dist/build.js"></script>
</body>
</html>Copy the code

App.vue

<template>
  <div class="demo">
    <h1>Simple-webpack demo</h1>
    <p>This is a simple Vue demo</p>
  </div>
</template>

<script>
</script>

<style>
</style>Copy the code

app.js

import Vue from 'vue'
import App from './App.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})Copy the code

Add the webpack.config configuration

Write the address and filename of our entry file and output file first.

const webpack = require('webpack')
const path = require('path')

module.exports = {
  entry: './src/app.js'.output: {
    path: path.resolve(__dirname, './dist/'),
    filename: 'build.js'}}Copy the code

Add the vue – loader

module.exports = {
  entry: './src/app.js'.output: {
    path: path.resolve(__dirname, './dist/'),
    publicPath: '/dist/'.filename: 'build.js'
  },
  module: {
    rules: [{test: /\.vue$/.loader: 'vue-loader'.options: ' '}}}]Copy the code

At this point, the Webpack can be packaged into a usable program, you can package the file on the static server to run. The webPack Loader and packages used to complete this basic packaging are:

  • vue-loader GitHub – vuejs/vue-loader
  • babel-core babel-core
  • css-loader css-loader

There is a detailed description of this package on the NPM official website, which is not repeated here. You can go to see what work each loader completes in the above packaging process.

To make our code usable in older browsers, we added babel-Loader to convert the ES6 syntax in the file to the version configured in.bablerc at package time.

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

Create.babelrc under the directory and configure it as follows:

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

Then you need to install a Babel plugin, babel-preset-env. For this plugin, see babel-preset-env: a preset that configures Babel for you

Add an image to app.vue:

<template>
  <div class="demo">
    <h1>Simple-webpack demo</h1>
    <p>This is a simple Vue demo</p>
    <img src="./assets/logo.png" alt="">
  </div>
</template>Copy the code

Webpack will report an error when running webpack because there is no loader to load the binaries. Add file – loader:

module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: ' '
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [path.resolve(__dirname, './src')]}, {test: /\.(png|jpg|svg|git)$/,
        loader: 'file-loader',
        include: [path.resolve(__dirname, './src/assets')]}},Copy the code

At present, CSS can be used in the single file component, but SASS cannot be used yet. I will add a corresponding SASS loader to process SASS files, because CSS/SASS is the text segment separated by vue-Loader during code segmentation. We just need to add the corresponding configuration in options of vue-loader.

module: {
  rules: [
    {
      test: /\.vue$/,
      loader: 'vue-loader',
      options: {
        'scss': 'vue-style-loader! css-loader! sass-loader'.'sass': 'vue-style-loader! css-loader! sass-loader? indentedSyntax'}}, {test: /\.js$/,
      loader: 'babel-loader',
      include: [path.resolve(__dirname, './src')]}, {test: /\.(png|jpg|svg|git)$/,
      loader: 'file-loader',
      options: {
        name: '[name].[ext]? [hash]'}}},Copy the code

So far, a Webpack environment configuration with a packaged build Vue project has been written. Next, let’s add two more important AIDS, devServer and Hot Replace.

Add Dev Server and hot update

There are two ways to add a Dev Server mode:

  • webpack-dev-server
  • webpack-dev-middleware

You can see how to use and configure the two types of development on this website. Here we’ll take an easier approach and use webpack-dev-server directly. NPM install -s webpack-dev-server install -s webpack-dev-server install -s webpack-dev-server

"scripts": {
  "test": ""."dev": "webpack-dev-server --open"
}Copy the code

The open parameter indicates that the page is automatically opened in the browser after the service is started. Then open the webpack.config.js file and add the configuration for devServer. In addition to the above configuration, you can also change the host and port, so we’ll use the default. Adding hot replace is also very simple, webpack comes with this plugin, the specific use method can see the module hot replace, the new configuration code is as follows:

module: {
 //...
},
devServer: {
  historyApiFallback: true,
  hot: true,
  noInfo: false,
  overlay: true
},
plugins: [
  new webpack.HotModuleReplacementPlugin()
]Copy the code

Adding environment variables

Process is a module in Node whose env variable can be used to distinguish shell environment variables. This way we can distinguish between development and production builds by NPM run Dev and NPM run Build. Two NPM scripts are modified to distinguish shell environment variables. Here we use the cross-env NPM module to implement custom environment variables.

"scripts": {
  "test": ""."dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot"."build": "cross-env NODE_ENV=production webpack"
}Copy the code
// webpack.config.js
module.exports = {
    / /...
}
console.log(process.env.NODE_ENV)
if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'}}),new webpack.optimize.UglifyJsPlugin({
      sourceMap: true.compress: {
        warnings: false}}),new webpack.LoaderOptionsPlugin({
      minimize: true}})])Copy the code

Two plug-ins have been added to the Production environment to optimize packaged code and compress JS code. The first, DefinePlugin, provides webPack-consistent environment variables for the front-end code so that we can distinguish between different environments in the business code and the development and production environment in the Vue framework based on this environment variable. With a little more configuration refinement, a simple client-only WebPack configuration is written.

const webpack = require('webpack')
const path = require('path')

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, './dist/'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          'scss': 'vue-style-loader! css-loader! sass-loader'.'sass': 'vue-style-loader! css-loader! sass-loader'}}, {test: /\.js$/,
        loader: 'babel-loader',
        include: [path.resolve(__dirname, './src')]}, {test: /\.(png|jpg|svg|git)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]? [hash]'}}]}}if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true}})])else {
  module.exports.devtool = '#eval-source-map'
  module.exports.devServer = {
    historyApiFallback: true,
    hot: true,
    noInfo: false,
    overlay: true
  }
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.HotModuleReplacementPlugin()    
  ])
}Copy the code

This paper is just to sort out the process of creating a simple configuration for the following SSR configuration as the basis. Webpack configuration items are numerous, and the WebPack configuration provided in VUe-CLI is not nearly as simple. For a more advanced approach, read the reference article.

reference

  • Process Objects — JavaScript Standards Reference Tutorial (Alpha)
  • Webpack Chinese document
  • Ue – CLI WebPack configuration Analysis – chenBright – SegmentFault
  • Webpack-simple /template at master · vuejs-templates/webpack-simple · GitHub