mkdir webpack-demo && cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
此时, 就构造好了一个基础的webapck项目
在上步构造好的文件夹中添加index.html和index.js文件, 目录结构如下:
webpack-demo
|- package.json
|- dist
|- index.html
|- /src
|- index.js
其中index.html的内容为
<html>
<head>
<title>起步title>
head>
<body>
<script src="main.js">script>
body>
html>
index.js的内容为
import _ from 'lodash';
function component() {
let element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
package.json的内容为
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"dependencies": {
"lodash": "^4.17.15"
}
}
npm install
接下来就可以使用webpack命令打包了, 执行
npx webpack
执行结果:
Hash: c22be75961b98d37bd83
Version: webpack 4.43.0
Time: 245ms
Built at: 2020-05-15 4:27:40 PM
Asset Size Chunks Chunk Names
main.js 72.1 KiB 0 [emitted] main
Entrypoint main = main.js
[1] ./src/index.js 234 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/
这时可以看到在dist目录下生成了一个名称为app.js的文件, 使用浏览器打开index.html,一切正常的话就可以看到Hello webpack了
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
然后执行
npx webpack --webpack.config.js
同样可以实现上面的效果,这里的 --webpack.config.js可以指定任意符合标准的配置文件,如果存在名字为webpack.config.js的文件, 在没有指定参数的情况下webpack会默认执行这个配置
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"dependencies": {
"lodash": "^4.17.15"
}
}
这是, 执行npm命令即可打包
npm run build
还可以在sciprts中的webpack命令后添加参数