最近刚用完gulp又来捣鼓捣鼓webpack,这只是个简单的新手入门教程...不多说; 注意:安装webpack前检查nodejs的安装目录路径是否存在空格(Program Files (x86)),建议安装在无空格文件夹目录下。
全局安装(以管理员身份运行命令行)
$ npm install webpack -g初始配置文件package.json(一直回车,就会在项目目录下生成该文件)
$ npm init到项目目录安装,将webpack添加到package.json
$ npm install webpack --save-dev安装完成后,打开package.json将会看到如下代码
{ "name":"webpack-test", "version":"1.0.0", "description":"", "main":"index.js", "scripts": { "test":"echo "Error: no test specified"&& exit 1" }, "author":"", "license":"ISC", "devDependencies": { "webpack":"^1.13.0" } }同时还可以选择,安装不同的版本
$ npm install webpack@1.2.x --save-dev在项目目录下创建入口文件entry.js
vim entry.js document.write("hello webpack!");创建index.html
vim 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如果成功,会显示如下代码
Version: webpack 1.13.0 Time: 34ms Asset Size Chunks Chunk Names bunble.js 1.42 kB 0 [emitted] main [0] ./entry.js 33 bytes {0} [built]接下来打开index.html 如果页面上显示 hello webpack 说明已经成功第一步了
hello webpack更新一下entry.js
document.write(require("./content.js"));继续Run一下
$ webpack ./entry.js bundle.js --colors打开index.html将会看到
这里是 content.js 的内容!安装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
vim css/style.css body{ font-size: 36px; }更新entry.js
require("!style!css!./css/style.css"); document.write(require("./content.js"));Run一下
$ webpack ./entry.js bundle.js --colors更新entry.js
- require("!style!css!./css/style.css"); + require("./css/style.css"); document.write(require("./content.js"));Run一下
$ webpack ./entry.js bundle.js --module-bind 'css=style!css'每个项目下都必须配置有一个webpack.config.js,它的作用如同常规的gulpfile.js/Gruntfile.js,就是一个配置项,告诉webpack它需要做什么。
vim webpack.config.js module.exports = { entry:"./entry.js", output: { path: __dirname, filename:"bundle.js" }, module: { loaders: [ { test: /.css$/, loader:"style!css"} ] } };Now we can just run
$ webpackwebpack命令会优先读取项目中的webpack.config.js文件
--progress 打印打包日志
--colors 带颜色的日志
--watch 监控自动打包
-d 生成map映射文件
-p 压缩混淆脚本
服务器可以自动生成和刷新,修改代码保存后自动更新画面
http://localhost:8080/webpack-dev-server/bundle我是写完这个才发现这个教程的...不过不晚 传送门:https://github.com/ruanyf/webpack-demos
官网:http://webpack.github.io/ 文档:http://webpack.github.io/docs/
如有不正之处,欢迎指正。
http://www.thinksaas.cn/topics/0/500/500682.html