安装
mkdir webpack && cd webpack
npm init -y
npm install webpack webpack-cli --save-dev
init 的时候会生成package.json文件,name名是webpack,
然后下一步安装webpack的时候会报错
npm install webpack webpack-cli --save-dev
npm ERR! code ENOSELF
npm ERR! Refusing to install package with name "webpack" under a package
npm ERR! also called "webpack". Did you name your project the same
npm ERR! as the dependency you're installing?
npm ERR!
npm ERR! For more information, see:
npm ERR! <https://docs.npmjs.com/cli/install#limitations-of-npms-install-algorithm>
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2021-05-18T02_01_45_796Z-debug.log
这需要把package.json文件的name改成别的名字
这个应该是开始穿件文件的时候不叫webpack就行,但是习惯建文件建同名的所以有问题了
mkdir webpack-demo && cd webpack-demo
npm init -y //这样初始化生成的package.json的name就是webpack-demo
npm install webpack webpack-cli --save-dev
创建如下目录
webpack-demo
|- package.json
|- /dist
|- index.html
|- /src
|- index.js
index.js
import _ from "lodash";
function component(params) {
var ele = document.createElement("div");
ele.innerHTML = _.join(["Hello", "webpack"], " ");
return ele;
}
document.body.appendChild(component());
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
main.js为执行npx webpack自动生成,打开index.html可以看到Hello webpack
添加webpack.config.js
webpack-demo
|- package.json
+ |- webpack.config.js
|- /dist
|- index.html
|- /src
|- index.js
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
index.html中引入的main.js就可以替换为bundle.js