我已经阅读了很多关于webpack的教程,但是创建Web应用程序似乎比我想做的更多,因此,如果无法进行以下操作,我不想再浪费时间。
我正在第三方电子商务系统上创建网站,他们有一个编码模板的系统,该模板可用于更改其网站的结构。以下是我将要创建的其中一个模板的示例(尽管我将需要做出许多类型和变体,而不仅仅是一些)。
我简化这些模板创建的想法是创建一堆哈巴狗组件,并将它们放置在components /目录中。在components目录之外,我想制作利用这些组件的更高级别的pug模板。创建这些文件后,我将使用NPM进行构建,并且需要将模板文件转换为HTML并将其放置在/ dist文件夹中。
使用webpack很难吗?
项目的结构:
src/
..components/
....header/
......header1.pug
......header1.scss
..navcustom-template.pug
..customfooter-template.pug
..non-template-specific.scss
并一旦构建:
dist/
..navcustom-template.html
..customfooter-template.html
..non-template-specific.css
src/
..components/
....header/
......header1.pug
......header1.scss
..navcustom-template.pug
..customfooter-template.pug
..non-template-specific.scss
模板样本:
<!--
Section: NavCustom
-->
<style>
//Template Speific CSS Imports Here
</style>
<script type="text/javascript">
//Template Speific JS Imports Here
</script>
<header>
<div class="col-md-4">
// Social Media Code
</div>
<div class="col-md-4">
// Logo Code
</div>
<div class="col-md-4">
// Call to Action Code
</div>
</header>
<nav>
</nav>
答案 0 :(得分:2)
您可以使用以下软件包(全部使用--save-dev
)
raw-loader
加载Pug文件pug-html-loader
读取Pug文件html-webpack-pug-plugin
从帕格生成HTML html-webpack-plugin
(标准HTML插件加载程序)然后配置类似于以下内容的Webpack,其中index.js
是一个虚拟文件,如果您没有条目,则应创建该文件。您需要处理的每个Pug模板都写在底部的单独HtmlWebpackPlugin
对象中。
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
module.exports = {
entry: ['./src/index.js'],
output: {
path: __dirname + '/dist',
publicPath: '/'
},
module: {
rules: [
{
test: /\.pug$/,
use: [
"raw-loader",
"pug-html-loader"
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/navcustom-template.pug',
filename: 'navcustom-template.html'
}),
new HtmlWebpackPlugin({
template: 'src/customfooter-template.pug',
filename: 'customfooter-template.html'
}),
new HtmlWebpackPugPlugin()
]
}
所有Pug mixin(您的src/components
文件)将包含在输出中。此示例已经过测试并且可以正常工作。
编辑:要动态处理src
目录中的所有Pug文件,请使用以下配置:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin');
const fs = require('fs');
let templates = [];
let dir = 'src';
let files = fs.readdirSync(dir);
files.forEach(file => {
if (file.match(/\.pug$/)) {
let filename = file.substring(0, file.length - 4);
templates.push(
new HtmlWebpackPlugin({
template: dir + '/' + filename + '.pug',
filename: filename + '.html'
})
);
}
});
module.exports = {
entry: ['./src/index.js'],
output: {
path: __dirname + '/dist',
publicPath: '/'
},
module: {
rules: [
{
test: /\.pug$/,
use: [
"raw-loader",
"pug-html-loader"
]
}
]
},
plugins: [
...templates,
new HtmlWebpackPugPlugin()
]
}
这使用fs.readdirSync
来获取目录中的所有Pug文件。使用同步版本(而不是fs.readdir
)是因为module.exports
函数将在处理文件之前返回。