简单的新手入门教程...
安装
全局安装(以管理员身份运行命令行,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-loader
和css-loader
来处理
.js
文件使用jsx-loader
来编译处理
.scss
文件使用style-loader
、css-loader
和sass-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