I defined a snippet code and show it in web so users can copy to use but after build app with Webpack production mode the snippet gone.
I think that webpack treat it like unused code so it be removed when build.
Snippet code:
let html = `
<script>
(function(w, d, t, s, n) {
...
const fn = function() {
(w[n].q = w[n].q || []).push(arguments);
};
w[n] = w[n] || fn;
const f = d.getElementsByTagName(t)[0];
const e = d.createElement(t);
const h = '?v' + new Date().getTime();
e.async = true;
e.src = s + h;
f.parentNode.insertBefore(e, f);
})(window, document, 'script', '${process.env.UNIVERSAL_SCRIPT}', 'fd');
window.fd('form', { userId: '${form.userId}', formId: '${form.id}' });
</script>
`;
html = jsBeautify.html(html, { indent_size: 2 });
Render in react component:
<SyntaxHighlighter language="xml" style={monokai} id="html">
{html}
</SyntaxHighlighter>
Here is demo repository: https://github.com/minhtranite/webpack-remove-snippet. Please run start and start:prod to see the difference result.
It looks like you haven't defined the variable form as a result of which the build is failing. Or, language="html" is causing it to be parsed as html. language="text" will render it as text.
Related
I have integrated google tag manager in my react js application but the problem is I have to pass the gtm id present in gtm script dynamically and turn on and off datalyer dynamically depending upon the response of the value coming from API.
I have created a component LoadAppKeys which receives a value on which I decide whether gtm is enabled or not. But how do I pass the gtm id dynamically to the script present in head section of index.html and append the script in head if value is 1 and not if its 0.
class LoadAppKeys extends React.PureComponent {
componentDidMount() {
this.props.getStorefrontConfigs();
}
componentWillReceiveProps(nextProps) {
if (!nextProps.loading) {
const gtm = getGTM(nextProps.storefrontConfig);
if (R.equals(gtm.gtm_enabled, 1)) {
var script = document.createElement('script');
script.type = "text/javascript";
script.text = myGTM(window, document, 'script', 'dataLayer', "GTM-KQZGSBW");
document.head.appendChild(script);
}
}
}
-------------------------------------
function myGTM(w, d, s, l, i) {
(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({
'gtm.start':
new Date().getTime(), event: 'gtm.js'
}); var f = d.getElementsByTagName(s)[0],
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', gtm_id);
}
Want to load the script everytime the page based upon the value in loadAppKeys component.
You can directly call myGTM, instead of doing the whole script insertion. Otherwise if you want to do the insertion all you need is determine the src attribute, example:
script src = 'https://www.googletagmanager.com/gtm.js?id='+id
In there you don't mention how you get the id, but basically change id with your variable.
I have a project structure like
There are approx 10 JS files in com. lab1 and lab2 has a config.json file which tells, out of 10 files which files to be concatenated and placed as app-min.js in dist/lab1 or dist/lab2.
In the gulp file I've created something like this.
var filesArr = [];
var labName;
// Player Task
gulp.task('player', function () {
return gulp.src(filesArr)
.pipe(eslint())
.pipe(babel())
.pipe(concat('app-min.js'))
.pipe(uglify({
compress: {
drop_console: true
}
}).on('error', gutil.log))
.pipe(gulp.dest('dist/' + labName));
});
// Clean
gulp.task('clean', function () {
if (readJson()) {
return del([
'dist/' + labName
]);
}
return null;
});
// Watch
gulp.task('watch', function () {
gulp.watch(filesArr, gulp.series('player'));
});
// Read Json and create JS Array
function readJson() {
// LAB STRUCTURE
var _n = prompt('Specify the LAB name. ');
labName = _n;
var _path = path.resolve('./src/' + _n);
var _exists = fs.existsSync(_path);
if (_exists) {
var _json = fs.readFileSync(path.resolve(_path + '/labstructure.json'), 'utf-8');
var _jObj = JSON.parse(_json).labObj.components;
for (var i = 0; i < _jObj.length; i++) {
var _jsName = 'src/com/component/' + _jObj[i].ref + '.js';
if (filesArr.indexOf(_jsName) === -1) {
filesArr.push(_jsName);
}
}
}
return _exists;
}
gulp.task('default', gulp.series('clean', 'player', 'watch'));
Here the filesArr looks like:
[ 'src/com/component/ColorActClass.js',
'src/com/component/PanelCompClass.js',
'src/com/component/ToggleCompClass.js',
'src/com/component/SliderCompClass.js',
'src/com/component/CheckBoxCompClass.js',
'src/com/component/ButtonCompClass.js',
'src/com/component/LabelCompClass.js',
'src/com/component/InputBoxClass.js',
'src/com/component/ColorMonitorClass.js',
'src/com/component/MsgBoxClass.js',
'src/com/component/ConfBoxClass.js',
'src/com/component/NumberPadClass.js',
'src/com/main/lib/webfontloader.js',
'src/com/main/lib/howler.core.min.js',
'src/com/main/PlayerClass.js',
'src/kl1001_color/BrainClass.js' ]
This works perfectly fine at the first place. But when any JS is modified then in watch player task throws eslint error on some files which are untouched. This doesn't happen always rather if watch is running for 10-20 mins then it throws error. Like this:
In this case CheckBoxCompClass.js is not the file which is modified, but still got the issue. On top of that, the semicolon is in place. If this file has issue then eslint should have thrown the error at the first place.
Please help.
Accidentally, my NVM was set to an older version. Solved the issue after updating the NVM and by setting the current NVM version to the latest one.
Goal is to use this Gulp file to execute 'n' number of different source & destinations.
How can we pass the arguments(source, destination) so that the CSS-Generator task is accepting those source & destinations and giving out the separate output files.
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
var paths = {
styles: {
src1: "scss/slider-one/index.scss",
src2: "scss/slider-two/index.scss"
dest1: "slider-one",
dest2: "slider-two"
}
};
function style1() {
return (
gulp
.src(paths.styles.src1)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest1))
);
}
exports.style1 = style1;
function style2() {
return (
gulp
.src(paths.styles.src2)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest2))
);
}
exports.style2 = style2;
function watch() {
style1();
style2();
gulp.watch("scss/slider-one/*.scss", style1);
gulp.watch("scss/slider-two/*.scss", style2);
}
exports.watch = watch
Your source is scss/slider-one/index.scss & destination is slider-one and watch is scss/slider-one/*.scss.
slider-one is common in source, destination & watch.
So you can define the paths array as ["slider-one","slider-two"]
And you are calling the style1 & style2 as the callback of watch function. So you can club that and define that in one function.
And call that function inside for loop with parameters (source,destination,watch).
Full Code:
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
function runGulpSass(src,dest,watch) {
gulp.watch(watch, function() {
return gulp.src(src)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(dest))
});
}
exports.runGulpSass = runGulpSass;
function startGulp() {
var paths = ["slider-one","slider-two"];
for(var i=0;i<paths.length;i++) {
runGulpSass("scss/"+paths[i]+"/index.scss",paths[i],"scss/"+paths[i]+"/*.scss")
}
}
exports.watch = startGulp
[Edit] If there is no common value in source, destination & watch :
Define the paths array like this :
var paths = [
["scss/slider-one/index.scss","css/slider-one","slider-one/*.scss"],
["scss/slider-two/index.scss","css/slider-two","slider-two/*.scss"]
];
And set the runGulpSass function parameter like this :
runGulpSass(paths[i][0],paths[i][1],paths[i][2])
Hi Im just a rookie with polymer, I hope this question doesnt sound stupid for you :(
I am triying to make a image gallery and I am using this idea: From this page
<dom-module id="simple-gallery" >
<script>
HTMLImports.whenReady(function () {
(function() {
var current_index = 0;
var image_length = 0;
Polymer({
is: "simple-gallery",
ready: function() {
var images = Polymer.dom(this).querySelectorAll('img');
var container = this.$.links;
for (var img in images) {
images[img].addEventListener('click',this.load_popup);
container.appendChild(images[img]);
}
},
load_popup: function(e, detail, sender) {
e.preventDefault();
var links = document.getElementById('links');
image_length = links.getElementsByTagName('img').length;
var image_url = e.target.getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
var modal = document.getElementsByClassName("modal")[0];
modal.style.display = 'block';
current_index = parseInt(e.target.getAttribute('data-index').replace("s",""));
return false;
},
next: function () {
current_index = current_index + 1;
if(current_index == (image_length + 1) ){
current_index = 1;
}
var current_image = document.querySelectorAll("[data-index='s"+current_index+"']");
image_url = current_image[0].getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
},
prev: function () {
current_index = current_index - 1;
if(current_index == 0 ){
current_index = image_length;
}
var current_image = document.querySelectorAll("[data-index='s"+current_index+"']");
image_url = current_image[0].getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
},
close: function () {
var modal = document.getElementsByClassName("modal")[0];
modal.style.display = "none";
},
});
})();
});
</script>
<template>
I realy dont understand why this code works fine if I use it as in the example, but if I create a proyect with: polymer init app-drawer-template and I use this as an element wich is called from one of the views I have an error :(
Uncaught ReferenceError: HTMLImports is not defined(anonymous function) # simple-gallery.html:91
Surely I am not understanding well something but I dont know why, hope somebody has the time to give me a brief explanation :(
thanks a lot for your time.
I had the same issue so I have added following include in my main html:
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
Which worked for me.
Even though I have my userscript restricted to one domain, any site I visit that uses Jquery experiences all kinds of nasty issues when my script is active. Checking the error console in chrome reveals an identical error on all sites:
"Uncaught TypeError: Property '$' of object [object Window]"
What's causing this? My objective is to get my userscript running in noconflict mode on a site that uses both jquery and prototype. I didn't make the code above var = myFunction, so I don't know what about it is causing the problem I'm running into. Any suggestions?
// ==UserScript==
// #name Restore Dashboard Tags
// #namespace http://userstyles.org
// #description This script restores a user's tracked tag list to the sidebar on tumblr
// #author
// #homepage
// #history 1.0 first version
// #include http://www.tumblr.com/*
// #match http://www.tumblr.com/*
// ==/UserScript==
var jQuery, $ = null;
function addJQuery(callback) {
var p = null;
if(window.opera || window.navigator.vendor.match(/Google/)) {
var div = document.createElement("div");
div.setAttribute("onclick", "return window;");
p = div.onclick();
}
else {
p = Window;
}
jQuery = $ = p.jQuery.noConflict();
callback();
}
var myFunction = function() {
jQuery('div#right_column ul:first-child').after('<ul class="controls_section" id="tracked_tags"></ul>');
jQuery('div.tracked_tags a').each(function (i) {
var tagID = jQuery(this).attr("id");
var tagIDNumber = tagID.replace('tag_','');
var tagName = jQuery(this).attr("href");
var tagNameClean = tagName.replace('/tagged/','');
var tagContent ='';
tagContent += '<li><a href="'+tagName+'" id="'+tagID+'" class="tag">';
tagContent += '<div class="hide_overflow">'+tagNameClean+'</div>';
tagContent += '<span id="tag_unread_'+tagIDNumber+'" class="count" style=""></span></a></li>';
jQuery(tagContent).appendTo('div#right_column ul#tracked_tags');
});
};
var NewPosts = function(){
jQuery('div.tracked_tags > div').each(function (i) {
var thisIndex = jQuery(this).index();
if (jQuery(this).find('small').length){
var postCount = jQuery(this).find('small').text();
jQuery('div#right_column ul#tracked_tags li:eq('+thisIndex+')').find('.count').html(postCount.replace("new posts", "") );
}
});
setTimeout(NewPosts,30000);
}
addJQuery(myFunction);
addJQuery(NewPosts);
The problem has been solved! Someone on another site IDed the culprit as jQuery = $ = p.jQuery.noConflict();; since I wasn't loading my own copy of Jquery I didn't need noConflict, and its usage was hiding Jquery from the rest of the page.