学习是在webpack中文网,仅此记录,以供后期复习;
(https://doc.webpack-china.org/guides/getting-started/#-)
写在前面:
我认为学习之前应该了解的webpack4大基本模块:
1.入口
2.出口
3.loader
4.插件
一.基本使用
按照官网的步骤建立项目,记录如下:
1.项目目录
webpack-demo
|- package.json
+ |- /dist
+ |- index.html
- |- index.html
|- /src
|- index.js
2.index.js
import _ from 'lodash';
function component(){
var element = document.createElement('div');
element.innerHTML = _.join(['你好','申玉超'],'');
return element;
}
document.body.appendChild(component());
3.dist/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Asset Management</title>
<!-- <script src="https://unpkg.com/lodash@4.16.6"></script> -->
</head>
<body>
<!-- <script type="text/javascript" src="./src/index.js"></script> -->
<!-- bundle.js是打包之后的文件 -->
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
4.webpack.config.js(重点)
// path 模块应该是在安装webpack的时候自带的
const path = require('path');
module.exports = {
// 入口
entry: './src/index.js',
// 出口
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
5.package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// 运行webpack编译的脚本,不知为何,我的npx不能识别,node是8.9+的,所以只好跳过这个步骤,直接使用npm run build
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^3.10.0"
},
"dependencies": {
"lodash": "^4.17.5"
}
}
6.运行npm run build打包
7.打开dist/index.html浏览,不要打开src/index.html
二.管理资源(即加载各种资源文件到项目中)
加载各种资源导向项目中,需要使用很多loader
1.加载css
(1)安装loader
npm install --save-dev style-loader css-loader
(2)配置webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}]
}
}
(3)使用
src/index.js
import _ from 'lodash';
import './style.css'; // 应该使用相对路径,否则不能找到模块
function component(){
var element = document.createElement('div');
element.innerHTML = _.join(['你好','申玉超'],'');
return element;
}
document.body.appendChild(component());
src/style.css
body{
color: red;
font-size: 70px;
}