webpack的基本使用

本文主要介绍webpack的基本使用,通过简单的打包流程进行具体说明。

1.新建pack文件夹,运行npm init -y初始化package.json文件,不用-y则需要手动进行配置。

package.json文件内容如下:

{
    "name": "pack",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "dev": "webpack-dev-server"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "jquery": "^3.6.0"
    },
    "devDependencies": {
        "webpack": "^5.74.0",
        "webpack-cli": "^4.10.0",
        "webpack-dev-server": "^4.10.0"
    }
}

2.新建src文件夹,新建index.html和index.js文件

3.安装jquery,书写index.js文件如下

import $ from 'jquery'
$(function() {
    $('.btn').click(function() {
        $('#showContent').slideDown();
        $('#showContent').css('backgroundColor', 'yellow')
    })
})

4.安装webpack和webpack-cli包,创建webpack.config.js文件,配置内容如下:

module.exports = {
    mode: 'development',
    devServer: {
        open: true,
        host: '127.0.0.1',
        port: 8800,
        static: './'
    }
}

 5.安装webpack-dev-server包,修改命令如下:

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

 6.index.html文件引入"/bundle.js"文件,运行npm run dev命令即可

7.上述文件运行后并不会直接打开首页,故需要进行配置。首先运行npm i html-webpack-plugin -D

 命令,安装html-webpack-plugin包,配置预览页面。在webpack.config.js中的具体配置如下:

const HtmlWebpack = require('html-webpack-plugin')
const h = new HtmlWebpack({
    template: './src/index.html',
    filename: 'index.html'
})
module.exports = {
    mode: 'development',
    devServer: {
        open: true,
        host: '127.0.0.1',
        port: 8800,
        static: './'
    },
    plugins: [h]
}

8.在package.json文件中定义如下内容

 "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "dev": "webpack-dev-server",
        "build": "webpack"
    }

运行npm run build命令即可对文件进行打包,会生成dist这一最终的文件夹。

9.可进行项目入口与出口文件的配置。默认入口文件是src目录下的index.js文件,出口文件是main.js,现配置为bundle.js.需要使用npm内置的path包,完整代码如下:

const HtmlWebpack = require('html-webpack-plugin')
const path = require('path')
const h = new HtmlWebpack({
    template: './src/index.html',
    filename: 'index.html'
})
module.exports = {
    mode: 'development',
    devServer: {
        open: true,
        host: '127.0.0.1',
        port: 8800,
        static: './'
    },
    plugins: [h],
    entry: path.join(__dirname, './src/index.js'),
    output: {
        path: path.join(__dirname, './dist'),
        filename: 'bundle.js'
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值