Gulp build with browserify environment variable - environment-variables

I'm looking to include either an environment variable or file that my modules can access for conditional flow.
// contains env build specific data
// or value 'develop' || 'production'
var env = require('config');
I know I can access the CL arguments with yargs which is great, but I can't seem to find a way to get arguments into my browserify build.
var bundleStream = {
cache: {},
packageCache: {},
fullPaths: false,
entries: [filename],
extensions: config.extensions,
debug: config.debug,
paths: ['./node_modules', './app/js/'],
require: ['jquery', 'lodash']
};
var bundle = function() {
bundleLogger.start(filename);
return bundleStream
.bundle()
.on('error', handleErrors)
.pipe(source(filename.replace('-app', '-bundle')))
.pipe(gulp.dest(process.cwd()))
.on('end', reportFinished)
.pipe(browserSync.reload({
stream: true
}));
};

You could create a config.json file dynamically, and then require it in your modules:
var fs = require('fs');
var gutil = require('gulp-utils');
gulp.task('create-config', function(cb) {
fs.writeFile('config.json', JSON.stringify({
env: gutil.env.env,
tacos: 'delicious'
}), cb);
});
gulp.task('browserify', ['create-config'], function() {
//...
});
In your modules:
var config = require('./config.json');
if (config.env === 'production') {
//...
}
And on the command line:
gulp --env=production

Related

AWS CDK Code Pipelines- Why Can Local Obtain The Branch But Code Build Cannot?

My goal is to dynamically name resources to allow for multiple environments. For example, a "dev-accounts" table, and a "prod-accounts" table.
The issue I am facing is Code Build cannot dynamically name resources, whilst local can. Following the example above, I am receiving "undefined-accounts" when viewing the logs in Code Build.
Code to obtain the environment by branch name:
export const getContext = (app: App): Promise<CDKContext> => {
return new Promise(async (resolve, reject) => {
try {
const currentBranch = await gitBranch();
const environment = app.node.tryGetContext("environments").find((e: any) => e.branchName === currentBranch);
const globals = app.node.tryGetContext("globals");
return resolve({...globals, ...environment});
}
catch (error) {
return reject("Cannot get context from getContext()");
}
})
}
Further Explanation:
In the bin/template.ts file, I am using console.log to log the context, after calling const context = await getContext(app);
Local CLI outcome:
{
appName: 'appName',
region: 'eu-west-1',
accountId: '000000000',
environment: 'dev',
branchName: 'dev'
}
Code Build outcome:
{
appName: 'appName',
region: 'eu-west-1',
accountId: '000000000'
}
Note I've removed sensitive information.
This is my Code Pipeline built in the CDK:
this.codePipeline = new CodePipeline(this, `${environment}-${appName}-`, {
pipelineName: `${environment}-${appName}-`,
selfMutation: true,
crossAccountKeys: false,
role: this.codePipelineRole,
synth: new ShellStep("Deployment", {
input: CodePipelineSource.codeCommit(this.codeRepository, environment, {
codeBuildCloneOutput: true
}),
installCommands: ["npm i -g npm#latest"],
commands: [
"cd backend",
"npm ci",
"npm run build",
"cdk synth",
],
primaryOutputDirectory: "backend/cdk.out",
})
});
By using the key/value codeBuildCloneOutput: true, I believe I am completing a full clone of Code Commit repository, and thus the git metadata.
CodeBuild exposes the CODEBUILD_SOURCE_VERSION environment variable. For CodeCommit, this is "the commit ID or branch name associated with the version of the source code to be built".
const currentBranch = process.env.CODEBUILD_SOURCE_VERSION ?? await gitBranch();

Browsersync is running but does not refresh the page

I have MacOS + installed Docker container by Mark Shust (https://github.com/markshust/docker-magento) + installed browsersync on the host.
Magento has ".less" files in the folder: app/design/frontend. I set a folder as a current one in the cli. And run this command from the host:
browser-sync start --host "domain.test" --proxy "https://domain.test" --files "**/*.less" --https
I get this output:
[Browsersync] Proxying: https://domain.test
[Browsersync] Access URLs:
--------------------------------------
Local: https://localhost:3000
External: https://domain.test:3000
--------------------------------------
UI: http://localhost:3002
UI External: http://localhost:3002
--------------------------------------
[Browsersync] Watching files...
I can open https://domain.test and it works properly. http://localhost:3002 shows that there are no current connections. However, the output in the cli infoms: "[Browsersync] Reloading Browsers..."
if i change less, i still can find changes on the website but only after a manual reload.
The documentation mentions grunt configuration and there are some recipes as an example. I tried to use standard magento's file but it does not help. It looks like this:
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
watch: {
files: 'app/design/**/*.less',
tasks: ['less']
},
browserSync: {
dev: {
bsFiles: {
src : [
'app/design/**/*.css'
]
},
options: {
watchTask: true,
server: './'
}
}
}
});
// load npm tasks
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
// define default task
grunt.registerTask('default', ['browserSync', 'watch']);
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function (task) {
return task.replace('.js', '');
});
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'cssmin',
'usebanner'
].map(function (task) {
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function (theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});};
Should it work without gruntjs running? And why the page reload is not triggered?
PS: I did not place this question into https://magento.stackexchange.com/ cause i believe it's a general problem and not related to Magento.

Rollup with Gulp.js - Multiple outputs

I'm trying to use an array of outputs using Rollup on Gulp.
The documentation only shows a basic example with a single output file. (Although it states that the output property can contain an array)
.then(bundle => {
return bundle.write({
file: './dist/library.js',
format: 'umd',
name: 'library',
sourcemap: true
});
});
If I replace that for an array, it will fail:
.then(bundle => {
return bundle.write({
file: './dist/library.js',
format: 'umd',
name: 'library',
sourcemap: true
},
{
file: './dist/file2.js',
format: 'umd',
});
});
Error: You must specify "output.file" or "output.dir" for the build.
at error (/Users/alvarotrigolopez/Sites/extensions/experiments/bundle/node_modules/rollup/dist/shared/rollup.js:158:30)
at handleGenerateWrite (/Users/alvarotrigolopez/Sites/extensions/experiments/bundle/node_modules/rollup/dist/shared/rollup.js:23403:20)
I've tried using the output option as well and using #rollup/stream instead of just rollup.
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var rollup = require('#rollup/stream');
gulp.task('js', function() {
return rollup({
input: './app.js',
output: [
{
file: 'bundle.js',
format: 'umd',
},
{
file: 'test.js',
format: 'umd',
}
]
})
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(gulp.dest('./build/js'));
});
Unknown output options: 0, 1. Allowed options: amd, assetFileNames, banner, chunkFileNames, compact, dir, dynamicImportFunction, entryFileNames, esModule, exports, extend, externalLiveBindings, file, footer, format, freeze, generatedCode, globals, hoistTransitiveImports, indent, inlineDynamicImports, interop, intro, manualChunks, minifyInternalExports, name, namespaceToStringTag, noConflict, outro, paths, plugins, preferConst, preserveModules, preserveModulesRoot, sanitizeFileName, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, strict, systemNullSetters, validate

How to configure webpack devServer port?

I'm trying to use webpack in my Symfony app in docker, but I'm still getting error:
GET http://localhost:8000/sockjs-node/info?t=1556798329924 404 (Not Found)
Everything works fine axcepts this error...
App is running on port 8000 and node on port 8081. The address with 8081 port is accessible, but how can I tell webpack to use port 8081 with devServer?
Here is my webpack.config.js:
const Encore = require('#symfony/webpack-encore');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const outputPath = './public/build/';
const publicPath = '/build';
Encore
.setOutputPath(outputPath)
.setPublicPath(publicPath)
// Clean output dir before build
.cleanupOutputBeforeBuild()
.splitEntryChunks()
.enableSingleRuntimeChunk()
// uncomment if you're having problems with a jQuery plugin
.autoProvidejQuery()
// Generate JS files
.addEntry('loader', './assets/javascript/loader.js')
.addEntry('admin-loader', './assets/javascript/admin.js')
// Generate CSS files
.addStyleEntry('forms', './assets/styles/forms.scss')
.addStyleEntry('grid', './assets/styles/grid.scss')
.addStyleEntry('reboot', './assets/styles/reboot.scss')
.addStyleEntry('styles', './assets/styles/styles.scss')
.addStyleEntry('utilities', './assets/styles/utilities.scss')
.addStyleEntry('admin', './assets/styles/admin.scss')
.enableEslintLoader()
.configureTerserPlugin((options) => {
options.cache = true;
options.parallel = true;
options.terserOptions = {
output: {
comments: false,
}
}
})
.configureSplitChunks((options) => {
options.chunks = 'all',
options.maxInitialRequests = Infinity,
options.cacheGroups = {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `pckg.${packageName.replace('#', '')}`;
},
}
}
})
// Enable SASS loader with PostCSS config
.enableSassLoader()
.enablePostCssLoader()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
// CSS Hot Loader for HMR in webpack dev server
.addLoader({
enforce: 'post',
test: /\.(s?c|sa)ss$/,
exclude: /node_modules/,
loader: 'css-hot-loader',
})
.addPlugin(new StyleLintPlugin({
lintDirtyModulesOnly: Encore.isProduction(),
context: './assets/styles/',
quiet: false,
}));
const config = Encore.getWebpackConfig();
// Export settings and generate files
module.exports = config;
Does anyone know?

Webpack2 cannot resolve: config.context absolute path

I am trying to run my webpack config file (see below), but I am still getting certain type of errors that reffers to a paths I use in my webpack settings:
- config.context
- config.module.rules
- config.output
My idea was, that I set up my config.context path absolutely (as it is written in docs), otherwise my webpack.config files reffers to node_modules in parents directory. But still, when I run webpack -w --env.dev command, it throws following errors:
It seems to me, that config.context cant handle absolute path as it should. Any help how to set up paths correctly? Thank you!
My webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractText = require('extract-text-webpack-plugin');
module.exports = function (env) {
var project = {
env: env.prod ? 'prod' : 'dev',
jsBase: './routesMap/',
cssBase: './src/css/'
}
var config = {
context: path.resolve(__dirname),
entry: {
'routesMap': project.jsBase + 'main.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: '[name].js'
},
plugins: [
new ExtractText({
filename: 'styles.min.css',
disable: false,
allChunks: true
})
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, '/routesMap'),
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['es2015'],
plugins: ["transform-runtime"]
}
}
]
}
};
return config;
}
That's an issue with the latest webpack version. Try using uppercase drive letters in shell, e.g. C:/ instead c:/.
More info https://github.com/webpack/webpack/issues/4530.
I uninstalled latest webpack version (I had webpack 2.3.0) and installed version of 2.2.0, problem solved! As #zemirco stated in his answer, it has something to do with casesensitive letters in absolute path. Unfortunatelly changing small letter to big one doesnt help for me, so I just changed webpack version.

Resources