1:首先我们创建一个目录,初始化 npm,然后 在本地安装 webpack,接着安装 webpack-cli(此工具用于在命令行中运行 webpack):
mkdir webpack-demo && cd webpack-demo //创建文件,切入这个文件夹
npm init –y //初始化文件
npm install webpack webpack-cli --save-dev //安装webpack
2: npm init –y //文档里面会创建package.json文件
3:现在我们将创建以下目录结构、文件和内容://main文件不用创建,打包生成的文件
package.json
"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": {}
}
4:我们需要在本地安装 library:
npm install --save lodash //
5:更改代码
src/index.js
src/index.js,index.html
+ import _ from 'lodash';
+
function component() {
var element = document.createElement('div');
- // Lodash, currently included via a script, is required for this line to work
+ // Lodash, now imported by this script
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
<!doctype html>
<html>
<head>
<title>起步</title>
- <script src="https://unpkg.com/lodash@4.16.6"></script> //NPM已经本地安装lodash
</head>
<body>
- <script src="./src/index.js"></script> //打包进入
+ <script src="main.js"></script>
</body>
</html>
在这个设置中,index.js 显式要求引入的
6:npx webpack,会将我们的脚本作为入口起点,然后 输出 为 main.js
7:在浏览器中打开 index.html
,如果一切访问都正常,你应该能看到以下文本:'Hello webpack'。
8:使用配置文件
webpack.config.js
8:使用配置文件
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 //根据配置项执行,你会发现,打包文件为
bundle.js
9:package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack" //用来使用 npm run build 命令,来替代我们之前使用的 npx 命令
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
}
}
//npm run build