webpack学习小结

刚入职的时候,勉大神,明叔手把手教学,本来早就该看懂学会了。

这刚恋爱的代码狗,2个月后,终于开始静下心学习了,对不起组内悉心栽培的小伙伴大神们。

1、webpack是什么

webpack是一个前端的模块化管理和打包工具。

2、webpack有什么用

webpack可以做到以下的几个方法

可以管理维护项目中的模块依赖;

(1)整合依赖,优化依赖,把每一个异步块都作为一个文件打包,加快前端的加载速度;

(2)可以能过loader转换各种资源文件,也就是说,具有处理所有类型文件的能力;

(3)可以解析任何类型的模块,AMD,CMD,普通的js都可以,这样就省去了转换第三方库的力气。

(4)强大的插件系统

(5)热编译,不需要重启前端服务器哦

3、webpack环境安装

安装webpack

npm install webpack -g

安装css的loader

npm install css-loader style-loader

安装开发服务器

npm install webpack-dev-server -g

  

4、上代码

 一、命令行模式开启

index.html

<!-- index.html -->
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <script src="bundle.js"></script>
</body>
</html>

entry.js

require("./style.css") // 载入 style.css
document.write('It works.')
document.write(require('./module.js'))

module.js

// module.js
module.exports = 'It works from module.js.'

 style.css

/* style.css */
body { background: yellow; }

跑起来吧

webpack entry.js bundle.js --module-bind 'css=style-loader!css-loader'

然后我们一起来看一下这一坨屎

二、开启配置模式

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": "ice",
  "license": "MIT",
  "devDependencies": {
    "css-loader": "^0.21.0",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.2"
  }
}

npm install一下哦,安装一下依赖

webpack.config.js

var webpack = require('webpack')

module.exports = {
  entry: './entry.js',
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {test: /.css$/, loader: 'style-loader!css-loader'}
    ]
  },
  plugins: [
    new webpack.BannerPlugin('This file is created by ice')
  ]
}

然后webpack一下就行了

最后备忘一下几条命令

带进度和颜色的编译

webpack --progress --colors

 自动监控编译

webpack --progress --colors --watch

开发服务器运行方式

webpack-dev-server --progress --colors

显示故障信息

webpack --display-error-details

  

打完收工,睡觉

原文地址:https://www.cnblogs.com/yingbing/p/7266492.html