增长src/print.js
:javascript
export default function printMe() { console.log('I get called from print.js!'); }
在src/index.js
中导入它:html
import _ from 'lodash'; import printMe from './print'; function component() { let element = document.createElement('div'); let btn = document.createElement('button'); element.innerHTML = _.join(['Hello', 'webpack'], ' '); btn.innerHTML = 'Click here, then watch the console!'; btn.onclick = printMe; element.appendChild(btn); return element; } document.body.appendChild(component());
在webpack.config.js
中增长一个入口:java
const path = require('path'); module.exports = { entry: { app: './src/index.js', print: './src/print.js' }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };
到这里,还须要手动修改dist/index.html
:webpack
<html lang="en"> ... <body> <script src="app.bundle.js"></script> </body> </html>
打包后能够看到效果:git
通过以上实践,咱们发现每次修改输出文件名,都得手动修改dist/index.html
文件,若是给输出文件名增长了hash值维护起来更是麻烦。懒是进步的动力:github
安装 HtmlWebpackPlugin 插件:web
npm install --save-dev html-webpack-plugin
webpack.config.jsnpm
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: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };
HtmlWebpackPlugin会生成一个index.html,替换掉以前的文件。json
HtmlWebpackPlugin插件
html-webpack-template提供默认模板以外,还提供了一些额外的功能。bash
/dist
文件夹npm install --save-dev clean-webpack-plugin
webpack.config.js
... const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { ... plugins: [ ... new CleanWebpackPlugin() ], ... };
webpack经过manifest追踪全部模块到输出bundle之间的映射。
经过WebpackManifestPlugin能够将manifest数据提取为一个json文件。
The end... Last updated by: Jehorn, April 24, 2019, 4:22 PM
demo源码