preface

We often use vuE-CLI scaffolding to set up a Vue development environment for efficiency. Yes, this tool saves us a lot of time, but have you ever wondered how a Vue development environment is set up? And if you built it yourself, would you be able to build it?

Based on these ideas, I tamped up the Webpack4, and get down the small project, feel a small project down the goods is still quite big, so write an article, share experience, ha ha!!

Based on personal time and energy, this project is divided into two parts:

  • Webpack4 Manual build Vue development environment (this article)
  • Manually build Vue project folder todoList (including Vue bucket)

Hope you can finish the tutorial, and can receive the goods you want, hee hee, ok, go!!

I. Set up the Running environment of WebPack

Due to the length of the article, this tutorial will not cover the knowledge of Webpack4 in detail. If you are confused or confused about the steps to build webpack4, you can do a Google search first.

Initialize the project

Run NPM init -y on the command line to initialize the project and produce package.json files

Install webPack dependencies

npm i webpack webpack-cli --save-dev

Set up the basic project directory

Basic configuration of webpack.base.dev.js

Modifying script Commands

Modify the scripts configuration in package.json

Run webpack

In main.js type document.write(“Hello World”)

Configure the webpack.base.dev.js file based on the above image

Run the NPM run test command on the command line. Js files will be generated in the dist folder

In index.html, if Hello World is successfully printed, the webPack runtime environment is successfully configured.

2. Start setting up the Vue environment

Vue operating environment is divided into development environment and production environment, different environment for the function of the implementation requirements are not the same, such as production environment needs to compress code, and development environment needs sourceMap for debugging, and these two environments also have a common configuration!!

In the following sections, I’ll walk you through the features that need to be implemented in different environments

Create a new file in build

  • webpack.base.conf.jsCommon profile
  • webpack.dev.conf.jsDevelopment environment configuration files
  • webpack.prod.conf.jsProduction environment configuration file

Common profile

Webpack.base.conf.js is a common configuration file that needs to implement the following functions:

  • Font processing
  • Image processing and optimization
  • Identify Vue files
  • Enable Babel transcoding to convert ES6 to ES5 code
  • Music file processing
  • Configure the packaged HTML template
  • Configure the resolve module

Configure the command to run the script in the package.json file:

"test":"webpack --config build/webpack.base.conf.js"

To run the webpack.base.conf.js configuration file, run NPM run test on the command line

Development environment configuration files

Webpack.dev.conf.js is a configuration file for a development environment that focuses on debugging efficiency:

  • Package CSS and LESS files and set sourceMap to facilitate locating and debugging
  • postcss-loaderAutomatic prefix adding
  • Configure devServer to enable the hot update function

Configure the command to run the script in the package.json file:

"dev":"cross-env NODE_ENV=development webpack-dev-server --inline --progress --config build/webpack.dev.conf.js"

To run the webpack.dev.conf.js configuration file, run NPM run dev on the command line

Production environment configuration file

Webpack.prod.conf.js is a production environment configuration file that focuses on compressed code and performance:

  • Package handles CSS and LESS files
  • mini-css-extract-pluginExtract styles into separate CSS files
  • postcss-loaderAutomatic prefix adding
  • clean-webpack-pluginThe dist folder is created each time the package is cleaned
  • optimize-css-assets-webpack-pluginCompress the CSS file code
  • terser-webpack-pluginZip the JS file code

Configure the command to run the script in the package.json file:

"build":"cross-env NODE_ENV=production webpack --config build/webpack.prod.conf.js"

To run the webpack.prod.conf.js configuration file, run NPM run build on the command line

3. Set up the public profile function

The above three configuration files need to achieve the functions are listed, now as long as the function to build, to configure it, ok, start!!

Start the common configuration functionality in webpack.base.conf.js

Configure processing fonts, pictures, music functions

Handling fonts, images, and music requires installing dependencies

npm i url-loader file-loader --save-dev

The configuration code is as follows

const path = require('path');

module.exports = {
    entry: path.resolve(__dirname, '.. /src/main.js'),
    output: {
        filename: 'js/[name].[hash:5].js',
        path: path.resolve(__dirname, '.. /dist'),
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.(png|jpe? g|gif|svg)(\? . *)? $/, use: [{ loader:'url-loader',
                        options: {
                            limit: 10000,
                            name: 'img/[name]-[hash:5].[ext]',}}]}, {test: /\.(woff2? |eot|ttf|otf)(\? . *)? $/, loader:'url-loader',
                options: {
                    limit: 10000,
                    name: 'fonts/[name]-[hash:5].[ext]',}}, {test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\? . *)? $/, use: [ { loader:'url-loader',
                        options: {
                            limit: 4096,
                            name: 'media/[name]-[hash:5].[ext]',}}]}},}Copy the code

Url-loader and file-loader have similar functions. They both process images, font ICONS and other files in Webpack

The relationship between them is that url-loader encapsulates file-loader, but url-loader does not depend on file-loader

Url-loader can process images based on the limit attribute. When the size of an image is smaller than limit (byte), the image is transferred to Base64. When the size is larger than limit, the image is processed by file-loader.

ES6 converts ES5 code

When I learned how to configure ES6 conversion code using Babel, I really spent a lot of effort. It took a long time to configure, and I didn’t know what the relationship was between many loaders. Later I saw the official website and other people’s blogs.

Install the relevant loader first

npm i babel-loader @babel/core @babel/polyfill @babel/preset-env core-js@3 --save-dev

  • babel-loaderOnly ES6 syntax conversions are supported, but the new APIS of ES6 are not
  • babel-polyfillYou can add new additions to THE ES6 API for client support
  • babel-preset-envYou can configure the runtime environment to be JS compatible
  • babel-coreThe JS code is analyzed into AST, which is convenient for each plug-in to analyze the syntax for corresponding processing

Look at the configuration code

This configuration only supports ES6 syntax conversion, and does not support the new ES6 API

Add import @babel/polyfill to the entry file main.js

This way, you can use the new API of ES6, but you will find that the JS file is bigger after packaging, and there are many ES6 apis in it that you do not use, so you need to import on demand

Create the babel.config.js file in the root directory and set the configuration in it

Well, this can be implemented on demand, can greatly reduce the size of packaged JS files, HMMMM, I also finally put the knowledge out (face) (bitter face) ~~~

Configure packaged Vue files

First, install the dependencies

npm i vue vue-loader vue-template-compiler --save-dev

Create a new Vue file app.vue in the SRC folder

Import the Vue from the main.js entry file and mount it to the node

Ok, start packing the configuration of the Vue file

That’s it. The code for packing the Vue and mounting the node is typed by hand

Configure the HTML template page

Install dependencies

npm i html-webpack-plugin --save-dev

Use the HTML-webpack-plugin to create HTML pages and automatically import the generated files from the package

const HtmlWebpackPlugin = require('html-webpack-plugin');

plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname,'.. /index.html'),
            filename: 'index.html'}),]Copy the code

For details, see the NPM documentation

www.npmjs.com/package/htm…

Configure the resolve module

Configure alias to facilitate path retrieval and configure the default file name extension

    resolve: {
        extensions: ['.js'.'.json'.'.vue'].alias: {
            The '@': path.resolve(__dirname,'.. /src')}}Copy the code

"@":" Point to SRC folder"

Ok, now that you’ve completed the common part of the configuration file, it’s time to configure for the environment!!

You can run the common configuration file by running NPM run test on the command line

Iv. Production environment configuration

All right, open it!!

Do this in the webpack.prod.conf.js file

Defining environment variables

The DefinePlugin plugin is provided in Webpack to make it easy to define environment variables

plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')}})],Copy the code

Handles CSS and LESS files

Production CSS and LESS files require extracting CSS styles into a separate CSS file

And the prefix, sourceMap, is automatically added

Handles CSS and LESS files

npm i css-loader less less-loader --save-dev

Automatic prefix adding

npm i postcss-loader autoprefixer --save-dev

Extract CSS styles to separate CSS files

npm i mini-css-extract-plugin --save-dev

The length is too long to screenshot, directly on the code

const webpackConfig = require('./webpack.base.conf');
const merge = require('webpack-merge');
const webpack = require('webpack'); // Remove CSS style const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = merge(webpackConfig,{
    mode: 'production',
    devtool: 'cheap-source-map',
    module: {
        rules: [
            {
                test: /\.(c|le)ss$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            publicPath: '.. / '
                        }
                    },
                    {
                        loader: 'css-loader'
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            ident: 'postcss'.sourceMap: true,
                            plugins: loader=>[
                                require('autoprefixer')({
                                    browsers: [
                                        "last 2 versions"."1%" >
                                    ]
                                })
                            ]
                        }
                    },
                    {
                        loader: 'less-loader'
                    }
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'css/[name]-[hash:5].css',
            chunkFilename: 'css/[id]-[hash:5].css',})],}Copy the code

Clean up packaging and create folders

As you go through the packaging process, you’re going to see that every time you pack, you’re going to add more files to the Dist folder, so obviously that’s an area that we need to deal with

Installation-dependent dependencies

npm i clean-webpack-plugin --save-dev

Dist const CleanWebpackPlugin = require(dist const CleanWebpackPlugin = require('clean-webpack-plugin');

plugins: [
    new CleanWebpackPlugin(),
],
Copy the code

Compress JS and CSS code

Compressed CSS code

npm i optimize-css-assets-webpack-plugin --save-dev

Compressed JS code

npm i terser-webpack-plugin --save-dev

use

Optimization: {minimizer: [/ CSS/compression new OptimizeCssAssetsWebpackPlugin ({}), / / compression JS new TerserWebpackPlugin ({cache:true,
                parallel: true.sourceMap: true}), // More details can be found on the official website]}Copy the code

To run the development environment configuration file, run NPM run build on the command line

Ok, from the configuration of the development environment, it’s time to configure the production environment

5. Development environment configuration

Do this in the webpack.dev.conf.js file

A little tired (covering his face)

Defining environment variables

As with production, environment variables are defined first

new webpack.DefinePlugin({
    'process.env': {
        NODE_ENV: JSON.stringify('development')}}),Copy the code

Handles CSS and LESS files

CSS and LESS in the development environment do not need to extract styles, just add prefixes and sourceMap for easy debugging

Install dependencies

Handles CSS and LESS files

npm i style-loader css-loader less less-loader --save-dev

Automatic prefix adding

npm i postcss-loader autoprefixer --save-dev

const webpackConfig = require('./webpack.base.conf.js');
const merge = require('webpack-merge');
const path = require('path');
const webpack = require('webpack');

module.exports = merge(webpackConfig,{
    mode: 'development', / /source-map, which maps the compiled code to the original code to locate errors. Devtool:'inline-source-map',
    module: {
        rules: [
            {
                test: /\.(c|le)ss$/,
                use: [
                    {
                        loader: 'style-loader',
                        options: {
                            sourceMap: true
                        }
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            sourceMap: true,
                        }
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            ident: 'postcss'.sourceMap: true,
                            plugins: loader=>[
                                require('autoprefixer')({
                                    browsers: [
                                        "last 2 versions"."1%" >
                                    ]
                                })
                            ]
                        }
                    },
                    {
                        loader: 'less-loader',
                        options: {
                            sourceMap: true}}]}},}Copy the code

Configuration devServer

Hot update mode can be opened on Webpack, greatly speeding up the efficiency of opening.

Installation-dependent dependencies

npm i webpack-dev-server --save-dev

In the code

DevServer: {contentBase: path.resolve(__dirname,'.. /dist'),
        // hot: true,
        port: 9090,
        overlay: {
            warnings: true,
            errors: true
        },
        publicPath: '/'} plugins: [/ / enabled modules hot replacement (HMR) new webpack. HotModuleReplacementPlugin (), / / when open HMR using the relative path of the plugin will display module, Suggestions for the development environment. New webpack. NamedModulesPlugin (),,Copy the code

This way you can debug online, no need to manually refresh!! Hee hee

Well, the configuration of the development environment is complete

To run the production environment configuration file, enter NPM run dev on the command line

Six, summarized

The whole Vue development environment configuration, feel learned things or a lot of webpack4 function configuration also have a general understanding

It’s still a far cry from vue-CLI, but sometimes it’s nice to have a little something to toss around!!

Good, this compile article so far, because oneself level is limited, if have what mistake, please point out in time, each other good progress, ha ha!! Thank you guys. (Smiling face)

In the next article, I will use this Vue development environment to write the todoList project

I believe everyone is familiar with todoList, but the same project can be written in different ways, so in the next article, I will continue to manually build Vue folder, handwritten, using VUe-router-vuex to achieve, I believe it will be helpful to everyone, ok, end!!

Github source code: this tutorial source

The next article is manual Vue project construction, to be continued