使用 webpack 为 nunjucks 加载 data.json 文件
Load data.json file for nunjucks with webpack
我正在寻找使用 webpack 为我的 nunjucks 模板注入 data.json 文件的类似方法。
gulp 看起来像这样:
gulp.task('nunjucks', function(done) {
return gulp.src(paths.src.templates + '/*.njk')
.pipe(data(function() {
return require('./data.json')
}))
.pipe(nunjucksRender({
path: paths.src.templates,
envOptions: {
lstripBlocks: true,
autoescape: true,
trimBlocks: true
}
}))
.pipe(gulp.dest(paths.pages.base))
done();
});
有什么想法吗?我也在使用 laravel-mix 有帮助。
我以为我可以做到这一点,但没有成功:
mix.webpackConfig({
module: {
rules: [{
test: '/data.json',
loader: 'json-loader',
exclude: '/node_modules/'
}]
}
});
你可以使用 simple-nunjucks-loader(我是它的作者)。文档获得了与 html-webpack-plugin(用于 HTML 文件输出)集成并将数据传递给它的示例
https://www.npmjs.com/package/simple-nunjucks-loader#with-html-webpack-plugin
var HTMLWebpackPlugin = require('html-webpack-plugin');
var templateParameters = require('./data.json');
var htmlFiles = require('glob').sync(paths.src.templates + '/*.njk').map((file) => (
new HTMLWebpackPlugin({
template: file,
filename: file.replace('.njk', '.html'),
templateParameters: templateParameters
})
));
mix.webpackConfig({
module: {
rules: [
{
test: /\.njk$/,
use: [
{
loader: 'simple-nunjucks-loader'
}
]
}
]
},
plugins: [
...htmlFiles
]
});
我正在寻找使用 webpack 为我的 nunjucks 模板注入 data.json 文件的类似方法。 gulp 看起来像这样:
gulp.task('nunjucks', function(done) {
return gulp.src(paths.src.templates + '/*.njk')
.pipe(data(function() {
return require('./data.json')
}))
.pipe(nunjucksRender({
path: paths.src.templates,
envOptions: {
lstripBlocks: true,
autoescape: true,
trimBlocks: true
}
}))
.pipe(gulp.dest(paths.pages.base))
done();
});
有什么想法吗?我也在使用 laravel-mix 有帮助。
我以为我可以做到这一点,但没有成功:
mix.webpackConfig({
module: {
rules: [{
test: '/data.json',
loader: 'json-loader',
exclude: '/node_modules/'
}]
}
});
你可以使用 simple-nunjucks-loader(我是它的作者)。文档获得了与 html-webpack-plugin(用于 HTML 文件输出)集成并将数据传递给它的示例
https://www.npmjs.com/package/simple-nunjucks-loader#with-html-webpack-plugin
var HTMLWebpackPlugin = require('html-webpack-plugin');
var templateParameters = require('./data.json');
var htmlFiles = require('glob').sync(paths.src.templates + '/*.njk').map((file) => (
new HTMLWebpackPlugin({
template: file,
filename: file.replace('.njk', '.html'),
templateParameters: templateParameters
})
));
mix.webpackConfig({
module: {
rules: [
{
test: /\.njk$/,
use: [
{
loader: 'simple-nunjucks-loader'
}
]
}
]
},
plugins: [
...htmlFiles
]
});