webpack教你打包

1. webpack基本概念

目标: webpack本身是, node的一个第三方模块包, 用于打包代码

2.webpack能做什么 

很多文件打包整合到一起, 缩小项目体积, 提高加载速度 \

3. webpack的使用步骤

 1.默认入门和默认出口

    默认入口: ./src/index.js

    默认出口: ./dist/main.js

==注意:路径上, 文件夹, 文件名不能叫webpack/其他已知的模块名==

2.初始化包环境

yarn init -y
npm init -y

3.安装依赖包

yarn add webpack webpack-cli -D
npm i webpack webpack-cli -D

4.配置scripts(自定义命令)

scripts: {
	"build": "webpack"	
}

5.新建文件夹src,在写完代码后,

例如:将js文件进行打包

export const addFn = (a, b) => a + b

在入口文件index.js进行导入

import {addFn} from './add/add'

console.log(addFn(10, 20));

6.运行打包命令

yarn build
#或者 npm run build

7.更新打包

重新输入:

yarn build
npm  i   build

8.webpack默认只能识别js文件

9.插件的使用

目标: html-webpack-plugin插件, 让webpack打包后生成html文件并自动引入打包后的js

1.下载插件

    yarn add html-webpack-plugin  -D

2.webpack.config.js配置

// 引入自动生成 html 的插件
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // ...省略其他代码
    plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.html' // 以此为基准生成打包后html文件
        })
    ]
}

9.插件的使用

说明:像打包css,less,字体图标.,更改入口,出口文件....需要设置配置项

可以访问网址:

https://webpack.docschina.org/concepts/#entry

猜你喜欢

转载自blog.csdn.net/qq_59076775/article/details/120816758