I am new to JS and to Kotlin/JS. I have the following minimal working Javascript code for a Plugin for Obsidian from an example. It works as expected:
var obsidian = require('obsidian');
class SomePlugin extends obsidian.Plugin {
onload() {
new obsidian.Notice('This is a notice!');
}
}
module.exports = Plugin;
I was hoping to extend this plugin using Kotlin as I know the language, but I have some problems converting this to Kotlin/JS. My approach so far:
The runnable project can be found here on Github. Run gradle build to generate the build folder. It will fail in the browser step, but that step is not necessary. After the build the generated js file can be found in build\js\packages\main\kotlin\main.js.
main.kt
#JsExport
class SomePlugin: Plugin() {
override fun onload() {
Notice("This is a notice!")
}
}
#JsModule("obsidian")
#JsNonModule // required by the umd moduletype
external open class Component {
open fun onload()
}
#JsModule("obsidian")
#JsNonModule
external open class Plugin : Component {
}
#JsModule("obsidian")
#JsNonModule
external open class Notice(message: String, timeout: Number = definedExternally) {
open fun hide()
}
Edit: Thanks to the comment of #S.Janssen I switched the module type to umd
build.gradle.kts
plugins {
kotlin("js") version "1.5.20"
}
group = "de.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
implementation(npm("obsidian", "0.12.5", false))
}
kotlin {
js(IR) {
binaries.executable()
browser {
webpackTask {
output.libraryTarget = "umd"
}
}
}
}
tasks.withType<KotlinJsCompile>().configureEach {
kotlinOptions.moduleKind = "umd"
}
I don't actually need a result that can be run in the browser, but without the browser definition, it would not even generate a js file. With the browser part, an exception is thrown saying Can't resolve 'obsidian' in 'path\kotlin'. But at least a .js file is created under build/js/packages/test/kotlin/test.js. However the code is completely different from my expected code and also is not accepted by obsidian as a valid plugin code. I also tried some other gradle options. like "umd", "amd", "plain", legacy compiler instead of IR, nodejs instead of browser. But nothing creates a runnable js file. The error messages differ. With the legacy compiler it requires the kotlin.js file, that it cannot find even if I put it right next to it in the folder or copy the content into the script.
How do I get code functionally similar to the Javascript code posted above? I understand that it will have overhead, but the code currently generated does not even define or export my class by my understanding.
The error message that I get from obisidan debugger:
Plugin failure: obsidian-sample-plugin TypeError: Object prototype may only be an Object or null: undefined
The code generated:
(function (root, factory) {
if (typeof define === 'function' && define.amd)
define(['exports', 'obsidian', 'obsidian', 'obsidian'], factory);
else if (typeof exports === 'object')
factory(module.exports, require('obsidian'), require('obsidian'), require('obsidian'));
else {
if (typeof Component === 'undefined') {
throw new Error("Error loading module 'main'. Its dependency 'obsidian' was not found. Please, check whether 'obsidian' is loaded prior to 'main'.");
}if (typeof Plugin === 'undefined') {
throw new Error("Error loading module 'main'. Its dependency 'obsidian' was not found. Please, check whether 'obsidian' is loaded prior to 'main'.");
}if (typeof Notice === 'undefined') {
throw new Error("Error loading module 'main'. Its dependency 'obsidian' was not found. Please, check whether 'obsidian' is loaded prior to 'main'.");
}root.main = factory(typeof main === 'undefined' ? {} : main, Component, Plugin, Notice);
}
}(this, function (_, Component, Plugin, Notice) {
'use strict';
SomePlugin.prototype = Object.create(Plugin.prototype);
SomePlugin.prototype.constructor = SomePlugin;
function Unit() {
Unit_instance = this;
}
Unit.$metadata$ = {
simpleName: 'Unit',
kind: 'object',
interfaces: []
};
var Unit_instance;
function Unit_getInstance() {
if (Unit_instance == null)
new Unit();
return Unit_instance;
}
function SomePlugin() {
Plugin.call(this);
}
SomePlugin.prototype.onload_sv8swh_k$ = function () {
new Notice('This is a notice!');
Unit_getInstance();
};
SomePlugin.prototype.onload = function () {
return this.onload_sv8swh_k$();
};
SomePlugin.$metadata$ = {
simpleName: 'SomePlugin',
kind: 'class',
interfaces: []
};
_.SomePlugin = SomePlugin;
return _;
}));
You can find a working example of what you're going for here. I'll go through some of the changes that needed to be made to your code one-by-one in this reply.
Being unable to resolve obsidian
Can't resolve 'obsidian' in 'path\kotlin' occurs because the obsidian-api package is not a standalone library. Instead, it only consist of a obsidian.d.ts file, which is a TypeScript declaration file. Similar to a header file in other languages, this header file does not provide any implementations, but only the signatures and types for the library – meaning Kotlin/JS' webpack (or any JavaScript tooling, for that matter) won't be able to resolve the actual implementations. This is expected, and can be addressed by declaring the module as external. To do so in Kotlin/JS, create a directory called webpack.config.d, and add a file 01.externals.js with the following content:
config.externals = {
obsidian: 'obsidian',
};
(You can actually find an equivalent snippet in the offical sample-plugin configuration, as well, since this isn't a Kotlin/JS specific problem)
Grouping multiple #JsModule declarations
Because you're importing multiple declarations from the same package, instead of annotating multiple signatures with #JsModule / #JsNonModule, you'll have to create a separate file, and annotate it with #file:#JsModule("...") / #file:JsNonModule:
#file:JsModule("obsidian")
#file:JsNonModule
open external class Component {
open fun onload()
open fun onunload()
}
open external class Plugin(
app: Any,
manifest: Any
) : Component
open external class Notice(message: String, timeout: Number = definedExternally) {
open fun hide()
}
Kotlin's ES5 vs Obsidian's ES6
Additionally, some of your problems stem from the fact that Obsidian's examples implicitly make the assumption that you are targeting ES6 (while Kotlin's current target is ES5). Specifically, this makes a difference in regards to how your plugin exports its members, as well as how classes are instantiated.
Inheritance
In regards to inheritance (since YourPlugin inherits from Plugin), ES6 classes automatically initialize the parent class with all arguments. This is something that is not supported in ES5's prototype inheritance. This is why in the snippet above, we need to explicitly pass the Plugin class constructor the app and manifest parameters, and pass them through in the implementation of your specific plugin:
class SomePlugin(
app: Any,
manifest: Any
) : Plugin(
app,
manifest
)
Exports / Module System
In regards to exporting your plugin, Obsidian expects either module.exports or exports.default to be your Plugin class directly. To achieve this exact export behavior, a few conditions need to be met, which is unfortunately a bit cumbersome:
- The library target needs to be CommonJS: output.libraryTarget = "commonjs" (not CommonJS2)
- To prevent creating a level of indirection, as is usually the case, the exported library need to be set to null: output.library = null
- To export your Plugin under as default, its class declaration needs to be marked as #JsName("default").
Related
I'm looking to add another property to window. I can do that with this:
// global.d.ts
import { IConfig } from './src/models';
export {};
declare global {
interface Window {
_env: IConfig;
}
}
But then when I try to reference this new property in a different file, it complains:
// src/util.ts
// Property '_env' does not exist on type 'Window & typeof globalThis'.
export const URL = `https://example.com/${window._env.path}`;
But when I combine these into the same file, everything is fine and there are no errors. Is there anyway I can have these in a separate file?
I'm using TypeScript 4.1.2.
I went down a bit of a rabbit hole but found this relevant documentation
I was able to accomplish this exactly as you have written (different type of course) in an existing angular 8 project and svelte project using their existing polyfills.ts files for my global declaration.
Are you sure you tsconfig.json is compiling everything correctly?
I'm making a library based on TSDX, nice and powerful CLI for package development which is based on Rollup and allows customization of its config. I have a bunch of country flags SVGs in my project and I need to import them and show them dynamically when they are needed. It wasn't clear for me how dynamic imports are working there and is it a problem of TSDX or Rollup itself, so I opened up an issue in TSDX' repository about that. People helped me out so now there are two ways that I can see to achieve that:
Use rollup-plugin-copy and then require all the files statically through a switch statement.
Use a virtual module that exports an object containing all file names in a directory as described here in one of the Rollup's issues (#2463).
I feel like writing a switch statement manually for all of the country flags is not the best idea in my life, so I thought that second path is better as it doesn't require me to maintain more code, because it'll just generate the code that I need. So I set up a little TSDX package for testing with a single React component that looks like this:
import test from 'testmodule'
export default function () {
return test
}
Now testmodule is what should be resolved by Rollup. I have this config now:
module.exports = {
rollup (config) {
config.plugins.unshift({
name: 'plugin-test-module',
resolveId (id) {
console.log('resolveId', id);
if (id === 'testmodule') {
return id;
}
return null;
},
load (id) {
if (id === 'testmodule') {
return 'export default "Test is successful"';
}
return null;
},
});
return config;
},
};
So what should happen is I just need to see "Test is successful" in the browser.
Unfortunately, npm run build fails with error Cannot find module 'testmodule'. I've put console.log into resolveId() to see what's happening, and looks like it never receives testmodule in its id. I replaced unshift with just straight assignment to config.plugins (so it removes other Rollup plugins) and it successfully compiled, although I understand that this is bad, so it's not a solution. I've read Rollup's docs and it seems like some other plugin added by TSDX like node-resolve may be trying to resolve the import instead of my plugin, but I can't find a way to stop that. So the main question is how to get my plugin to work along with others like node-resolve.
If you're interested about what other plugins TSDX uses, they're all can be found here. Seems like Rollup doesn't do tech support on their issues page so I hope somebody here is familiar enough with it to help me with this stuff.
I've solved this issue, with #rollup/plugin-replace.
// .. another rollup plugin
const replace = require('#rollup/plugin-replace');
rollup(config, options) {
config.plugins.push(
replace({
delimiters: ['', ''],
values: {
'../../../assets': './assets',
'../../../../assets': './assets',
},
})
);
// ... your other config
return config;
},
So that will replace this:
function Image({ name, ...props }: ImageProps) {
const src =
name === 'bank-indonesia'
? require(`../../../assets/images/${name}.jpg`).default
: require(`../../../assets/images/${name}.svg`).default;
return <img alt={name} src={src} {...props} />;
}
Into this:
function Image(_ref) {
var name = _ref.name,
props = _objectWithoutPropertiesLoose(_ref, _excluded$2);
var src = name === 'bank-indonesia' ? require("./assets/images/" + name + ".jpg")["default"] : require("./assets/images/" + name + ".svg")["default"];
return React.createElement("img", Object.assign({
alt: name,
src: src
}, props));
}
I know this is really bad solution, but it works for be btw.
tl:dr;
class ModuleInBundleA extends ModuleInBundleC { … }
window.moduleInBundleB.foo(new ModuleInBundleA())
class ModuleInBundleB {
public foo(bar: ModuleInBundleA|ModuleInBundleC|number) {
if (bar instanceof ModuleInBundleA || bar instanceof ModuleInBundleC) {
// always false
…
}
}
}
Details:
I'm trying to start using TypeScript + Webpack 4.41.6 on the project that has mostly old codebase. Basically I want to package several small modules onto bundles to migrate softly without moving whole project onto new js stack.
I found out that Webpack can do this with code splitting, and package shared code into bundles on it's own with some configuration. However I can't really control what will be in every bundle unless I build every bundle separately and then only share types, using my own modules as external libraries and that's bit frustrating.
Maybe on this point you can say that I'm doing something wrong already and I would like to hear how can I achieve my goal of using bundles just as vanilla javascript (controlling defer/async on my own and using script tag on my own as well), and I don't really want to pack everything as an independent package with own configuration, types export and so on.
Hope you got overall context. Closer to the point.
I have the following function, that is bundled to it's own chunk called modal-manager.js.
public showModal (modal: ModalFilter|AbstractModal|number) {
let modalId: number;
console.log(modal);
console.log(typeof modal);
console.log(modal instanceof ModalFilter);
console.log(modal instanceof AbstractModal);
if (modal instanceof AbstractModal) {
modalId = modal.getId();
} else {
modalId = modal;
}
...
};
(Originally it had no ModalFilter as ModalFilter inherits AbstractModal but I included it for demonstration purposes)
The abstract modal is bundled automatically to modal-utils.js as it's shared between modules.
Next, I have another big bundle called filter.js. This one literally creates instance of ModalFilter const modalFilter = new ModalFilter(...). I think it's work mentioning that instance of modalFilter declared to the global window variable. The trouble is that filter.js calls modal.js code (through window.modalFilter.showModal(modalFilter)) with no problems whatsoever, but I see the following result of console.log:
ModalFilter {shown: false, loading: false, closing: false, html: init(1), id: 0, …}
modal.bundle.23e2a2cb.js:264 object
modal.bundle.23e2a2cb.js:265 false
modal.bundle.23e2a2cb.js:266 false
I disabled mapping to get more into code and see this:
ModalManager.prototype.showModal = function (modal) {
var modalId;
console.log(modal);
console.log(typeof modal);
console.log(modal instanceof _builder_component_modal_filter__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"]);
console.log(modal instanceof _modal_abstract__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]);
if (modal instanceof _modal_abstract__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]) {
modalId = modal.getId();
}
else {
modalId = modal;
}
this.modals[modalId].show();
this.scrollLock(modalId);
};
With my understanding of how javascript works, instanceof should check the object-creator function. As code chunks separated (modal.js has no same code with modal-utils.js) the creator function should be the same. However, getting more to the details I see that webpackJsonp can be really tricky and calling them from kind-of independent environments, still it should be the same environment where FilterModal, AbstractModal is called. The ModalManager could have own environment I believe. But code called is 100% the same. Could that webpackJsonp bundle-arrays be the source of the problem? If so, how can I avoid that and make modal.js bundle understand that both filter.js and others reference the same AbstractModal from modal-utils.js?
If I'm doing it wrong, is there a simple way to start bundling small and efficient scripts build with TypeScript and Webpack (or other tools)?
Also, I see the externals feature of Webpack, but haven't figured out how to use that in my case. In general, I'm ok with current set up except instanceof issue. The reason I want to avoid multiple builds is that I'll probably have dozens of smaller bundles that shared across different modules and having dozen of npm packages for each seems excessive.
Prefacing this with; I don't know the answer to the exact issue that you are facing in regards to the instanceOf part of your question. This is aimed at the "how did you do it" part.
Approx. 4 weeks ago we also changed from a .js to .ts implementation with about 1-2 hunderd .js files. Obviously we didn't want to migrate these all at once over to .ts as the effort was too high.
What we ended up doing was identifying .js scripts which needed to run on specific pages and added these into webpack as entry files. Then for all of the other suporting scripts, if we required their contents in our new .ts files, we actually created a large index/barrel file for them all, imported them in and then webpack will automatically include these in the correct scope alongside their respective .ts files.
What does this look like?
legacy.index.ts: For every single supporting .js file that we wanted to reference in any way in .ts.
var someFile_js = require("someFile.js");
export { someFile_js };
This then allowed us to import and use this in the .ts files:
import { someFile_js } from './legacy.index';
In reply to #tonix. To load a defined list:
webpack.config
const SITE_INDEX = require('./path-to-js-file/list.js')
module.exports = {
entry: SITE_INDEX
...
}
list.js
{
"filename1": "./some-path/filename1.js"
"filename2": "./some-path/filename2.ts"
}
Good evening to everyone.
I'm not sure how can I explain my issue. I will show it to you by showing examples of the code and expected results. I could not use code from the real issue because the code is under license. I am very sorry for that and I will be glad of someone can help me solve my issue.
I'm using latest version of webpack, babel.
My application is spliced to three parts what are dynamically imported by each other. It is mean if I run split chunks plugin it will really create three clear files.
The parts are Core, Shared, Application. Where the Core only creating an instance of the application.
Result of the parts is bundled to single file. So it is linked by one html's script tag.
Project structure is:
src/app // For Application
src/core // For Core
src/shared // For Shared
In webpack configuration I am resolving alias for import ˙Editor$˙.
I renamed naming of variables because they are including project name.
resolve: {
alias: {
"Editor$": path.resolve('./src/app/statics/Editor.js'),
}
},
The content of Core file is
function createInstance(name, id) {
import("app").then(App => {
App(name, id)
});
}
The little bit of Application file is
imports...
import Framework from "./framework"
function createApp(name, id) {
new Framework({name, id}).$mount(...)
}
export default createApp
In the Application classes (what are instantiated inside Framework)
Is this import
import Editor from "Editor"
The Editor class is a singleton. But only for created instance.
class Editor {
static instance;
id = null;
constructor(){
if(this.constructor.instance){
return this.constructor.instance
}
this.constructor.instance = this
}
static get Instance() {
return this.instance || (this.instance = new this())
}
static get Id {
return this.Instance.id;
}
}
export default Editor
The issue is webpack dependency resolving. Because webpack puts and unify all imports to the top of the file.
So the imports are evaluated once through the life-cycle of the program.
But I need to tell webpack something like: There is an instance creation. Declare the new Editor singleton for this scope. Don not use the already cached one.
My another idea how to fix this is to set context for the instance. And in the Editor singleton create something like new Map<Context, Editor> if you get what I mean. But I did not find a way how to set a context for an instance or scope the import only for it.
I will appreciate any help. I am googling two days and still no have idea how to do it without rewriting all the imports.
Sorry for bugs in my English. I am not native speaker and my brain is not for languages.
Thanks everyone who take look into my issue.
How about recreating the Editor:
// Editor.js
class Editor {
// ...
}
let instance;
export function scope(cb) {
instance = new Editor();
cb();
instance = null;
}
export default function createEditor() {
if(!instance) throw Error("Editor created out of scope!");
return instance;
}
That way you can easily set up different scopes:
// index.js
import {scope} from "./editor";
scope(() => {
require("A");
require("B");
});
scope(() => {
require("C");
});
// A
import Editor from "./editor";
(new Editor()).sth = 1;
// B
import Editor from "./editor";
console.log((new Editor()).sth); // 1
// C
import Editor from "./editor";
console.log((new Editor()).sth); // undefined
// note that this will fail:
setTimeout(() => {
new Editor(); // error: Editor created out of scope
}, 0);
That also works for nested requires and imports as long as they are not dynamic.
I am running mocha tests on my server, testing source scripts an isolated unit test manner.
One of the scripts I am testing makes a call to Webpack's require.ensure function, which is useful for creating code-splitting points in the application when it gets bundled by Webpack.
The test I have written for this script does not run within a Webpack context, therefore the require.ensure function does not exist, and the test fails.
I have tried to create some sort of polyfill/stub/mock/spy for this function but have had no luck whatsoever.
There is a package, webpack-require, which does allow for the creation of a webpack context. This can work but it is unacceptably slow. I would prefer to have some sort of lightweight polyfill targeting the require.ensure function directly.
Any recommendations? :)
Here is a very basic starting point mocha test.
The mocha test loads a contrived module containing a method which returns true if require.ensure is defined.
foo.js
export default {
requireEnsureExists: () => {
return typeof require.ensure === 'function';
}
};
foo.test.js
import { expect } from 'chai';
describe('When requiring "foo"', () => {
let foo;
before(() => {
foo = require('./foo.js');
});
it('The requireEnsureExists() should be true', () => {
expect(foo.requireEnsureExists()).to.be.true;
});
});
Ok, I finally have an answer for this after much research and deliberation.
I initially thought that I could solve this using some sort of IoC / DI strategy, but then I found the source code for Node JS's Module library which is responsible for loading modules. Looking at the source code you will notice that the 'require' function for modules (i.e. foo.js in my example) get created by the _compile function of NodeJs's module loader. It's internally scoped and I couldn't see an immediate mechanism by which to modify it.
I am not quite sure how or where Webpack is extending the created "require" instance, but I suspect it is with some black magic. I realised that I would need some help to do something of a similar nature, and didn't want to write a massive block of complicated code to do so.
Then I stumbled on rewire...
Dependency injection for node.js applications.
rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may
inject mocks for other modules
leak private variables
override variables within the module.
rewire does not load the file and eval the contents to emulate node's require mechanism. In fact it uses node's own require to load the module. Thus your module behaves exactly the same in your test environment as under regular circumstances (except your modifications).
Perfect. Access to private variables is all that I need.
After installing rewire, getting my test to work was easy:
foo.js
export default {
requireEnsureExists: () => {
return typeof require.ensure === 'function';
}
};
foo.test.js
import { expect } from 'chai';
import rewire from 'rewire';
describe('When requiring "foo"', () => {
let foo;
before(() => {
foo = rewire('./foo.js');
// Get the existing 'require' instance for our module.
let fooRequire = moduletest.__get__('require');
// Add an 'ensure' property to it.
fooRequire.ensure = (path) => {
// Do mocky/stubby stuff here.
};
// We don't need to set the 'require' again in our module, as the above
// is by reference.
});
it('The requireEnsureExists() should be true', () => {
expect(foo.requireEnsureExists()).to.be.true;
});
});
Aaaaah.... so happy. Fast running test land again.
Oh, in my case it's not needed, but if you are bundling your code via webpack for browser based testing, then you may need the rewire-webpack plugin. I also read somewhere that this may have problems with ES6 syntax.
Another note: for straight up mocking of require(...) statements I would recommend using mockery instead of rewire. It's less powerful than rewire (no private variable access), but this is a bit safer in my opinion. Also, it has a very helpful warning system to help you not do any unintentional mocking.
Update
I've also seen the following strategy being employed. In every module that uses require.ensure check that it exists and polyfill it if not:
// Polyfill webpack require.ensure.
if (typeof require.ensure !== `function`) require.ensure = (d, c) => c(require);