I'd like to export PDF documents using jsPDF in an Ember app, but I can't figure out how to make the library available within the app.
So far, I've installed the library using bower:
bower.json
{
"name": "myApp",
"dependencies": {
...
"jspdf": "~1.2.61"
}
}
...and imported it in the ember-cli-build.js file:
ember-cli-build.js
...
app.import(app.bowerDirectory + '/jspdf/dist/jspdf.min.js');
...
However, when I try to use it (by calling var doc = new jsPDF() in an Ember action), I get this:
ReferenceError: jsPDF is not defined
What am I missing?
add your bower compoent here :
module.exports = function(defaults) {
....
app.import(app.bowerDirectory + '/jspdf/dist/jspdf.min.js'); // Your file
....
};
Try to change your code to :
actions:{
createPDF: function() {
var doc = new jsPDF(); // This part is your mistake
doc.text(20, 20, 'Hello world.');
doc.save('Test.pdf');
}
}
call your action for your button like
<button type="button" {{action "createPDF"}}>Create PDF</button>
and then Stop your Ember serve then again start it
Ember serve
that will work. when you add something to ember-cli-build.js you must stop and start your serve again .
Also for more information read this document : https://guides.emberjs.com/v2.7.0/addons-and-dependencies/managing-dependencies/
Related
I have a bootstrap template with custom css and js that I want to use with ember.js.
I am stuck with integrating the js.
I have to say that I usually don't work on the frontend side, so if this is an obvious mistake I made, excuse me.
I want to stick with the js I have from the template and don't want to include ember-bootstrap for example.
node version: v14.15.5, ember-cli: 3.25.0
npm packages to include: bootstrap#5.0.0-beta2, flickity, flickity-imagesloaded, flickity-as-nav-for, flickity-fade, jarallax
I have identified two tasks here. First, I need to integrate the existing npm packages. Then I need to add the custom scripts.
Current status
1. Packages
I added the npm packages to ember-cli-build.js over app.import()
// ember-cli-build.js file
const EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function (defaults) {
let app = new EmberApp(defaults, {});
app.import("node_modules/bootstrap/dist/js/bootstrap.min.js");
app.import("node_modules/jarallax/dist/jarallax.min.js", {
using: [{ transformation: 'cjs', as: 'jarallax' }]
});
app.import("node_modules/flickity/dist/flickity.pkgd.min.js");
app.import("node_modules/flickity-as-nav-for/as-nav-for.js");
app.import("node_modules/flickity-fade/flickity-fade.js");
app.import("node_modules/flickity-imagesloaded/flickity-imagesloaded.js");
return app.toTree();
};
When I go to the debug tab in my browser I see the packages are getting loaded under assets/node_modules/.. but js does not have any effect.
I tried to load the package in index.html over a script tag:
<script type="text/javascript" src="{{rootURL}}assets/node_modules/flickity/dist/flickity.pkgd.min.js"></script>
I get the error in the browser console window:
Refused to execute http://localhost:4200/assets/node_modules/flickity/dist/flickity.pkgd.min.js as script because "X-Content-Type-Options: nosniff" was given and its Content-Type is not a script MIME type.
2. Custom js scripts
The custom scripts have a moin theme.js script that imports everything else.
// js/theme.js
// Theme
import './aos';
import './bigpicture';
// ...
The imported Javascript scripts from theme.js also have imports like
// js/aos.js (imported from theme.js)
import AOS from 'aos';
const options = {
duration: 700,
easing: 'ease-out-quad',
once: true,
startEvent: 'load'
};
AOS.init(options);
The original theme.js also had import for Bootstrap and the other libraries.
// js/theme.js
// Vendor
import 'bootstrap';
import 'flickity';
// ...
import 'jarallax';
// Theme
import './aos';
import './bigpicture';
// ...
I had the js directory under vendor, public and app the import via the script tag did not work either. Importing from app.js has no effect.
I'm using ember-bootstrap add-on which is working fine but I would like to use the Cerulean theme from https://bootswatch.com/cerulean/. If I just overwrite the .CSS files in bower_components/bootstrap/dist/css then I expect they will be overwritten the next time I do a bower install or upgrade ember. How do I get around that please?
First of all you need to manually install bootstrap:
$ bower install bootstrap --save
Then edit ember-cli-build.js so it looks like that:
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// If you do not use ember-bootstrap - then you can omit these lines
'ember-bootstrap': {
'importBootstrapCSS': false
}
});
app.import(app.bowerDirectory + '/bootstrap/dist/css/bootstrap.css');
app.import(app.bowerDirectory + '/bootstrap/dist/js/bootstrap.js');
app.import(app.bowerDirectory + '/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', {
destDir: 'fonts'
});
return app.toTree();
};
Now you have fully working bootstrap. To add Celurian theme copy its bootstrap.css to vendor/ directory.
Then remove original bootstrap.css from ember-cli-build.js and add theme css:
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// If you do not use ember-bootstrap - then you can omit these lines
'ember-bootstrap': {
'importBootstrapCSS': false
}
});
//app.import(app.bowerDirectory + /bootstrap/dist/css/bootstrap.css');
// The name does not matter, default bootstrap.css will work as well
app.import('vendor/celurian.css');
app.import(app.bowerDirectory + '/bootstrap/dist/js/bootstrap.js');
app.import(app.bowerDirectory + '/bootstrap/dist/fonts/glyphicons- halflings-regular.woff', {
destDir: 'fonts'
});
return app.toTree();
};
So, in essence, you need to add required files to vendor directory and import them in ember-cli-build.js.
The other way would be to use SASS and just import required files from app.scss.
I want to use CKEditor with my Ember app.
I am 100% a n00b with Ember, but I'm getting there.
I have tried my darndest to figure this out, but I've gotten nowhere :(
I have tried to use ember-ckeditor. This ended up with the editor throwing a bunch of net::ERR_NAME_NOT_RESOLVED errors for things such as config.js and other "assets" it expected to find in the assets folder.
I have tried ember-cli-ckeditor. Same exact issues as above.
These two addons have pretty lame documentation. For example, I have no idea how provide a custom config file, CSS, etc. Or what if I want to use CkFinder?
The two above addons also throw some depreciated warnings when loading up the server, but I disgress....
I finally tried to manually include ckeditor v4.5.6 in the vendor folder.
I then included in ember-cli-build.js as such: app.import('vendor/ckeditor/ckeditor.js');
I'm not sure if I'm correct in doing this, and if so, how do I include use the editor plugin within my controller or component?
CKEDITOR.replace("content"); as per usual outside of Ember?
Please school me!
To use ckeditor without addons (creating your own component):
Install ckeditor using bower:
bower install ckeditor --save
Install broccoli-funnel, you will need it for ckeditor's assets:
npm install broccoli-funnel --save-dev
In your ember-cli-build.js:
At the top of file requere funnel
var Funnel = require('broccoli-funnel');
In app's options exclude ckeditor's assets from fingerprinting:
var app = new EmberApp(defaults, {
fingerprint: {
exclude: ['assets/ckeditor/']
}
});
Import ckeditor's js and assets:
app.import('bower_components/ckeditor/ckeditor.js');
var ckeditorAssets = new Funnel('bower_components/ckeditor', {
srcDir: '/',
destDir: '/assets/ckeditor'
});
/**
* If you need to use custom skin, put it into
* vendor/ckeditor/skins/<skin_name>
* Also, custom plugins may be added in this way
* (look ckeditor's info for details)
* If you don't need custom skins, you may remove
* ckeditorCustoms
*/
var ckeditorCustoms = new Funnel('vendor/ckeditor', {
srcDir: '/',
destDir: '/assets/ckeditor'
});
return app.toTree([ckeditorAssets, ckeditorCustoms]);
If your app is not in website's root, you may need to put this script in body section of index.html, before other scripts:
<script type="text/javascript">
window.CKEDITOR_BASEPATH = '/path-to/assets/ckeditor/';
</script>
Create a component. Warning: this is a code from my abandoned pet project, and I'm 99% sure that it will not work for you "as is" because of missing dependencies and because it was created for different html layout. But I think it may help anyway. If you wish to try and copy-paste it, here are dependencies:
npm install --save-dev ember-browserify
npm install --save-dev sanitize-html
Component's code:
/* globals CKEDITOR */
import Ember from 'ember';
import layout from '../templates/components/md-ckeditor'; //component's name!
import SanitizeHTML from 'npm:sanitize-html';
export default Ember.Component.extend({
layout: layout,
classNames: ['input-field'],
_editor: null,
bindAttributes: ['disabled', 'readonly', 'autofocus'],
validate: false,
errorsPath: 'errors',
init() {
this._super(...arguments);
const propertyPath = this.get('valueBinding._label');
if (Ember.isPresent(propertyPath)) {
Ember.Binding.from(`targetObject.${this.get('errorsPath')}.${propertyPath}`)
.to('errors')
.connect(this);
}
},
didInsertElement() {
var i18n = this.get('i18n');
if (Ember.isPresent(this.get('icon'))) {
this.$('> span').css('padding-left', '3rem');
}
this._setupLabel();
this._editor = CKEDITOR.inline(this.element.querySelector('.ckeditor'), {
skin: 'minimalist',
toolbar: [
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'],
['Undo', 'Redo'],
['Bold', 'Italic', 'Strike'],
['Link', 'Unlink'],
['NumberedList', 'BulletedList', 'Blockquote'],
['Source']
],
linkShowAdvancedTab: false,
linkShowTargetTab: false,
language: i18n.get('locale'),
removePlugins: 'elementspath'
});
this._editor.on('instanceReady', (e) => {
this._updateValidClass();
});
this._editor.on('change', (e) => {
this.set('value', e.editor.getData());
});
this._editor.on('focus', (e) => {
var label = this.$('> label, > i');
label.addClass('active');
});
this._editor.on('blur', (e) => {
var label = this.$('> label, > i');
var text = SanitizeHTML(e.editor.getData(), {
allowedTags: []
}).trim();
if (text !== '') {
label.addClass('active');
} else {
label.removeClass('active');
}
});
},
willDestroyElement()
{
this._editor.destroy();
this._editor = null;
},
id: Ember.computed('elementId', function () {
return `${this.get('elementId')}-input`;
}),
validClass: Ember.computed('value', 'errors', function () {
var errors = this.get('errors');
if (errors && errors.get && errors.get('firstObject')) {
return 'invalid';
} else if (!!this.get('value')) {
return 'valid';
} else {
return '';
}
}),
validClassChanged: Ember.observer('validClass', function () {
Ember.run.once(this, '_updateValidClass');
}),
_updateValidClass() {
if (this._editor && this._editor.container && this._editor.container.$) {
Ember.$(this._editor.container.$).removeClass('invalid valid').addClass(this.get('validClass'));
}
},
_setupLabel() {
const label = this.$('> label, > i');
if (Ember.isPresent(this.get('value'))) {
label.addClass('active');
}
}
});
Template:
{{textarea
id=id
value=value
name=name
required=required
readonly=readonly
disabled=disabled
maxlength=maxlength
class="materialize-textarea ckeditor"
classNameBindings="validate:validate: validClass"
}}
<label for="{{id}}">{{label}}</label>
<small class="red-text">
{{#if errors}} {{errors.firstObject}} {{else}} {{/if}}
</small>
Check next example
https://github.com/ebryn/ember-ckeditor/blob/master/addon/components/ember-ckeditor.js
Or next package ember-cli-ckeditor
https://www.npmjs.com/package/ember-cli-ckeditor
I'm trying to upload images to cloudinary from an EmberJS app (v2.6), following the post of Beerlington where it uses cloudinary_js (now with new API v2) and in order to install it :
npm install blueimp-file-upload --save
npm install cloudinary-jquery-file-upload --save
But when I'm trying to initialize the cloudinary the library is not recognized.
#app/initializers/cloudinary.js
export default {
name: 'cloudinary',
initialize: function(/* container, app */) {
jQuery.cloudinary.config({
cloud_name: ENV.CLOUDINARY_NAME
});
}
};
#console
TypeError: Cannot read property 'config' of undefined
Since ember.js is essentially a client side framework, you need to use bower libraries instead of npm (more).
Install Cloudinary using bower:
bower install cloudinary-jquery-file-upload --save
(blueimp will be installed as a dependency.)
Add the imports to your ember-cli-build.js file:
/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
app.import("bower_components/jquery/dist/jquery.js");
app.import("bower_components/blueimp-file-upload/js/vendor/jquery.ui.widget.js");
app.import("bower_components/blueimp-file-upload/js/jquery.iframe-transport.js");
app.import("bower_components/blueimp-file-upload/js/jquery.fileupload.js");
app.import('bower_components/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js');
return app.toTree();
};
Add jQuery to the global definitions in .jshintrc (showing fragment here):
{
"predef": [
"document",
"window",
"-Promise",
"jQuery",
"$"
],
"browser": true,
// rest of file...
}
Add cloudinary too if you intend to use the cloudinary namespace directly.
Now you can use Cloudinary and Blueimp in your code. For example:
import Ember from 'ember';
export default Ember.Route.extend(
{
model() {
$.cloudinary.config({"cloud_name": "your_cloud"});
$(document).ready(function () {
$(".cloudinary-fileupload").cloudinary_fileupload(
// etc.
)}
);
}
});
I'm new to Mocha and I am trying to use it to test a simple React component. The test would pass if the react component doesn't have any CSS styling but throws a syntax error if the tag within the React component contains any className:
Testing.react.js
import React from 'react';
export default class Testing extends React.Component {
render() {
return (
<section>
<form>
<input type="text" />
</form>
</section>
);
}
}
testing.jsx
import {
React,
sinon,
assert,
expect,
TestUtils
} from '../../test_helper';
import TestingSample from '../../../app/components/Testing.react.js';
describe('TestingSample component', function(){
before('render and locate element', function(){
var renderedComponent = TestUtils.renderIntoDocument(
<TestingSample />
);
var inputComponent = TestUtils.findRenderedDOMComponentWithTag(
renderedComponent, 'input'
);
this.inputElement = inputComponent.getDOMNode();
});
it('<input> should be of type "text"', function () {
assert(this.inputElement.getAttribute('type') === 'text');
});
})
The test would pass:
> mocha --opts ./test/javascripts/mocha.opts --compilers js:babel/register --recursive test/javascripts/**/*.jsx
TestSample component
✓ <input> should be of type "text"
1 passing (44ms)
after I added the className inside of the input tag an error shows up:
import React from 'react';
import testingStyle from '../../scss/components/landing/testing.scss';
export default class Testing extends React.Component {
render() {
return (
<section>
<form>
<input type="text" className="testingStyle.color" placeholder="Where would you like to dine" />
</form>
</section>
);
}
}
Test result:
SyntaxError: /Users/../../../Documents/project/app/scss/components/landing/testing.scss: Unexpected token (1:0)
> 1 | .color {
| ^
2 | color: red;
3 | }
I've searched online but no luck so far. Am I missing something? Please help me out or point me to the right direction would be greatly appreciated.
I'm currently using:
Node Express Server
React
React-router
Webpack
Babel
Mocha
Chai
Sinon
Sinon-Chai
There is a babel/register style hook to ignore style imports:
https://www.npmjs.com/package/ignore-styles
Install it:
npm install --save-dev ignore-styles
Run tests without styles:
mocha --require ignore-styles
you can use a css compilers run mocha, the compiler js as follow:
css-dnt-compiler.js
function donothing() {
return null;
}
require.extensions['.css'] = donothing;
require.extensions['.less'] = donothing;
require.extensions['.scss'] = donothing;
// ..etc
and run the mocha command like this:
mocha --compilers js:babel-core/register,css:css-dnt-compiler.js --recursive
My same answer as here, this is what I used to get working on Babel 6
package.json
"scripts": {
"test": "mocha --compilers js:babel-core/register
--require ./tools/testHelper.js 'src/**/*-spec.#(js|jsx)'",
tools/testHelper.js
// Prevent mocha from interpreting CSS #import files
function noop() {
return null;
}
require.extensions['.css'] = noop;
This enables you to have your tests inside your src folder alongside your components. You can add as many extensions as you would like with require.extensions.
Since you're using webpack, use null-loader to load null when webpack encounters a required CSS/LESS/SASS/etc file in your components. Install via npm and then update your webpack config to include the loader:
{
test: /(\.css|\.less|.\scss)$/,
loader: 'null-loader'
}
Obviously this will prevent you from loading CSS in your actual application, so you'll want to have a separate webpack config for your test bundle that uses this loader.
For those looking how to handle this in jest - you just add a handler for style files:
// package.json
{
"jest": {
"moduleNameMapper": {
"\\.(css|less|scss|sass)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}
// __mocks__/styleMock.js
module.exports = {};
More here.
None of these solutions worked for me, as I'm using mocha-webpack, and it doesn't accept the "--compilers" switch. I implemented the ignore-styles package, as described in the most popular answer, but it seemed inert, with no difference in my Istanbul coverage report (.less files still being tested).
The problem is the .less loader that I was using in my webpack.config.test.js file. Simply swapping less-loader for null-loader fixed my problem.
module: {
rules: [
{
test: /\.less$/,
use: ['null-loader']
}
]
}
For me, this is by far the simplest solution, and targets my testing configuration directly, rather than having to alter/add to the package.json scripts, or worse, add new .js files.
One simple way is to import 'ignore-styles'; in your test classes..
The code below works without any dependencies. Just add it to the top of the tests.
var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function () {
if (arguments[0] && arguments[0].endsWith(".css"))
return;
return originalRequire.apply(this, arguments);
};
Although very old, this question is still relevant, so let me throw in another solution.
Use pirates, a package to add hooks to require() - if you use Babel, you already have it.
Example code:
// .test-init.js
const { addHook } = require('pirates');
const IGNORE_EXTENSIONS = ['.scss', '.svg', '.css'];
addHook((code, filename) => '', { exts: IGNORE_EXTENSIONS });
This way you can call mocha like so: mocha --require .test-init.js [whatever other parameters you use]
This is straightforward, elegant and unlike ignore-styles it doesn't imply you are ignoring styles only. Also, this is easily extendable if you need to apply some more trickery to your tests like mocking entire modules.