[英]Simplest possible node.js + nunjucks example
可能永遠不會使用 node.js 或 Nunjucks 進行任何實際開發,但現在出於某種原因需要:
Nunjucks
node.js
下運行預編譯模板我已經做好了:
node.js
和npm
(例如有node
和npm
命令)mkdir njtest && cd njtest
npm install nunjucks
(獲得了node_modules/nunjucks
目錄)mkdir templates
在模板中,我創建了兩個文件index.html
和layout.html
,其中包含以下jinja2/nunjucks
內容
layout.html
<!doctype html>
<head>
<title>simple example</title>
</head>
<body>
<h1>Simple example</h1>
{% block body %}{% endblock %}
</body>
index.html
{% extends "layout.html" %}
{% block body %}
hello world
{% endblock %}
./node_modules/nunjucks/bin/precompile templates >templates.js
在templates.js
中我有預編譯的代碼。
接下來我應to do
來獲得一個正在運行的網絡服務器什么將使用預編譯的template.js
?
請不要搜索這個問題的任何高級內容。 對於了解節點和 javascript 的人來說,這可能是一個愚蠢的簡單問題。
我所知道的,將需要,創建一個文件讓說app.js
並需要與node
一起運行它 - 但應該包含什么?
require 'nunjucks';
可能是這樣的: var res = nunjucks.render('templates.js');
還有什么? (最簡單的(一次性)解決方案)。 注意:要在服務器端而不是在瀏覽器中使用 Nunjucks。
首先初始化Node應用程序,如下所示:
cd njtest
npm init
您可以按“Enter”接受大多數問題的默認值,如果您在創建app.js 后執行此操作,那么它將自動檢測到並將其用作簡單服務器的入口點。
安裝Express:
npm install express --save
然后按如下方式創建app.js
:
var express = require( 'express' ),
app = express(),
nunjucks = require( 'nunjucks' ) ;
// Define port to run server on
var port = process.env.PORT || 9000 ;
// Configure Nunjucks
var _templates = process.env.NODE_PATH ? process.env.NODE_PATH + '/templates' : 'templates' ;
nunjucks.configure( _templates, {
autoescape: true,
cache: false,
express: app
} ) ;
// Set Nunjucks as rendering engine for pages with .html suffix
app.engine( 'html', nunjucks.render ) ;
app.set( 'view engine', 'html' ) ;
// Respond to all GET requests by rendering relevant page using Nunjucks
app.get( '/:page', function( req, res ) {
res.render( req.params.page ) ;
} ) ;
// Start server
app.listen( port ) ;
console.log( 'Listening on port %s...', port ) ;
現在啟動一個瀏覽器,轉到http:// localhost:9000然后彈出你的頁面!
希望有幫助......
我為 Nunjucks + SCSS + TypeScript 創建了簡單的構建器
文檔: https://github.com/Artik-Man/SamuraiJS
NPM: https://www.npmjs.com/package/samuraijs
npm i samuraijs
創建samurai.js
文件:
import {Samurai} from "samuraijs";
new Samurai({
paths: {
source: 'src',
destination: 'dist'
}
});
將以下行添加到您的 package.json:
{
"scripts": {
"serve": "node samurai.js --serve",
"build": "node samurai.js --build"
},
"type": "module"
}
將你的 *.njk 文件放在src/
目錄下,運行
npm run serve
並打開localhost:3000
或者npm run build
來構建項目。
不要考慮構建配置。 只需編寫您的項目!
我希望我的建造者能解決你的問題:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.