npm install -g webpack
npm install webpack --save-dev
mkdir webpack-base && cd webpack-base
npm init -y
npm install --save-dev webpack
npm install --save lodash
mkdir app && touch app/index.js
import _ from 'lodash'
function component () {
var element = document.createElement('div')
element.innerHTML = _.join(['Hello', 'webpack'], ' ')
return element
}
document.body.appendChild(component())
touch index.html
<html>
<head>
<title>webpack 2 demo</title>
</head>
<body>
<script src="dist/bundle.js"></script>
</body>
</html>
touch webpack.config.js
var path = require('path')
module.exports = {
entry: './app/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
}
}
package.json
添加
"scripts": {
"build": "webpack"
},
npm run build
index.html
entry
字段设置test
指定加载器处理的文件类型, use
指定对应的加载器autoprefixer
自动处理css兼容性问题下面是一个基础的webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const path = require('path');
const config = {
entry: './path/to/my/entry/file.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js'
},
module: {
rules: [
{test: /\.(js|jsx)$/, use: 'babel-loader'}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
};
module.exports = config;
webpack默认只支持js模块, 要打包css文件需要使用css-loader
处理css文件, style-loader
应用样式
npm install css-loader style-loader
style.css
body {
background-color: yellow;
}
style.css
console.log(require('./content.js'))
require('!style!css!./style.css')
require('!style!css!./style.css')
每次都写很长的加载器前缀很麻烦, 可以在编译命令指定加载器绑定到文件后缀名
webpack ./entry.js bundle.js --module-bind "css=style!css"
此时entry.js
可以简化
require('./style.css')
将配置信息添加到webpack.config.js
配置文件后, 每次只需要执行webpack
即可完成打包任务
module.exports = {
entry: './entry.js',
output: {
}
}
webpack --progress --colors --watch
安装:
npm install webpack-dev-server -g
运行:
webpack-dev-server --progress --colors
执行命令之后会在本地8080端口启动静态服务器访问当前目录
运行总是报错
command not found: webpack-dev-server
还是用watch吧
npm install -D babel-plugin-root-import
.babelrc
添加plugin:
```
{
“presets”: [
],
“plugins”: [
[
“babel-plugin-root-import”,
{
“rootPathPrefix”: “@”,
“rootPathSuffix”: “src”
}
],
]
}```