I'm looking for the similar way to inject data.json file for my nunjucks template with webpack. With gulp would look something like this:
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();
});
Any idea? I'm also using laravel-mix is that helps.
I thought I can do this, but didn't work:
mix.webpackConfig({
module: {
rules: [{
test: '/data.json',
loader: 'json-loader',
exclude: '/node_modules/'
}]
}
});
You can use simple-nunjucks-loader (I'm the author of it). Docs got example of integrating with html-webpack-plugin (for HTML files output) and passing data to it
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
]
});