学习链接:https://www.webpackjs.com/guides
在一个文件内运行命令npm init会生成package.json文件
npm init
运行以下命令:
npm install --save-dev webpack
npm install --save-dev webpack-cli
会更新package.json文件,以上的--save-dev表示安装在开发环境(其中,如果安装了webpack4.x.x,需要安装webpack-cli)
安装模块会生成package-lock.json,当我们从其他地方克隆项目时,需要安装相关依赖,该文件为默认的安装模块,使用命令npm install则会安装默认模块。
由于开发环境的不同,不建议对webpack做全局安装
demo目录结构
package.json
{
"name": "testwebpack",
"version": "1.0.0",
"description": "the study about webpack",
"main": "index.js",
"scripts": {
"test": "test",
"dev": "webpack"
},
"keywords": [
"webpack"
],
"author": "fanqingyun",
"license": "ISC",
"devDependencies": {
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0"
},
"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')
}
};
index.html
<!doctype html>
<html>
<head>
<title>起步</title>
<!-- <script src="https://unpkg.com/lodash@4.16.6"></script> -->
</head>
<body>
<!-- <script src="./src/index.js"></script> -->
<script src="bundle.js"></script>
</body>
</html>
index.js
import _ from 'lodash'; // 需要自己 npm install --save lodtash
function component() {
var element = document.createElement('div');
// Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
console.log(element.innerHTML)
return element;
}
document.body.appendChild(component());
webpack的默认配置文件为webpack.config.js,构建时可以npx webpack,如果需要执行其他配置文件,如config.js,则可以npx webpack --config config.js。像后者执行其他配置文件的情况下,每次构建都要写得很长,此时可以在package.json文件里配置script字段,如下:
此时就可以用npm run dev来构建
当前指定构建输出的文件名为bundle.js,如果没有指定,默认为main.js
打开index.html运行结果