webpack4 + ejs 构建多页应用
目录结构
├─build webpack配置目录
│ ├─plugins.js
│ ├─rules.js
│ ├─transfromAssets.js //简单的一个插件,处理路径问题
│ └─webpack.config.js
└─src
├─components ejs公用组件目录
├─css
├─js
├─index.ejs 模板文件
└─about.ejs
源码地址:github
使用ejs模板
- 安装 ejs-loader、html-loader
- 在 src根节点创建ejs文件,作为html的模板
- 使用html-webpack-plugin引入ejs模板
index.ejs 需要向header.ejs传入htmlWebpackPlugin,否则html-webpack-plugin配置的title可能会不起作用
<%= require('./components/header.ejs')({path:'index',htmlWebpackPlugin}) %>
<div id="root">
内容
</div>
<%= require('./components/footer.ejs')() %>
header.ejs
<head>
<meta charset="utf-8">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
webpack plugins,因为是多个页面,所以通过for循环插入HtmlWebpackPlugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
const plugins = [];
...
nav.forEach(value => {
plugins.push(
new HtmlWebpackPlugin({
filename: `${value.path}.html`,
template: path.resolve(__dirname, '../src', `${value.path}.ejs`),
inject: true,
chunks: ['common', value.path],
favicon: './src/assets/img/favicon.ico',
title: 'title',
minify: {
collapseWhitespace: true
}
})
)
})
...
处理css
- 使用了less,所以需要安装loader:css-loader、less-loader
- 添加浏览器前缀,兼容不同版本浏览器,需要安装postcss-loader、autoprefixer
- 需要压缩生成的css文件,安装插件:optimize-css-assets-webpack-plugin、cssnano
- 将css分离成css文件,安装mini-css-extract-plugin
处理js
安装下babel-loader、@babel/core、@babel/preset-env,处理es6的语法。
webpack配置
plugins.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const optimizeCss = require('optimize-css-assets-webpack-plugin');
const TransfromAssets = require('./transfromAssets');
const path = require('path');
const nav = require(`../src/data.js`).nav;
const plugins = [];
nav.forEach(value => {
plugins.push(
new HtmlWebpackPlugin({
filename: `${value.path}.html`,
template: path.resolve(__dirname, '../src', `${value.path}.ejs`),
inject: true,
chunks: ['common', value.path],
favicon: './src/assets/img/favicon.ico',
title: 'title',
minify: {
collapseWhitespace: true
}
})
)
})
const otherPlugins = [
new MiniCssExtractPlugin({
filename: '[name].[hash:8].css',
chunkFilename: '[id].css',
}),
new optimizeCss({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorOptions: {
discardComments: {
removeAll: true
}
},
canPrint: true
}),
new TransfromAssets()
];
plugins.splice(nav.length, 0, ...otherPlugins);
module.exports = plugins;
rules.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = [{
test: /\.(c|le)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: "postcss-loader",
options: {
plugins: [
require("autoprefixer")
]
}
},
'less-loader'
]
},
{
test: /\.js$/, //js文件加载器
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.html$/,
use: [{
loader: 'html-loader',
options: {
interpolate: true,
minimize: false
}
}]
}, {
test: /\.ejs/,
use: ['ejs-loader'],
}
]
transfromAssets.js 一个插件,作用:
- 将common.js删掉(common.js引入了公用的css,css有用但js无用所以就删啦)
- 将js、css存放至单独的目录,并将html里路径指向正确的路径
function TransfromAssets(options) {};//也可以是一个类
TransfromAssets.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compilation, callback) {
for (var filename in compilation.assets) {
if (/common.*js$/.test(filename)) {
delete compilation.assets[filename];
continue;
}
if (/.*[js|css]$/.test(filename)) {
let type = /.*js$/.test(filename) ? 'js' : 'css';
let source = compilation.assets[filename].source();
let size = compilation.assets[filename].size();
compilation.assets[`${type}/${filename}`] = {
source: () => source,
size: () => size
}
delete compilation.assets[filename];
}
if (/html$/.test(filename)) {
let source = compilation.assets[filename].source();
source = source.replace(/\<script.*?<\/script>/ig, value => ~value.indexOf('common') ? '' : value);
source = source.replace(/href=\"\S+?.css\"/ig, value => value.slice(0, 6) + 'css/' + value.slice(6));
source = source.replace(/src=\".*?.js\"/ig, value => value.slice(0, 5) + 'js/' + value.slice(5));
compilation.assets[filename].source = () => source;
}
}
callback();
})
};
module.exports = TransfromAssets;
webpack.config.js
const path = require('path');
const plugins = require('./plugins');
const rules = require('./rules');
module.exports = {
entry: {
common: '@src/js/common.js',
index: '@src/js/index.js',
detail: '@src/js/list.js',
},
output: {
path: path.resolve(__dirname, '../dist/'),
filename: "[name].[hash:8].js"
},
devServer: {
inline: true,
historyApiFallback: true,
},
resolve: {
alias: {
'@': path.join(__dirname, '..'),
'@src': path.join(__dirname, '..', 'src')
}
},
module: {
rules
},
plugins
}
webpack4 + ejs 构建多页应用的更多相关文章
- React构建单页应用方法与实例
React作为目前最流行的前端框架之一,其受欢迎程度不容小觑,从这门框架上我们可以学到许多其他前端框架所缺失的东西,也是其创新性所在的地方,比如虚拟DOM.JSX等.那么接下来我们就来学习一下这门框架 ...
- Nodejs in Visual Studio Code 12.构建单页应用Scrat实践
1.开始 随着前端工程化深入研究,前端工程师现在碉堡了,甚至搞了个自己的前端网站http://div.io/需要邀请码才能注册,不过里面的技术确实牛.距离顶级的前端架构,目前博主应该是far away ...
- 通过Web Api 和 Angular.js 构建单页面的web 程序
通过Web Api 和 Angular.js 构建单页面的web 程序 在传统的web 应用程序中,浏览器端通过向服务器端发送请求,然后服务器端根据这个请求发送HTML到浏览器,这个响应将会影响整个的 ...
- 用webpack4从零开始构建react脚手架
用webpack4从零开始构建react脚手架 使用脚手架 git clone git@github.com:xiehaitao0229/react-wepack4-xht.git` `cd reac ...
- vue2.0 构建单页应用最佳实战
vue2.0 构建单页应用最佳实战 前言 我们将会选择使用一些 vue 周边的库vue-cli, vue-router,vue-resource,vuex 1.使用 vue-cli 创建项目2.使 ...
- webpack4.0构建项目流程
webpack4.0构建项目流程,具体的就不一一唠叨了,这里给出构建流程步骤: 流程大图: 下载高清大图
- 使用 Vuex + Vue.js 构建单页应用
鉴于该篇文章阅读量大,回复的同学也挺多的,特地抽空写了一篇 vue2.0 下的 vuex 使用方法,传送门:使用 Vuex + Vue.js 构建单页应用[新篇] ------------------ ...
- 使用 Vuex + Vue.js 构建单页应用【新篇】
使用 Vuex + Vue.js 构建单页应用[新篇] 在去年的七月六号的时候,发布了一篇 使用 Vuex + Vue.js 构建单页应用 的文章,文章主要是介绍 vuex 的基本使用方法,发现对大部 ...
- 构建单页Web应用
摘自前端农民工的博客 让我们先来看几个网站: coding teambition cloud9 注意这几个网站的相同点,那就是在浏览器中,做了原先“应当”在客户端做的事情.它们的界面切换非常流畅,响应 ...
随机推荐
- 蒙特卡洛树搜索算法 —— github上的implement的原代码
首先在网上看到了关于蒙特卡洛搜索算法的介绍,如下: https://www.cnblogs.com/steven-yang/p/5993205.html 并从中发现了一个在GitHub上impleme ...
- Python3入门(十三)——常用内置模块之时间日期模块datatime
1.日期时间模块——datatime //其他模块例如time.calender等模块暂不展开 (1)获取当前时间:datatime.now(): from datetime import datet ...
- 报错:Error starting Jetty. JSON Metrics may not be available.java.net.BindException:地址已在使用
报错背景: 刚在CDH中集成Flume插件,启动报错 报错现象: Error starting Jetty. JSON Metrics may not be available. java.net.B ...
- Nginx限制ip访问
首先建立下面的配置文件放在nginx的conf目录下面,命名为blocksip.conf: 加入以下代码: #屏蔽soso蜘蛛IP deny 113.108.12.154; #此为搜搜蜘蛛IP den ...
- 01点睛Spring4.1-依赖注入
转载:https://www.iteye.com/blog/wiselyman-2210252 1.1 声明bean 使用上例建立的testMavenSpring项目,将pom.xml文件中的 < ...
- AI - TensorFlow - 示例04:过拟合与欠拟合
过拟合与欠拟合(Overfitting and underfitting) 官网示例:https://www.tensorflow.org/tutorials/keras/overfit_and_un ...
- Apache POI操作pptx基本使用
最近有一个ppt操作的需求,因此查了下相关的资料 ppt分类 (1)2007版之前的 是基于二进制的文件格式 细节没有完全公开,第三方厂商多是用单向工程方法猜测和分析出来的.WPS做得好一些,但开源的 ...
- 常见问题:MySQL/B+树
平衡二叉树 此前讲红黑树时也提到了平衡二叉树,红黑树和AVL树都是能保证树不退化的平衡二叉树,平衡二叉树采用二分思想组织数据,能大大提高单点查找数据的效率,其组装过程略. 作为对比,此处也列出平衡二叉 ...
- 工具中修改设置Default VM Arguments
转自:https://www.cnblogs.com/zouhao/p/6513177.html
- transform-transition-animation(2)
transform transform : none | <transform-function> [ <transform-function> ]* 也就是: transfo ...