Generate a local HTML file with PUG (npm / gulp) - javascript

How to create a HTML file with the same name as my pug file each time I save using gulp?
All the docs on https://pugjs.org/ explain how to return pug in console...

You need task runner or module bundler for that. So choose one -grunt/gulp/webpack. Consider webpack as newest one and width best functionality.
Here an example width gulp as moust easy to understand from my point of view.
First install npm packages for compiling pug and watch for changes - npm install --save gulp-pug gulp-watch.
Then create and config your gulpfile.js.
First import an npm modules
var pug = require('gulp-pug');
var watch = require('gulp-watch');
Then create compiling task
gulp.task('pug',function() {
return gulp.src('PATH_TO_TEMPLATES/*.jade')
.pipe(pug({
doctype: 'html',
pretty: false
}))
.pipe(gulp.dest('./src/main/webapp/'));
});
And then create watcher
gulp.task('watch', function () {
return watch('PATH_TO_TEMPLATES/*.jade', { ignoreInitial: false })
.pipe(gulp.dest('pug'));
});
And run gulp-watch from you console.

Here an example width gulp 4.0
install npm packages for compiling pug/jade by following command
npm install --save gulp-pug .
create script with name gulpfile.js
//gulpfile.js
var gulp = require("gulp"), pug = require('gulp-pug');
function pugToHtml(){
return gulp.src('src')
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('dest'));
}
exports.pugToHtml = pugToHtml;
We can run the above code using the following command in your file directory:
gulp pugToHtml

You can now do the same without requiring gulp-watch as well.
Require module:
var pug = require('gulp-pug');
Task example:
//create task
gulp.task('pug', function buildHTML(){
gulp.src('src/pre/*.pug')
.pipe(pug())
.pipe(gulp.dest('src/post'));
});
Watch:
//pug serve
gulp.task('watch', ['pug'], function() {
gulp.watch(['src/pug-pre/*.pug'], ['pug']);
});
You can then run gulp watch. You can also set watch to the default task so you only have to write gulp in Terminal, if you are not automating anything else:
// default task
gulp.task('default', ['watch']);

Related

Ignore variable dependency of node_module webpack

I have built a library that I want to use in a Next.JS project. Within this library a certain dependency is using an import via a string passed into a require statement within the source code where the import is taking place. This is causing webpack to not recognize the import. I don't want to change code within any node_modules as this is not a preferred approach but how can I ensure that my project using the library I built is able to compile and run?
Within file_using_string_passed_into_require_to_get_import.js:
let importName = "./potential_import_A.js"
if(condition){
importName = "./potential_import_B.js"
}
module.exports = require(importName)
This is the folder structure:
Project/
| node_modules
| my-library
| node_modules
| library-dependency
| file_using_string_passed_into_require_to_get_import.js
| potential_import_A.js
| potential_import_B.js
To create a local (unpublished) library package
Create a 'my-library' folder (outside your current project dir).
Do npm init (Folder must include the 'package.json' )
Include source code (potential_import_A), exporting any desired functions.
In the actual project folder:
cd into the folder of the project that needs to use your library.
Run npm install --save local/path/to/my-library.
The --save will add the package to your dependencies in the project's package.json file, as it does with 3rd party published packages. It will also add a copy of the source code to the node modules folder of the project, as always.
Importing your new library:
import/require the package as you would normally, from any project.
For example
import { myFunction } from "my-library"
I got it to work by excluding node_modules from the webpack build. Since I am using Next.JS this is within my next.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
webpack: (
config,
{
buildId, dev, isServer, defaultLoaders, nextRuntime, webpack,
},
) => {
if (isServer) {
config.target = 'node';
config.node = {
__dirname: true,
global: true,
__filename: true,
};
config.externals = [nodeExternals()], // in order to ignore all modules in node_modules folder
config.externalsPresets = {
node: true, // in order to ignore built-in modules like path, fs, etc.
};
}
return config;
},
};

How to make uglify and grunt index all imports and generate one single file

I have just started using grunt and I want it to use combine all files and uglify them.
But my issues is that it combines and uglifys, but it doesn't remove import statements. (I'm using uglify and concat)
What I want -
// File.js
import something from './something.js';
something.someFunction("hello world");
and
// something.js
export default {
someFunction: function(msg){console.log(msg)}
}
to
// all.js
var something = {
someFunction: function(msg){
console.log(msg)
}
}
something.someFunction("hello world");
Compressing is not an issue.
If you want to combine the source code into one file, you can use rollup.js to help you.
download Node.js to get npm
update npm: npm install -g npm
npm install -g rollup
check: rollup -v
And then, running the below command will work as you expected.
rollup --format es --input file.js -o all.js
You can generate by rollup.config.js also.
rollup -c
// rollup.config.js
const AUTHOR = ""
const OutputFileName = `bundle` // in your case is `all`.js
const banner = `// Copyright (c) ..., all right reserved.`
const footer = `// powered by ${AUTHOR}`
export default {
input: './index.js', // in your case is `File.js`
output: [
{
file: `./${OutputFileName}.js`,
format: 'es', // amd, umd, iife, cjs, ...
// 👇 Option
// banner,
// footer
},
{ // You can generate different formats at once.
file: `./${OutputFileName}_cjs.js`,
format: 'cjs',
banner,
footer,
},
]
}
For compress
get uglifyjs: npm install uglify-js -g
uglifyjs all.js -m -c -o all.min.js

Gulp don't move file

I'm trying to move file from a directory to an other with gulp, but when i run my gulpfile, nothing happens, and i have this output
[19:25:22] Using gulpfile ~/Dev/Anikey/gulpfile.js
[19:25:22] Starting 'default'...
[19:25:22] Finished 'default' after 19 ms
My gulpfile.js :
const {src, dest} = require('gulp');
function copy() {
return src('src/public/style/*.css')
.pipe(dest('dist/style/'))
}
exports.default = copy;
Do someone know how to fix that please ?
I found this https://fettblog.eu/gulp-4-parallel-and-series/
As mentionned in this article, the new task execution using gulp 4 required gulp.series for sequential execution and gulp.parallel for parallel execution.
So try to add a build task with series like this, even if you have only 1 task :
const gulp = require('gulp');
const copy = () => {
return gulp.src('src/public/style/*.css')
.pipe(gulp.dest('dist/style/'))
}
const build = gulp.series(copy);
exports.default = build;
I fix the problem myself by using npm instead of yarn. To replace yarn, I deleted all dependencies file and then do a npm install, and just after a npx gulp - - watch and it works

How to avoid bundling ReactJs multiple times using Gulp?

I am trying to use ReactJS as view library rendering on client-side. Also I am imports lots of components from Material-UI as components.
One issue is that I need to use gulp to setup browserify(for using module in browser ) and babelify(compiling JSX to Javascript). But I found that if React is bundled more than one time, the UI would have error on behavior and styling.
According to this article, I setup the gulpfile.js as the following.
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');
var babelify = require('babelify');
var dependencies = [
'react',
'react-dom',
'material-ui',
'react-tap-event-plugin'
];
var scriptsCount = 0;
gulp.task('scripts', function () {
bundleApp(false);
});
gulp.task('deploy', function (){
bundleApp(true);
});
gulp.task('watch', function () {
gulp.watch(['./app/*.js'], ['scripts']);
});
gulp.task('default', ['scripts','watch']);
function bundleApp(isProduction) {
scriptsCount++;
var appBundler = browserify({
entries: './app/app.js',
debug: true
})
if (!isProduction && scriptsCount === 1){
browserify({
require: dependencies,
debug: true
})
.bundle()
.on('error', gutil.log)
.pipe(source('vendors.js'))
.pipe(gulp.dest('./web/js/'));
}
if (!isProduction){
dependencies.forEach(function(dep){
appBundler.external(dep);
})
}
appBundler
.transform("babelify", {presets: ["es2015", "react"]})
.bundle()
.on('error',gutil.log)
.pipe(source('bundle.js'))
.pipe(gulp.dest('./web/js/'));
}
If I run:
gulp scripts
more than once, the UI would have some problems and error in console.
So HOW should I modify the gulpfile to avoid bundling the React? Help please.
You need to include react-addons-transition-group to your external dependency list. I was facing the same problem.
Here is what I did to resolve it.
Cleaned up node_modules rm -rf node_modules
npm install react-addons-transition-group --save
npm install
Run gulp scripts
I hope that helps.

how does the ignore parameter works in gulp and nodemon?

I'm trying to create a gulpfile that lint my personal javascript files (.js) but ignore any vendor/third party libaries.
My gulp file is listed below:
var gulp = require("gulp"),
uglify = require("gulp-uglify"),
jshint = require("gulp-jshint"),
jasmine = require("gulp-jasmine"),
nodemon = require("gulp-nodemon");
// lint JS files for bad habbits
gulp.task("lint", function () {
gulp.src(["**/*.js", "node_modules/*"])
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
gulp.task("nodemon", function () {
nodemon({
script: "server.js",
ext: "html css jade js",
ignore: ["node_modules/*"]
})
.on("change", ["lint"])
.on("restart", function () {
console.log("Change detected, restarting server ...");
});
});
gulp.task("default",["nodemon"]);
When I run the "gulp default" command in my terminal it still lint the javascript files in the node_modules. I've tried variations of the glob syntax but I can't seem to achieve the desired behaviour.
Any idea where I've gone wrong?
Thanks.
The glob pattern you've set, node_modules/* only matches the files in the root of the node_modules directory, but not all the children with an highter depth.
You need to set is as node_modules/**/*, this will match everything. I advice you however to only match js files, with node_modules/**/*.js.
You also need to negate the pattern with !, gulp does not know that you want to do that, so it will look like:
gulp.src(['**/*.js', '!node_modules/**/*.js'])
For nodemon, following the same thing you can use the node_modules/**/* pattern.
The library used by gulp for globbing is minimatch.
use this ignore: ["node_modules/"] without '*' and it will work

Categories

Resources