使用webpack打包详细案例教程
-
首先安装node环境,使用node中的工具npm安装webpack
node.js 下载地址:http://nodejs.cn/download/
node.js安装教程:转载:https://blog.youkuaiyun.com/antma/article/details/86104068
-
安装webpack命令,-g 为全局安装
npm install webpack@3.6.0 -g
-
查看是否安装完成
webpack --version
-
目录结构
info.js文件
export const name='Jie';
export const age=20;
export const height=1.88;
main.js文件
// 使用 commonjs的模块化规范
const {add, mul} = require('./mainUtil.js')
console.log(add(100, 200));
console.log(mul(100, 200));
// 使用ES6模块化规范
import {name, age, height} from './info.js'
console.log(name);
console.log(age);
console.log(height);
mainUtil.js文件
function add(num1, num2) {
return num1 + num2
}
function mul(num1, num2) {
return num1 * num2
}
module.exports = {
add,
mul
}
index.html文件
<!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>Document</title>
</head>
<body>
<script src="./dist/bundle.js"></script>
</body>
</html>
-
使用webpack打包文件命令,执行命令式要在进入到01-webpack文件夹下面
webpack ./src/main.js ./dist/bundle.js
-
使用webpack打包文件时出现:无法加载文件 D:\nodejs\node_global\webpack.ps1,因为在此系统上禁止运行脚本。
解决办法:
- 使用管理员身份启动vs code
- 执行:get-ExecutionPolicy,显示Restricted,表示状态是禁止的
- 执行:set-ExecutionPolicy RemoteSigned
- 执行:get-ExecutionPolicy,显示RemoteSigned 后再重新执行打包的命令
-
打包成功,打包成功后会在dist文件下面生成一个bundle.js文件,然后在index.html中直接引入bundle.js文件,就可以使用了