The basic idea is to start with a new JHipster project (v5.8.2) and integrate the Metronic Angular theme in it.
I haven't found much in the way of documentation for this task, but sluggishly I've integrated the various css/js bundles, the components, however I ran across a problem with some of their directives.
So basically in toggle.directive.ts after the view initiates it tries to create a new KTToggle see
ngAfterViewInit(): void {
this.toggle = new KTToggle(this.el.nativeElement, this.options);
}
KTToggle is defined in scripts.bundle.js that I've already imported in vendor.ts.
I've also copied typings.d.ts file from metronic in src/main/webapp/app.
The problem is that it doesn't find KTToggle, when running npm run webpack:build I get no error, but when actually trying to access the page I get
ERROR ReferenceError: "KTToggle is not defined"
Additionally in IntelliJ I get the following error
TS2350: Only a void function can be called with the 'new' keyword
I tried to declare KTToggle straight in the directive
declare var KTToggle: any;
But this give me the same ReferenceError.
Also in tsconfig.json I tried to point to the typings file through typeRoots, types, files all gave me either the same error or for types caused other parts of the app to fail.
I'm not too experienced with Angular/Webpack but I suspect the typing is not properly loaded, because if I try to go to the definition of KTToggle in IntelliJ it points me to the scripts.bundle.js file.
I welcome any kind of help, thank you.
Additional info:
typings.d.ts
/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
id: string;
}
declare var KTMenu: any;
declare var KTOffcanvas: any;
declare var KTScrolltop: any;
declare var KTHeader: any;
declare var KTToggle: any;
declare var KTUtil: any;
declare var KTPortlet: any;
declare var KTDialog: any;
declare var Chart: any;
scripts.bundle.js
.....
KTToggle=function(t,e){var n=this,i=KTUtil.get(t);KTUtil.get("body");if(i){var o={togglerState:"",targetState:""}
....
L.E. 2020-04-11
What we ended up doing was setting a new entry point in the the webpack configuration file (both dev and prod), like this:
entry: {
global: './src/main/webapp/content/scss/global.scss',
main: './src/main/webapp/app/app.main',
// metronic scripts bundled, contains needed JS for Metronic functionalities
metronicScripts: [
'./src/main/webapp/content/metronic/assets/demo/default/base/scripts.bundle.js'
]
},
and then in the common webpack configuration we modified the HtmlWebpackPlugin to include the new chunk like so:
new HtmlWebpackPlugin({
template: './src/main/webapp/index.html',
chunks: [
// include metronic bundle before the main bundle so that we can utilize metronic variables in components and initialize the layout for example
'metronicScripts'
,'polyfills'
,'main'
,'global'
],
chunksSortMode: 'manual',
inject: 'body'
}),
Afterwards we could use the various elements from metronic inside components like so
...
declar var KTUtil: any;
#Component({...})
...
ngOnInit() {
KTUtil.init();
}
(ERROR ReferenceError: "KTToggle is not defined") mean you not load the script file toggle.js,
So make sure you load all what Metronic loaded in index.html file and not delete imports of it, by default Metronic load this files in index.html :
<script src="assets/js/global/components/base/util.js" type="application/javascript"></script>
<script src="assets/js/global/components/base/header.js" type="application/javascript"></script>
<script src="assets/js/global/components/base/menu.js" type="application/javascript"></script>
<script src="assets/js/global/components/base/offcanvas.js" type="application/javascript"></script>
<script src="assets/js/global/components/base/scrolltop.js" type="application/javascript"></script>
<script src="assets/js/global/components/base/toggle.js" type="application/javascript"></script>
<script src="assets/js/global/components/base/dialog.js" type="application/javascript"></script>
<script src="assets/js/global/components/base/wizard.js" type="application/javascript"></script>
For someone stumbling upon this question, looking for answers, adding the reference to bundled files in angular.json file, resolved the issue for me.
"architect": {
"build": {
...
"options": {
....
"scripts": [
"src/assets/vendors/global/vendors.bundle.js",
"src/assets/js/demo1/scripts.bundle.js"
],
..
}
..
}
I am trying to use full page with angular 2,
I am getting the below error when importing it in my app.module.ts.
"(SystemJS) Unexpected token <
SyntaxError: Unexpected token <
at eval (<anonymous>)
at Object.eval (http://localhost:3000/app/app.module.js:16:22)
at eval (http://localhost:3000/app/app.module.js:40:4)
at eval (http://localhost:3000/app/app.module.js:41:3)
at eval (<anonymous>)
Evaluating http://localhost:3000/node_modules/ng2-fullpage
Evaluating http://localhost:3000/app/app.module.js
Evaluating http://localhost:3000/main.js
Error loading http://localhost:3000/main.js"
Below are my files:
systemjs.config.js
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// '#jquery':'npm:jquery/jquery.min.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ng2-fullpage': 'npm:ng2-fullpage',
// 'jquery': 'npm:jquery/dist/jquery.js',
'fullpage.js': 'npm:fullpage.js/jquery.fullPage.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
// format:'register',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import {HttpModule} from '#angular/http';
import {routing} from './app.routing';
import {NavbarComponent} from './components/navbar/navbar.component';
import { MnFullpageDirective } from 'ng2-fullpage';
import {MnFullpageService} from 'ng2-fullpage';
import { AppComponent } from './app.component';
import { ResumeComponent } from './components/resume/resume.component';
import { AboutComponent } from './components/about/about.component';
import {HomeComponent} from './components/home/home.component';
#NgModule({
imports: [ BrowserModule,HttpModule, routing ],
declarations: [ AppComponent, ResumeComponent, AboutComponent, HomeComponent, NavbarComponent,
MnFullpageDirective
],
bootstrap: [ AppComponent ],
providers: [MnFullpageService]
})
export class AppModule { }
index.html
<!DOCTYPE html>
<html>
<head>
<title>Nakul Chawla</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://bootswatch.com/cyborg/bootstrap.min.css" />
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="styles.css">
<!--<link rel="stylesheet" href="../node_modules/fullpage.js/dist/jquery.fullpage.css" />-->
<!--<script src="node_modules/jquery/jquery.js"></script>-->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<base href="/">
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
I am taking help from the npm page which reference a plunkr:
npm package
enter link description here
http://embed.plnkr.co/1p9zKp4CNI1HncAh1h9m
plunkr
I have seeked help from other stack overflow pages and tried everything, but the error seems to persist.
I have posted another variation of the question on stackoverflow, both errors have the same issue.
Unable to load ng2-fullpage in my angular-2 quickstart app
I have no clue how to resolve this, tried everything now.
Thanks in advance.
There are certainly many issues that may lead to this error. I got it when using SystemJS in connection with web-servers such as live-server that offer a convenient function for single page web applications, namely to route all non-existing files to the index.html of the project. So if SystemJS tries to resolve a dependency that is not installed, the webserver will present the index.html that most often starts with <!DOCTYPE html>. This may be the unexpected < mentioned in the error.
Solution:
Check if your server routes non-existing files to an html file.
Stop routing for the debugging.
Launch your application. Find out using the network tab in your browser tools which files get an 404 error.
Install missing dependencies using jspm install my_dependency.
Iterate until all files can be found.
Enable routing of missing files to some html file, again.
I wrote a custom mode for the ACE editor
my-mode.js
ace.define('my-mode', [/* ... */], function(require, exports, module) { /* ... */ });
that I try to use
index.js
var editor = ace.edit('editor');
editor.getSession().setMode('my-mode');
I installed the ACE editor (ace-builds) and requirejs with bower
bower.json
{
"name": "my-project",
"dependencies": {
"ace-builds": "^1.2.3",
"requirejs": "^2.2.0"
}
}
and configured requirejs
requirejs-config.js
require.config({
paths: {
ace: "bower_components/ace-builds/src-noconflict/ace"
}
});
My page looks like this
index.html
<body>
<div id="editor"></div>
<script src="bower_components/requirejs/require.js"></script>
<script src="requirejs-config.js"></script>
<script src="bower_components/ace-builds/src-noconflict/ace.js"></script>
<script src="my-mode.js"></script>
<script src="index.js"></script>
</body>
Sadly, the call
editor.getSession().setMode('my-mode');
leads to an error
Failed to load resource: http://localhost:5555/bower_components/ace-builds/src-noconflict/mode-my-mode.js
the server responded with a status of 404 (Not Found)
How can I configure ace and requirejs such that my-mode is found?
I found a solution. Before my-mode is used (for example at the beginning of index.js) call
ace.config.setModuleUrl('my-mode', '/path/to/my-mode.js');
I'm writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for the style.
index.js
import * as stylesheet from '../assets/styles/app.scss';
import * as jquery2 from '../dist/scripts/jquery.min';
import * as jquery3 from '../node_modules/jquery/dist/jquery.min';
console.log($('my-app'));
index.html
<!DOCTYPE html>
<html lang="fr">
<head>
<body>
<script src="dist/app.js"></script>
</body>
</html>
Project structure
.
├── app/
│ ├── index.js
├── assets/
├── dist/
│ ├── scripts/
│ │ ├── jquery.min.js
├── index.html
├── node_modules/
│ ├── jquery/
│ │ ├── dist/
│ │ │ ├── jquery.min.js
├── package.json
└── tests/
package.json
…
"scripts": {
"build:app": "browserify -e ./app/index.js -o ./dist/app.js",
"copy:jquery": "cpy 'node_modules/jquery/dist/jquery.min.js' ./dist/scripts/",
…
},
"devDependencies": {
"babel-core": "6.3.x",
"babel-preset-es2015": "6.3.x",
"babelify": "7.2.x",
"cpy": "3.4.x",
"npm-run-all": "1.4.x",
"sassify": "0.9.x",
"semantic-ui": "2.1.x",
…
},
"browserify": {
"transform": [
[ "babelify", { "presets": [ "es2015"]}],
[ "sassify", { "auto-inject": true}]
]
}
Question
Using classic <script> tag to import jquery works fine, but I'm trying to use the ES6 syntax.
How do I import jquery to satisfy semantic-ui using ES6 import syntax?
Should I import from the node_modules/ directory or my dist/ (where I copy everything)?
index.js
import {$,jQuery} from 'jquery';
// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;
First, as #nem suggested in comment, the import should be done from node_modules/:
Well, importing from dist/ doesn't make sense since that is your distribution folder with production ready app. Building your app should take what's inside node_modules/ and add it to the dist/ folder, jQuery included.
Next, the glob –* as– is wrong as I know what object I'm importing (e.g. jQuery and $), so a straigforward import statement will work.
Last you need to expose it to other scripts using the window.$ = $.
Then, I import as both $ and jQuery to cover all usages, browserify remove import duplication, so no overhead here! ^o^y
Based on the solution of Édouard Lopez, but in two lines:
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
You can create a module converter like below:
// jquery.module.js
import 'https://code.jquery.com/jquery-3.6.0.min.js'
export default window.jQuery.noConflict(true)
This will remove global variables introduced by jQuery (jQuery & $) and export jQuery object as default.
Then use it in your script:
// script.js
import $ from "./jquery.module.js";
$(function(){
$('body').text('youpi!');
});
Do not forget to load it as a module in your document:
<script type='module' src='./script.js'></script>
http://plnkr.co/edit/a59ETj3Yo2PJ0Aqkxbeu?p=preview
Import the entire JQuery's contents in the Global scope. This inserts $ into the current scope, containing all the exported bindings from the JQuery.
import * as $ from 'jquery';
Now the $ belongs to the window object.
If it helps anyone, javascript import statements are hoisted. Thus, if a library has a dependency (eg bootstrap) on jquery in the global namespace (window), this will NOT work:
import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
import 'bootstrap/dist/js/bootstrap.min';
This is because the import of bootstrap is hoisted and evaluated before jQuery is attached to window.
One way to get around this is to not import jQuery directly, but instead import a module which itself imports jQuery AND attaches it to the window.
import jQuery from './util/leaked-jquery';
import 'bootstrap/dist/js/bootstrap.min';
where leaked-jquery looks like
import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
export default $;
export { jQuery };
EG, https://github.com/craigmichaelmartin/weather-app--birch/blob/4d9f3b03719e0a2ea3fb5ddbbfc453a10e9843c6/javascript/util/leak_jquery.js
The accepted answer did not work for me
note : using rollup js dont know if this answer belongs here
after
npm i --save jquery
in custom.js
import {$, jQuery} from 'jquery';
or
import {jQuery as $} from 'jquery';
i was getting error :
Module ...node_modules/jquery/dist/jquery.js does not export jQuery
or
Module ...node_modules/jquery/dist/jquery.js does not export $
rollup.config.js
export default {
entry: 'source/custom',
dest: 'dist/custom.min.js',
plugins: [
inject({
include: '**/*.js',
exclude: 'node_modules/**',
jQuery: 'jquery',
// $: 'jquery'
}),
nodeResolve({
jsnext: true,
}),
babel(),
// uglify({}, minify),
],
external: [],
format: 'iife', //'cjs'
moduleName: 'mycustom',
};
instead of rollup inject, tried
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
// 'node_modules/jquery/dist/jquery.js': [ '$' ]
// 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};
package.json
"devDependencies": {
"babel-cli": "^6.10.1",
"babel-core": "^6.10.4",
"babel-eslint": "6.1.0",
"babel-loader": "^6.2.4",
"babel-plugin-external-helpers": "6.18.0",
"babel-preset-es2015": "^6.9.0",
"babel-register": "6.9.0",
"eslint": "2.12.0",
"eslint-config-airbnb-base": "3.0.1",
"eslint-plugin-import": "1.8.1",
"rollup": "0.33.0",
"rollup-plugin-babel": "2.6.1",
"rollup-plugin-commonjs": "3.1.0",
"rollup-plugin-inject": "^2.0.0",
"rollup-plugin-node-resolve": "2.0.0",
"rollup-plugin-uglify": "1.0.1",
"uglify-js": "2.7.0"
},
"scripts": {
"build": "rollup -c",
},
This worked :
removed the rollup inject and commonjs plugins
import * as jQuery from 'jquery';
then in custom.js
$(function () {
console.log('Hello jQuery');
});
webpack users, add the below to your plugins array.
let plugins = [
// expose $ and jQuery to global scope.
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
];
I did not see this exact syntax posted yet, and it worked for me in an ES6/Webpack environment:
import $ from "jquery";
Taken directly from jQuery's NPM page. Hope this helps someone.
If you are not using any JS build tools/NPM, then you can directly include Jquery as:
import 'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;
You may skip import(Line 1) if you already included jquery using script tag under head.
import {jQuery as $} from 'jquery';
My project stack is: ParcelJS + WordPress
WordPress got jQuery v1.12.4 itself and I have also import jQuery v3^ as module for other depending modules as well as bootstrap/js/dist/collapse, for example... Unfortunately, I can’t leave only one jQuery version due to other WordPress modular dependencies.
And ofcourse there is conflict arises between two jquery version. Also keep in mind we got two modes for this project running Wordpress(Apache) / ParcelJS (NodeJS), witch make everything little bit difficulty. So at solution for this conflict was searching, sometimes the project broke on the left, sometimes on the right side.
SO... My finall solution (I hope it so...) is:
import $ from 'jquery'
import 'popper.js'
import 'bootstrap/js/dist/collapse'
import 'bootstrap/js/dist/dropdown'
import 'signalr'
if (typeof window.$ === 'undefined') {
window.$ = window.jQ = $.noConflict(true);
}
if (process) {
if (typeof window.jQuery === 'undefined') {
window.$ = window.jQuery = $.noConflict(true);
}
}
jQ('#some-id').do('something...')
/* Other app code continuous below.......... */
I still didn’t understand how myself, but this method works. Errors and conflicts of two jQuery version no longer arise
Pika is a CDN that takes care of providing module versions of popular packages
<script type='module'>
import * as $ from 'https://cdn.skypack.dev/jquery';
// use it!
$('#myDev').on('click', alert);
</script>
Skypack is Pika, so you could also use: import * as $ from 'https://cdn.pika.dev/jquery#^3.5.1';
import $ from 'jquery'
// export for others scripts to use
window.$ = window.jQuery = $
First of all, install and save them in package.json:
npm i --save jquery
npm i --save jquery-ui-dist
Secondly, add a alias in webpack configuration:
resolve: {
root: [
path.resolve(__dirname, '../node_modules'),
path.resolve(__dirname, '../src'),
],
alias: {
'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
},
extensions: ['', '.js', '.json'],
}
It work for me with the last jquery(3.2.1) and jquery-ui(1.12.1).
See my blog for detail: http://code.tonytuan.org/2017/03/webpack-import-jquery-ui-in-es6-syntax.html
Import jquery (I installed with 'npm install jquery#1.9.1')
import 'jquery/jquery.js';
Put all your code that depends on jquery inside this method
+function ($) {
// your code
}(window.jQuery);
or declare variable $ after import
var $ = window.$
I wanted to use the alread-buildy jQuery (from jquery.org) and all the solutions mentioned here didn't work, how I fixed this issue was adding the following lines which should make it work on nearly every environment:
export default ( typeof module === 'object' && module.exports && typeof module.exports.noConflict === 'function' )
? module.exports.noConflict(true)
: ( typeof window !== 'undefined' ? window : this ).jQuery.noConflict(true)
You can import like this
import("jquery").then((jQuery) => {
window.$ = jQuery;
window.jQuery = jQuery;
import("bootstrap").then((_bs)=>{
$(function() {});
})
});
If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:
new webpack.ProvidePlugin({
'window.jQuery': 'jquery'
});
The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.
http://requirejs.org/
I recently downloaded require.js 2.0 and I am getting error in my console:
Uncaught TypeError: Object function (){var g=ga.call(arguments,0),e;if(f&&v(e=g[g.length-1]))e.__requireJsBuild=!0;g.push(d);return b.apply(null,g)} has no method 'nameToUrl'
Is order.js plugin still supported by requirejs? I don't see its documentation in the website.
When I try to remove the file the script breaks.
In my index file, I included requirejs script in the head section:
<!DOCTYPE html>
<html>
<head>
<title>
My Mobile Application
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<link rel="stylesheet" href="public/css/style.css" />
<script data-main="scripts/main.js" src="scripts/require.js"></script>
</head>
<body></body>
</html>
Then in my main.js file:
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
app: '../app',
assets: '../assets',
views: '../app/views',
templates: '../app/templates',
collections: '../app/collections',
models: '../app/models'
}
});
// Start the main app logic.
requirejs([
'jquery/jquery',
'assets/jqm.config',
'jquery/mobile',
'text'
]);
require([
'app'
],
function( App ){
$(document).ready( function(){
App.initialize();
});
}
);
I sees to it that App.initialize doesn't have any errors and what App.initialize is doing is just simple geo location. The requirejs simply ask for order.js, and when I put the code it's having the same error as mentioned above.
Thank you!
Your assumption that order is no longer supported is correct. It was removed in favour of the shim configuration option:
So, the the order plugin has been removed and following the lead of
Tim Branyen and Dave Geddes, of use and wrap respectively, requirejs
2.0 integrates that kind of dependency tree specification directly in requirejs.
Require 2.0 upgrade notes - https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0
Also, check the shim documentation on the RequireJS site - http://requirejs.org/docs/api.html#config-shim
Oh figured it out.
//This is our main applicatoon boot loader or bootstrap
//here we are loading necessary scripts dependencies like
//jquery, jqm.config, mobile, text
requirejs.config({
baseUrl: 'js/libs',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
app: '../app',
assets: '../assets',
views: '../app/views',
templates: '../app/templates',
collections: '../app/collections',
models: '../app/models'
}
});
// Start the main app logic.
require(["jquery","assets/jqm.config","jquery/mobile","text","app"],
function(
$,
config,
mobile,
text,
App
) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
App.initialize();
});
});