首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我该如何使用nunjucks文件作为webpack的入口点?

我该如何使用nunjucks文件作为webpack的入口点?
EN

Stack Overflow用户
提问于 2017-10-09 22:34:44
回答 3查看 4.1K关注 0票数 3

我在ejs上看过这篇文章。但是,我如何与webpack实现同样的目标呢?

我试图结合html-webpack-plugin使用nunjucks加载程序,但是我得到了以下错误:[nunjucks-loader] non-web targets are not supported

这是我的密码:

下面是配置:

代码语言:javascript
复制
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  //template: './client/index.html',
  filename: 'index.html',
  inject: 'body',
  template: 'nunjucks-html-loader!./client/templates/index.njk',
});

module: {
    loaders: [
      {
        test: /\.html$/,
        use: ['html-loader']
      }, 
      {
        test: /\.|njk|nunjucks$/,
        use: ['nunjucks-loader']
      }]
  };
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-10-09 22:34:44

这可能是很长的时间,但请容忍我:

问题是nunjucks加载程序将其作为JavaScript文件(根据第一段)传递。

相反,使用nunjucks-html-加载程序

使用npm或纱线安装:首先,我们安装nunjucks-html-加载程序:

代码语言:javascript
复制
npm i nunjucks-html-loader -D

代码语言:javascript
复制
yarn add nunjucks-html-loader -D

我还建议安装(这是可选的) webpack-glob-folder-entries (更多)

代码语言:javascript
复制
npm i webpack-glob-folder-entries -D

代码语言:javascript
复制
yarn add webpack-glob-folder-entries -D

然后,如果考虑到以下文件夹结构:

代码语言:javascript
复制
- client/
     -templates/
          -index.njk   
          -layout.njk
          -_partials/
- webpack.config.js

在index.njk内部,我们有这样的东西:

代码语言:javascript
复制
<!-- index.nunjucks -->
{% extends "layout.njk" %}
{% block content %}
   <h1> Here comes my content that is injected to layout.njk!</h1>
{% endblock %}

我们可以使用以下设置配置webpack:

代码语言:javascript
复制
//#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,你就可以走了。

注意:

代码语言:javascript
复制
searchPaths: ['./client/templates'],

很重要。下面是Webpack将使用的基本路径,用于查找index.njk正在调用的任何文件。试着把这条路弄乱一点,以了解它是如何工作的。但是删除它。

此外,webpack 不支持目录。我使用webpack-glob-folder-entries编写了一个帮助函数,它为我提供了nunjucks加载程序可以查看的所有子文件夹的列表。请理解,如果您不指定文件夹(即使它是一个子目录),它将而不是工作。

换句话说,如果您想要使用_partials文件夹(如上面所示),并且不将其指定为'./client/templates/_partials',加载程序将不会选择它!

另外,

代码语言:javascript
复制
 test: /\.html$|njk|nunjucks/,

不是用于index.njk,而是用于index.njk调用的文件,在本例中是layout.njk。未能包含njk或nunjucks扩展将不会加载layout.njk,它将给您一个错误。

票数 9
EN

Stack Overflow用户

发布于 2018-08-22 14:17:20

我在寻找解决方案的时候也遇到了这个问题,被接受的解决方案对我不起作用,所以我觉得把我的解决方案添加到混合方案中是很合适的,比如如何在web包中使用nunjucks作为条目。

我一直遇到有多个入口点的问题,直到最后我找到了下面的回购并修复了这个问题。

使用Nunjucks-同构装载机

注意,在撰写本文时,npm注册中心尚未通过最近的代码更改进行更新,因此您需要从package.json直接链接到回购程序。

这是我的:概念库的证明

下面是我写的webpack配置,以供参考:

代码语言:javascript
复制
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin')

// Notice, the below methods searches src/components and adds a HtmlWebpackPlugin for each folder
// This is required, even for subfolders otherwise you nunjuck includes will nto work.
const d = './src/components';
const entryFolders = fs.readdirSync(path.resolve(d))
			.map(f => path.join(__dirname, path.join(d, f))  )
			.filter(f => fs.statSync(f).isDirectory());

function getHtmlComponentPlugins() {
	return entryFolders.map(templatePath => {
		const name = templatePath.split('\\').pop()

		const sett = {
	    	customData: { foo: 'bar' },
	    	filename: path.relative(__dirname, templatePath.replace('src\\', '') + `\\${name}.html`),
	    	template: templatePath + `\\${name}.njk`
	  	};

		return new HtmlWebpackPlugin(sett)
	});
}

module.exports = function() {
	return {
		devtool: '#source-map',
		mode: 'development',
		entry: [
			'./src/index.js'
		],
		output: {
			path: path.resolve(__dirname, 'dist')
		},
	    resolve: {
	      extensions: [ '.js' ]
	    },
		module: {
		    rules : [
				{
				  	test: /\.(njk|nunjucks|html|tpl|tmpl)$/,
				  	use: [
				    	{
				    		loader: 'nunjucks-isomorphic-loader',
				      		query: {
				        	root: [
				        		path.resolve(__dirname, 'src'),
				        		
				        	].concat(entryFolders)
				      	}
				    }
				  ]
				}
		    ]
		},
		plugins: [
		  new HtmlWebpackPlugin({
		    customData: { foo: 'bar' },
		    filename: 'index.html',
		    template: 'src/index.njk'
		  })
		].concat(getHtmlComponentPlugins())
	};
}

票数 2
EN

Stack Overflow用户

发布于 2019-02-05 09:05:49

与其将加载程序(nunjucks- loader )和Webpack插件(HtmlWebpackPlugin)混合在一起,不如让女妖-webpack-插件试试。

它看起来像是HtmlWebpackPlugin的一个很好的替代品!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46655964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档