I am having a really hard time using local AMD modules in an Aurelia project that uses es6, JSPM, and system.js. I am hoping someone out there can help me configure my project to enable me to import/load my AMD modules and use them in my project. The local AMD style modules are in a format similar to the following:
define
(['require',
'lib/alerts/STARTSTOP',
'lib/alerts/STOPPED',
...
],
function( require, STARTSTOP, STOPPED, ... ) {
return {
alert: function( data ) {
var type = data.type;
var ev = data.event;
var cls = require( 'lib/alerts/' + ev );
return new cls( data );
}
};
});
When I try to import/load this module into an es6 module I am running into the following error: Uncaught TypeError: Unexpected anonymous AMD define.. I get this error when trying to load the module in either of the following ways:
System.import('lib/alerts/AlertFactory').then( (m) => {
console.log( m );
});
or
import AlertFactory from 'lib/alerts/AlertFactory.js';
I have also made sure to add the following script to my index.html:
<script>
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
</script>
In addition to the above I have also added a meta format property to my config.js file, but that hasn't seemed to help either.
meta: {
...
"lib/alerts/*.js": {
"format": "amd"
}
}
Does anyone have any ideas on why I am running into the error I am seeing and how to properly load my modules? I appreciate any help/insight you can offer.
UPDATE
I finally realized that the main issue here is that I'm trying to use existing AMD modules in and Aurelia project, and the default Aurelia gulp build assumes that all code is written in ES6 and not mixed with AMD. That's why I'm having issues. Vanilla jspm/system.js handle a mix of module formats, but Aurelia does not out of the box.
Just put your AMD modules out of src so babel will not be able to transpile it. Here is working solution I use to import jquery modules:
First, I have local_packages folder in project root and I have jquery module local_packages/somelib/js/mymodule.js
Then in config.js
paths: {
...
"local/*": "local_packages/*",
}
map: {
...
"somelib": "local/somelib",
"somelib1": "/local_packages/somelib1",
}
And finally my import looks like: import 'somelib/js/mymodule';
Related
I am building a new project in Rails 6. I have a front-end library I want to use (#tarekraafat/autocomplete.js) that is installed by yarn and exists in my node_modules directory, but is not being made available to other JS code in the browser. Here is what I have set up currently:
/package.json:
"dependencies": {
"#tarekraafat/autocomplete.js": "^8.2.1"
}
/app/javascript/packs/application.js:
import "#tarekraafat/autocomplete.js/dist/js/autoComplete.min.js"
/app/views/.../example.html.erb
<script type="text/javascript">
window.onload = () => {
new autoComplete({
[...]
});
};
</script>
I am getting an error in the browser pointing to the new autoComplete():
Uncaught ReferenceError: autoComplete is not defined
Some reading seems to indicate that I need to modify the /config/webpack/environment.js file, in which I have tried various versions of the following with no luck (including restarting the dev server):
/config/webpack/environment.js:
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
autoComplete: 'autocomplete.js'
})
);
module.exports = environment
First, what do I need to do to add this library so it can be used correctly? Second, as someone who has not directly used webpack previously, what is the function of adding this definition to the environments.js file, and why don't I need to do it for some libraries (bootstrap, popper) but I do for others (jquery, and maybe autocomplete.js)?
In Webpacker, the usage of this library would be as follows:
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
new autoComplete(...)
// app/javascript/packs/application.js
import "../src/any_file"
This alone does not import the autoComplete variable into the global scope. To do that, the simplest thing is assign the variable to window from within your webpack dependency graph.
// app/javascript/src/any_file.js
import autoComplete from "#tarekraafat/autocomplete"
window.autoComplete = autoComplete
As an aside, you don't need to use the ProvidePlugin configuration for this library. The ProvidePlugin says: “add this import to all files in my dependency graph.” This might be helpful for something like jQuery to make legacy jQuery plugins work in webpack. It is not necessary to make your autocomplete lib work
I'm running a gulp-concat script, which concats jquery, slick-carousel, t.js and my index.js files.
const pack = () => {
return gulp.src(['./node_modules/jquery/**/jquery.js', './node_modules/slick-carousel/**/slick.js', './assets/js/t.js-master/t.js', './js/index.js'])
// .pipe(gulp_babel({
// 'presets': ['#babel/env'],
// 'plugins': ["transform-remove-strict-mode"]
// }))
.pipe(gulp_concat('main.js'))
// .pipe(gulp_uglify())
.pipe(gulp.dest('./build'));
}
As you can see, I removed any pipes that might be causing the issue. The only task running is gulp-concat. (index.js is all in ES5 and I'm running on latest version of firefox, no need for babel atm) When I open my page, however, I get the error
Uncaught ReferenceError: define is not defined
Looking at main.js, I found a define object at the end of the jquery section - but only in the concatinated file, not the jquery in node_modules. I didn't add this, and I'm not using require.js as far as I know:
define( [
"./core",
"./selector",
"./traversing",
"./callbacks",
"./deferred",
"./deferred/exceptionHook",
"./core/ready",
"./data",
"./queue",
"./queue/delay",
"./attributes",
"./event",
"./event/focusin",
"./manipulation",
"./manipulation/_evalUrl",
"./wrap",
"./css",
"./css/hiddenVisibleSelectors",
"./serialize",
"./ajax",
"./ajax/xhr",
"./ajax/script",
"./ajax/jsonp",
"./ajax/load",
"./core/parseXML",
"./core/parseHTML",
"./effects",
"./effects/animatedSelector",
"./offset",
"./dimensions",
"./deprecated",
"./exports/amd",
"./exports/global"
], function( jQuery ) {
"use strict";
return jQuery;
} ); // jQuery seems to end here
How is this extra code being added, and how might I avoid it? I'm also using browserSync, but don't think that's related.
I've just checked the source of jQuery and there is a file:
https://github.com/jquery/jquery/blob/3.5.1/src/jquery.js
So what you need to do is to simply exclude it and it should fix the issue :)
I am working with an existing application (canvas-lms) that uses RequireJS in its build system. I'm working on a pseudo-standalone application that plugs into Canvas (a "client_app" in Canvas parlance). This is a fontend-only app that makes API calls back to the host Canvas app. The details aren't terribly important for my question - all a client_app needs to do is have a build script that spits out a JS file in a defined place within the Canvas app tree.
I'm trying to use Webpack to build my app instead of RequireJS. Everything works great if I keep all my dependencies self-contained (e.g. npm-install everything I need); however, Canvas already provides many of these dependencies (e.g. React, jQuery), and in jQuery's case, it provides a patched version that I'd like to use instead. This is where I start to have problems.
Getting React to work was easy; Canvas installs it with bower, so I was able to add an alias in my webpack config to point at it:
alias: {
'react': __dirname + '/vendor/canvas/public/javascripts/bower/react/react-with-addons',
}
(__dirname + /vendor/canvas is a symlink in my application tree to the host Canvas application's tree)
Where I'm having trouble is trying to load the provided copy of jQuery.
Canvas has the following jQuery structure:
/public/javascripts/jquery.js:
define(['jquery.instructure_jquery_patches'], function($) {
return $;
});
/public/javascripts/jquery.instructure_jquery_patches.js:
define(['vendor/jquery-1.7.2', 'vendor/jquery.cookie'], function($) {
// does a few things to patch jquery ...
// ...
return $;
});
/public/javascripts/vendor/jquery.cookie.js -- looks like the standard jquery.cookie plugin, wrapped in an AMD define:
define(['vendor/jquery-1.7.2'], function(jQuery) {
jQuery.cookie = function(name, value, options) {
//......
};
});
and finally, /public/javascripts/vendor/jquery-1.7.2.js. Not going to paste it in, since it's bog-standard jQuery1.7.2, except that the AMD define has been made anonymous -- reverting it to the stock behaviour doesn't make a difference.
I want to be able to do something like var $ = require('jquery') or import $ from 'jquery' and have webpack do whatever magic, poorly-documented voodoo it needs to do to use jquery.instructure-jquery-patches.
I've tried adding the path to resolve.root in my webpack.config.js file:
resolve: {
extensions: ['', '.js', '.jsx'],
root: [
__dirname + '/src/js',
__dirname + '/vendor/canvas/public/javascripts'
],
alias: {
'react': 'react/addons',
'react/addons/lib': 'react/../lib'
}
},
This should mean that when I do a require('jquery'), it first finds /public/javascripts/jquery.js, which defines a module with instructure_jquery_patches as a dependency. That falls into instructure_jquery_patches, which defines a module with two dependencies ('vendor/jquery-1.7.2', 'vendor/jquery.cookie').
In my main entry point (index.js), I am importing jQuery (also tried a commonjs require, no difference), and trying to use it:
import React from 'react';
import $ from 'jquery';
$('h1').addClass('foo');
if (__DEV__) {
require('../scss/main.scss');
window.React = window.React || React;
console.log('React: ', React.version);
console.log('jQuery:', $.fn.jquery);
}
Building the bundle with webpack seems to work; there are no errors. When I try to load the page in the browser, though, I'm getting an error from within jquery.instructure-jquery-patches.js:
It would seem that jQuery is not availble within jquery.instructure-jquery-patches.
It is, however, available in the global scope after the page loads, so jQuery is being evaluated and executed.
My guess is that I'm running into some sort of requirejs/amd asynchronicity problem, but that's a shot in the dark. I don't know enough about requirejs or amd to know for sure.
TobiasK's comment pointed me at needing to add amd: { jQuery: true } to my webpack config. Everything is working now.
I'm trying to dynamically load custom modules based on a data attribute. It's almost working perfectly but for some reasons my module is called twice with different paths and I can't figure why.
My project structure looks like that:
+ Assets
+ js
• main.js
+ libs
+ modules
• mod.env.js
• mod.utils.js
• mod.session.js
+ plugins
+ views
• signup.js
• login.js
• home.js
In my main.js file I have some basic configuration:
require.config({
baseUrl: '/Assets/js',
paths: {
// Libs
'jquery' : 'libs/jquery/jquery-2.0.3.min',
// Module for the project
'env': 'modules/atmco.env',
'utils': 'modules/atmco.utils',
'session': 'modules/atmco.session'
}
});
Still in the main.js file is where I put the logic for the conditial loading of the modules:
require(['require', 'jquery','env'],
function ( require, $, env ) {
'use strict';
function init() {
// Grab the modules/pages on the data attribute of the body
var modules = $('body').data('modules') || '';
var pages = $('body').data('page') || '';
// Initialize the environment stuff for your project
env.initEnv();
if ( pages ) {
require(['./views/' + pages.toLowerCase().split(/\s*,\s*/)[0]]);
}
}
// Initialize the application when the dom is ready
$(function () {
init();
});
}
);
My page has the right attributes (<body data-page="Signup" data-module="">) but for some reasons requirejs tries to call 2 different files:
The custom module is called as expected
"/Assets/js/views/signup.js"
Then it tries to call "/Assets/js/signup.js" which doesn't exists
Finally, here's a look at how I define my custom module, including the custom name. It seems pretty basic:
define('view/signup',
['utils'],
function ( utils ) {
console.log('my module' + utils.lang );
return {
};
}
);
If anyone could point me to my mistake it would really help me with my app and understanding better how requirejs works. Thanks a lot!
Found the solution:
Naming (or naming in fact) the module was actually messing the module definition. Therefor I just needed to adjust the code to:
define(
['utils'],
function ( utils ) {
console.log('my module' + utils.lang );
return {
};
}
);
This question really helped me out figuring it:
Requirejs function in define not executed
My page includes several components that exist as separate AMD modules. Each of these components is turned into a single file by the Require.js optimiser. Because several of these components share dependencies (e.g. jQuery and d3), the optimiser paths config uses CDN URLs for those dependencies, rather than bundling them into the optimised file.
Here's where it gets tricky. I've written a module loader plugin for Ractive.js called rvc.js, which allows me to include Ractive components that are defined in HTML files. (Yes, I'm asking for help on how to use my own library.)
This works fine - code like this gets optimised as you'd expect:
define( function ( require ) {
var ChartView = require( 'rvc!views/Chart' );
var view = new ChartView({ el: 'chart' });
});
Because Ractive is used by several of the components, it should be served from a CDN like jQuery and d3. But it's used by rvc.js during the optimisation process, which means that the Ractive entry for the optimiser's paths config can't point to a CDN - it has to point to a local file.
Is there a way to tell Require.js 'use the local file during optimisation, but load from CDN at runtime'?
So here's the solution I eventually settled on. It feels somewhat kludgy, but it works:
Stub out the loaders and the library you don't want bundled
Add an onBuildWrite function that rewrites modules depending on the library, so that they think they're requiring something else entirely - in this case Ractive_RUNTIME
Add an entry to your runtime AMD config's paths object, so that Ractive_RUNTIME points to the CDN
My optimiser config now looks like this:
{
baseUrl: 'path/to/js/',
out: 'build/js/app.js',
name: 'app',
optimize: 'none',
paths: {
'amd-loader': 'loaders/amd-loader',
'rvc': 'loaders/rvc',
'Ractive': 'lib/Ractive'
},
stubModules: [ 'amd-loader', 'rvc', 'Ractive' ],
onBuildWrite: function ( name, path, contents ) {
if ( contents === "define('Ractive',{});" ) {
// this is the stub module, we can kill it
return '';
}
// otherwise all references to `Ractive` need replacing
return contents.replace( /['"]Ractive['"]/g, '"Ractive_RUNTIME"' );
}
}
Meanwhile, the script that loads the app.js file created by the optimiser has a config entry that points to the CDN:
require.config({
context: uniqueContext,
baseUrl: baseUrl,
paths: {
'amd-loader': 'loaders/amd-loader',
'rvc': 'loaders/rvc',
'Ractive': 'lib/Ractive',
'Ractive_RUNTIME': 'http://cdn.ractivejs.org/releases/0.3.9/Ractive.min'
}
});