webpack学习_管理输出(管理资源插件)
管理输出步骤
Step1:在src新建文件print.js添加逻辑
Step2:在src/index.js import 引用新添加的逻辑
Step3:更新dist/index.html文件,修改引入的文件(引入的JS文件)
Step4:对应修改webpack/.config.js配置文件(entry和output)
Step5:执行npm prun build
src/print.js
export default function printMe() { console.log('I get called from print.js!'); }
src/index.js
import _ from 'lodash'; + import printMe from './print.js'; function component() { var element = document.createElement('div'); + var btn = document.createElement('button'); element.innerHTML = _.join(['Hello', 'webpack'], ' '); + btn.innerHTML = 'Click me and check the console!'; + btn.onclick = printMe; + + element.appendChild(btn); return element; } document.body.appendChild(component());
dist/index.html
<!doctype html>
<html>
<head>
- <title>Asset Management</title>
+ <title>Output Management</title>
+ <script src="./print.bundle.js"></script>
</head>
<body>
- <script src="./bundle.js"></script>
+ <script src="./app.bundle.js"></script>
</body>
</html>
webpack.config.js
const path = require('path');
module.exports = {
- entry: './src/index.js',
+ entry: {
+ app: './src/index.js',
+ print: './src/print.js'
+ },
output: {
- filename: 'bundle.js',
+ filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
设定HtmlWebpackPlugin插件
插件HtmlWebpackPlugin默认生成index.html文件,当执行 npm prun build的时候 生成的index.html文件会把原本的替换掉
Step1:安装HtmlWebpackPlugin插件
Step2:在webpack.config.js里面配置(主要是引入和在plugins里面写入)
Step3:npm run build运行
Step1
npm install --save-dev html-webpack-plugin
Step2
const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
+ plugins: [
+ new HtmlWebpackPlugin({
+ title: 'Output Management'
+ })
+ ],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
设定cleanWebpackPlugin 插件
每次构建前清理/dist文件夹,那么里面就只会生成用到的文件(减少用于的代码和文件)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
plugins: [
+ new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

浙公网安备 33010602011771号