标注:本笔记来自 imooc-qbaty老师-webpack深刻与实战
gitbash(or CMD)进行命令操做css
lenovo@lenovo-PC MINGW64 ~ $ cd /d/imooc/ lenovo@lenovo-PC MINGW64 /d/imooc $ mkdir webpack-test lenovo@lenovo-PC MINGW64 /d/imooc $ cd webpack-test/ lenovo@lenovo-PC MINGW64 /d/imooc/webpack-test $ npm init # 一路回车初始化好npm...初始化完成会建立 package.json # 安装 webpack 做为开发依赖,安装后会建立 node_modules 及在 package.json 中添加 webpack 配置 lenovo@lenovo-PC MINGW64 /d/imooc/webpack-test $ npm install webpack --save-dev lenovo@lenovo-PC MINGW64 /d/imooc/webpack-test $ ls node_modules/ package.json lenovo@lenovo-PC MINGW64 /d/imooc/webpack-test $ atom ./
而后在 atom 中webpack-test目录下建立 hello.js 代码以下:html
function hello(string) { alter(string); }
# 打包 'hello.js', 事先全局安装 webpack (npm install webpack -g) lenovo@lenovo-PC MINGW64 /d/imooc/webpack-test $ webpack hello.js hello.bundle.js
打开 hello.bundle.js 代码包括 webpack 所需的代码和 hello.js 中的函数(最下方),注意函数上方的 /* 0 */
, 表明模块代号。node
而后再在 atom 中 webpack-test 目录下建立 word.js, 代码以下:webpack
function world() { return {}; }
hello.js 中最上方添加代码:require('./world.js');
// 引入 world.js;
从新打包 $ webpack hello.js hello.bundle.js
, 再打开 hello.bundle.js 看一下下方加入了 world.js 代码和模块代号 /* 1 */
git
上边测试了 webpack 对js文件的引入,下边再学习一下对 css 文件处理:
atom 中 webpack-test 目录下建立 style.css, 代码以下:web
html, body { padding: 0; margin: 0; } body { background: green; }
css 文件须要 webpack loader 安装以下:npm
lenovo@lenovo-PC MINGW64 /d/imooc/webpack-test $ npm install css-loader style-loader --save-dev
atom 中 webpack-test 目录下建立 index.html, 代码以下:json
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>webpack-test</title> </head> <body> <script src="hello.bundle.js"></script> </body> </html>
引入css文件方法有两种:浏览器
require('style-loader!css-loader!./style.css');
从新打包 hello.js, 浏览器打开 index.html 会发现背景颜色变为了green,css起做用。bash
require('./style.css');
gitbash: $ webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader' --watch
一样css起做用。
说明:
--module-bind 'css=style-loader!css-loader'
webpack 提供的命令,打包时模块绑定css的加载器为 style-loader & .css-loader
--watch
webpack命令,监听打包的 hello.js 文件,只要改变自动会打包
--progress
命令窗口显示打包进度
--display-modules
命令窗口列出 hello.js 引入的全部模块
--display-reasons
命令窗口显示 打包引入模块的缘由