这是一份可以快速在不同 PHP 项目移植的 webpack 配置,适合仅使用 PHP 路由,支持版本号和走接口获取数据的前端项目。
首先来看看打包编译的结果:
经过打包编译后的资源文件将会放到 public/static/,模版文件放到 resource/view/。
public
|_static
|_css
|_*.css
|_js
|_*.js
|_verdor.js
|_manifest.js
resource
|_view
|_*.php
打包前的 src 文件在项目根目录:
src
|_assets
|_css
|_*.css
|_js
|_*.js
|_*.html // 模版文件
在这里使用 webpack + html-webpack-plugin + extract-text-webpack-plugin 来完成目标。
先编写一份静态资源和模版文件的入口配置:
// entries.config.js
/**
* [ENTRIES 多入口配置]
*/
exports.ENTRIES = {
vendor: './src/assets/js/vendor',
index: './src/assets/js/main.js',
PA: './src/assets/js/hello.js',
less: './src/assets/js/less.js'
}
/**
* [TEMPLATES html-webpack-plugin 多模版配置]
* @type {String} template 路径相对于 webpack 配置文件
* @type {String} filename 路径相对于 webpack output 路径
* @type {Array} chunks 取自以上 ENTRIES 对象中的 key
* 其它配置请参考 https://www.npmjs.com/package/html-webpack-plugin
*/
exports.TEMPLATES = [{
template: './src/index.html',
filename: '../resource/view/index.php',
chunks: ['vendor', 'manifest', 'index']
},{
template: './src/test.html',
filename: '../resource/view/test.php',
chunks: ['vendor', 'manifest', 'PA']
},{
template: './src/less.html',
filename: '../resource/view/less.php',
chunks: ['vendor', 'manifest', 'less']
}]
在 webpack.config.js 引入该配置
// webpack.config.js
// 引入配置项
const ENTRIES = require('./entries.config.js').ENTRIES
const TEMPLATES = require('./entries.config.js').TEMPLATES
其中 ENTRIES 配置到 entry 选项,TEMPLATES 对象需要遍历并生成一份 html-webpack-plugin 配置,然后合并到 plugin 选项中。
具体配置如下:
// webpack.config.js
let WebpackPlugins = []
const TEMPLATES = require('./entries.config.js').TEMPLATES
WebpackPlugins = WebpackPlugins.concat(TEMPLATES.map(item => {
return new HtmlWebpackPlugin(item)
}))
module.exports = () => {
// ... 其它配置
plugins: WebpackPlugins
}
必须注意的是,html-webpack-plugin 的 chunks 选项照搬 webpack 配置中的 entry 对象。而 PHP 项目中静态资源的路径通常是 /static/***。问题是 entry 中的路径不能加 / 否则会提示不能使用绝对路径的错误。
我们可以采用模版语法的方式来解决这个问题:
在 index.html 的