webpack开发环境配置以及打包各种文件资源-闲鱼前端的webpack精通之路(二)

子成君 709 1

初始化及安装

1. 初始化 packge.json
输入指令: npm init

2. 下载并安装 webpack

npm install webpack webpack-cli -g // 全局安装
npm install webpack webpack-cli -D // 本地安装

编译打包应用

1.基本使用

webpack开发环境配置以及打包各种文件资源-闲鱼前端的webpack精通之路(二)

开发环境指令:webpack src/index.js -o build/index.js --mode=development
功能:webpack 能够编译打包 js 和 json 文件,并且能将 es6 的模块化语法转换成浏览器能识别的语法。
生产环境指令:webpack src/index.js -o build/index.js --mode=production
功能:在开发配置功能上多一个功能,压缩代码。

上面例子的指令含义为将src/js目录下的index.js文件 编译输出为build/js目录下的build.js文件  -o 即指定输出目录  --mode指定开发模式

webpack 能够编译打包 js 和 json 文件。能将 es6 的模块化语法转换成浏览器能识别的语法。能压缩代码。

但不能编译打包 css、img 等文件。不能将 js 的 es6 基本语法转化为 es5 以下语法(最低只能到es5)

2.打包样式资源

通过webpack.config.js文件配置webpack:

在src和packge.json的同级目录下创建webpack.config.js文件,通过配置该文件,可以直接运行webpack命令进行打包,以及进行静态资源打包。

基本配置联合注释和目录结构查看,如下:

目录:

webpack开发环境配置以及打包各种文件资源-闲鱼前端的webpack精通之路(二)

代码:

/**
*webpack.config.js =>  webpack的配置文件
*作用 :指示webpack 做什么事情
*所有的构建工具都是基于nodejs平台运行的  模块化默认采用commonjs
*/

// resolve用来拼接绝对路径
const path = require('path')


module.exports = {
    //webpack配置
    //入口起点
    entry: path.join(__dirname, 'src','index'),
    //输出
    output: {
        // 输出文件名
        filename: 'index.js',
        // __dirname nodejs 的变量 ,代表当前文件的目录绝对路径
        path: path.join(__dirname, 'build')
    },
    // loader的配置
    module:{
        rules:[
            // 详细的loader配置
            {
                // 匹配哪些文件
                test: /\.scss$/,
                // 使用哪些loader进行处理
                use:[
                    'style-loader',
                    // 将css文件变成commonjs模块加载js中(样式的字符串)
                    'css-loader',
                    'sass-loader'
                ]
            }
        ]
    },
    // plugins的配置
    plugins:[
        // 详细plugins配置
    ],
    // 模式
    mode:'development'
    // mode:'production'
}

webpack不能打包的文件可以通过loader以及插件来完成,上图的loader中已经写明了对.scss文件的处理,需要注意的只是包的安装,缺啥补啥装啥就是了

特别说明的是rules下use数组中loader的执行顺序是从数组右到左依次执行

对于webpack.config.js文件的配置编写,配合之前发的自动生成插件和代码提示食用,体验感好到爆!

编写webpack配置时的代码提示以及webpack文件自动生成方案

5年前 (2020-06-29) 0
编写webpack配置时的代码提示以及webpack文件自动生成方案

3.打包html资源

打包html资源需要借助插件来完成

npmjs.com搜索安装html-webpack-plugin插件

webpack开发环境配置以及打包各种文件资源-闲鱼前端的webpack精通之路(二)

使用插件具体分为 ①安装 ②引入 ③配置三个步骤,配置方法在npmjs.com搜索对应插件在该插件的readme里可以看到

简单的html文件打包,安装引入以及配置html-webpack-plugin插件如下plugins的配置:

/**
*webpack.config.js =>  webpack的配置文件
*作用 :指示webpack 做什么事情
*所有的构建工具都是基于nodejs平台运行的  模块化默认采用commonjs
*/

// resolve用来拼接绝对路径
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    //webpack配置
    //入口起点
    entry: path.join(__dirname, 'src','index'),
    //输出
    output: {
        // 输出文件名
        filename: 'index.js',
        // __dirname nodejs 的变量 ,代表当前文件的目录绝对路径
        path: path.join(__dirname, 'build')
    },
    // loader的配置
    module:{
        rules:[
            // 详细的loader配置
            {
                // 匹配哪些文件
                test: /\.scss$/,
                // 使用哪些loader进行处理
                use:[
                    'style-loader',
                    // 将css文件变成commonjs模块加载js中(样式的字符串)
                    'css-loader',
                    'sass-loader'
                ]
            }
        ]
    },
    // plugins的配置
    plugins:[
        // 详细plugins配置
        //html-webpack-plugin
        //功能:默认会创建一个空的HTML,自动引入打包输出的所有资源(JS/CSS)
        //需求:需要有结构的HTML文件
        new HtmlWebpackPlugin({  // Also generate a test.html
            template: './src/index.html'
          })
    ],
    // 模式
    mode:'development'
    // mode:'production'
}

指定了模板文件为src下的index.html,此时创建一个index.html(无需引入任何)

webpack开发环境配置以及打包各种文件资源-闲鱼前端的webpack精通之路(二)

在scss文件里随便写一个样式,之后执行webpack

webpack开发环境配置以及打包各种文件资源-闲鱼前端的webpack精通之路(二)

打包结果多出了一个index.html,且已经帮我们引入了打包后的index.js

打开html可以查看样式是否生效

4.打包图片资源

上面已经说了webpack不能打包的文件可以通过loader以及插件来完成,这里图片的打包所用到的loader是url-loader和html-loader,url-loader依赖于file-loader,所以需要把file-loader包也安装一下

都是配置上的内容在npm包主页可以看到详细说明

代码实例:

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    rules: [
      {
        test: /\.less$/,
        // 要使用多个loader处理用use
        use: ['style-loader', 'css-loader', 'less-loader']
      },
      {
        // 问题:默认处理不了html中img图片
        // 处理图片资源
        test: /\.(jpg|png|gif)$/,
        // 使用一个loader
        // 下载 url-loader file-loader
        loader: 'url-loader',
        options: {
          // 图片大小小于8kb,就会被base64处理
          // 优点: 减少请求数量(减轻服务器压力)
          // 缺点:图片体积会更大(文件请求速度更慢)
          limit: 8 * 1024,
          // 问题:因为url-loader默认使用es6模块化解析,而html-loader引入图片是commonjs
          // 解析时会出问题:[object Module]
          // 解决:关闭url-loader的es6模块化,使用commonjs解析
          esModule: false,
          // 给图片进行重命名
          // [hash:10]取图片的hash的前10位
          // [ext]取文件原来扩展名
          name: '[hash:10].[ext]'
        }
      },
      {
        test: /\.html$/,
        // 处理html文件的img图片(负责引入img,从而能被url-loader进行处理)
        loader: 'html-loader'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ],
  mode: 'development'
};

5.打包其他资源

打包其他资源(除了html/js/css资源以外的资源)

用file-loader打包其他文件,rules里新增规则:

  rules: [
      {
        // 排除css/js/html资源
        exclude: /\.(css|js|html|less)$/,
        loader: 'file-loader',
        options: {
          name: '[hash:10].[ext]'
        }
      }
    ]

6.devServer

即热重载,避免每次更新都需要手动执行webpack指令,在mode和entry同级编写devServer配置,例如:

  // 开发服务器 devServer:用来自动化(自动编译,自动打开浏览器,自动刷新浏览器~~)
  // 特点:只会在内存中编译打包,不会有任何输出
  // 启动devServer指令为:npx webpack-dev-server
  devServer: {
    // 项目构建后路径
    contentBase: resolve(__dirname, 'build'),
    // 启动gzip压缩
    compress: true,
    // 端口号
    port: 3000,
    // 自动打开浏览器
    open: true
  }

7.开发环境配置

将上述配置集合汇总一下,再加上各类型文件输出路径,实例如下:

/*
  开发环境配置:能让代码运行
    运行项目指令:
      webpack 会将打包结果输出出去
      npx webpack-dev-server 只会在内存中编译打包,没有输出
*/

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/js/index.js',
  output: {
    filename: 'js/built.js',
    path: resolve(__dirname, 'build')
  },
  module: {
    rules: [
      // loader的配置
      {
        // 处理less资源
        test: /\.less$/,
        use: ['style-loader', 'css-loader', 'less-loader']
      },
      {
        // 处理css资源
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        // 处理图片资源
        test: /\.(jpg|png|gif)$/,
        loader: 'url-loader',
        options: {
          limit: 8 * 1024,
          name: '[hash:10].[ext]',
          // 关闭es6模块化
          esModule: false,
          outputPath: 'imgs' // 图片资源目录
        }
      },
      {
        // 处理html中img资源
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        // 处理其他资源
        exclude: /\.(html|js|css|less|jpg|png|gif)/,
        loader: 'file-loader',
        options: {
          name: '[hash:10].[ext]',
          outputPath: 'media'  // 他资源目录
        }
      }
    ]
  },
  plugins: [
    // plugins的配置
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ],
  mode: 'development',
  devServer: {
    contentBase: resolve(__dirname, 'build'),
    compress: true,
    port: 3000,
    open: true
  }
};

发表评论 取消回复
OwO 图片 链接 代码

  1. casino en ligne France
    casino en ligne France 超级小萌新

    You ought to be a part of a contest for one of the most useful sites on the net.
    I most certainly will highly recommend this site!
    <a href=https://mylinku.com/lindseyann>casino en ligne France</a>
    Good article. I will be experiencing many of these issues as well..

    <a href="https://git.libx.ir/brittfigueroa9">casino en ligne</a>
    Hi! I've been following your website for a long
    time now and finally got the bravery to go ahead
    and give you a shout out from New Caney Tx! Just wanted to tell you
    keep up the good work!
    <a href="https://gitea.fcliu.net/williemaebarr">casino en ligne</a>
    It's going to be ending of mine day, but before end
    I am reading this wonderful article to improve my know-how.

    <a href="https://www.globalscaffolders.com/employer/les-meilleurs-casinos-en-ligne-en-france-acceptant-paypal-:-guide-des-casinos-populaires/">casino en ligne</a>
    Excellent post. I was checking constantly this blog and I am impressed!
    Very helpful information specifically the last part :) I care
    for such info much. I was seeking this particular information for a very long
    time. Thank you and best of luck.
    <a href="https://gitea.manavik.one/waynemarina52">casino en ligne</a>
    Good post. I learn something new and challenging on sites I
    stumbleupon every day. It's always interesting to
    read articles from other writers and practice
    a little something from their websites.
    <a href="https://jooble.az/employer/serveur-prive">casino en ligne France</a>
    I'm curious to find out what blog platform you happen to be working with?
    I'm having some small security issues with my latest site and
    I would like to find something more secure. Do you have any solutions?

    <a href="https://www.xn--ob0bv3xdjilia71ica881v.com/bbs/board.php?bo_table=event&wr_id=2778">casino en ligne</a>
    Hola! I've been reading your web site for some
    time now and finally got the bravery to go ahead and give you a shout
    out from Humble Texas! Just wanted to mention keep up the good job!

    <a href="http://sdgit.zfmgr.top/anjacrist42712">meilleur casino en ligne</a>
    I believe everything typed was very logical. However, think about
    this, what if you added a little information? I mean, I don't wish to tell you how to
    run your website, but suppose you added something to possibly get people's attention? I mean webpack开发环境配置以及打包各种文件资源-闲鱼前端的webpack精通之路(二) |
    前端打更人 is a little vanilla. You could glance at Yahoo's home
    page and watch how they create post headlines to grab viewers to click.
    You might try adding a video or a related picture or
    two to get readers interested about what you've got to say.
    Just my opinion, it would make your blog a little
    livelier.
    <a href="https://www.bierenbroodspot.net/manuelabui116">casino en ligne fiable</a>
    With havin so much written content do you ever run into
    any problems of plagorism or copyright violation? My blog has a lot
    of unique content I've either authored myself
    or outsourced but it looks like a lot of it is popping it up all over the web without my agreement.
    Do you know any solutions to help reduce content from being ripped off?
    I'd really appreciate it.
    <A HREF='https://git.dihe.moe/marshapool859'>meilleur casino en ligne</A>

分享