打包后的目录结构:
webpack.config.js
// path 模块提供了一些用于处理文件路径
const path = require('path');
// fs模块用于对系统文件及目录进行读写操作
const fs = require('fs');
// 访问内置的插件
const webpack = require('webpack');
// cnpm install html-webpack-plugin --save-dev
const HtmlWebpackPlugin = require('html-webpack-plugin');
// cnpm install clean-webpack-plugin --save-dev
const CleanWebpackPlugin = require("clean-webpack-plugin");/**
* webpack配置
* @type {Object}
*/
const option = {};/**
* 入口
* @type {Object}
*/
option.entry = {};
/**
* 出口
* @type {Object}
*/
option.output = {};
// 打包根路径
option.output.path = path.resolve("./dist");
// 打包后js文件的相对路径
// option.output.filename = "js/[name]/index_[chunkhash:8].js";
option.output.filename = "js/[name].[chunkhash].js";
/**
* 打包类型
* @type {String}
*/
option.devtool = "eval-source-map";
/**
* 本地服务器配置
* @type {Object}
*/
option.devServer = {};
// 本地服务器根路径
option.devServer.contentBase = "./public";
// 是否记录历史
option.devServer.historyApiFallback = false;
// 是否实时刷新
option.devServer.inline = true;
// 监听端口
option.devServer.port = 8080;
/**
* 插件
* @type {Array}
*/
option.plugins = [];
// BannerPlugin插件
option.plugins.push(new webpack.BannerPlugin('版权所有,翻版必究'));
// 清除文件的CleanWebpackPlugin插件
option.plugins.push(new CleanWebpackPlugin(['dist/*.*','dist/js/*.js'],{
root:__dirname,
verbose:true,
dry:false
}));/**
* 测试多入口
* key值:打包后的文件name
* value值:源代码中的文件name
*/
option.entry.index = './src/main.js'; // => js/[name].[chunkhash].js => js/index.ff1e318532ae5fd984de.js
option.entry.a = './src/aa.js'; // => js/[name].[chunkhash].js => js/a.010a88238103e5fa9139.js
option.entry.b = './src/bb.js'; // => js/[name].[chunkhash].js => js/b.9f92cb4ee4ecd280c3af.js/**
* 测试多个html文件
* template : 源代码中的html文件
* filename : 打包后的html文件
* chunks : 要引入打包后的哪些js文件,从entry的key值里面找寻
*/
option.plugins.push(new HtmlWebpackPlugin({
template:'./src/aa/index.html',
filename:'aa_index.html',
chunks:['a']
}));
option.plugins.push(new HtmlWebpackPlugin({
template:'./src/bb/index.html',
filename:'bb_index.html',
chunks:['b']
}));
option.plugins.push(new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html',
chunks:['index','a','b']
}));//导出
module.exports = option;