Writing in the front

Thanks to the failure of Webpack class library last time (last article), I remember the importance of Webpack and other related packaging tools again. After a little research, I found that in fact, many people with a little work experience generally have a low understanding of Webpack. Most of the time, we know the NPM run build, but we don’t know what Webpack does after the run. Another reason is that most of the time, we are in the business development, packaging and launching work is basically handled by the team master. As a result, many people do not have access to Webpack configurations, let alone modify and optimize them. Therefore, this time, I will share my notes on the basic configuration exercise of Webpack, hoping to give a reference to friends who want to know about Webpack configuration. The steps are detailed and simple, and I hope that beginners can start quickly. If you find fault with the words of big guys, your opinions are indispensable nutrition for our younger generation.

Configure the environment

This paper uses Ts + Vue, which is popular at present, as the contact carrier, and Webpack uses Webpack@5. I hope I can get familiar with the combination of Ts + Vue in the process of practicing Webpack configuration, so as to facilitate the later transfer of technology stack

First, Webpack configuration

1. NPM and TS initialize and install webPack-related packages

npm init -y
tsc --init
npm i webpack webpack-cli webpack-dev-server -D
Copy the code

2. Create the following files and folders according to the structure

/build/webpack.base.config.js
/build/webpack.dev.config.js
/build/webpack.pro.config.js
/build/webpack.config.js

/src/tpl/index.html

/src/index.ts
Copy the code

/ SRC/TPL /index.html. Note that class=’app’ is the identification point for all subsequent changes

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial scale=1.0"> <title>Typescript</title> </head> <body> <div class="app"></div> </body> </ HTML >Copy the code

4, in the/build/webpack. Base. Config. Js writes based configuration

const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
  // Import file
  entry: "./src/index.ts".// Output file name, default output to the root directory
  output: {
    filename: "app.js"
  },
  // Configure the file extension to compile
  resolve: {
    extensions: ['.js'.'.ts'.'tsx']},// Configure files to be compiled by ts-loader
  module: {
    rules: [{test: /\.tsx? $/i,
        use: [{
          loader: "ts-loader"}].exclude: /node_modules/}},// Add an HTML plug-in and specify a template file
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/tpl/index.html"}})]Copy the code

5, in the/build/webpack. Dev. Config. Js development environment configuration is added

// Reserve configuration related to the development environment
module.exports = {}
Copy the code

6, in the/build/webpack. Pro. Config. Js add production environment configuration

const { CleanWebpackPlugin } = require('clean-webpack-plugin') 
module.exports = {
  // Delete the old ones every time you compile and keep only the latest ones
  plugins: [
    new CleanWebpackPlugin()
  ]
}
Copy the code

7. Import all configurations in /build/webpack.config.js

const {merge} = require('webpack-merge')
const baseConfig = require('./webpack.base.config')
const devConfig = require('./webpack.dev.config')
const proConfig = require('./webpack.pro.config')

// Combine base configuration with production/development configuration based on environment parameters
module.exports = (env, argv) = > {
  let config = argv.mode === 'development' ? devConfig : proConfig
  return merge(baseConfig, config)
}
Copy the code

Install the plugins used during the WebPack configuration

npm i typescript ts-loader html-webpack-plugin clean-webpack-plugin webpack-merge
Copy the code

9. Configure the WebPack startup script in package.js

"scripts": {
    "start": "webpack-dev-server --mode=development --config ./build/webpack.config.js"."build": "webpack --mode=production --config ./build/webpack.config.js"
  },
Copy the code

2. Configure vUE

1, NPM I Vue install VUE

2. Introduce Vue in/SRC /index.ts and create an instance

import Vue from 'vue'
let app = new Vue({
  el: '.app'.data: {
    name: 'typescript',},template: '<h1>Hello {{ name }}</h1>'
})
Copy the code

3. Run NPM start to compile and run, an error is reported

4, / build/webpack. Base. Config. The resolve of js configuration items to add alias vue, introducing the vue ES6 full version, run successfully vue

resolve: {
    extensions: ['.js'.'.ts'.'tsx'].alias: {
      vue: 'vue/dist/vue.esm.js'}},Copy the code

5. Next, try importing a component, creating a hello. vue component in/SRC/Components

<template>
  <h1>Hello {{ name }} </h1>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  data(){
    return {
      name: 'typescript'}}})</script>

<style scoped>
h1 {
  color: cadetblue;
}
</style>
Copy the code

/ SRC /index.ts/hello. vue

import Vue from 'vue'
// Add the vue suffix. If you do not add the ts suffix, an error is reported
import Hello from './components/Hello.vue'

let app = new Vue({
  el: '.app'.components: {
    Hello
  },
  template: '<Hello />'
})
Copy the code

7, the compiler reported an error, adding vue.shims.d.ts definition file to the.vue file

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}
Copy the code

8, parsing. Vue files need to install related plug-ins

npm i -D vue-loader vue-template-compiler css-loader

9. Modify webPack configuration

In. / build/webpack base. Config. Js extensions of the resolve to add the vue extensions

resolve: {
    extensions: ['.js'.'.ts'.'tsx'.'vue'].alias: {
      vue: 'vue/dist/vue.esm.js'}},Copy the code

Add vue-loader, vue-style-loader, and CSS-loader to rules in module. Add appendTsSuffixTo in ts-loader options. Ts suffixes are automatically added to. Vue files to facilitate TS-Loader parsing

module: {
    rules: [{test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.tsx? $/i,
        use: [{
          loader: "ts-loader".options: {
            appendTsSuffixTo: [/\.vue$/]}}],exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader'.'css-loader']]}},Copy the code

Finally, add vue-loader plug-in

const { VueLoaderPlugin } = require('vue-loader')
module.exports = {
  .......
  plugins: [...new VueLoaderPlugin()
  ]
}
Copy the code

10. Run NPM start to compile, and the entire configuration process is complete

Incurable diseases

At present, many NPM packages are iterated frequently, so there may be packaging failure caused by incompatibility of plug-in versions in the process of reconfiguring this article. Therefore, various configuration files are attached for your reference:

// package.json
{
  "name": "vue-ts"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "start": "webpack-dev-server --mode=development --config ./build/webpack.config.js"."build": "webpack --mode=production --config ./build/webpack.config.js"
  },
  "keywords": []."author": ""."license": "ISC"."devDependencies": {
    "clean-webpack-plugin": "^ 4.0.0"."css-loader": "^ 6.5.1." "."html-webpack-plugin": "^ 5.5.0"."ts-loader": "^ 9.2.6"."typescript": "^ 4.5.2." "."vue-loader": "^ 15.9.8"."vue-template-compiler": "^ 2.6.14"."webpack": "^ 5.64.4"."webpack-cli": "^ 4.9.1." "."webpack-dev-server": "^ 4.6.0"."webpack-merge": "^ 5.8.0"
  },
  "dependencies": {
    "vue": "^ 2.6.14"}}Copy the code
// webpack.base.config.js is fully configured
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
module.exports = {
  entry: "./src/index.ts".output: {
    filename: "app.js"
  },
  resolve: {
    extensions: ['.js'.'.ts'.'tsx'.'vue'].alias: {
      vue: 'vue/dist/vue.esm.js'}},module: {
    rules: [{test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.tsx? $/i,
        use: [{
          loader: "ts-loader".options: {
            appendTsSuffixTo: [/\.vue$/]}}],exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'vue-style-loader'.'css-loader']]}},plugins: [
    new HtmlWebpackPlugin({
      template: "./src/tpl/index.html"
    }),
    new VueLoaderPlugin()
  ]
}
Copy the code
// webpack.config.js is fully configured
const {merge} = require('webpack-merge')
const baseConfig = require('./webpack.base.config')
const devConfig = require('./webpack.dev.config')
const proConfig = require('./webpack.pro.config')

// Combine base configuration with production/development configuration based on environment parameters
let config = process.env.NODE_ENV === 'development' ? devConfig : proConfig
console.log(process.env.NODE_ENV)
module.exports = merge(baseConfig, config)
Copy the code
// webpack.pro.config.js is fully configured
const { CleanWebpackPlugin } = require('clean-webpack-plugin') 
module.exports = {
  plugins: [
    new CleanWebpackPlugin()
  ]
}
Copy the code

conclusion

In the reign of the era of the framework now may be a lot of people have been inseparable from the framework, as the framework, automated build tools more and more intelligent, more details are encapsulated, more of our time is occupied by the business development, I asked myself a question, when a certain time, when I put down the framework, I can also do these myself not complex configuration? This problem reminds me that in the leisure time of completing business development, we should not lose the seemingly tedious and meaningless basic things. After all, those are the things that can support us to go further!

Write in the last

The blogger will continue to update good articles, welcome to follow the blogger yo!! If the article is helpful to you, please click like, collect + attention and grow up with the blogger!! ❤ ❤ ❤