Webpack入门
通过搭建Demo工程来入门Webpack
Demo工程
地址:https://github.com/fengqingxiuyi/WebpackFirst
npm 初始化
localhost:~ mmh$ cd Desktop/
localhost:Desktop mmh$ mkdir test
localhost:Desktop mmh$ cd test/
//npm初始化,并且选择yes
localhost:test mmh$ npm init -y
//创建index.js文件
localhost:test mmh$ touch index.js
创建index.html
localhost:test mmh$ vi index.html
html内容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="./index.js"></script>
</head>
<body>
</body>
</html>
安装Webpack
localhost:test mmh$ npm i webpack -D
localhost:test mmh$ npm i webpack-cli -D
localhost:test mmh$ npm i webpack-dev-server -D
localhost:test mmh$ vi package.json
因为安装了webpack-dev-server,所以在package.json中配置脚本,方便使用,内容如下:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
}
}
配置Webpack
localhost:test mmh$ vi webpack.config.js
内容如下
// webpack.config.js
const path = require('path')
module.exports = {
// 入口:表示要使用webpack打包哪个文件
entry: path.join(__dirname, './index.js'),
// 出口:输出文件的相关配置
output: {
// 指定打包好的文件,输出到哪个目录中去
path: path.join(__dirname, './dist'),
// 指定输出的文件名称
filename: 'bundle.js'
}
}
同时修改index.html
localhost:test mmh$ vi index.html
内容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="/bundle.js"></script>
</head>
<body>
</body>
</html>
安装three.js测试使用
localhost:test mmh$ npm i three
安装好之后,package.json的内容如下:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"three": "^0.117.1"
}
}
然后编辑index.js
localhost:test mmh$ vi index.js
内容如下:
import * as THREE from 'three';
var camera, scene, renderer;
var geometry, material, mesh;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.02;
renderer.render( scene, camera );
}
启动
localhost:test mmh$ npm run dev
然后在浏览器中打开网址,如:http://localhost:8080/