百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

webpack配置解析及从零开始搭建一个开发环境

toyiye 2024-06-27 01:03 13 浏览 0 评论

基本配置

  1. mode: webpack工作在那种模式下,并使用相应模式的内置优化,可选值为'none', 'development' , 'production'
  2. entry: 打包入口文件, 值可以是字符串、数组、对象和函数,函数的返回值必须是可用的文件入口路径
  3. context: context 是entry的上下文,即表示入口文件所处的目录的绝对路径
const resolve = (...args) => {
  return path.resolve(__dirname, '..', ...args)
}

module.exports = {
  // 使用开发环境
  mode:'development',
  // 当前文件路径
  context: '',
  entry: {
    // 当前文件的父文件夹下的src目录(默认使用src目录下的index.js)
    app: '../src'
  }
}
  1. output: 定义webpack打包后的文件如何输出
output: {
  // 输入目录
  path: resolve('dist'),
  // 资源的基础路径, 决定webpack引用资源时资源的完整路径(完整路径=publicPath + filename)。
  // 比如打包后的文件名为js/1.c0a92244ebbea7068c7e.js
  /*
    1. 相对路径, 即publicPath: './', 完整路径为: ./js/1.c0a92244ebbea7068c7e.js
    2. 绝对路径, 即publicPath: '/assets/', 完整路径为: /assets/js/1.c0a92244ebbea7068c7e.js
  */
  publicPath: '/',
  // 文件名, 根据entry中的配置生成对应的文件
  filename: assetsPath('js/[name].[chunkhash].js'),
  // 块名, 非入口(non-entry) chunk 文件的名称
  chunkFilename: assetsPath('js/[id].[chunkhash].js')
},
  1. resolve: 配置模块如何解析, 一般常用resolve.alias和resolve.extensions
resolve: {
  // 配置别名
  alias: {
    '@': resolve('src')
  },
  // 自动解析确定的扩展名
  // 如import xx from 'src/test', 会匹配文件test.js, test.jsx, test.json或test目录
  extensions: ['.js', '.jsx', 'json']
}
  1. module: 根据rules和noParse配置来决定如何处理项目中的不同类型的文件
module: {
  rules: [
    // 使用babel-loader处理js或jsx文件
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: 'babel-loader'
    },
    // loader和options是use: [{ loader: 'xx', options: {...} }]的简写
    {
      test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
      exclude: [resolve('src/assets/icons')],
      loader: 'url-loader',
      options: {
        limit: 10000,
        name: assetsPath('images/[name].[hash:8].[ext]')
      }
    }
  ]
}
  1. plugins: 用于以各种方式自定义 webpack 构建过程。以下是一些插件配置及其介绍
plugins: [
  // 提供全局React, 这样在每个页面中就每次都使用`import React from 'react'`引入react
  new webpack.ProvidePlugin({
    React: 'react'
  }),
  // 每次构建前清空原来的dist目录
  new CleanWebpackPlugin(),
  // 将css提出到每个单独的文件中(只在生产环境下有效)
  isProd && new MiniCssExtractPlugin({
    filename: 'static/css/[name].[hash].css',
    chunkFilename: 'static/css/[id].[hash].css'
  }),
  // 将src/static下的文件及文件夹复制到output.path/static
  new CopyWebpackPlugin({
    patterns: [
      {
        from: resolve('src/static'),
        to: 'static'
      }
    ]
  }),
  // 生成html模板
  new HtmlWebpackPlugin({
    template: resolve('index.html'),
    filename: 'index.html',
    inject: true
  }),
].filter(Boolean)
  1. devtool: 定义是否生成以及如何生成 source map
  • 开发环境下,一般使用'eval-cheap-module-source-map'或'source map',不同类型的source map会影响构建和重新构建的速度。更多配置请见webpack devtool
  • 生产环境下,一般禁用source map来效防止代码泄漏

开发服务器

devServer: {
  // 启用 webpack 的模块热替换
  hot: true,
  // 输出构建消息到浏览器控制台
  inline: true,
  // 打包进度输出到控制台
  progress: true,
  // 服务器开启GZIP压缩
  compress: true,
  // 服务器默认使用http, 如需使用https, 则将其设置为true即可
  // https: true
  // 应用程序可通过局域网内ip访问
  host: '0.0.0.0',
  // 端口号
  port: 8080,
  // 如果编译错误, 将全屏显示错误信息
  overlay: true,
  // 除了初始启动信息之外的任何内容都不会被打印到控制台
  quiet: true,
  // 资源的基础路径, 同output.publicPath
  publicPath: '/',
  // 告诉服务器从哪里提供内容, 只有在你想要提供静态文件时才需要
  contentBase: false,
  // 使用轮询获取文件更新信息
  watchOptions: {
    poll: true
  },
  // 路由使用history模式, 所有路径都将指向index.html
  historyApiFallback: true,
  // 提供在服务器内部在所有其他中间件之前执行自定义中间件
  before: app => {
    app.get(/^.+\.html$/g, (req, res) => {
      return res.redirect(req.url.replace(/(index)?\.html$/, ''))
    })
  },
  // 请求转发, 解决本地开发跨域问题
  proxy: [
    {
      // 可通过context指定多个路径, 如context: ['/api', '/users']
      context: ['/api'],
      target: `http://localhost:3000`,
      pathRewrite: {
      },
      changeOrigin: true,
      secure: false
    }
  ]
}

搭建一个webpack4

创建package.json

创建一个空文件夹,然后进入文件夹内执行命令yarn init -y或npm init -y生成默认的package.json

[vegan.qian@dell webpack4]$ yarn init -y
yarn init v1.22.4
warning The yes flag has been set. This will automatically answer yes to all questions, which may have security implications.
success Saved package.json
Done in 0.04s.

安装webpack依赖

yarn add -D webpack webpack-cli

安装babel依赖

yarn add -D @babel/cli @babel/core @babel/preset-env @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators @babel/plugin-transform-runtime

安装完成后,在项目根目录下创建.babelrc文件,并输入以下配置

{
  "presets": ["@babel/preset-env"],
  "plugins": [
    [
      "@babel/plugin-proposal-decorators",
      {
        "legacy": true
      }
    ],
    [
      "@babel/plugin-proposal-class-properties",
      {
        "loose": true
      }
    ],
    "@babel/plugin-transform-runtime"
  ]
}

创建项目结构

在项目中,创建如下目录结构

.
├── index.html
├── package.json
├── README.md
├── scripts
│   ├── utils.js
│   ├── webpack.base.config.js
│   ├── webpack.dev.config.js
│   └── webpack.prod.config.js
├── src
│   ├── index.js
│   ├── static
│   │   └── images
│   │       └── 1.jpg
│   └── styles
│       └── index.less
└── yarn.lock

编写公共方法

  • 在scripts目录下新建文件utils.js, 然后输入以下内容。这里的resolve函数用于解析以根目录为参考点的路径,assetsPath用于定义打包后的资源输出目录(默认为static目录)
const path = require('path')

const resolve = (...args) => {
  return path.resolve(__dirname, '..', ...args)
}

const assetsPath = (...args) => {
  return path.posix.join('static', ...args)
}

module.exports = {
  resolve,
  assetsPath
}

提取公共配置

  • 在scripts目录下新建文件webpack.base.config.js
  • 编写开发和生成环境下共用的配置代码
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { resolve, assetsPath } = require('./utils')
const isProd = Object.is(process.env.NODE_ENV, 'production')

module.exports = {
  context: resolve(''),
  entry: {
    app: resolve('src')
  },
  resolve: {
    alias: {
      '@': resolve('src')
    },
    extensions: ['.js', '.jsx', 'json']
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.(le|c)ss$/,
        use: [
          isProd ? {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: !isProd
            }
          } : 'style-loader',
          'css-loader',
          'postcss-loader',
          {
            loader: 'less-loader'
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: assetsPath('images/[name].[hash:8].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    isProd && new MiniCssExtractPlugin({
      filename: `static/css/[name]${isProd ? '.[hash]' : ''}.css`,
      chunkFilename: `static/css/[id]${isProd ? '.[hash]' : ''}.css`
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: resolve('src/static'),
          to: 'static'
        }
      ]
    })
  ].filter(Boolean),
  devtool: 'source-map'
}
  • 安装配置中需要的依赖
yarn add -D copy-webpack-plugin mini-css-extract-plugin clean-webpack-plugin babel-loader style-loader css-loader postcss-loader less-loader url-loader

Postcss配置

在webpack.base.config.js中,我们使用到了postcss-loader来处理css文件,所以也需要对其进行配置

  • 安装postcss插件
yarn add -D postcss-import postcss-url autoprefixer
  • 在项目根目录下创建文件.postcssrc.js,并输入以下内容
module.exports = {
  "plugins": {
    "postcss-import": {},
    "postcss-url": {},
    // to edit target browsers: use "browserslist" field in package.json
    "autoprefixer": {}
  }
}

开发环境配置

  • 在scripts目录下新建文件webpack.dev.config.js, 并写入以下配置
const webpack = require('webpack')
const { merge } = require('webpack-merge')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const ifaces = require('os').networkInterfaces()
const baseWebpackConfig = require('./webpack.base.config')
const { resolve } = require('./utils')

const port = 8080

const ips = Object
  .keys(ifaces)
  .reduce((result, id) => result.concat(ifaces[id].filter(item => item.family === 'IPv4')), [])
  .reduce((result, { address }) => {
    if (!result.includes(address)) {
      result.push(address)
    }

    return result
  }, ['localhost'])

module.exports = merge(baseWebpackConfig, {
  mode: 'development',
  output: {
    path: resolve('dist'),
    publicPath: '/',
    filename: '[name].js',
    chunkFilename: '[name].chunk.js'
  },
  devServer: {
    hot: true,
    inline: true,
    progress: true,
    compress: true,
    host: '0.0.0.0',
    port: port,
    quiet: true,
    overlay: true,
    publicPath: '/',
    contentBase: false,
    watchOptions: {
      poll: true
    },
    historyApiFallback: true,
    before: app => {
      app.get(/^.+\.html$/g, (req, res) => {
        return res.redirect(req.url.replace(/(index)?\.html$/, ''))
      })
    },
    proxy: [
      {
        context: ['/api'],
        target: `http://localhost:3000`,
        pathRewrite: {
        },
        changeOrigin: true,
        secure: false
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"'
      }
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      template: resolve('index.html'),
      filename: 'index.html',
      inject: true
    }),
    new FriendlyErrorsPlugin({
      compilationSuccessInfo: {
        messages: [
          'Client available on:',
          ...ips.map(ip => `http://${ip}:${port}`)
        ]
      },
      onErrors: null
    })
  ]
})
  • 安装配置中需要的依赖
yarn add -D webpack-dev-server webpack-merge html-webpack-plugin friendly-errors-webpack-plugin

配置scripts

  • 安装跨平台环境变量设置库cross-env, yarn add -D cross-env
  • 在package.json中增加start脚本
"scripts": {
  "start": "cross-env NODE_ENV=development webpack-dev-server --config scripts/webpack.dev.config.js"
}
  • 运行命令yarn run start
[vegan.qian@dell webpack4]$ yarn run start
yarn run v1.22.4
$ cross-env NODE_ENV=development webpack-dev-server --config scripts/webpack.dev.config.js
10% building 1/1 modules 0 active[HPM] Proxy created: [ '/api' ]  ->  http://localhost:3000
? ?wds?: Project is running at http://0.0.0.0:8080/
? ?wds?: webpack output is served from /
? ?wds?: 404s will fallback to /index.html
98% after emitting

 DONE  Compiled successfully in 3016ms                               20:33:24 PM

 I  Client available on:
 I  http://localhost:8080
 I  http://127.0.0.1:8080
 I  http://192.168.1.10:8080

这样,一个简单的webpack开发环境就搭好了。

生产环境配置

  • 在scripts目录下新建文件webpack.prod.config.js, 并写入以下配置
const webpack = require('webpack')
const { merge } = require('webpack-merge')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const baseWebpackConfig = require('./webpack.base.config')
const { resolve, assetsPath } = require('./utils')

module.exports = merge(baseWebpackConfig, {
  mode: 'production',
  output: {
    path: resolve('dist'),
    publicPath: '/',
    filename: assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new HtmlWebpackPlugin({
      template: 'index.html',
      inject: true
    }),
    new webpack.HashedModuleIdsPlugin(),
    new webpack.optimize.ModuleConcatenationPlugin()
  ],
  devtool: false
})
  • 在package.json中添加build脚本
"scripts": {
  "start": "cross-env NODE_ENV=development webpack-dev-server --config scripts/webpack.dev.config.js",
  "build": "cross-env NODE_ENV=production webpack --inline --progress --config scripts/webpack.prod.config.js"
}
  • 运行命令 yarn run build, 可以看到文件已经成功被打包到dist目录中
[vegan.qian@dell webpack4]$ yarn run build
yarn run v1.22.4
$ cross-env NODE_ENV=production webpack --inline --progress --config scripts/webpack.prod.config.js
Hash: df058a216561223f9e59
Version: webpack 4.43.0
Time: 1158ms
Built at: 07/09/2020 8:49:43 PM
                                  Asset       Size  Chunks                         Chunk Names
                             index.html  332 bytes          [emitted]
static/css/app.df058a216561223f9e59.css   77 bytes       0  [emitted] [immutable]  app
                    static/images/1.jpg   34.8 KiB          [emitted]
  static/js/app.f8fff264ae5cd3f62371.js   3.38 KiB       0  [emitted] [immutable]  app
Entrypoint app = static/css/app.df058a216561223f9e59.css static/js/app.f8fff264ae5cd3f62371.js
[pLGG] ./src/styles/index.less 39 bytes {0} [built]
[tjUo] ./src/index.js 1.83 KiB {0} [built]
    + 9 hidden modules
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [Q3Bv] ./node_modules/html-webpack-plugin/lib/loader.js!./index.html 469 bytes {0} [built]
Child mini-css-extract-plugin node_modules/css-loader/dist/cjs.js!node_modules/postcss-loader/src/index.js!node_modules/less-loader/dist/cjs.js!src/styles/index.less:
    Entrypoint mini-css-extract-plugin = *
    [ajKL] ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src!./node_modules/less-loader/dist/cjs.js!./src/styles/index.less 317 bytes {0} [built]
        + 1 hidden module
Done in 2.33s.

打包后目录结构:

.
├── dist
│   ├── index.html
│   └── static
│       ├── css
│       │   └── app.a44eef0cadd0c2efc8d7.css
│       ├── images
│       │   └── 1.jpg
│       └── js
│           └── app.f8fff264ae5cd3f62371.js
├── index.html
├── package.json
├── README.md
├── scripts
│   ├── utils.js
│   ├── webpack.base.config.js
│   ├── webpack.dev.config.js
│   └── webpack.prod.config.js
├── src
│   ├── index.js
│   ├── static
│   │   └── images
│   │       └── 1.jpg
│   └── styles
│       └── index.less
└── yarn.lock

这样,一个简单的webpack打开环境就已经配置完了。

本文中的所有代码都已经上传到github。 地址: https://github.com/idelink/webpack


及时获取更新,了解更多动态,请关注 https://www.gogoing.site

如果你觉得这篇文章对你有帮助,欢迎关注微信公众号-前端学堂,更多精彩文章等着你!

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码