想联系一下webpack
的使用方式,所以抛弃了任何手脚架
工具,自己创建了一个多页面应用,然后手写了webpack
相关配置,但是通过npm build
打包的时候发现虽然是多个html
文件,但是所有的html
里面引入的js
都是相同的(都引入了所有的js(打包后的)文件),啥问题呢?
源码地址:https://gitee.com/qingyun1029/webpack-for-multiple-page-demo
使用方式:
- 克隆项目到本地
git clone git@gitee.com:qingyun1029/webpack-for-multiple-page-demo.git
- 安装依赖模块
npm install
- 打包代码
webpack.base.conf.js
打包后的代码结构如下:
about.html(格式化后代码片段)
home.html(格式化后代码片段)
可以看到这两个html
页面都引入了另一个和自己没关系的js
文件,怎么回事呢?
项目相关配置,如使用源码,请 忽略 下面内容!!!!
————————————————————————————————————————————————
'use strict'
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'production',
entry: {
// home: path.resolve(__dirname, 'src/pages/home/index.js'),
// about: path.resolve(__dirname, 'src/pages/about/index.js'),
home: './src/pages/home/index.js',
about: './src/pages/about/index.js',
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].[chunkhash].js',
},
resolve: {
extensions: ['.js', '.json'],
// alias: {
// 'vue$': 'vue/dist/vue.esm.js',
// '@': resolve('src'),
// }
},
module: {
// rules: [
// {
// test: /\.js$/,
// loader: 'babel-loader',
// include: [resolve('src')]
// }
// ]
},
plugins: [
new HtmlWebpackPlugin({
filename: 'home.html',
template: 'src/pages/home/html/index.html',
inject: true,
// favicon: resolveApp('favicon.ico'),
minify: {
removeComments: true,
collapseWhitespace: true,
// removeAttributeQuotes: true,
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
// chunksSortMode: 'dependency'
}),
new HtmlWebpackPlugin({
filename: 'about.html',
template: 'src/pages/about/html/index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
},
}),
],
}
build.js
const ora = require('ora')
const webpack = require('webpack')
const webpackConfig = require('./webpack.base.conf.js')
const chalk = require('chalk')
const spinner = ora('building for production...')
spinner.start()
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors1111111.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete222222222.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
chunks
选项即可