赞
踩
安装 node 模块 glob ( 扫描文件就靠它了 )
yarn add glob -D
const glob = require('glob')
自动扫描获取入口文件、html 模版(统一放在 utils.js 文件里)
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const appDirectory = fs.realpathSync(process.cwd())
// 获取文件公共方法
const getFiles = filesPath => {
let files = glob.sync(filesPath)
let obj = {}
let filePath, basename, extname
for (let i = 0; i < files.length; i++) {
filePath = files[i]
extname = path.extname(filePath) // 扩展名 eg: .html
basename = path.basename(filePath, extname) // 文件名 eg: index
// eg: { index: '/src/views/index/index.js' }
obj[basename] = path.resolve(appDirectory, filePath)
}
return obj
}
// 打包入口
// 1.允许文件夹层级嵌套;
// 2.入口js的名称不允许重名;
const entries = getFiles('src/views/**/*.js')
// 页面的模版
// 1.允许文件夹层级嵌套;
// 2.html的名称不允许重名;
const templates = getFiles('src/views/**/*.html')
// 获取entry入口,为了处理在某些时候,entry入口会加 polyfill等:
// 1.允许文件夹无限层级嵌套;
// 2.入口的名称不允许重名;
const getEntries = () => {
let entry = {}
for (let name in entries) {
entry[name] = entries[name]
}
return entry
}
webpack 打包入口
module.exports = {
entry: utils.getEntries(),
}
html 模版自动引入打包资源(区分 dev 和 prod 环境,配置不同,同样抽离到 utils.js 文件更好一些)
const HtmlWebpackPlugin = require('html-webpack-plugin')
// 生成webpack.config.dev.js的plugins下new HtmlWebpackPlugin()配置
const getHtmlWebpackPluginsDev = () => {
let htmlWebpackPlugins = []
let setting = null
for (let name in templates) {
setting = {
filename: `${name}.html`,
template: templates[name],
inject: false, // js插入的位置,true/'head'/'body'/false
}
// (仅)有入口的模版自动引入资源
if (name in getEntries()) {
setting.chunks = [name]
setting.inject = true
}
htmlWebpackPlugins.push(new HtmlWebpackPlugin(setting))
setting = null
}
return htmlWebpackPlugins
}
// 生成webpack.config.prod.js的plugins下new HtmlWebpackPlugin()配置
const getHtmlWebpackPluginsProd = () => {
let htmlWebpackPlugins = []
let setting = null
for (let name in templates) {
setting = {
filename: `${name}.html`,
template: templates[name],
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
inject: false, // js插入的位置,true/'head'/'body'/false
}
// (仅)有入口的模版自动引入资源
if (name in getEntries()) {
setting.chunks = ['manifest', 'vendor', 'common', name]
setting.inject = true
}
htmlWebpackPlugins.push(new HtmlWebpackPlugin(setting))
setting = null
}
return htmlWebpackPlugins
}
将 html-webpack-plugin 解构放到 plugins 里
const utils = require('./utils')
...
plugins: { // dev
...utils.getHtmlWebpackPluginsDev(),
},
...
...
plugins: { // build
...utils.getHtmlWebpackPluginsProd(),
},
...
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。