I am developing a set of modules for others to use using dojo 1.7. All modules are AMD modules and using relative paths within the package. My modules will need to be loaded cross domain, and not interfere with or care about the version of dojo running on the page consuming the modules (Let's assume someone is using. If I understand the documentation correctly, I can specify a packing remapping by doing something like this:
var dojoConfig = {
packages: [
{
name: "myDojo",
location: "path/to/my/dojo",
packageMap: {
dojo: "myDojo",
dijit: "myDijit",
dojox: "myDojox"
}
},
{
name: "myDijit",
location: "path/to/my/dijit",
packageMap: {
dojo: "myDojo"
}
},
{
name: "myDojox",
location: "path/to/my/dojox",
packageMap: {
dojo: "myDojo",
dijit: "myDijit",
dojox: "myDojox"
}
},
{
name: "myPackage",
location: "path/to/my/package",
packageMap: {
dojo: "myDojo",
dijit: "myDijit",
dojox: "myDojox"
}
}
]
}
Is there a way to burn the remapping into a dojo build so that using any module in my package will automatically use my dojo/dijit/dojox modules instead of the ones loaded in the local version of dojo? If so, what would the profile look like? If possible, I would like consumers to be able to do something like this:
<html>
<head>
<script src="some/differnt/version/of/dojo.js" type="text/javascript" data-dojo-config="config settings"></script>
<script type="text/javascript">
// For legacy syntax users:
dojo.registerModulePath("hisPackage", "http://somedomain.com/scripts/myPackage");
dojo.require("hisPackage.HisModule");
dojo.ready(function() {
// do stuff
});
// Or for AMD users:
require(["http://somedomain.com/scripts/myPackage/MyModule"], function(HisModule) {
// do stuff
}
</script>
</head>
<body></body>
</html>
Thanks in advance for any help.
Did you try this in your dojoConfig
var dojoConfig = { ...
packages: [
{name:'dojo',location:'//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/'},
{name:'dijit',location:'//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dijit/'},
'dojotut'
]
...
}
Related
I'm working on an aurelia project, using typescript to create the javascript. Now I tried to add another custom library, 'hash-set' (using jspm install npm:hash-set --save). However I can't seem to actually use this package (using systemjs as loader).
My document structure is like:
\
dist\
src\
app.html
app.js
main.js
jsp_packages\
npm\
hash-set#1.0.1\
node_modules\
index.html
config.js
package.json
tsconfig.json
The important files (I think, please state in the comments if I miss something):
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body aurelia-app="src/main">
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script>
SystemJS.import('aurelia-bootstrapper');
</script>
</body>
</html>
app.ts
This is compiled to app.js as prebuilt step. Using es2015 as target configuration.
import {hashSet} from 'hash-set';
export class App {
public myText: string;
hashFn(value) {
return value.toString();
}
constructor() {
alert("oh");
const h = hashSet;
const StringSet = hashSet(this.hashFn);
alert('oh2');
}
}
config.js
System.config({
defaultJSExtensions: true,
transpiler: false,
paths: {
"*": "dist/*",
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
meta: {
"bootstrap": {
"deps": [
"jquery"
]
}
},
map: { /*lots of aurelia and other library stuff*/
"hash-set": "npm:hash-set#1.0.1"
}
}
});
And it's also listed in package.json # {"jspm":{"dependencies":"hash-set": "npm:hash-set#^1.0.1"}}}
Now when I try to run above code (typescript compiles to app.js as prebuilt step), the app.js/app.ts loads, as expected. (frankly removing the hash-set specific code makes everything work as expected).
However during construction "oh" is shown, but "oh2" is never. Debugging over the code shows that "hashSet" is "undefined". Which leads me to believe that that systemjs isn't including the hash-set correctly?
Am I missing something?
EDIT: digging into the generated js (app.js) file I notice something weird:
define(["require", "exports", "hash-set"], function (require, exports, hash_set_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class App {
hashFn(value) {
return value.toString();
}
constructor() {
alert('oh');
const h = hash_set_1.hashSet;
const StringSet = hash_set_1.hashSet(this.hashFn);
alert('oh2');
}
}
exports.App = App;
});
//# sourceMappingURL=app.js.map
While debugging, hash_set_1 is actually of the type I expect hash_set_1.hashSet to be. Actually manually editing the javascript to not use hash_set_1.hashSet but rather just hash_set_1 works.
Trying
import hashSet from 'hash-set'; (notice lack of {}) changes the generated javascript offending line to const StringSet = hash_set_1.default(this.hashFn); which is still not correct (default isn't defined either).
If you look at the code, you'll see it is exported as:
module.exports = function hashSet(hashFn) {
Doing import { hashSet } from 'hash-set'; cannot work because the export would have to be module.exports.hashSet = ....
It should work if you do:
import hashSet = require("hash-set");
I've tried the solution in other SO post, e.g. this, but it didn't seem to work. I always got undefined as a result.
My configuration in my HTML.
<script type="text/javascript">
var require = {
config: {
'config': { --> if I change this to app, I could read the value in app.js
userId: 1
}
}
};
</script>
<script src="lib/require.min.js" data-main="app"></script>
My config module:
define(['module'], function (module)
{
return {
userId: module.config().userId,
userName: "Test"
}
});
I use the config module in my app.
require(['modules/config', 'modules/A'], function (config, a)
{
var userId = config.userId; --> undefined
var userName = config.userName; --> Test
});
Any idea? Did I miss something? I use JQuery 1.12.3 and RequireJS 2.2.0.
Solution
Edit the config you pass to RequireJS to:
var require = {
config: {
'modules/config': {
userId: 1
}
}
};
Explanation
Your modules ids are not matching. When you require your module, you use require(['modules/config', .... So the module name is modules/config. However, in your RequireJS configuration you provide a configuration for the module named config. So when you use module.config() inside modules/config, RequireJS searches for a module named modules/config in the configuration and does not find it. So you get undefined. Performing the fix I mentioned earlier will allow RequireJS to find the configuration.
Alternatively you could use paths to have the module be loaded under the name config:
var require = {
paths: {
config: 'modules/config'
},
config: {
config: {
userId: 1
}
}
};
And use require(['config', ....
I followed the below technique to get it working. The files included in HTML. They can defined in config paths.
Directory structure:
-index.html
-modules
- myModule.js
-app.js
HTML (index.html)
<script type="text/javascript">
// require would refer to the require.js global. So i am using requireVar
var requireVar = {
config: {
userId: 1
}
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js"></script>
<script src="modules/myModule.js"></script>
<script src="app.js"></script>
file myModule.js
define("modules/myModule",function ()
{
return function(){
return requireVar.config.userId;
}
});
and finally my app.js
require(['modules/myModule'], function (myModule)
{
alert("");
var userId = myModule();
console.log(userId);
});
Suppose that I have class like this (written in typescript) and I bundle it with webpack into bundle.js.
export class EntryPoint {
static run() {
...
}
}
In my index.html I will include the bundle, but then I would also like to call that static method.
<script src="build/bundle.js"></script>
<script>
window.onload = function() {
EntryPoint.run();
}
</script>
However, the EntryPoint is undefined in this case. How would I call the bundled javascript from another script then?
Added: Webpack config file.
It seems that you want to expose the webpack bundle as a library. You can configure webpack to expose your library in the global context within a variable of your own, like EntryPoint.
I don't know TypeScript so the example uses plain JavaScript instead. But the important piece here is the webpack configuration file, and specifically the output section:
webpack.config.js
module.exports = {
entry: './index.js',
output: {
path: './lib',
filename: 'yourlib.js',
libraryTarget: 'var',
library: 'EntryPoint'
}
};
index.js
module.exports = {
run: function () {
console.log('run from library');
}
};
Then you will be able to access your library methods like you expect:
<script src="lib/yourlib.js"></script>
<script>
window.onload = function () {
EntryPoint.run();
};
</script>
Check the gist with the actual code.
I managed to get this working without any further webpack.config.js modifications, by simply using the import statement which i called from my main/index.js file:
import EntryPoint from './EntryPoint.js';
window.EntryPoint = EntryPoint;
For reference, here's my weback.config.js file.
Initially I tried accomplishing the same using require, however it assigned the module wrapper to window.EntryPoint as opposed to the actual class.
In my circumstance I was able to call a function from within the bundled JavaScript from another script by writing the function to the window when creating it.
// In the bundled script:
function foo() {
var modal = document.createElement('div');
}
// Bind to the window
window.foo = foo;
// Then, in the other script where I want to reference the bundled function I just call it as a normal function
<button onClick="window.foo()">Click Me</button>
I wasn't able to use Babel so this worked for me.
I had a similar challenge, I wanted to create a bundle for multiple pages within a journey and wanted each page to have it's own entry point into the code, and without a separate bundle for each page.
Here's my approach, which is very similar to Kurt Williams but from a slightly different angle, also without changing webpack config:
JourneyMaster.js
import { getViewData } from './modules/common';
import { VIEW_DATA_API_URL } from './modules/constants';
import { createLandingPage, createAnotherPage } from './modules/components/pageBuilder';
window.landingPageInit = () => {
getViewData(VIEW_DATA_API_URL).then(viewData => {
createLandingPage(viewData);
});
};
window.anotherPageInit = () => {
getViewData(VIEW_DATA_API_URL).then(viewData => {
createAnotherPage(viewData);
});
};
// I appreciate the above could be one liners,
// but readable at a glance is important to me
Then an example of how I call these methods at the end of the html page:
<script src="/js/JourneyMaster.js"></script>
<script>window.landingPageInit();</script>
WEBPACK.CONFIG.JS
1.USING UMD
module.exports={
mode:'development',
entry:'./yourentry.js',
output:{
path:path.resolve(__dirname,"dist"),
filename:'main.js',
publicPath:'/dist/',
libraryTarget:'umd',
library:'rstate',
umdNamedDefine: true,
libraryExport: 'default'
}
}
index.html
<script src="dist/main.js"></script>
<script>
window.onload = function () {
rstate()=>{}
</script>
main.js
export default function rstate(){
console.log("i called from html")
}
2.USING VAR
module.exports={
mode:'development',
entry:'./yourentry.js',
output:{
path:path.resolve(__dirname,"dist"),
filename:'main.js',
publicPath:'/dist/',
libraryTarget:'var',
library: 'EntryPoint'
}
}
index.html
<script>
window.onload = function () {
EntryPoint.rstate()=>{}
</script>
main.js
module.exports={
rstate=function(){
console.log("hi module")
}
}
3.USING AMD as library we use like(for those who want to make lib)
define(['jquery', './aux-lib.js'], function ($) { ..(1).. });
Many of the answers so far work, it would only be necessary to clarify that Webpack will not recognize the library until it is built once declared.
You should use npm run build right after creating your library,
before continuing to work with npm start.
At least that's how it works for me, using only webpack.
Maybe this is some impostor syndrome on my part, but I think 'real' coders will cringe at my answer. Regardless, I found this solution to be the best fitting for being pragmatic about my time with my hobby project:
Chane your JS function declaration from:
function renderValue(value) {
to:
global.renderValue = function(value) {
Of course, you'll want to require('path/to/your_custom_js') as you would any file.
I found this answer here:
https://www.fastruby.io/blog/rails/webpack/from-sprockets-to-webpacker.html
This took me forever to figure out as the accepted answer wasn't working for me. Just make sure the function name is the same as the library in the config and it's bundled with the config specified -- npx webpack --config webpack.config.js --mode=development -- hopefully this saves people a few hours.
index.js (function to be bundled) >>
function EntryPoint() {
console.log('called from bundle');
}
module.exports = EntryPoint;
webpack.config.js >>
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var',
library: 'EntryPoint'
},
};
start.html (where the bundled function is called) >>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Azure SDK Storage Example</title>
<script type="text/javascript" src="./dist/main.js"></script>
</head>
<body>
<h1>Azure SDK Storage Example</h1>
</body>
</html>
<script>
EntryPoint();
</script>
App.ts:
namespace mytypescript.Pages {
export class Manage {
public Initialise() {
$("#btnNewActivity").click(() => {
alert("sdc'");
});
}
}
}
mypage.html:
<input class="button" type="button" id="btnNewActivity" value="Register New Activity" />
<script type="text/javascript">
var page = new mytypescript.Pages.Manage();
page.Initialise();
</script>
I am using Esri's ArcGis CDN and I want to have some custom modules. My directory structure is as follows
Scripts
app
basemap.js
test.js
Views
Maps
General.cshtml
In General.html I have this for my dojo config
<script data-dojo-config="async: 1, dojoBlankHtmlUrl: '/blank.html',
packages: [ {
name: 'app',
//Can't configure location correctly
location: location.pathname.replace(/\/[^/]+$/, '') + ''
} ]"
src="//js.arcgis.com/3.7/"></script>
Testing usage in test.js
require([
"dojo/ready",
"app/basemap"
], function (ready, basemap) {
basemap.test();
}
If I use an absolute path location: 'http://localhost:53862/Scripts/app' then it works fine.
I've tried a few other things for '' but I can't seem to navigate from the Maps folder across to my app folder. All the examples I looked at either specify a subdirectory for the location or an absolute path. Is there I way I can do something like ../Scripts/app?
I recommend you read "Configuring Dojo with dojoConfig" and "Using Custom Modules with a CDN".
Eg Google CDN.
dojo config, look at property baseUrl
<script data-dojo-config="async: 1,
dojoBlankHtmlUrl: '/blank.html',
baseUrl: '/Scripts',
packages:[
{ name:'dojo',location:'//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/'},
{ name:'app',location:location.pathname.replace(/\/[^/]+$/, '') + 'app'}]"
src="//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js">
</script>
after, test your custom module
require([
"dojo/ready",
"app/basemap"
], function (ready, basemap) {
basemap.test();
}
I changed my dojoconfig to the following
<script data-dojo-config="
packages: [ {
name: 'app',
location: '//' + window.location.host + '/Scripts/app'
} ]"
src="//js.arcgis.com/3.7/"></script>
Which set my app package to http://localhost:53862/Scripts/app
I've got a config for requirejs that is shared with multiple applications. When the app is loaded, the app receives an object with the layout of the app (and various other params). I want to use that object to define modules/packages for the app.
siteMap = { modules: { "foo": { … }, "bar": { … }, … }, other: "stuff" }
/shared/
libs/
bootstrap.js
jquery.js
…
app.js
/$appName/
foo/
index.html
edit.html
main.js
bar/
index.html
stuff.html
main.js
…
I imagine there must be a way to add packages that goes something like this:
// /shared/app.js
require.config({
paths: {
"bootstrap": ["//hosted.bootstrap.js","/shared/libs/bootstrap.js"],
"jquery": ["//hosted.jquery.js","/shared/libs/jquery.js"],
"siteMap": "//appName.example.com/api/siteMap"
},
…
});
require(['jquery','siteMap','bootstrap'], function($,siteMap) {
for ( var module in siteMap.modules )
{
require.config.packages[module] = siteMap.modules[module];
// OR
require.addPackage(siteMap.modules[module]);
}
});
You could nest another require() call to load the additional modules after siteMap tells you what should be loaded. Something like this:
require(['jquery','siteMap','bootstrap'], function($,siteMap) {
// .map assumes modern browser or use of something like es5-shim
var modulesToLoad = siteMap.modules.map(function(m) { return m + '/main'; } );
require(modulesToLoad, function() {
// kick off the rest of app logic
});
});