preface

It has been nearly two months since the last article that Webpack4 set up vUE project in 9102, and I have no time to write the article. The company has a lot of projects, and I have been working overtime in the past two months. Therefore, I can not share the article with you until today. If you want to read the previous article, go here to juejin.cn/post/684490…

All right, let’s cut the crap and start stroking the code.

1. Create a folder

Mkdir wepack-vueCopy the code

2. Create a package.json file

npm init -yCopy the code

3. The webpack configuration

Create a New Build folder

mkdir buildCopy the code

Build folder create webpack.base.conf.js, webpack.dev.conf.js, webpack.prod.conf.js

  • Webpack.base.conf.js holds the common configuration
  • Webpack.prod.conf.js stores the production environment configuration
  • Webpack.dev.conf.js holds the development environment configuration

Create the SRC folder and create main.js

Create index. HTML

<! DOCTYPE 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> Webpack builds vue project </title> </head> <body> <div id="app"></div>
</body>
</html>Copy the code

Download webpack webpack-dev-server webpack-cli

npm i webpack webpack-dev-server webpack-cli -DCopy the code

Open webpack.base.config.js and configure the overall webPack properties

var path = require('path');
var webpack = require('webpack');
module.exports = {
    entry: {
        main: path.resolve(__dirname, '.. /src/main.js')
    },
    output: {
        path: path.resolve(__dirname, '.. /src'),
        filname: '[name].[bash].js',}, the module: {rules: []}, pligins: [new webpack. HashedModuleIdsPlugin (), / / solve behind the venderhashResolve: {}}Copy the code

4. Configuration loader

  • Download babel-loader, babel-core, babel-preset-dev, rules and configure JS

Babel-preset -env helps us configure Babel. All we need to do is tell it what we want to be compatible with (the target runtime environment), and it will automatically convert the code to be compatible with the corresponding environment.

Babel-core is the core of Babel, the core API of Babel is in this module

If Babel is 7.x, babel-core must be 6.x, otherwise it will not be compatible

npm i babel-loader@7 babel-core babel-preset-env -DCopy the code

rules:[
    {
        test: /\.js$/,
        use: ['babel-loader'],
        exclude: /node_modules/
    }
]Copy the code
  • Create a. Babelrc file. Babelrc is the Babel global configuration file

{
    "preset": [['env', {"targets"{// specify the environment to translate to // browser environment"browsers": ["1%" >."last 2 versions"."not ie <= 8"],}, // Whether to translate ES6's modular syntax into other types"modules": false}}]]Copy the code

  • Download file-loader, rules and config files (images and fonts)

npm i file-loader -DCopy the code

rules:[
    {
        test: /\.(jpg|png|svg|gif)$/,
        use: ['file-loader'] {},test: '/\.(woff|woff2|eot|ttf|otf)$/',
        use: ['file-loader']]},Copy the code
  • Download csS-loader, ue-style-loader, sass-loader, node-sass, and configure CSS, SCSS, and SASS

npm i css-loader vue-style-loader sass-loader node-sass -DCopy the code

rules:[
    {
        test: /\.(sa|sc|c)ss$/,
        use: [
                {loader: 'vue-style-loader'},
                'css-loader'.'sass-loader']]},Copy the code

  • Download less, less-loader, and configure less

npm i less-loader less -DCopy the code

rules:[
    {
        test: /\.less$/,
        use: [
                {loader: 'vue-style-loader'},
                'css-loader'.'less-loader']]},Copy the code

5. Generate AN HTML file

  • Download the HTml-webpack-plugin and configure it

npm i html-webpack-plugin -DCopy the code

Var HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__diename, '.. /index.html')}),]Copy the code

6. Configure the parsing module

Resolve: {// Enable users to import modules without extensions: ['.js'.'.json'.'.vue'.'css']}Copy the code

The base module configates something but does not complete it, adding it bit by bit later, and then configuring dev and Prod

7. Configuration webpack. Dev. Conf

  • Download webpack – merge

npm i webpack-merge -DCopy the code

  • webpack.dev.js

var merge = require('webpack-merge');
var baseConfig = require('./webpack.base.conf');
var path = require('path');
var webpack = reuire('webpack');
module.exports = merge(baseConfig, {
    devtool: 'inline-source-map'// Compression mode:'development'
    devServer: {
     hot: true// Open:trueContentBase: path.resolve(__dirname,'.. /dist'), / / tell services which provide content from}, plugins: [new. Webpack. HotModuleReplacementPlugin (), / / open hot update]})Copy the code

8. Configuration webpack. Prod. Conf

  • webpack.prod.conf.js

var merge = require('webpack-merge');
var baseConfig = require('./webpack.base.conf');
var path = require('path');
var webpack = reuire('webpack');
module.exports = merge(baseConfig, {
    devtool: 'source-map'// Compression mode:'production'
    plugins: [
    ]
})Copy the code

9. The configuration vue – loader

  • Download vue-loader, Vue, vue-template-compiler, and configure the VUE parsing file, configure webpack.base.cond.js

npm i vue vue-loader vue-template-compiler -D
Copy the code

var VueLoaderPlugin = require('vue-loader/lib/plugin'); // omit the code...... rules:[ {test: /\.vue$/,
        use: ['vue-loader'], exclude: /node_modules/},] // omit the code.......Copy the code

// omit the code.... Plugins: [new VueLoaderPlugin(), // It is your job to copy the other rules you defined and apply them to the language blocks in the.vue file.Copy the code

  • Configure the vue alias to make sure webpack can find the. Vue file

// omit code... reslove: {alias: [
        'vue$': 'vue/dist/vue.esm.js', // configure the alias to ensure that webpack can find the. Vue fileThe '@': path.resolve(__dirname, '.. /src')]}Copy the code

  • Create a new app. vue file

<template>
    <div>{{str}}</div>
</template>
<script>
export default {
  name: 'App'.data () {
    return {
      str: 'hello'
    }
  }}
</script>
<style>
div {
  color: red;
}
</style>
Copy the code

  • Introduce vue in main.js

import VUe from 'vue'
import App from './App'

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

10. Configure commands

  • Find the package.json file and configure the development and packaging commands

// omit code..."scripts": {
  "dev": "webpack-dev-server --progress --config build/webpack.dev.conf.js"."build": "webpack --config build/webpack.prod.conf.js"
  }Copy the code

  • Run the project

npm run devCopy the code

You can see the project is already running



11. Import different addresses based on the environment

  • Create the config folder and create dev.ev.js and prod.env.js

Dev.env.js development environment configuration

'use strict'

module.exports = {
    NODE_ENV: '"development"',
    BASE_API: '"http://1456"',}Copy the code

Prod.env.js Production environment configuration

'use strict'

module.exports = {
    NODE_ENV: '"production"',    BASE_API: '"http://123.com"',}Copy the code

Optimize the WebPack configuration

  • Dist file was not cleared when the file was packaged, and was packaged again.

Download the clean-webpack-plugin and configure the webpack.prod.conf.js file

npm i clean-webpack-plugin -DCopy the code

Var CleanWebpackPlugin = require('clean-webpack-plugin'); // omit code... plugins: [ new CleanWebPackPlugin(); ]Copy the code

  • Extract CSS based on different environments

Download the mini-CSs-extract-plugin and configure the webpack.prod.conf.js file

npm i mini-css-extract-plugin -DCopy the code

Change the code that uses vue-style-loader in webpack.prod.conf.js to

 module: {
        rules: [
            {
                test: /\.(c|sc|sa)ss$/,
                use: [
                  {
                    loader: MiniCssExtractPlugin.loader,
                  },
                  'css-loader'.'sass-loader'] {},test: /\.less$/,
            use: [
                {
                loader: MiniCssExtractPlugin.loader,
                },
                'css-loader'.'less-loader']]}},Copy the code

Configure in plugin for webpack.prod.conf.js

new MiniCssExtractPlugin({
    filename: '[name].[hash].js'
})Copy the code

Remove the code that uses vue-style-loader from webpack.base.conf.js and define it in webpack.dev.conf.js

  module: {
    rules: [
      {
        test: /\.(c|sc|sa)ss$/,
        use: [
          {
            loader: 'vue-style-loader',},'css-loader'.'sass-loader'] {},test: /\.less$/,
        use: [
          {
            loader: 'vue-style-loader',},'css-loader'.'less-loader']]}},Copy the code

This configuration vue – loader has mentioned vue-loader.vuejs.org/zh/guide/ex…

  • Third-party libraries are packaged separately

Extract the dependent third-party libraries and package them separately to speed up the packaging process

Download autodll webpack — the plugin

npm i autodll-webpack-plugin -DCopy the code

Configure it in webpack.base.conf.js

var AutodllWebpackpackPlugin = require('autodll-webpack-plugin');
plugins: [
    new AutodllWebpackpackPlugin ({
        inject: true,
        debugger: true,
        filename: '[name].js',
        path: './dll',
        entry: {
            vendor: ['vue']}})]Copy the code

tips: injectWhen true, the plugin automatically inserts packaged third-party library files into HTML.
filenameIs the name of the packaged file.
pathIs the packaged path.
entryIs the entrance.
vendorIs the name you specify, the contents of the array is the name of the third party library to package, do not write the full path, Webpack will automatically go
node_modulesFound in the.
  • Extract common code

Add the following plug-in object to the plugins property of webpack.base.conf.js

new webpack.optimize.SplitChunksPlugin()Copy the code

  • Compress JS and CSS when packaging

Download optimize- CSS -assets-webpack-plugin and uglifyjs-webpack-plugin

npm i uglifyjs-webpack-plugin uglifyjs-webpack-plugin -DCopy the code

Optimize – CSS-assets-webpack-plugin and Uglifyjs-webpack-plugin are introduced respectively in webpack.prod.conf.js and optimization is added

var OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
var UglifyJsPlugin = require("uglifyjs-webpack-plugin"); / /... Optimization: {minimizer: [// compression JS new UglifyJsPlugin({uglifyOptions: {compress: {warnings:false// Remove warning drop_debugger:true// Remove debugger drop_console:true// Remove console.log},}, cache:true, // enable caching parallel:true// Parallel compressionsourceMap: false // set to true if you want JS sourceMaps}), // Compression CSS new OptimizeCSSAssetsPlugin({})]},Copy the code

  • The CSS automatically adds prefixes

Download postCSS-Loader and autoprefixer

npm i postcss-loader autoprefixer -DCopy the code

Add postCSs-loader to the use of webpack.dev.conf.js and webpack.prod.conf.js respectively

use: [
    'postcss-loader'
]Copy the code

Add postcss.config.js under the project

Module. exports = {plugins: [require(plugins, plugins, plugins, plugins)'autoprefixer')]}Copy the code

The above configuration of the project can run, thank you, if there is a mistake, please point out, together in the code farming road more and more far

Grateful cheat point star project address github.com/mr-mengbo/w…

placeholder

The next article will cover the vUE build backend project