前提:安装了Node.js。
项目创建
创建并进入目录,在本地安装webpack以及webpack-cli。
mkdir projectname && cd projectname
npm init -y
npm install webpack webpack-cli --save-dev
接下来创建以下目录及文件:
project
projectname
|- package.json
+ |- dist
+ |- index.html
+ |- /src
+ |- index.js
/src/index.js
function component(){
var element = document.createElement('div');
element.innerHTML = "Hello webpack";
return element;
}
document.body.appendChild(component());
/dist/index.html
<DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>webpack_demo</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
修改package.json'中的内容,确保安装包是私有的。移除main入口。
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
+ "private": true,
- "main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9"
},
"dependencies": {}
}
webpack.config.js
const path=require('path');
module.exports = {
entry: './src/index.js', //入口文件
output: { //输出文件
filename: 'bundle.js',
path: path.resolve(__dirname,'dist');
}
};
运行项目
在目录位置下运行npx webpack --config webpack.config.js,即完成编译。
npx webpack --config webpack.config.js
Hash: d9af8237df6e25d9ef16
Version: webpack 4.42.1
Time: 463ms
Built at: 2020-04-12 11:57:50
Asset Size Chunks Chunk Names
bundle.js 1 KiB 0 [emitted] main
Entrypoint main = bundle.js
[0] ./src/index.js 179 bytes {0} [built]
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/
E:\web-project\webpack_project\bigbearhome>
为了方便运行本地webpack,在`package.json``添加脚本:
{
"name": "bigbearhome",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11"
},
"dependencies": {
"lodash": "^4.17.15"
}
}
运行npm run build即可运行本地webpack。
npm run build
Hash: d9af8237df6e25d9ef16
Version: webpack 4.42.1
Time: 77ms
Built at: 2020-04-12 12:01:13
Asset Size Chunks Chunk Names
bundle.js 1 KiB 0 [emitted] main
Entrypoint main = bundle.js
[0] ./src/index.js 179 bytes {0} [built]
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/