webpack(3)基础的打包过程

没有配置文件的打包

如果我们没有使用配置文件webpack.config.js,那么我们就需要通过命令来打包
 

案例

我们首先创建一个webpackTest文件夹,然后在文件夹中再创建2个子文件夹distsrc

  • dist:打包后的文件夹
  • src:源代码文件夹

接着在src文件夹中创建4个文件,分别是info.jsmain.jsmathUtils.jsindex.html
infomathUtils是模块化的js文件,main是主入口,index是首页,整体项目结构如下

代码内容如下:

// info.js
const height = 180;
const weight = 180

export {height, weight}
// mathUtils.js
function add(num1, num2) {
  return num1 + num2
}

function mul(num1, num2) {
  return num1 * num2
}

module.exports = {
  add, mul
}
//main.js
// 1.CommonJS模块化
const {add, mul} = require('./mathUtils')

console.log(add(20, 30))
console.log(mul(50, 80))


// 2.es6模块化
import {height, weight} from "./info";

console.log(height)
console.log(weight)

最后我们来到webpackTest目录下,输入以下命令:

webpack ./src/main.js -o ./dist/bundle.js --mode development
  • ./src/main.js:需要打包的文件路径
  • ./dist/bundle.js:需要打包到哪个文件夹下
  • --mode development:打包的模式是开发者环境

结果如下

我们会发现webpack会将打包的文件放到了我们指定的dist目录下

最后只需要在index.html中引入打包后的main.js即可

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script src="./dist/bundle.js/main.js"></script>
</body>
</html>

我们访问index首页,查看控制台,就能看到我们源代码main.js中写的打印日志了

说明使用webpack打包成功了

原文地址:https://www.cnblogs.com/jiakecong/p/14989890.html