這可能是很長,但是請多多包涵:
的問題是,nunjucks裝載機並將其作爲一個JavaScript文件(According to the first paragraph)。可以使用nunjucks-html-loader。
通過使用NPM或紗線安裝: 首先,我們安裝nunjucks-HTML裝載機:
npm i nunjucks-html-loader -D
OR
yarn add nunjucks-html-loader -D
我還建議安裝(可選的)webpack-glob-folder-entries
(更多關於此)
npm i webpack-glob-folder-entries -D
或
yarn add webpack-glob-folder-entries -D
然後,如果我們認爲我們有以下文件夾結構:
- client/
-templates/
-index.njk
-layout.njk
-_partials/
- webpack.config.js
而且裏面index.njk我們有這樣的事情:
<!-- index.nunjucks -->
{% extends "layout.njk" %}
{% block content %}
<h1> Here comes my content that is injected to layout.njk!</h1>
{% endblock %}
我們可以只配置的WebPack,使用以下設置:
//#1: Define the HTML Webpack Plugin:
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
filename: 'index.html',
inject: 'body',
// Here is part of the magic, we get the index.njk but we tell
// webpack to pass it through the nunjucks-html-loader
template: 'nunjucks-html-loader!./client/templates/index.njk',
});
// Optional, but highly recommended. Create a returnEntries:
// Webpack doesn't support glob paths. For the nunjucks-html-loader
// we need each path to be specified for it to work (YES, even subdirectories!)
function returnEntries(globPath){
let entries = glob_entries(globPath, true);
let folderList = new Array();
for (let folder in entries){
folderList.push(path.join(__dirname, entries[folder]));
}
return folderList;
}
module.exports = {
// You should not have this the same. This is from my site. Go down to see the important part:
entry: './client/index.js',
output: {
filename: production ? '[name]-[hash].js' : 'bundle.js',
path: __dirname + '/dist',
publicPath: 'dist/' //Important!!! : https://github.com/webpack/webpack/issues/1426
},
// #2 We load the HTMLWebpackPluginConfig
plugins: [
HtmlWebpackPluginConfig,
extractTextPlugin
],
resolve: {
extensions: ['.Webpack.js', '.web.js', '.ts', '.js', '.tsx']
},
// HERE is the important part
module: {
loaders: [
{
// HTML LOADER
// Super important: We need to test for the html
// as well as the nunjucks files
test: /\.html$|njk|nunjucks/,
use: ['html-loader',{
loader: 'nunjucks-html-loader',
options : {
// Other super important. This will be the base
// directory in which webpack is going to find
// the layout and any other file index.njk is calling.
searchPaths: [...returnEntries('./client/templates/**/')]
// Use the one below if you want to use a single path.
// searchPaths: ['./client/templates'],
}
}]
}
]
}
}
然後只是運行webpack
,你很好走。
注:
searchPaths: ['./client/templates'],
是很重要的。以下是Webpack將用於查找index.njk調用的任何文件的基本路徑。試着弄清楚這條路是如何工作的。但不要刪除它。
另外,webpack 不支持glob目錄的。我使用webpack-glob-folder-entries
編寫了一個輔助函數,它給了我nunjucks-html-loader可以查看的所有子文件夾的列表。請理解,如果你不指定文件夾(即使它是一個子目錄),它會而不是工作)。
換句話說,如果你想使用_partials文件夾(如上所述),並且你沒有將它指定爲'./client/templates/_partials',那麼加載器將不會提取它!
此外,
test: /\.html$|njk|nunjucks/,
是不是用於index.njk但爲index.njk呼叫,在這種情況下layout.njk文件。如果不包含njk或nunjucks擴展名,將不會加載layout.njk,它會給你一個錯誤。