一.使用Webpack
1.Webpack命令
webpack -h
帮助命令webpack -v
查看版本webpack <entry> [<entry>] <output>
输入一个或多个entry打包命令
2.Webpack-cli
- 安装
npm install -g webpack-cli
- 作用:交互式的初始化一个项目
- 初始化webpack项目
webpack-cli init 项目名
3.Webpack配置
webpack
命令:如果直接执行webpack
会直接找当前文件夹下webpack的配置文件,默认webpack.config.js
文件webpack --config webpack.conf.dev.js
指定webpack的配置文件
4.使用第三方框架脚手架
- Vue-cli
- Angular-cli
- React-starter
二.打包JS
1.打包js文件方式
webpack entry<entry> output
指定入口和出口文件进行打包webpack --config webpack.conf.js
使用webpack配置文件进行打包
2.实例操作
-
ES6 Module的模块规范打包文件
-
创建sum.js用于导出计算的函数,创建app.js作为webpack的entry文件
//sum.js export default function(a,b) { return a+b; } //app.js import sum from './sum' console.log('sum(1,2)=',sum(1,2));
-
执行
webpack --entry ./app.js --output ./bundle.js
打包app.js文件到bundle.js文件中 -
在index.html中引入bundle.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test</title> </head> <body> <script src="./bundle.js"></script> </body> </html>
-
-
CommonJS Module的模块规范打包文件
-
创建minus.js用于导出计算的函数,创建app.js作为webpack的entry文件
//minus.js module.exports = function(a,b){ return a-b; } //app.js let minus = require('./minus'); console.log('minus(10,8) = ',minus(10,8));
-
执行
webpack --entry ./app.js --output ./bundle.js
打包app.js文件到bundle.js文件中 -
在index.html中引入bundle.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test</title> </head> <body> <script src="./bundle.js"></script> </body> </html>
-
-
AMD Module的模块规范打包文件
-
创建multi.js用于导出计算的函数,创建app.js作为webpack的entry文件
//multi.js define(function(require, factory) { 'use strict'; return function(a,b){ return a*b; } }); //app.js require(['./multi'],function(multi){ console.log('multi(2,3) = ',multi(2,3)); })
-
执行
webpack --entry ./app.js --output ./bundle.js
打包app.js文件到bundle.js文件中 -
在index.html中引入bundle.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test</title> </head> <body> <script src="./bundle.js"></script> </body> </html>
-
-
使用配置文件打包
-
webpack.conf.js
module.exports = { entry: { app:'./app.js' }, output: { filename: '[name].[hash:5].js' } }
-
如果使用webpack.config.js为文件名的话,则可是直接使用
webpack
打包 -
如果使用其他作为文件名的话,需要使用
webpack --config 文件名
打包
-
未完待续…