webpack 的小 demo

 

 

 

简单的新手入门教程...

安装

全局安装(以管理员身份运行命令行,mac电脑进行sudo chown -R $USER /user/local)

$ npm install webpack -g

初始配置文件package.json(一直回车,就会在项目目录下生成该文件)

$ npm init

到项目目录安装,将webpack添加到package.json

$ npm install webpack --save-dev

安装完成后,打开package.json将会看到如下代码


{
  "name": "abs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.25.1"
  }
}
同时还可以选择,安装不同的版本
$ npm install webpack@1.2.x --save-dev

举颗栗子

在项目目录下创建入口文件entry.js

document.write("hello webpack!");

创建index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>webpack</title>

</head>

<body>

<script type="text/javascript"src="./bundle.js"></script>

</body>

</html>

Run一下

$ webpack ./entry.js bundle.js --colors

如果报错

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

ERROR in multi ./entry.js bundle.js
Module not found: Error: Can't resolve 'bundle.js' in '/Users/xiaoxiaoliu/liuxiao/abs'
 @ multi ./entry.js bundle.js main[1]
➜  abs webpack src/entry.js --output dist/bundle.js

Insufficient number of arguments or no entry found.
Alternatively, run 'webpack(-cli) --help' for usage info.

很有可能是因为webpack版本太高 用的最新的4.17.0

解决办法:webpack ./entry.js  bundle.js中间加一个--output

webpack ./entry.js --output bundle.js

如果成功,会显示如下代码

Hash: a1a2f87b02214a005ef0
Version: webpack 4.25.1
Time: 340ms
Built at: 2018-11-13 10:55:48
    Asset       Size  Chunks             Chunk Names
bundle.js  962 bytes       0  [emitted]  main
Entrypoint main = bundle.js
[0] ./entry.js 33 bytes {0} [built]
接下来打开index.html 如果页面上显示 hello webpack 说明已经成功第一步了

添加一个文件

添加一个文件content.js
module.exports ="这里是 content.js 的内容!";
更新一下entry.js
document.write(require("./content.js"));

打包CSS

安装css-loader,style-loader模块 其他模块:http://webpack.github.io/docs/loader-conventions.html

.css文件使用style-loadercss-loader来处理 

.js文件使用jsx-loader来编译处理 

.scss文件使用style-loadercss-loadersass-loader来编译处理

$ npm install css-loader --save 

or

$ npm install css-loader --save-dev

添加文件style.css


body{
    background: #f66;
}

更新entry.js

require("!style!css!./css/style.css");

document.write(require("./content.js"));

Run一下

$ webpack ./entry.js bundle.js --colors

未完待续

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值