目录结构
文件内容:
main_packed.js
main_packed.js 文件是生成出来的
style.css
@charset "utf-8";
/* style.css */
body { background: yellow; }
module1.js
module.exports = 'this is module1.js.'
main.js
require("!style-loader!css-loader!./css/style.css")
document.write('It works.')
document.write(require('./js/module1.js')) // 引用其他模板
index.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
<body>
<script src="./assets/bin/main_packed.js"></script>
安装: npm install webpack -g <br />
打包:webpack main.js main_packed.js <br />
安装其他转换器:npm install css-loader style-loader -g <br />
使用转换器打包:webpack entry.js bundle.js --module-bind 'css=style-loader!css-loader' <br />
开发环境(会生成目标文件)<br />
手动编译:webpack --progress --colors<br />
自定义编译(监听模式运行):webpack --progress --colors --watch<br />
开发环境(使用webpack-dev-server不会生成目标文件)<br />
安装服务器:npm install webpack-dev-server -g <br />
启动服务器:webpack-dev-server --progress --colors <br />
访问:http://localhost:8080/ <br />
发布(即生成目标文件) <br />
手动编译:webpack --progress --colors <br />
</body>
</html>
package.json
{
"name": "webpack-example",
"version": "1.0.0",
"description": "A simple webpack example.",
"main": "bundle.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"webpack"
],
"author": "zhaoda",
"license": "MIT",
"devDependencies": {
"css-loader": "^0.21.0",
"style-loader": "^0.13.0",
"webpack": "^1.12.2"
}
}
webpack.config.js
var webpack = require('webpack')
var path = require('path')
module.exports = {
entry: './assets/src/main.js', // 要编译的源目录
output: { // 编译后存放的目录
// path: __dirname,
path: path.resolve(__dirname, './assets/bin'),
filename: 'main_packed.js'
},
module: {
loaders: [ // 转换器
{test: /\.css$/, loader: 'style-loader!css-loader'}
]
},
plugins: [ // 插件
new webpack.BannerPlugin('This file is created by janchou.')
]
}
执行命令:
安装webpack:npm install webpack -g
安装插件:npm install css-loader style-loader -g
编译:webpack --progress --colors
安装web服务器:npm install webpack-dev-server -g
启动web服务器:webpack-dev-server --progress --colors
访问:http://localhost:8080/
参考文章:
http://webpackdoc.com/