惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cisco Talos Blog
Cisco Talos Blog
S
SegmentFault 最新的问题
大猫的无限游戏
大猫的无限游戏
Project Zero
Project Zero
博客园 - 叶小钗
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
Lohrmann on Cybersecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
NISL@THU
NISL@THU
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Palo Alto Networks Blog
博客园_首页
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Last Week in AI
Last Week in AI
量子位
Security Latest
Security Latest
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
博客园 - 【当耐特】
T
Threat Research - Cisco Blogs
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
宝玉的分享
宝玉的分享
V2EX - 技术
V2EX - 技术
P
Privacy International News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
Webroot Blog
Webroot Blog
Apple Machine Learning Research
Apple Machine Learning Research
Jina AI
Jina AI
美团技术团队
Hacker News: Ask HN
Hacker News: Ask HN
人人都是产品经理
人人都是产品经理
S
Securelist
S
Security Affairs
WordPress大学
WordPress大学
J
Java Code Geeks
月光博客
月光博客
N
News and Events Feed by Topic
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog

博客园 - givebest

Glarity Summary - 利用 ChatGPT为Bilibili及YouTube视频内容生成摘要 (免费无广告) Nodejs CMS——基于 NestJS/NuxtJS 的完整开源项目 Vee-validate 父组件获取子组件表单校验结果 Vue.js + Nuxt.js 项目中使用 Vee-validate 表单校验 又拍云 Node.js 实现文件上传、删除 Docz 用 MDX 写 React UI 组件文档 - givebest Mac 远程连接 Windows - givebest 更优雅的方式: JavaScript 中顺序执行异步函数 Node.js 上传文件 - givebest - 博客园 win10 系统右键菜单不显示文字(只有小图标)修复方法 JavaScript 排序算法(JavaScript sorting algorithms) JavaScript addEventListener 第三个参数 Kindle电子阅读器收不到个人文档推送解决方案 纯CSS3大转盘抽奖(响应式、可配置) - givebest - 博客园 JavaScript简单分页,兼容IE6,~3KB 原生JavaScript实现hasClass、addClass、removeClass、toggleClass - givebest - 博客园 JavaScript闭包(Closure) GitHub Pages 绑定二级域名 - givebest HTML5 Canvas绘制转盘抽奖 - givebest - 博客园
webpack 实现的多入口项目脚手架
givebest · 2017-06-25 · via 博客园 - givebest

简介

基于 webpack2 实现的多入口项目脚手架,主要使用 extract-text-webpack-plugin 实现 js 、css 公共代码提取,html-webpack-plugin 实现 html 多入口,less-loader 实现 less 编译,postcss-loader 配置 autoprefixer 实现自动添加浏览器兼容前缀,html-withimg-loader 实现 html 内引入图片版本号添加和模板功能,babel-loader 实现 ES6 转码功能, happypack 多线程加速构建速度。

目录

├── dist                     # 构建后的目录
├── config                   # 项目配置文件
│   ├── webpack.config.js    # webpack 配置文件
│   └── postcss.config.js    # postcss 配置文件
├── src                      # 程序源文件
│   └── js                   # 入口
│   ├   └── index.js         # 匹配 view/index.html
│   ├   └── user         
│   ├   ├    ├── index.js    # 匹配 view/user/index.html
│   ├   ├    ├── list.js     # 匹配 view/user/list.html
│   ├   └── lib              # JS 库等,不参与路由匹配
│   ├       ├── jquery.js 
│   └── view                 
│   ├    └── index.html       # 对应 js/index.js
│   ├    └── user         
│   ├        ├── index.html   # 对应 js/user/index.js
│   ├        ├── list.html    # 对应 js/user/list.js
│   └── css                   # css 文件目录
│   ├    └── base.css          
│   ├    └── iconfont.css     
│   └── font                  # iconfont 文件目录
│   ├    └── iconfont.ttf         
│   ├    └── iconfont.css
│   └── img                   # 图片文件目录
│   ├    └── pic1.jpg         
│   ├    └── pic2.png     
│   └── template              # html 模板目录
│       └── head.html         
│       └── foot.html            

配置

多入口

根据 JS 目录获取多入口数组

const ROOT = process.cwd();  // 根目录

let entryJs = getEntry('./src/js/**/*.js');

/**
 * 根据目录获取入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntry (globPath) {
	let entries = {};
	Glob.sync(globPath).forEach(function (entry) {
		let basename = path.basename(entry, path.extname(entry)),
			pathname = path.dirname(entry);
		// js/lib/*.js 不作为入口
		if (!entry.match(/\/js\/lib\//)) {
			entries[pathname.split('/').splice(3).join('/') + '/' + basename] = pathname + '/' + basename;
		}
	});
	return entries;
}

// webpack 配置
const config = {
	entry: entryJs,
	output: {
		filename: 'js/[name].js?[chunkhash:8]',
		chunkFilename: 'js/[name].js?[chunkhash:8]',
		path: path.resolve(ROOT, 'dist'),
		publicPath: '/'
	},  
}

module

使用 babel 实现 ES2015 转 ES5,less 转 css 并使用 postcss 实现 autoprefixer 自动添加浏览器兼容,url-loader 实现 css 引用图片、字体添加版本号,html-withimg-loader 实现 html 引用图片添加版本号并实现模板功能。

module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader?id=js',
                options: {
                    presets: ['env']
                }
            }
        },
        {
            test: /\.(less|css)$/,
            use: ExtractTextPlugin.extract({
                fallback: 'style-loader?id=styles',
                use: [{
                        loader: 'css-loader?id=styles',
                        options: {
                            minimize:  !IsDev
                        }
                    }, 
                    {
                        loader: 'less-loader?id=styles'
                    }, 
                    {
                        loader: 'postcss-loader?id=styles',
                        options: {
                            config: {
                                path: PostcssConfigPath
                            }
                        }
                    }
                ]
            })
        },
        {
            test: /\.(png|jpg|gif)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 100,
                        publicPath: '',
                        name: '/img/[name].[ext]?[hash:8]'
                    }
                }
            ]
        },
        {
            test: /\.(eot|svg|ttf|woff)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 100,
                        publicPath: '',
                        name: '/font/[name].[ext]?[hash:8]'
                    }
                }
            ]
        },
        // @see https://github.com/wzsxyz/html-withimg-loader
        {
            test: /\.(htm|html)$/i,
            loader: 'html-withimg-loader?min=false'
        }
    ]
},


// postcss.config.js
module.exports = {
	plugins: [
		require('autoprefixer')({
			browsers: ['> 1%', 'last 5 versions', 'not ie <= 9'],
		})
	]
}

View 视图

根据目录对应关系,获取 js 对应的 html 入口

let entryHtml = getEntryHtml('./src/view/**/*.html'),
    configPlugins;

entryHtml.forEach(function (v) {
	configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
resolve: {
    alias: {
        views:  path.resolve(ROOT, './src/view')	
    }
},

/**
 * 根据目录获取 Html 入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntryHtml (globPath) {
	let entries = [];
	Glob.sync(globPath).forEach(function (entry) {
		let basename = path.basename(entry, path.extname(entry)),
			pathname = path.dirname(entry),
			// @see https://github.com/kangax/html-minifier#options-quick-reference
			minifyConfig = IsDev ? '' : {
				removeComments: true,
				collapseWhitespace: true,
				minifyCSS: true,
				minifyJS: true	
			};

		entries.push({
			filename: entry.split('/').splice(2).join('/'),
			template: entry,
			chunks: ['common', pathname.split('/').splice(3).join('/') + '/' + basename],
			minify: minifyConfig
		});

	});
	return entries;
}

plugins

使用 happypack 多线程加快构建速度,CommonsChunkPlugin 实现提取公用 js 为单独文件,extract-text-webpack-plugin 实现提取公用 css 为单独文件,

let configPlugins = [
    new HappyPack({
        id: 'js',
        // @see https://github.com/amireh/happypack
        threadPool: HappyThreadPool,
        loaders: ['babel-loader']
    }),
    new HappyPack({
        id: 'styles',
        threadPool: HappyThreadPool,
        loaders: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
    }),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'common'
    }),
    // @see https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle
    new ExtractTextPlugin({
        filename: 'css/[name].css?[contenthash:8]',
        allChunks: true
    })
];

entryHtml.forEach(function (v) {
	configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
plugins: configPlugins,

开发

webpack-dev-server 实现开发环境自动刷新等功能

// webpack 配置
devServer: {
    contentBase: [
        path.join(ROOT, 'src/')
    ],
    hot: false,
    host: '0.0.0.0',
    port: 8080
}

开发

npm start

http://localhost:8080/view

构建

cross-env 实现区分开发和生产环境构建

命令 说明
npm run dev 开发环境构建,不压缩代码
npm run build 生产环境构建,压缩代码

仓库

欢迎 star

https://github.com/givebest/webpack2-multiple-entry

转载请注明出处:http://blog.givebest.cn/webpack/2017/06/25/webpack-multiple-entry.html