Learning is in the Chinese web pack, just this record for later review;
(https://doc.webpack-china.org/guides/getting-started/#-)
Write before:
I think there are four basic modules of webpack that I should know before learning: 1. Entrance 2. Export 3.loader 4. Plug-ins
I. Basic Use
Follow the steps on the website to set up the project as follows:
1. Project Directory
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(['Hello','Shen Yuchao'],'');
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 Is the packaged file -->
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
4. webpack.config.js (focus)
// The path module should come with the webpack when it is installed
const path = require('path');
module.exports = {
// Entrance
entry: './src/index.js',
// Exit
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
5.package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// Running a webpack-compiled script, for some reason, my npx is not recognized, and my node is 8.9+, so I have to skip this step and use npm run build directly
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^3.10.0"
},
"dependencies": {
"lodash": "^4.17.5"
}
}
6. Run npm run build packaging
7. Open dist/index.html browsing instead of src/index.html
2. Manage resources (that is, load various resource files into the project)
Loading a variety of resource-oriented projects requires a lot of Loaders
1. Load css
(1) Install loader
npm install --save-dev style-loader css-loader
(2) Configure 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) Use
src/index.js
import _ from 'lodash';
import './style.css'; // Relative paths should be used, otherwise modules cannot be found
function component(){
var element = document.createElement('div');
element.innerHTML = _.join(['Hello','Shen Yuchao'],'');
return element;
}
document.body.appendChild(component());
src/style.css
body{
color: red;
font-size: 70px;
}