how to import seed module in javascript gnome-shell extension - javascript

It's quite simple: My js is part of a gnome-shell extension and contains several import lines:
[...]
const Gettext = imports.gettext;
const MessageTray = imports.ui.messageTray;
imports.searchPath.push("/opt/tempmon/lib"); // append custom search path
const Helper = imports.tempmon; // import helper module
[...implementation...]
I've compiled my shared lib with seed-module.h successfully and placed it under /opt/tempmon/lib/libseed_tempmon.so
Looking Glass (lg) displays:
gjs/seed (I'm confused) couldn't find the "JS-Module tempmon in search path".
What action is needed to get my module included in the JS environment?

Related

Elixir Phoenix - How to create and import javascript files into specific templates

I'm currently experimenting with the Elixir Phoenix framework together with Liveview. For my project, I would like to write some Javascript code that is only imported on certain pages (templates). Although this seems like something very trivial, I am struggling to get it working.
At this moment I created a seperate Javascript file as such assets/js/custom.js. After doing this, I added the following line to my root.html.heex as a first test to see if this already works. For this line, I simply looked at how app.js is imported.
<script defer phx-track-static type="text/javascript" src={Routes.static_path(#conn, "/assets/custom.js")}></script>
The next step would then be to figure out how to import it in a seperate template instead of the root. However, this first test already failed resulting in the following error:
[debug] ** (Phoenix.Router.NoRouteError) no route found for GET /assets/custom.js (MyAppWeb.Router)
(my_app 0.1.0) lib/phoenix/router.ex:405: MyAppWeb.Router.call/2
(my_app 0.1.0) lib/my_app_web/endpoint.ex:1: MyAppWeb.Endpoint.plug_builder_call/2
(my_app 0.1.0) lib/plug/debugger.ex:136: MyAppWeb.Endpoint."call (overridable 3)"/2
(my_app 0.1.0) lib/my_app_web/endpoint.ex:1: MyAppWeb.Endpoint.call/2
(phoenix 1.6.15) lib/phoenix/endpoint/cowboy2_handler.ex:54: Phoenix.Endpoint.Cowboy2Handler.init/4
(cowboy 2.9.0) c:/Users/arnod/Desktop/phoenixtut/my_app/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
(cowboy 2.9.0) c:/Users/arnod/Desktop/phoenixtut/my_app/deps/cowboy/src/cowboy_stream_h.erl:306: :cowboy_stream_h.execute/3
(cowboy 2.9.0) c:/Users/arnod/Desktop/phoenixtut/my_app/deps/cowboy/src/cowboy_stream_h.erl:295: :cowboy_stream_h.request_process/3
(stdlib 4.0.1) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
Could somebody help me figure this one out? How does one add seperate Javascript files and only import them in specific templates?
You can import all your custom javascript once in app.js, assign them as hooks which you can then use in your (live) views, wherever needed, for example;
custom.js
export const SomeFunction = {
mounted() {
alert("some function ran!");
}
}
app.js snippet
...
import {SomeFunction} from "./custom.js"
let Hooks = {}
Hooks.SomeFunction = SomeFunction
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}, hooks: Hooks})
...
Then in your live view render function (or template) add the hook
...
def render(assigns) do
~H"""
...
<div id="my-hook" phx-hook="SomeFunction"></div>
...
end
...
More about javascript interoperability can be found on the Phoenix hex page here. You can tie them to all sorts of phoenix events.
nb. Also note that #conn isn't available in live views, only #socket is.

How to programmatical import module to local scope of nodejs?

The code environment is browser. bundle tool is webpack. I have a router.js file like:
import foo from './views/foo.vue'
import bar from './views/bar.vue'
import zoo from './views/zoo.vue'
//use foo, bar, zoo variables
I've many '.vue' files to import like this under views folder. Is there a programmatical way to auto import all [name].vue as local variable [name]? So when I add or remove a vue file in views, I don't need to manually edit router.js file. this one seems a little dirty.
for (let name of ['foo', 'bar', 'zoo']) {
global[name] = require(`./views/${name}.vue`)
}
Nope, that's it. You have a choice between dynamic import and automation, or explicit coding and type-checking / linting.
Unfortunately, it's one or the other. The only other way to do it is meta-programming, where you write code to write your code.
So you generate the import statements in a loop like that, and write the string into the source file, and use delimiting comment blocks in the source file to identify and update it.
The following works for me with webpack and vue.
I actually use it for vuex and namespaces. Hope it helps you as well.
// imports all .vue files from the views folder (first parameter is the path to your views)
const requireModule = require.context('./views', false, /\.vue$/);
// create empty modules object
const modules = {};
// travers through your imports
requireModule.keys().forEach(item => {
// replace extension with nothing
const moduleName = item.replace(/(\.\/|\.vue)/g, '');
// add item to modules object
modules[moduleName] = requireModule(item).default;
});
//export modules object
export default modules;

How to import a module from the static using dynamic import of es6?

I'm trying to add dynamic import into my code to have a better performance on the client-side. So I have a webpack config where is bundling js files. On SFCC the bundled files are in the static folder where the path to that files is something like this: /en/v1569517927607/js/app.js)
I have a function where I'm using dynamic import of es6 to call a module when the user clicks on a button. The problem is that when we call for that module, the browser doesn't find it because the path is wrong.
/en/lazyLoad.js net::ERR_ABORTED 404 (Not Found)
This is normal because the file is on /en/v1569517927607/js/lazyLoad.js.
There is a way to get it from the right path? Here is my code.
window.onload = () => {
const lazyAlertBtn = document.querySelector("#lazyLoad");
lazyAlertBtn.addEventListener("click", () => {
import(/* webpackChunkName: "lazyLoad" */ '../modules/lazyLoad').then(module => {
module.lazyLoad();
});
});
};
I had the same problem and solved it using the Merchant Tools > SEO > Dynamic Mapping module in Business Manager.
There you can use a rule like the following to redirect the request to the static folder:
**/*.bundle.js i s,,,,,/js/{0}.bundle.js
All my chunk files are named with the <module>.bundle pattern.
Here you can find more info :
https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/content/b2c_commerce/topics/search_engine_optimization/b2c_dynamic_mappings.html
Hope this helps.
I believe you'll likely need to do some path.resolve() magic in either your import statement or your webpack.config.js file as is shown in the accepted answer to this question: Set correct path to lazy-load component using Webpack - ES6
We did it in a different way. That required two steps
From within the template file add a script tag that creates a global variable for the static path. Something like
// inside .isml template
<script>
// help webpack know about the path of js scripts -> used for lazy loading
window.__staticPath__ = "${URLUtils.httpsStatic('/')}";
</script>
Then you need to instruct webpack to know where to find chunks by changing __webpack_public_path__ at runtime
// somewhere in your main .js file
// eslint-disable-next-line
__webpack_public_path__ = window.__staticPath__ + 'js/';
Optional step:
You might also want to remove code version from your __staticPath__ using replace (at least we had to do that)
__webpack_public_path__ = window.__staticPath__.replace('{YOUR_CODE_VERSION_GOES_HERE}', '') + 'js/';

Webpack 4 how to require sources as separated chunks and load them on demand

I have noticed that when I am importing source in the old way, like this: require('./my-script') it injects the code of the script into the main bundle.js.
And when I am importing like this: import('./my-script')
it created a separate new file and I even can name it with:
import(/* name.js */ './my-script');
That is nice, but in the new way of using import instead of require - how can I send parameters to the imported function?
For example, in require I could do require('./my-script')('something');
However this cannot be achieved using import
How can I pass parameters to an imported function and make it as a separate chunk in webpack?
This is the my-script.js (for example only):
// my-script.js
module.exports = str => {
return `${str} was returned`;
}
import(name) is used for code splitting (creating separate chunks) and will return a promise for the module's exports once the chunk has been retrieved asynchronously.
With your example, it can be used with something like the following:
import('./my-script').then(myScript => myScript.default('hello'))
The Dynamic imports section provides a more complete example and describes how import() is used for code splitting and here in Magic Comments are options listed which you can use to control how the chunk is created and when it's retrieved so you can tweak the user experience.

TypeScript: Handling import from external libraries

I just started using Famo.us and wanted to use it as an opportunity to learn typescript at the same time to leverage on its awesomeness. So I did the following
Used yo famous to create the Famo.us project as per the documentation
I was not sure how to include typescript so I created a typeScriptHTML project, copies the .csproj file over and manually edited it. I tried using the NVTS and specified that it should create it from an existing folder but I always got an error saying that the file path was too long. It checked and some of the modules have very long path. Couldn't even delete them and the system was saying the same thing. In the end I discarded the idea and used the typescript html application. It generated no errors.
I added a file app.ts, wrote some sample code in it and it generated the js file as expected.
Now I wanted to translate main.js to main.ts and I'm stuck with the following issues
i. var Engine = require('famous/core/Engine'); gives the error could not find symbol 'require'.
ii. import Engine = require('famous/core/Engine') gives the error: Unable to resolve external module "famous/core/Engine". Changing the path to "../lib/famous/core/Engine" gives a similar error with a different file name.
iii. Created a file Famous.d.ts but I don't think I'm getting it I'm not doing something right
declare module "famous/core/Engine" {
class Engine{
public createContext(): Engine
}
export = Engine
}
In the end, my confusion is how to I translate the sample code to typescript:
/*globals define*/
define(function(require, exports, module) {
'use strict';
///first
var Engine = require('famous/core/Engine');
var DeviceView = require('./DeviceView');
var mainContext = Engine.createContext();
var device;
createDevice();
function createDevice() {
var deviceOptions = {
type: 'iphone',
height: window.innerHeight - 100
};
device = new DeviceView(deviceOptions);
mainContext.add(device);
}
});
Any assistance appreciated.
It turned out to be a lot easier than I thought. One way was to declare the class and export it as a module
declare class Engine{
...
}
export module 'famous/core/Engine'{ export = Engine; }
Manage to get a tiny definition of famous running using this.

Categories

Resources