I have a shell script which gives the commit hash and I want to run npm version and would like to concatenate with the hash.
So putting the shell command in js file and running with node works. Since the command is very short I want to run inline.
This works
npm --no-git-tag-version version $(node bump.js)
But would like to run in one line
npm --no-git-tag-version version+ git rev-parse --short HEAD
Here is my bump.js file
const shell = require('shelljs');
const { version } = require('../package.json');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// npm --no-git-tag-version version $(node config/bump.js)
// Ex: npm --no-git-tag-version version "10.1.6-develop-80a3053"
let commitHash = '';
if (commitHash = shell.exec('git rev-parse --short HEAD', { silent: true })) {
// Getting the base version from package.json
const baseVersion = version.match(/[\d+]{1,}\.[\d+]{1,}\.[\d+]{1,}/)[0];
// Concatenating base-version with develop-commit-hash
const hashedVersion = `${baseVersion}-develop-${commitHash}`;
shell.echo(`npm --no-git-tag-version version ${hashedVersion}`, { silent: true });
}
shell.exit(0);
I created a node script which checks if my project contains lock file or not. If it doesn't then I want to abort my npm build. Any idea how to do that?
lock-check.js
const path = require('path');
const fs = require("fs");
const lockFiles = ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock"];
let exists = 0;
function checkIfExists() {
lockFiles.forEach(
(lf) => {
if (fs.existsSync(lf)) {
exists++;
}
});
return exists > 0;
}
package.json
...
"scripts": {
"prestart": "node ./lock-check.js" // Abort the task
"start": "webpack-dev-server --config config/webpack.dev.js --hot --inline"
}
...
To abort the build process you just have to call process.exit(1),
Here I have used 1 but you can use any non-zero exit code to tell it wasn't a successful build as 0 means successful.
You can read more on official nodejs docs
I have read the document of build library in VUE-CLI3.0.
My directory:
--src
--components
--componentA.vue
--componentB.vue
....
--componentZ.vue
--build
--libs.js
I want to run one command with my one entry "libs.js" (Maybe there is a loop to create multiple entries in libs.js) to bundle my components separately. The destination folder maybe like the following:
--dist
--componentA.css
--componentA.command.js
--componentA.umd.js
--componentA.umd.min.js
...
--componentZ.css
--componentZ.command.js
--componentZ.umd.js
--componentZ.umd.min.js
Can anyone give me some suggetions?
I add a script file. In which, I get the list of components and using 'child_process' to execute each command.
The following is an example:
lib.js
const { execSync } = require('child_process')
const glob = require('glob')
// console font color
const chalk = require('chalk')
// loading
const ora = require('ora')
// 获取所有的moduleList
const components = glob.sync('./src/components/*.vue')
// const buildFile = path.join(__dirname, 'build.js')
// const webpack = require('vuec')
const spinner = ora('Packaging the components...\n').start()
setTimeout(() => {
spinner.stop()
}, 2000)
for (const component of components) {
// const file = path.join(__dirname, module);
const name = component.substring(component.lastIndexOf('/') + 1).slice(0, -4)
const cmd = `vue build -t lib -n ${name} ${component} -d lib/components/${name}`
execSync(cmd)
console.log(chalk.blue(`Component ${name} is packaged.`))
}
console.log(`[${new Date()}]` + chalk.green('Compeleted !'))
What's more, add a script command in package.json:
"build-all": "node ./src/build/lib.js"
You just enter npm run build-all. That's all~
I've got a Wordpress/MySQL docker container, which I use for developing themes & plugins. I access this on localhost:8000.
It uses a Gulp build process & I am trying to add browsersync to the mix. I'm having a hard time getting the browsersync to actually proxy out of the container. From the Gulp output I can see that its generating the changes, just not actually making any changes in the browser.
Heres my docker-compose.yml, gulpfile, dockerfile & shell script.
version: '2'
services:
wordpress_db:
image: mariadb
restart: 'always'
ports:
- 3360:3306
volumes:
- ./db_data:/docker-entrypoint-initdb.d
environment:
MYSQL_ROOT_PASSWORD: wordpress
MYSQL_DATABASE: wordpress
wordpress:
depends_on:
- wordpress_db
image: wordpress
restart: 'always'
environment:
WORDPRESS_DB_NAME: wordpress
WORDPRESS_DB_USER: root
WORDPRESS_DB_PASSWORD: wordpress
ports:
- 8000:3000
volumes:
- ./uploads:/var/www/html/wp-content/uploads
- ./plugins:/var/www/html/wp-content/plugins
- ./theme:/var/www/html/wp-content/themes/theme
links:
- wordpress_db:mysql
composer:
image: composer/composer:php7
depends_on:
- wordpress
restart: 'no'
environment:
ACF_PRO_KEY: this_would_be_my_ACF_pro_key_:)
volumes_from:
- wordpress
working_dir: /var/www/html/wp-content/themes/theme
command: install
node:
restart: 'no'
image: node:slim
depends_on:
- wordpress
volumes_from:
- wordpress
working_dir: /var/www/html/wp-content/themes/theme
build:
context: .
dockerfile: WordpressBuild
args:
- SITE_VERSION=0.0.1
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var watchify = require('watchify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpSequence = require('gulp-sequence');
var processhtml = require('gulp-minify-html');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var watch = require('gulp-watch');
var cleanCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var fontawesome = require('node-font-awesome');
var prod = gutil.env.prod;
var onError = function(err) {
console.log(err.message);
this.emit('end');
};
// bundling js with browserify and watchify
var b = watchify(browserify('./src/js/app', {
cache: {},
packageCache: {},
fullPaths: true
}));
gulp.task('js', bundle);
b.on('update', bundle);
b.on('log', gutil.log);
function bundle() {
return b.bundle()
.on('error', onError)
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(prod ? babel({
presets: ['es2015']
}) : gutil.noop())
.pipe(concat('app.js'))
.pipe(!prod ? sourcemaps.write('.') : gutil.noop())
.pipe(prod ? streamify(uglify()) : gutil.noop())
.pipe(gulp.dest('./assets/js'))
.pipe(browserSync.stream());
}
// fonts
gulp.task('fonts', function() {
gulp.src(fontawesome.fonts)
.pipe(gulp.dest('./assets/fonts'));
});
// sass
gulp.task('sass', function() {
return gulp.src('./src/scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: [].concat(require('node-bourbon').includePaths, ['node_modules/foundation-sites/scss', 'node_modules/motion-ui/src', fontawesome.scssPath])
}))
.on('error', onError)
.pipe(prod ? cleanCSS() : gutil.noop())
.pipe(prod ? autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}) : gutil.noop())
.pipe(!prod ? sourcemaps.write('.') : gutil.noop())
.pipe(gulp.dest('./assets/css'))
.pipe(browserSync.stream());
});
gulp.task('watch', function(){
gulp.watch('./src/scss/**/*.scss', ['sass']);
gulp.watch('./src/js/**/*.js', ['js']);
});
// browser-sync task for starting the server.
gulp.task('serve', function() {
//watch files
var files = [
'./assets/css/*.scss',
'./*.php'
];
//initialize browsersync
browserSync.init(files, {
//browsersync with a php server
proxy: "localhost",
notify: false
});
gulp.watch('./src/scss/**/*.scss', ['sass']);
// gulp.task('default', gulpSequence(['fonts', 'sass', 'js', 'watch']));
});
// use gulp-sequence to finish building html, sass and js before first page load
gulp.task('default', gulpSequence(['fonts', 'sass', 'js'], 'serve'));
The docker-compose.yml refers to the following dockerfile:
FROM node
# Grab our version variable from the yml file
ARG SITE_VERSION
# Install gulp globally
RUN npm install -g gulp node-gyp node-sass
# Install dependencies
COPY ./gulp-build.sh /
RUN chmod 777 /gulp-build.sh
ENTRYPOINT ["/gulp-build.sh"]
CMD ["run"]
which installs gulp and node-sass, and also copies the following gulp-guild.sh script into the container:
#!/bin/bash
cd /var/www/html/wp-content/themes/theme
# npm rebuild node-sass && npm install && gulp --dev
npm rebuild node-sass && npm install && gulp
The primary problem with your configuration is that you're pointing to localhost in the gulpfile. This points to the local container, not your host machine, so browsersync won't be able to connect to Wordpress.
You first need to update the gulpfile to point to the wordpress service, on its internal port:
browserSync.init(files, {
// The hostname is the name of your service in docker-compose.yml.
// The port is what's defined in your Dockerfile.
proxy: "wordpress:3000",
notify: false,
// Do not open browser on start
open: false
})
Then you need to add a port mapping to expose the browsersync server from your node service. In your docker-compose.yml file:
node:
ports:
- "3000:3000"
- "3001:3001"
You should now be able to access the browsersync proxy on localhost:3001.
P.S. In case you have more than one site serving in one ngninx docker container, you can edit nginx config file for specific site in /etc/nginx/conf.d/somesite.conf and add new line:
listen: 3000;
Background: I am compiling 2 dependent TypeScript files to js, which produces also source maps (one source map per file) using tsc 1.0
I'm using -m commonjs and then use browserify to generate a single bundle.js
However I noticed that I get the original source map references twice in the bundle, which doesn't seem to work.
Passing --debug doesn't seem to do the trick either.
I had a feeling this issue: https://github.com/substack/node-browserify/issues/325 is somewhat related, but I couldn't figure out how the issue was resolved.
Also https://github.com/substack/browser-pack was suggested, but again I don't fully understand how to use it, is it a replacement to browserify?
Bottom line, I would like to merge the 2 js files but "merge" the js to ts source maps using browserify. Is that possible?
tsify is a browserify plugin that is better and replaces e.g. typescriptifier.
npm install tsify browserify watchify
You use tsify like this:
browserify src/index.ts -p tsify --debug -o build/index.js
Notice that this supports browserify --debug switch, no extra tricks required. So you can also use it with watchify like this:
watchify src/index.ts -p tsify --debug -o build/index.js
Using the minifyify browserify plugin I believe you can use TypeScript with Browserify and retain the source maps. After compiling the TypeScript files you should be able to pass the "entry" file (the one that imports the other one via commonjs syntax) through browserify with the minifyify plugin.
var browserify = require('browserify'),
bundler = new browserify();
bundler.add('entry.js');
bundler.plugin('minifyify', {map: 'bundle.js.map'});
bundler.bundle({debug: true}, function (err, src, map) {
if (err) console.log(err);
fs.writeFileSync('bundle.js', src);
fs.writeFileSync('bundle.js.map', map);
});
Here is my working solution:
var settings = {
projectName : "test"
};
gulp.task("bundle", function() {
var mainTsFilePath = "src/main.ts";
var outputFolder = "bundle/src/";
var outputFileName = settings.projectName + ".min.js";
var pkg = require("./package.json");
var banner = [
"/**",
" * <%= pkg.name %> v.<%= pkg.version %> - <%= pkg.description %>",
" * Copyright (c) 2015 <%= pkg.author %>",
" * <%= pkg.license %>",
" */", ""
].join("\n");
var bundler = browserify({
debug: true,
standalone : settings.projectName
});
// TS compiler options are in tsconfig.json file
return bundler.add(mainTsFilePath)
.plugin(tsify)
.bundle()
.pipe(source(outputFileName))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify())
.pipe(header(banner, { pkg : pkg } ))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(outputFolder));
});
I created example project.
You can run it with $(npm bin)/gulp build --env=dev for development environment and source maps will be generated.
There is gulpfile.js:
'use strict';
var path = require('path'),
gulp = require('gulp'),
del = require('del'),
typescript = require('gulp-typescript'),
sourcemaps = require('gulp-sourcemaps'),
browserify = require('browserify'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
uglify = require('gulp-uglify'),
gutil = require('gulp-util'),
inject = require('gulp-inject'),
babel = require('gulp-babel'),
argv = require('yargs').argv;
var devEnvironment = 'dev',
prodEnvironment = 'prod',
environment = argv.env || prodEnvironment,
isDevelopment = environment === devEnvironment;
var projectPath = __dirname,
srcDir = 'src',
srcPath = path.join(projectPath, srcDir),
buildDir = path.join('build', environment),
buildPath = path.join(projectPath, buildDir),
distDir = 'dist',
distRelativePath = path.join(buildDir, distDir),
distPath = path.join(buildPath, distDir);
var tsSrcPath = path.join(srcPath, 'typescript'),
tsGlob = path.join(tsSrcPath, '**', '*.ts'),
tsBuildPath = path.join(buildPath, 'tsc');
var indexHtmlName = 'index.html',
indexJsName = 'index.js';
var distIndexJsPath = path.join(distPath, 'index.js'),
distIndexHtmlPath = path.join(distPath, indexHtmlName);
var tsProject = typescript.createProject('tsconfig.json');
console.log('Environment: ' + environment);
gulp.task('clean', function () {
return del([buildPath]);
});
gulp.task('tsc', ['clean'], function () {
var stream = gulp.src([tsGlob]);
if (isDevelopment) {
stream = stream
.pipe(sourcemaps.init());
}
stream = stream
.pipe(typescript(tsProject))
.pipe(babel({
presets: ['es2015']
}));
if (isDevelopment) {
stream = stream.pipe(sourcemaps.write({sourceRoot: tsSrcPath}));
}
return stream.pipe(gulp.dest(tsBuildPath));
});
gulp.task('bundle', ['tsc'], function () {
var b = browserify({
entries: path.join(tsBuildPath, indexJsName),
debug: isDevelopment
});
var stream = b.bundle()
.pipe(source(indexJsName))
.pipe(buffer());
if (!isDevelopment) {
stream = stream.pipe(uglify());
}
return stream
.on('error', gutil.log)
.pipe(gulp.dest(distPath));
});
gulp.task('build', ['bundle'], function() {
return gulp.src(path.join(srcPath, indexHtmlName))
.pipe(inject(gulp.src([distIndexJsPath], {read: false}), {ignorePath: distRelativePath, addRootSlash: true}))
.pipe(gulp.dest(distPath));
});
You should pay attention to lines:
stream = stream.pipe(sourcemaps.write('', {sourceRoot: tsSrcPath})); - write inline source maps with sourceRoot pointing to your typescript sources path. Inline maps are written directly to .js files generated by tsc to build/dev/tsc.
debug: isDevelopment - in development environment make browserify generate his own source maps for resulting bundle build/dev/dist/index.js file so it will have source maps referencing .js files from build/dev/tsc which in turn have source maps referencing .ts files from src/typescript.
With this setup you will be able to see and debug .ts files in browser:
I faced similar issue when trying to debug my Angular2 app running in Chrome in Visual Studio Code (Using Debugger for Chrome extension)
I use gulp as my task runner and my setup is as follows:
Typescript files -> tsc -> intermediate es5 js -> browserify (plus uglify in production build) -> compiled bundle
My directory structure is as follows:
|- src
|- my .ts files here
|- main.ts - my entry file
|- dist
|- intermediate files go here
|- web
|- app.js - final bundle
|- app.js.map - final bundle map
|- gulpfile.js
gulpfile.js:
var gulp = require('gulp'),
tsc = require('gulp-typescript'),
browserify = require('browserify'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer');
gulp.task('tsc', [], () => {
return gulp.src(['src/**/*.ts'])
.pipe(sourcemaps.init())
.pipe(tsc({
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}))
.pipe(sourcemaps.write(null, {
"sourceRoot": function(file) {
let parts = file.relative.split('\\');
let root = Array(parts.length + 1).join('../') + 'src';
return root;
}
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('bundle', ['tsc'], () => {
let b = browserify({
entries: 'dist/main.js',
debug: true,
});
return b.bundle()
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./', {
"sourceRoot": "../",
}))
.pipe(gulp.dest('web/'));
})
gulp.task('default', ['bundle']);
Explanation/reasoning:
For some reason browserify doesn't read and parse .js.map files linked in .js file (via special comment at the end) but it does when the source map is embedded in js file. So, by passing null instead of path to sourcemaps it will embed it at the end of generated .js file.
Next issue I noticed was that sourcemaps doesn't automatically follow directory structure (add '../' to sourceRoot when it goes to next directory level), so I made a quick function to complement this. Keep in mind that it only works on Windows - on Linux you'd have to change split character.
function(file) {
let parts = file.relative.split('\\'); // put '/' here on Linux
let root = Array(parts.length + 1).join('../') + 'src';
return root;
}
Certainly there is a way to detect correct path separator, I'm debugging only on Windows thus it's not important for my purposes.
I hope it helps someone, cause I've spent whole Sunday morning tracking down this problem.