复制起步demo
准备
首先,调整一下我们的项目:
project
|- /src+ |- print.js
我们在 src/print.js 文件中添加一些逻辑:
src/print.js
export default function printMe() {console.log('I get called from print.js!');}
并且在 src/index.js 文件中使用这个函数:
src/index.js
import _ from 'lodash';+import printMe from './print.js';function component() {const element = document.createElement('div');+ const 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 文件,来为 webpack 分离入口做好准备:
dist/index.html
<!DOCTYPE html><html><head><meta charset="utf-8" />- <title>管理资源</title>+ <title>管理输出</title>+ <script src="./print.bundle.js"></script></head><body>- <script src="bundle.js"></script>+ <script src="./index.bundle.js"></script></body></html>
现在调整配置。我们将在 entry 添加 src/print.js 作为新的入口起点(print),然后修改 output,以便根据入口起点定义的名称,动态地产生 bundle 名称:
webpack.config.js
const path = require('path');module.exports = {- entry: './src/index.js',+ entry: {+ index: './src/index.js',+ print: './src/print.js',},output: {- filename: 'bundle.js',+ filename: '[name].bundle.js',path: path.resolve(__dirname, 'dist'),},};
npm run build
我们可以看到,webpack 生成 print.bundle.js 和 index.bundle.js 文件,这也和我们在 index.html 文件中指定的文件名称相对应。如果你在浏览器中打开 index.html,就可以看到在点击按钮时会发生什么。
但是,如果我们更改了我们的一个入口起点的名称,甚至添加了一个新的入口,会发生什么?会在构建时重新命名生成的 bundle,但是我们的 index.html 文件仍然引用旧的名称。让我们用 HtmlWebpackPlugin 来解决这个问题。
添加HtmlWebpackPlugin
作用:生成html并自动加载打包后的js
npm install --save-dev html-webpack-plugin
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');module.exports = {、、、plugins: [new HtmlWebpackPlugin({title: '管理输出',}),],};
清理 /dist 文件夹
webpack.config.js
output: {filename: '[name].bundle.js',path: path.resolve(__dirname, 'dist'),+ clean: true,},
