转载请注明出处: http://qiudeqing.com/tools/2016/03/08/webpack.html

安装

1.全局:

npm install -g webpack

2.项目:

npm install webpack --save-dev

hello world

  1. mkdir webpack-base && cd webpack-base
  2. npm init -y
  3. npm install --save-dev webpack
  4. npm install --save lodash
  5. 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())
    
  6. touch index.html

     <html>
     <head>
     <title>webpack 2 demo</title>
     </head>
     <body>
     <script src="dist/bundle.js"></script>
     </body>
     </html>
    
  7. touch webpack.config.js

     var path = require('path')
    
     module.exports = {
     entry: './app/index.js',
     output: {
         filename: 'bundle.js',
         path: path.resolve(__dirname, 'dist'),
     }
     }
    
  8. package.json添加

     "scripts": {
         "build": "webpack"
     },
    
  9. npm run build
  10. 浏览器访问index.html

名词解释

下面是一个基础的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;

使用Loader加载css

webpack默认只支持js模块, 要打包css文件需要使用css-loader处理css文件, style-loader应用样式

npm install css-loader style-loader

1 新建style.css

body {
    background-color: yellow;
}

2 入口文件引入style.css

console.log(require('./content.js'))
require('!style!css!./style.css')

3 重新编译, 打开html文件, 样式已经加载

绑定Loader

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: {

}
}

watch文件修改自动编译

webpack --progress --colors --watch

服务器辅助开发

安装:

npm install webpack-dev-server -g

运行:

webpack-dev-server --progress --colors

执行命令之后会在本地8080端口启动静态服务器访问当前目录

运行总是报错

command not found: webpack-dev-server

还是用watch吧

从根目录import

```

参考资料