微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

webpack是什么

一、webpack是什么

webpack一个用于现代 JavaScript 应用程序的静态模块化打包构建工具

模块化:服务端Common.js(module.exports,require),浏览器端ES Module(export,export default,import {} from xxx)

src目录 你写的源代码

npm run build

dist--index.html,js css

二、webpack快速使用

2.1 初始化package.json

npm init -y

2.2 安装webpack相关依赖

 npm i webpack webpack-cli -D

2.3 写一点点测试代码

src index.js,tools.js

public index.html 引入dist/main.js

2.4 在package.json中添加打包脚本

{
  ....
  "scripts": {
    "build":"webpack"
  },
  ...
}

2.5 编写webpack配置文件

编写webpack配置文件,让webpack实现灵活环境定制,如下:

//引入相关依赖
const webpack = require('webpack')
const path=require('path')
​
//创建一个webpak配置对象
const config = {
    //设置模式
    mode:'development',
    //配置入口
    entry:'./src/main.js',
    //配置出口
    output: {
       //打包路径
      path:path.resolve(__dirname,'dist'),
       //打包文件名 
        filename: 'js/bundle.js',
      //清理无用文件
        clean:true
        
    }
}
​
​
//抛出对象
module.exports=config

2.5 安装webpack服务器

  1. 安装webpack-dev-server: npm i webpack-dev-server -D

  2. 配置webpack.config.js

    {
      ....
    ​
          //配置webpack服务器
          devServer: {
              port: 9999,
              //静态目录位置
              static: {
                  directory:'dist'
              }
          }
      ....
    }

  3. 配置package.json运行脚本

    {
    ...
      "scripts": {
        "build": "webpack",
        "serve": "webpack serve"
      },
    ...
    }

2.5 自动注入html

  1. 安装html-webpack-plugin: npm i html-webpack-plugin -D

  2. 配置webpack.config.js

    //引入相关依赖
    const webpack = require('webpack')
    const path = require('path')
    //引入html-webpack-plugin
    const HtmlWebpackPluin=require('html-webpack-plugin')
    ​
    //创建一个webpak配置对象
    const config = {
        //设置模式
        mode:'development',
        //配置入口
        entry:'./src/main.js',
        //配置出口
        output: {
           //打包路径
          path:path.resolve(__dirname,'dist'),
           //打包文件名 
            filename: 'js/bundle[contenthash].js',
          //清理无用文件
            clean:true
            
        },
        //配置插件
        plugins: [
            new HtmlWebpackPluin({
                //从哪个模板生成html
                template:'./public/index.html',
                //生成后的html文件名
                filename:'index.html'
            })
        ],
        //sl
        //配置webpack服务器
        devServer: {
            port: 9999,
            //静态目录位置
            static: {
                directory:'dist'
            }
        }
    }
    ​
    ​
    //抛出对象
    module.exports=config

原文地址:https://www.jb51.cc/wenti/3287877.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐