webpack指南梳理学习 - 安装和基本构建
导读
webpack是前端开发过程中使用超多,用户量超广的一款前端开发打包编译工具,用起来让你欲罢不能,爱不释手。作为目前最火的打包工具,它又是如何使用工作的呢?接下来,我们来通过官网的指南学习梳理webpack的基础知识,掌握webpack的常用功能知识点
webpack安装
前提
在学习之前,我相信你们已经基本掌握前端的相关基础知识点,而且本地电脑环境已经搭配好node.js
以及npm
,目前webpack最新的版本是
4.33.0
,我们需要安装webpack
及webpack-cli
npm install --save-dev webpack
npm install --save-dev webpack-cli
配置package.json中的npm命令
"scripts": {
"start": "npx webpack --config webpack.config.js"
}
解读:由于webpack安装在本地,需要使用npx启动,所以在执行npm build
命令的时候,就相当于在执行:npx webpack --config webpack.config.js
webpack基本构建
首先我们创建一个目录,初始化 npm
本地项目:
初始化本地项目
mkdir webpack-test && cd webpack-test
npm init -y
cnpm install webpack webpack-cli --save-dev
项目目录结构
webpack-test
|- package.json
|- webpack.config.js
|- /dist
|- index.html
|- /src
|- index.js
package.json
{
"name": "webpack",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npx webpack --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.33.0",
"webpack-cli": "^3.3.3"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
src/index.js
import _ from 'lodash';
function component(){
let element = document.createElement("div")
element.innerHTML = _.join(['Hello','webpack'], ' ')
return element
}
document.body.appendChild(component())
dist/index.html
<!doctype html>
<html>
<head>
<title>基本构建</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
打包构建
D:\me\npm\test\webpack-test (master -> origin)
λ npm start
> [email protected] start D:\me\npm\test\webpack-test
> npx webpack --config webpack.config.js
Hash: 2ef1925c867aef539fef
Version: webpack 4.33.0
Time: 457ms
Built at: 2019-06-11 10:52:42
Asset Size Chunks Chunk Names
bundle.js 70.4 KiB 0 [emitted] main
Entrypoint main = bundle.js
[1] ./src/index.js 216 bytes {0} [built]
[2] (webpack)/buildin/global.js 472 bytes {0} [built]
[3] (webpack)/buildin/module.js 497 bytes {0} [built]
+ 1 hidden module
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/