Under the use of webpack

foreword

Here we explain the processing: scss, css extract mini-css-extract-plugin, css optimization compression css-minimizer-webpack-plugin, js optimization compression terser-webpack-plugin, set directory alias, Devtool, magic annotation in webpack, Multi-entry, multi-exit, environment variables, no vue scaffolding, build a vue project by yourself (this time build vue3)

1. Handle scss

1. To install, enter the following command

 npm i sass sass-loader -D

2. Configure in webpackconfig.js
insert image description here
3. Function: You can pack scss files that cannot be compiled by the browser into ones that the browser can recognize

2. css extraction mini-css-extract-plugin

insert image description here

1. To install, enter the following command

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

2. Configure in the webpack.config.js file

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    
    
  plugins: [new MiniCssExtractPlugin()],
  module: {
    
    
    rules: [
      {
    
    
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
};

Function: You can extract the css file separately and put it in a folder for easy management

Three, css optimization compression css-minimizer-webpack-plugin

1. To install, run the following command

npm  i  css-minimizer-webpack-plugin -D

2. Configure in the webpack.config.js file

  • This will only enable CSS optimization in production.
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
    
    
  module: {
    
    
    rules: [
      {
    
    
        test: /.s?css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
    ],
  },
  optimization: {
    
    
    minimizer: [
      // 在 webpack@5 中,你可以使用 `...` 语法来扩展现有的 minimizer(即 `terser-webpack-plugin`),将下一行取消注释
      // `...`,
      new CssMinimizerPlugin(),
    ],
  },
  plugins: [new MiniCssExtractPlugin()],
};

  • If you also want to enable CSS optimization in the development environment, set optimization.minimize to true:
// [...]
module.exports = {
    
    
  optimization: {
    
    
    // [...]
    minimize: true,
  },
};

Role: This plugin uses cssnano to optimize and compress CSS. Using query strings in source maps and assets will be more accurate, support caching and run in concurrent mode.

Four, js optimization compression terser-webpack-plugin

1. To install, run the following command

 npm i terser-webpack-plugin -D

2. Configure in the webpack.config.js file

const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
    
    
  optimization: {
    
    
    minimize: true,
    minimizer: [new TerserPlugin()],
  },
};

Role: This plugin uses terser to compress JavaScript.

Five, set the directory alias

1. Configure in the webpakc.config.js folder

module.exports = {
    
    
    resolve: {
    
    
        alias: {
    
    
            '@': path.resolve(__dirname, './src'), //设置@为src目录的别名
        }
    },
};

insert image description here
insert image description here

Six, Devtool

1. Configure in the webpack.config.js file

devtool:"eval-cheap-source-map"

insert image description here

Function: Function: There is a one-to-one correspondence between errors and source codes. This option controls whether to generate and how to generate source maps

Seven, magic annotations in webpack

Prefetch tells the browser that this is a resource that may be used in the future.

Browsers usually obtain these resources in an idle state, and after obtaining the resources, put them in the HTTP cache to facilitate future requests.

  • 1. Installation: first install jQuery
npm i jquery  -S
  • 2. Add a magic comment when configuring import in the webpack.config.js file:
 getJQ(){
    
    
        import(/* webpackChunkName:"jquery",webpackPrefetch:true */"jquery")
        .then(({
     
     default:$})=>{
    
    
             
              alert($("body").text())
        })
    }
//  构造函数
   render(){
    
    
       return(<div onClick={
    
    this.getJQ}> 你好react 我喜欢你</div>)
   }

insert image description here

Function: webpackChunkName: "jquery" Name the current js file
webpackPrefetch: true The network is free to preload js

Eight, multi-entry, multi-exit

1. Configure in the webpack.config.js file

	entry:{
    
    
		"index":'./src/index.js', //入口
		"start":'./src/start.js'
	},
	output: {
    
     //出口
		filename: "[name]-[chunkhash].js", //文件名
		path: __dirname + "/dist" //文件夹
	},

	plugins: [
		/* 把template 文件拷贝到dist目录并插入打包的js(main.js) */
		new HtmlWebpackPlugin({
    
    
			template: './public/index.html', //模板
			chunks:["index"],//入口
			filename:'index.html'//文件名
		}),
		new HtmlWebpackPlugin({
    
    
			template: './public/start.html',
			chunks:["start"],
			filename:'start.html'
		}),
      ]

insert image description here

Function: Two or more entry files can be packaged at the same time

Nine, environment variables

Introduction: Use the environment command to compress the code in the product environment, the production environment does not compress the code, open devtool

Project development:

  • Product environment baseURL hhtp://dida100.com:8888
  • Production environment baseURL http://localhost:8080

cross-env: Run scripts that set and use environment variables across platforms

1. pass parameters

1. Run the following command to install the plugin in the project:

npm  i  cross-env -D

2. Configure in the pack.json file

"build": "cross-env NODE_ENV=production webpack",
"serve": "cross-env NODE_ENV=development webpack serve",

insert image description here
Configure the following code in webpack.config.js:

devtool:process.env.NODE_ENV==="production"?false:"eval-cheap-source-map",
mode:process.env.NODE_ENV,

Use it in the js file

if(process.env.NODE_ENV=="production"){
    
    
	var baseURL = "http://dida100.com:8080"
}else{
    
    
	var baseURL = "http://localhost:8080"
}
console.log(baseURL)

Ten, build a vue project by yourself without vue scaffolding (this time build vue3)

1. Run the following command to install the plugin in the project:

npm   i  vue -S

npm i 
vue-hot-reload-api 
vue-loader 
vue-style-loader
vue-template-compiler 
-D

  • vue-hot-reload-api hot update
  • vue-loader handles .vue files
  • vue-style-loader handles styles
  • vue-template-compiler compile template

insert image description here

2. Configure in the webpack.config.js file

01 导入
const {
    
     VueLoaderPlugin } = require('vue-loader')
---
02配置
rules: [{
    
     test: /\.vue$/, use: ['vue-loader'] }]---
03插件
​ plugins: [new VueLoaderPlugin()]

insert image description here

1. vue document

  • Template file public/start.html
<div id="app"></div>
  • src/start.js
mport {
    
     createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')//创建App并挂载

  • src/App.vue
<template>
	<div>
		<h1>你好vue3</h1>
		<p>{
    
    {
    
    msg}}</p>
		<input type="text" v-model="msg" />
		<button @click="num++">{
    
    {
    
    num}}</button>
	</div>
</template>

<script>
	export default{
    
    
		data(){
    
    
			return{
    
    
				msg:"有饭吃才是王道",
				num:5
			}
		}
	}
</script>

insert image description here

Ten, link and script

  • Wait for the page content to load before loading js
<script  defer src=""></script>
  • preload css ahead of time
<link href="" rel=prefetch>

Guess you like

Origin blog.csdn.net/m0_68907098/article/details/128009663