webpack入门与进阶:简单构建(一)

251 阅读2分钟

为什么需要构建工具

  • 转换ES6语法
  • 转换JSX
  • CSS前缀补全/预处理器
  • 压缩混淆
  • 图片压缩

种类:grunt、gulp、rollup、webpack、parcel

为什么选择webpack

  • 社区生态丰富(下载量大)
  • 配置灵活和插件化扩展
  • 官方更新迭代速度快

初识webpack

  • 配置文件名称
    • 默认配置文件:webpack.config.js
    • 可以通过webpack--config指定配置文件
     // package.json
     "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack --mode=production --config webpack.prod.js",
        "dev": "webpack-dev-server --mode=development --config webpack.dev.js"
      },
    
  • 配置组成
    • entry: 打包入口文件,默认指定:./src/index.js
    • output: 打包的输出,默认输出:./dist/main.js
    • mode: 环境
    • module: Loader配置
    • plugins:插件配置

零配置webpack,只有entry和output的默认配置,没有配置module和plugins。

modules.exports = {
    entry: "./src/index.js",
    output: "./dist/main.js",
    mode: "production",
    module: {
        rules: [
            {test: /\.txt$/, use: 'raw-loader'}
        ]
    },
    plugins: [
        new HtmlwebpackPlugin({
            template: './src/index.html'
        })
    ]
}

环境搭建

安装webpack和webpack-cli

  • 执行命令:npm init -y
    • -y 的意思是,选择yes,会创建一个初始文件
  • npm install webpack webpack-cli --save-dev
    • --save-dev意思是安装到devDependencies,而不会安装到dependencies
  • 检查是否安装成功: ./node_modules/.bin/webpack -v,可查看webpackwebpack-cli 版本号

image.png

2、配置打包文件

在根目录下新建 webpack.config.js

'use strict';

const path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  mode: 'production'
}

3、简单运用webpack打包

  • ①在根目录下新建 src/helloWorld.jssrc/index.js ,目录结构如下: image.png helloWorld.js 文件内容如下:
export function helloWorld() {
  return 'hello world';
}

index.js 文件内容如下:

import { helloWorld } from './helloWorld'

document.write(helloWorld());
  • ②执行打包命令 ./node_modules/.bin/webpack
  • ③打包后的效果 image.png
  • ④测试打包后的文件 创建文件 dist/index.html ,并打这个文件,此时,页面上有“hello world”,说明运行成功!
<!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>Document</title>
</head>
<body>
  
</body>

<script src="./bundle.js" type="text/javascript"></script>
</html>
  • ⑤简化打包命令

之前的打包命令(./node_modules/.bin/webpack)比较繁琐,可通过 npm script 运行 webpack ,通过 npm run build 运行构建。
原理:模块局部安装会在node_modules/.bin目录创建软连接 image.png