webpack3的学习

https://edu.51cto.com/center/course/lesson/index?id=229013

一、介绍

什么是webpack?

webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

简单来说,webpack是一个前端模块化方案,更侧重模块打包,我们可以把开发中的所有资源(图片、js 文件、css 文件等)都看成模块,通过 loader(加载器)和 plugins(插件)对资源进行处理,打包成符合生产环境部署的前端资源。

 

二、安装

1、安装nodejs;

检查是否安装了node环境:node -v

bash-3.2$ node -v
v8.2.1                   

2、全局安装webpack;

npm install -g webpack

查看webpack的版本:webpack -v

如果安装很慢,可以安装一下淘宝镜像

$ npm install -g cnpm --registry=https://registry.npm.taobao.org

3、新建目录,用 npm init 初始化项目

mkdir webpack-study && cd webpack-study

npm init

嫌麻烦的同学,一直回车即可。或者使用以下命令

npm init -y 

看一下生成的package.json

{
  "name": "webpack-study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

4、集成 webpack

npm install webpack@3 --save-dev
npm install webpack@3 webpack-cli --save-dev

备注:如果你不加@3,它会自动帮你安装最新版本的webpack,此时你可能是webpack4的最新版本;安装了此步骤,运行 webpack -v 如果依然显示bash: webpack-cli: command not found,那你就进行全局安装 npm i webpack@3 -g。

package.json文件内,多了这几行

{
  "name": "webpack-study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^3.12.0"
  }
}

5、创建js文件

首先创建一个目录叫 src,然后在该目录下创建 javascript 文件,叫 app.js,结构如下

.
├── node_modules
├── package.json
└── src
    └── app.js

快速使用命令行为

mkdir src && touch src/app.js

运行命令

$ webpack ./src/app.js ./dist/app.bundle.js

这样一个简单的webpack代码打包就完成了。

 

 

三、webpack 的其他用法

--watch 热更新
-p 代码压缩

 

 

 

posted @ 2019-07-27 22:57  前端开发-周先生  阅读(49)  评论(0)    收藏  举报