上一篇文章 (一)webpack入門——webpack的安裝 中,咱們知道了webpack的安裝,接下來咱們要學習如何使用webpack。javascript
如下內容來自webpack文檔(不是直譯): http://webpack.github.io/docs/usage.htmlhtml
var cats = ['dave', 'henry', 'martha']; module.exports = cats;
cats = require('./cats.js'); console.log(cats);
npm install webpack --save-devjava
module.exports = { entry: './src/app.js', output: { path: './dist', filename: 'app.bundle.js' } };
['dave', 'henry', 'martha']
webpack只支持本地JavaScript模塊,可是不少人使用ES201五、CoffeeScript、TypeScript等的轉譯器。webpack的‘loaders’便可解決轉譯的問題。Loaders是特殊的模塊,webpack用來加載其餘的用別的語言寫的模塊到webpack能夠識別的JavaScript中。例如,babel-loader使用Babel來加載ES2015文件。node
'json-loader'加載JSON文件jquery
{ "presets": [ "es2015" ] }
module.exports = { entry: './src/app.js', output: { path: './dist', filename: 'app.bundle.js', }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }] } }
npm install jquery babel-polyfill --save
import 'babel-polyfill'; import cats from './cats'; import $ from 'jquery'; $('<h1>Cats</h1>').appendTo('body'); const ul = $('<ul></ul>').appendTo('body'); for (const cat of cats) { $('<li></li>').text(cat).appendTo(ul); }
webpack
8. 加載index.html文件這個app才能運行起來webpack
<!DOCTYPE html> <html> <head> <metacharset="utf-8"> </head> <body> <scriptsrc="dist/app.bundle.js"charset="utf-8"></script> </body> </html>
當你打開index.html時,你能夠看到cats的內容列表git
在你的工做流程中,一般你想作一些額外的包的處理。例如壓縮文件便於客戶端更快速的加載。插件能夠解決這個問題。咱們將會增長uglify插件到配置文件中:github
const webpack = require('webpack'); module.exports = { entry: './src/app.js', output: { path: './dist', filename: 'app.bundle.js', }, module: { loaders: [{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', }] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, output: { comments: false, }, }), ] }
uglify插件包含在webpack裏,因此不須要額外的引用模塊,可是不是全部的都是這樣,webpack不包含的插件,第三方插件或者本身寫的插件是要包含額外的引用模塊的。web