从零学习搭建webpack工程(一)

592 阅读2分钟

传送门:

从零学习搭建webpack工程(二)

从零学习搭建webpack工程(三)

一 、初始化项目,实现webpack打包。

1、新建文件夹webpack-tempalate,cd到当前文件夹,打开git bash 使用命令npm init -y生成 package.json。

2、安装 wenpack,webpack-cli,执行命令npm install -D webpack webpack-cli。 package.json如下图:

{
"name": "webpack-template",//工程项目名称
"version": "1.0.0",//版本号
"description": "",//描述
"main": "index.js",
"scripts": {//脚本
    "test": "echo \"Error: no test specified\" && exit 1"
    },
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {//依赖 
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10"
    }
}

3、在根目录新建文件夹src,在src下新建 index.js 文件,文件目录

4、package.json中script添加 "dev": "webpack --mode=development"

// --mode=development--mode=production,是表示开发环境或是生产环境,生产环境下会对代码进行压缩。

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode=production"
  }

5、使用命令 npm run dev,此时会在根目录下生成文件夹dist,dist下main.js文件。main.js文件即为src下 index文件的打包文件。

!当前版本的webpack为4.41.2,默认入口文件为src下的index.js,打包输出dist下main.js。

二 、配置 wenpack.config.js

1、根目录下新建 wenpack.config.js

module.exports = {
    entry: {//入口
    },
    output: {//出口
    },
    modules:{},//配置loaders
    mode: "development",//环境development | production
    plugins:[]
}

(1)、entry配置:

在src下新建 index.js, list.js 可配置多入口

 entry: {
       index: `./src/index.js`,
       list: `./src/list.js`
   }

(2)、output配置: 在webpack.config.js中引入path :const path = require('path')

output: {
       filename: `[name]/[name].[hash:7].js`,//文件名称
       chunkFilename: `[id].[name].[hash:7].js`,//动态引入的JS文件会形成一个chunk,不会打包到js文件里面
       path: path.resolve(__dirname, dist)//出口路径
   },

2、配置package.json脚本script

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --config webpack.config.js"
  },

3、执行命令 npm run dev,在dist下会生成两个文件夹

三 、打包之前清空dist文件,需要安装plugin:clean-webpack-plugin

1、执行命令npm install clean-webpack-plugin, package.json会新增一条

2、在webpack.config.js中添加plugin 引入clean-webpack-plugin

const { CleanWebpackPlugin } = require("clean-webpack-plugin")

plugins: [
    new CleanWebpackPlugin()
]

传送门:

从零学习搭建webpack工程(二)

从零学习搭建webpack工程(三)