webpack从0到1的配置(一)

这篇关于webpack学习的文章包括以下知识点:

  1. 打包入口、打包出口、loaders、plugins
  2. 配置打包脚本命令npm run devnpm run build
  3. css打包压缩,js打包压缩
  4. 启用devServer,启用一个本地服务器,可通过localhost:8080在开发环境下调试
  5. 配置开发环境、生产环境不同的配置和环境变量

准备工作:

  • 新建项目文件夹webpackLearn
  • npm init webpackLearn项目
  • 新建webpack.config.js、index.html、src文件夹.....最终项目目录如下图所示
  • 我们指定main.js为打包入口(下图中mian.js拼写错误,修改为main.js)

  • npm install webpack --save-dev      下载webpack(我这里是4.36.1版本)
  • 如果你使用的是webpack4+的版本,还需安装webpack-cli
  • npm install webpack-cli --save-dev 下载webpack-cli
  • 自此每个文件都是空的,现在给每个文件写些东西
  • index.html文件:

 

<!--index.html没有引入main.js文件-->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
<body>
  <div>
    <p id="text-p">这里是index.html文件</p>
  </div>
</body>
</html>
  • main.js文件:
// 把index.html的文字颜色改为红色
const text_p = document.getElementById('text-p');
text_p.style.color = 'red';

开始配置:

  • 打开webpack.config.js文件配置打包入口,打包出口
// webapck.config.js文件
const path = require('path');
module.exports = {
  entry: {
    main: './src/main.js'
  },
   ouput: {
    filename: '[name].js', // 打包后文件名为mian.js
    path: path.resolve(__dirname, 'dist') //打包后的文件资源在dist文件下
  }
}
  • 配置打包脚本npm run build
  • 在package.json文件的scripts选项里
  • webpack配置文件可以随便取名字,只要在下图写对就行
"scripts": {
    "build": "webpack --config ./webpack.config.js", // 打包命令npm run build
    "test": "echo \"Error: no test specified\" && exit 1"
},
  • 说明一下,上图也可以配置成,执行npm run build,会自动去找webpack.config.js命名的文件
"scripts": {
    "build": "webpack", // 打包命令npm run build
    "test": "echo \"Error: no test specified\" && exit 1"
},
  • ok, 现在可以在终端运行npm run build 命令了
  • 结果项目中多出了一个dist文件夹,dist文件夹下有main.js文件,可以打开看一下。
  • 但是!!!!打包生成的项目没有index.html文件啊,怎么在浏览器打开呢?
  • 接下来我们将学习到plugins的配置
  • 点击webpack从0到1的配置(二)
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值