Webpack学习日记---(1)基础入门

该文详细介绍了Webpack的基础配置,包括项目初始化、自定义配置、自动引入JS文件、处理样式资源、清理打包文件、处理图片和媒体资源、使用ESLint检查代码以及Babel转译JS文件。还涉及Vue开发环境的搭建,如Vue文件解析、自动化热更新和开发生产环境的配置差异。
摘要由CSDN通过智能技术生成

 学习webpack时,为了方便自己复习,写了该博客。

一.基础入门

1.项目初始化

终端输入命令

npm init //生成package.json
npm i -D webpack webpack-cli //安装webpack的npm包

新建src目录和app.js文件

src/app.js:
console.log("测试");

配置package.json

"scripts": {
	"build": "webpack ./src/app.js"
},

终端执行命令

npm run build

文件目录生成dist,webpack默认配置打包成功

2.自定义配置

新建webpack.config.js

const path = require('path');
module.exports = {
    mode:'development', // 开发模式
    entry: path.resolve(__dirname,'./src/app.js'),    // 入口文件
    output: {
        filename: 'main.js',      // 打包后的文件名称
        path: path.resolve(__dirname,'./myDist')  // 打包后的目录
    }
}

修改package.json

"scripts": {
    "build": "webpack --config ./webpack.config.js"
},

再次执行打包命令,可看到输出的目录已经变为自定义的myDist

3.自动引入js文件

打包后生成随机名称的js文件,修改webpack.config.js

module.exports = {
	...
    output: {
        filename: '[name].[hash:8].js',      // 打包后的文件名称
        path: path.resolve(__dirname,'./dist')  // 打包后的目录
    }
}

借助插件:html-webpack-plugin

npm i -D html-webpack-plugin

新建index.html,修改打包配置

module.exports = {
	...
    plugins:[
        new HtmlWebpackPlugin({
            template:path.resolve(__dirname,'./index.html')
        })
    ]
}

修改app.js测试是否自动引入

console.log("测试")

执行打包命令,用浏览器打开打包后的index.html,可看到引入成功

若有多个html文件,修改webpack.config.js

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

4.清除上次打包的文件

webpack5已经内置,只需在output里配置即可

output:{
	...
	clean:true
}

5.处理样式资源

需借助loader, 用于对模块的源代码进行转换

npm i -D style-loader 
npm i -D css-loader //安装对应样式的loader

不同样式资源对应的loader

样式loader
csscss-loader
lessless-loader
sasssass-loader
stylusstylus-loader

新建public/css/index.css

.box{
    color: red;
}

app.js引入,想要打包必须引入

import '../public/css/index.css'

修改index.html

<h1 class="box">hello webPack</h1>

修改打包配置

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"], // 从右向左解析
      },
    ],
  },
};

执行打包命令,浏览器打开index.html

6.样式资源添加浏览器前缀并拆分css

借助插件postcss-loader,autoprefixer,mini-css-extract-plugin

npm i -D postcss-loader autoprefixer  mini-css-extract-plugin

修改打包配置

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {

    ...

    // 插件
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, './index.html')
        }),
        new CleanWebpackPlugin(),
        new MiniCssExtractPlugin({
            filename: "[name].[hash].css",
            chunkFilename: "[id].css",
        })
    ],

    // 加载器
    module: {
        rules: [
            {
                test: /\.css$/,
                // 从右向左解析
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: [
                                    require('autoprefixer')
                                ]
                            }
                        }
                    }
                ]
            },
        ]
    }
}

执行打包命令,可看到拆分成功

7.打包 图片、字体、媒体、等文件

借助插件file-loaderurl-loader 【之前,现在内置了】

  module: {
        rules: [
            {
                test: /\.(jpe?g|png|gif)$/i, //图片文件
                type:'asset',
                generator: {
                    filename: 'static/image/[name].[hash:8].[ext]'
                }
            },
            {
                test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, //媒体文件
                type:'asset',
                generator: {
                    filename: 'static/media/[name].[hash:8].[ext]'
                }
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i, // 字体
                type:'asset',
                generator: {
                    filename: 'static/font/[name].[hash:8].[ext]'
                }
            },
        ]
    }

官方文档:

在 webpack 5 之前,通常使用:

  • raw-loader 将文件导入为字符串
  • url-loader 将文件作为 data URI 内联到 bundle 中
  • file-loader 将文件发送到输出目录

资源模块类型(asset module type),通过添加 4 种新的模块类型,来替换所有这些 loader:

  • asset/resource 发送一个单独的文件并导出 URL。之前通过使用 file-loader 实现。
  • asset/inline 导出一个资源的 data URI。之前通过使用 url-loader 实现。
  • asset/source 导出资源的源代码。之前通过使用 raw-loader 实现。
  • asset 在导出一个 data URI 和发送一个单独的文件之间自动选择。之前通过使用 url-loader,并且配置资源体积限制实现。

8.eslint检查代码格式【可略过】

安装:

npm install eslint-webpack-plugin eslint --save-dev

配置webpack.config.js

plugins: [
		...
        new ESLintPlugin({
            // 检测哪些文件
            context:path.resolve(__dirname,"src")
        }),
],

新建.eslintrc.js

module.exports = {
    //继承Es1int规则
    extends: ["eslint:recommended"],
    env: {
        node: true,//启用node中全局变里
        browser: true,//启用浏览器中全局度量
    },
    parserOptions: {
        ecmaVersion: 6,
        sourceType: "module",
    },
    rules: {
        "no-var": 2,//不能使用var定义变量
    },
}

9.babel转义js文件

安装:

npm i -D babel-loader @babel/preset-env @babel/core

配置webpack.config.js

 module: {
        rules: [
            ...
            {
                test: /\.m?js$/,
                exclude: /node_modules/,//排除工具包里的js
                loader: 'babel-loader',
            }
        ]
    }

新建babel.config.js

module.exports = {
    // 智能预设
    presets:["@babel/preset-env"]
}

babel-loader会将 ES6/7/8语法转换为ES5语法,一些新api不会转换 ,需要polyfill来帮助我们转换

npm install regenerator-runtime core-js

core-js/stable 是用于添加稳定的 ES 新特性 polyfill,而 regenerator-runtime/runtime 则是添加 generator 和 async/await 这类语法糖的 polyfill

//babel.config.js
module.exports = {
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "usage",
      "corejs": 3
    }]
  ]
}

babel.config.js要引入regenerator-runtime,借助@babel/plugin-transform-runtime

npm install --save-dev @babel/plugin-transform-runtime
//babel.config.js
module.exports = {
  "presets": [
    ["@babel/preset-env", {
      "useBuiltIns": "usage",
      "corejs": 3
    }]
  ],
   "plugins": [
    ["@babel/plugin-transform-runtime", {
      "corejs": false,
      "helpers": true,
      "regenerator": true,
      "useESModules": false
    }]
  ]
}

之后,在代码中使用 async/await 和 generator 语法时,就会自动引入所需的 polyfill,不再需要在每个文件中手动引入。

二.实战演习[搭建vue开发环境]

上面的入门已经搭建好了一些前端基础资源的打包,要想搭建vue开发环境,我们还需要一些配置。

1.vue文件解析

既然是vue的开发环境,那么解析vue文件当然是必要的,因此我们也需要下载vue的loader

npm i -D vue-loader vue-style-loader	//解析vue文件
npm i -D vue-template-compiler	//配置模板
npm i -S vue

配置打包文件webpack.config.js

const { VueLoaderPlugin } = require('vue-loader/dist/index')
module.exports = {
   	...
    // 加载器
    module: {
        rules: [
            ...
            //vue
            {
                test:/\.vue$/,
                use:['vue-loader']
            }
        ]
    },
    
    resolve:{
        alias:{
            // vue 模块路径映射  vue模块有多个版本
          'vue$':'vue/dist/vue.runtime.esm-browser.js',
          ' @':path.resolve(__dirname,'../src')
        },
        //解析时要匹配的文件扩展名
        extensions:['.js','.json','.vue']
    }
    
    plugins:[
        new VueLoaderPlugin()
   ]
}

新建src/App.vue测试是否配置成功

<template>
  <div>
    <h1>Hello Vue</h1>
  </div>
</template>

<script setup>

</script>

<style>

</style>

main.js

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.mount('#app')

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>webpack</title>
</head>
<body>
    <div id="app">
    </div>
<script type='text/javascript'>
</script>
</body>
</html>

执行打包命令,浏览器打开打包后的index.html,可看到搭建成功

2.自动化热更新

每次修改完代码,总得手动执行命令,如果能够热更新那就好了。我们可以配置webpack-dev-server进行热更新

npm i -D webpack-dev-server

修改配置webpack-config.js

module.exports = {
	...
    // 开发服务器
    devServer:{
        host:"localhost",
        port:"2754",
        open:true //自动打开浏览器
    }
}

修改package.json

  "scripts": {
    "build": "webpack serve --config ./webpack.config.js"
  },

执行打包命令,可看到启动完毕

现在我们修改文件后,不必再次执行打包命令即可看到效果

3.开发环境与生产环境

当实际配置项目时,我们需要区分开发环境和生产环境,所以新建文件夹config用于放置不同配置文件。

webpack.dev.js开发环境配置文件

不压缩代码,mode设置为development,构建速度快

webpack.prod.js

会将代码压缩提取公共模块等一系列优化措施用于构建出更小、更快的代码,并舍弃了一些用于开发的功能,构建速度相对慢一些,但会获得最佳性能和体积表现。

复制原来的配置文件到config里并修改文件名

webpack.dev.js:

// 记得修改一下绝对路径
module.exports = {
    // 开发模式
    mode: 'development',

    //入口 
    entry: path.resolve(__dirname, '../src/main.js'),    // 入口文件

    //出口
    output: {
        ...
        path: undefined  // 开发模式不需要输出
        clean:false		// 也不需要清空输出目录
    },
}

 webpack.prod.js:

// 记得修改一下绝对路径
module.exports = {
    // 开发模式
    mode: 'production',
    
    //出口
    output: {
        ...
        clean:true		// 清空输出目录
    },

	...

    // 开发服务器 删除 生产环境不需要服务器
    /*devServer:{
        host:"localhost",
        port:"2754",
        open:true //自动打开浏览器
    }*/
}

 修改package.json

  "scripts": {
    "build": "webpack --config config/webpack.prod.js",
    "dev":"webpack serve --config config/webpack.dev.js"
  },

输入命令npm run build,可看到生成了dist,打包成功

输入命令npm run dev,可看到服务器启动成功:

到此,一个简单的vue开发环境就配置好了。

参考文章:2020年了,再不会webpack敲得代码就不香了(近万字实战)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值