Rollupjs: Ignore lines of code - lodash

One of my javascript files is using the lodash template syntax:
const deliveryClient = new DeliveryClient({
enablePreviewMode: <%= options.enablePreviewMode %>,
projectId: '<%= options.projectId %>',
previewApiKey: '<%= options.previewApiKey %>',
defaultLanguage: '<%= options.defaultLanguage %>',
enableAdvancedLogging: <%= options.enableAdvancedLogging %>,
baseUrl: '<%= options.baseUrl %>',
typeResolvers: typeResolvers
});
But when i run rollup -c i'm getting a "unexpected token" error. Is there a way to tell rollup to ignore (just put it in the output file) some lines of code?
Or is there an other/better way to deal with lodash template syntax within RollupJS?
I just want to above code snippet to be in my final output!

I fixed it by using the rollup-plugin-replace plugin.
In my javascript I changed my code into the following:
const deliveryClient = new DeliveryClient('KENTICOOPTIONS');
and in the rollup.config.js I added the plugin with the following configuration:
replace({
include: 'lib/templates/plugin.template.js',
KENTICOOPTIONS: '<%= serialize(options) %>'
})
So this gives the final output of:
const deliveryClient = new DeliveryClient('<%= serialize(options) %>');
Which is exactly what i needed!

Related

How to add HTML comments to index.html when doing a build in Vue CLI?

Update 1: Fixed syntax issue that caused my initial build errors.
Update 2: Found my own solution using a Webpack plugin. See the accepted solution.
I want to add some custom HTML comments in the public/index.html during a build. I added something like this:
<!--
My Application
Version: <%= VUE_APP_VERSION %>
Build date: <%= VUE_APP_BUILD_DATE %>
-->
In my vue.config.js, I've set VUE_APP_VERSION and VUE_APP_BUILD_DATE accordingly:
let today = new Date().toLocaleDateString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
process.env.VUE_APP_VERSION = require('./package.json').version
process.env.VUE_APP_BUILD_DATE = today
But when I actually build (npm run build), the comments are removed completely and everything is minimized.
How do I preserve my comments?
Found a solution using HtmlWebpackPlugin and WebpackAutoInject plugins in my vue.config.js file; ditching the VUE_APP_* variable use in my index.html as it was causing me build errors.
npm install html-webpack-plugin --save-dev
npm install webpack-auto-inject-version --save-dev
My new vue.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackAutoInject = require('webpack-auto-inject-version')
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? process.env.VUE_APP_PUBLIC_PATH_EN
: '/',
configureWebpack: {
plugins: [
// index.html customization
new HtmlWebpackPlugin({
template: 'public/index.html',
filename: 'index.html',
inject: true,
deploy: process.env.VUE_APP_DEPLOY,
webtrends: '/webtrends/scripts/webtrends.load.js', // include webtrends script for OPS only
minify: {
removeComments: false
}
}),
// Auto inject version
new WebpackAutoInject({
SILENT: true,
// options
components: {
AutoIncreaseVersion: false,
InjectAsComment: false
},
componentsOptions: {
InjectByTag: {
// https://www.npmjs.com/package/dateformat
dateFormat: 'isoUtcDateTime'
}
}
})
]
}
}
Then in my index.html (with a custom script to include on build):
<!--
My application
Version: [AIV]{version}[/AIV]
Build date: [AIV]{date}[/AIV]
-->
<% if (htmlWebpackPlugin.options.deploy === 'ops') { %>
<script src="<%= htmlWebpackPlugin.options.webtrends %>"></script>
<% } %>
I was able to get this to work by using "HTML-escaped interpolation" syntax.
<%= VALUE %> for unescaped interpolation;
<%- VALUE %> for HTML-escaped interpolation; 👈🏻 this one
<% expression %> for JavaScript control flows.
Note the different closing tag too.
So your index.html becomes:
<!--
My Application
Version: <%- VUE_APP_VERSION %>
Build date: <%- VUE_APP_BUILD_DATE %>
-->

Using variables in Gruntfile.js

I have a Gruntfile.js, where I have a string I's repeating many times. So I decided to proceed with a variable, hence I introduced var file_path.
module.exports = function(grunt) {
'use strict';
var today = new Date();
var year = today.getFullYear();
var file_path = 'here/there/';
grunt.initConfig({
jshint: {
all: [
'<%= file_path %>/assets/js/app.js',
'<%= file_path %>/admin/assets/js/admin.js',
]
},
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['jshint']);
};
But it's not working. Throwing the following error:
Running "jshint:all" (jshint) task
Warning: An error occurred while processing a template (file_path is not defined). Use --force to continue.
When I changed <%= file_path %> to <%= this.file_path %>, the process runs but the paths are not resolved.
Running "jshint:all" (jshint) task
>> 0 files linted. Please check your ignored files.
With other registered tasks it's confirmed that, No source files were found..
BTW I incorporated year in another task that is working fine. Attached a screenshot:
So, I tried the same syntax in jshint task, like below:
all: [
file_path + 'assets/js/app.js',
file_path + 'admin/assets/js/admin.js',
]
It's producing the same result of not linting any file at all.
However I tried the following console.log, outside of grunt.initConfig():
grunt.log.write(file_path + 'assets/js/app.js');
It's displaying the correct concatenated path to the file: here/there/assets/js/app.js.
How can I incorporate variables in Gruntfile?
If you are wanting to use Template strings like this:
all: [
'<%= file_path %>/assets/js/app.js',
'<%= file_path %>/admin/assets/js/admin.js',
]
Then configure your Gruntfile.js to this:
module.exports = function(grunt) {
'use strict';
var today = new Date();
var year = today.getFullYear();
grunt.initConfig({
file_path: 'here/there',
// ^-- Note: there is no trailing forward slash.
jshint: {
all: [
'<%= file_path %>/assets/js/app.js',
'<%= file_path %>/admin/assets/js/admin.js',
]
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['jshint']);
};

Bootstrap "grunt watch" wont create bootstrap.min.css

I am almost absolutely new to grunt.
I used grunt with bootstrap 3.1.1 and the grunt watch-command worked out great. My bootstrap.min.css file was compiled every time. (i upload my bootstrap.min.css)
Later on i lost my 3.1.1 grunt file (long story short my computer crashed).
So now with Bootstrap 3.2.0 i was going to restablish my grunt-work-flow.
But now when i use grunt watch i only get the "bootstrap.css" and "bootstrap.theme.css" compiled.
I have spent the last hours to figure this out without success.
WHAT I WANT
I want grunt watch to compile the minified "bootstrap.min.css"
So how do i call the min.css-function on the watch?
I will be glad to get some help.
Grunt watch will only watch the files then run tasks you have set. I am assuming in your gruntfile you ahve something like this:
css: {
files: [
'bootstrap.css',
],
tasks: ['less'],
},
In the less task you should have something like below. Note the cleancss option being set to true:
options: {
cleancss: true
},
files: {
"dest/bootstrap.min.css": "src/bootstrap.css",
"dest/bootstrap.theme.min.css": "src/bootstrap.theme.css"
}
UPDATE:
Based on the file you uploaded you should be running the cssmin:core task when the watch is triggered.
UPDATE 2:
To update the watch task you can just add the cssmin:core task to the less subtask:
less: {
files: 'less/**/*.less',
tasks: ['less', 'cssmin:core]
}
Here you are telling it to run the less task, followed by the cssmin task whenever one of the less files is changed while watching.
Your gruntfile.js will have a 'watch' section as below
watch: {
src: {
files: '<%= jshint.core.src %>',
tasks: ['jshint:src', 'qunit', 'concat']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'qunit']
},
less: {
files: 'less/**/*.less',
tasks: 'less'
}
},
The tasks under less subsection define the tasks that 'grunt watch' will run. In Bootstrap 3.3.2 (I guess in 3.1.1 also it would be the same) is the 'cssmin' task that minifies the core bootstrap css. So you need to add the task to less so the code above becomes
watch: {
src: {
files: '<%= jshint.core.src %>',
tasks: ['jshint:src', 'qunit', 'concat']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'qunit']
},
less: {
files: 'less/**/*.less',
tasks: ['less', 'cssmin']
}
},
None of the above worked for me. Looks like the css minification command changed to cssmin:minifyCore so I have updated my watch task to the following:
watch: {
src: {
files: '<%= jshint.core.src %>',
tasks: ['jshint:core', 'qunit', 'concat']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'qunit']
},
less: {
files: 'less/**/*.less',
tasks: ['less', 'cssmin:minifyCore']
}
},
Hopefully this helps others!

Debug CoffeeScript with IntelliJ

I'm starting a fresh web project and the last part of my configuration is to enable debugging for my CoffeeScripts files.
The whole project is build using a Grunt task that compile coffee to js and generates the proper map file but I cannot make the Coffeescript debuging work in IntelliJ.
Note that I don't want to use IntelliJ File Watchers.
Here is my Gruntfile :
module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
coffee:
options:
sourceMap: true
files:
expand: true
flatten: true
cwd: 'src/'
src: ['**/*.coffee']
dest: 'src/'
ext: '.js'
concat:
option:
separator: ';'
dist:
src: ['src/**/*.js']
dest: 'dist/<%= pkg.name%>.js'
uglify:
options:
banner: '/*! <%= pkg.name %> v<%= pkg.version%> by Pierre Degand <%= grunt.template.today("dd-mm-yyyy") %> */\n'
dist:
files:
'lib/<%= pkg.name%>.min.js': ['<%= concat.dist.dest %>']
watch:
files: ['<%= coffee.files.src %>']
tasks: ['coffee', 'concat', 'uglify']
grunt.loadNpmTasks('grunt-contrib-concat')
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.registerTask('default', ['coffee', 'concat', 'uglify'])
My Simple CoffeeScript file (Break point is on line 2 on IntelliJ) :
name = 'Pierre'
console.log "Hello #{name} !"
Generated JS file from Grunt :
(function() {
var name;
name = 'Pierre';
console.log("Hello " + name + " !!");
}).call(this);
/*
//# sourceMappingURL=app.js.map
*/
The source map
{
"version": 3,
"file": "app.js",
"sourceRoot": "",
"sources": [
"app.coffee"
],
"names": [],
"mappings": "AAAA;CAAA,GAAA,EAAA;;CAAA,CAAA,CAAO,CAAP,IAAA;;CAAA,CACA,CAAA,CAAa,CAAb,EAAO,CAAM;CADb"
}
And finally the html I use to test
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="src/app.js"></script>
</body>
</html>
When I used File watchers, the .js and the .map.js were subfiles of the .coffee file, can I achieve the same behavior without using File Watchers ?
If I right-click/"Debug index.html" in IntelliJ, I can read "Hello Pierre!!" in my IntelliJ debuger console, but the script is not breaked on the console.log()
Did someone had same troubles ?
Thanks!
When I used File watchers, the .js and the .map.js were subfiles of the .coffee file, can I achieve the same behavior without using File Watchers?
No, you can't. This is a file watchers feature
If I right-click/"Debug index.html" in IntelliJ, I can read "Hello Pierre!!" in my IntelliJ debuger console, but the script is not breaked on the console.log()
This works for me if I refresh a page in browser after the code was executed. Please vote for this ticket

Devise is not working with flash runtime of Plupload

I'm running Rails 3.0.9, Devise 1.4 and Plupload 1.4.3.2. Everything works fine with HTML5 runtime.
But when I add before_filter authenticate_user! to my application controller and switch to flash runtime things go bad.
When I try to upload some images:
Started POST "/uploads" for 127.0.0.1 at 2011-06-29 12:58:48 +0200
Processing by UploadsController#create as JS
Parameters: {"Filename"=>"me_dark_ui_01.png", "name"=>"me_dark_ui_01.png", "_inzercia_session"=>"BAh7CEkiEF9jc3JmX3Rva2VuBjoGRUZJIjE0NjlmSkZCd25VMkl1UEFzTTFUVTUwTFVYTjRHYkJJSTlGKzBWTXFlSzc0PQY7AEZJIhl3YXJkZW4udXNlci51c2VyLmtleQY7AFRbCEkiCVVzZXIGOwBGWwZpB0kiIiQyYSQxMCQ4SkVLZGVja0dLVk5jbm10MEVoNmRPBjsAVEkiD3Nlc3Npb25faWQGOwBGIiUwY2Y1ZjM4MDRlMGEzOTM3MzQ5ZTQzM2RkNjk5MTc0Mg%253D%253D--b0e6653c44645e7db420dff1dd9908f4b8938e6d", "authenticity_token"=>"469fJFBwnU2IuPAsM1TU50LUXN4GbBII9F+0VMqeK74=", "upload_token"=>"07ea1a1ec4539436878b8e13ae6347164fcd3eac", "_http_accept"=>"application/javascript", "file"=>#<ActionDispatch::Http::UploadedFile:0x520bae0 #original_filename="me_dark_ui_01.png", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"file\"; filename=\"me_dark_ui_01.png\"\r\nContent-Type: application/octet-stream\r\n", #tempfile=#<File:C:/Users/Deli/AppData/Local/Temp/RackMultipart20110629-4684-osz0l9>>, "Upload"=>"Submit Query"}
Completed in 21ms
My Uploads#create action
def create
#upload = Upload.new
#upload.photo = params[:file] if params.has_key?(:file)
# detect Mime-Type (mime-type detection doesn't work in flash)
#upload.photo_content_type = MIME::Types.type_for(params[:name]).to_s if params.has_key?(:name)
#upload.upload_token = params[:upload_token]
#upload.save!
strong textrespond_to :js
end
Plupload settings:
<% session_key_name = Rails.application.config.session_options[:key] %>
jQuery(document).ready(function() {
$("#uploader").pluploadQueue({
runtimes: 'flash',
url: '<%= uploads_path %>',
max_file_size: '10mb',
multiple_queues: true,
flash_swf_url: "/javascripts/plupload/plupload.flash.swf",
silverlight_xap_url: "/javascripts/plupload/plupload.silverlight.xap",
multipart: true,
multipart_params: {
'_http_accept': 'application/javascript',
'authenticity_token' : '<%= form_authenticity_token %>',
'upload_token' : '<%= #upload_token %>',
'<%= session_key_name %>' : encodeURIComponent('<%= u cookies[session_key_name] %>')
},
filters: [
{title: "Images", extensions: "jpg,jpeg,png"}
],
init: {
FileUploaded: function(up, file, info) {
eval(info["response"]);
}
}
});
});
Problem solved with adding
urlstream_upload: true
to the plupload configuration.