(Tauri) js import not working: "Failed to resolve module specifier" - javascript

I'm encountering a problem with Tauri plugins (I'm using Tauri 1.2.2).
I've created a basic app with
npx create-tauri-app
with npm as its package manager.
I've left everything the way it was installed, except for the fact that I'm trying to use the Plugin-Log plugin for Tauri.
(https://github.com/tauri-apps/tauri-plugin-log)
To install it, I've added
tauri-plugin-log = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "dev" }
in src-tauri/Cargo.toml, then ran
npm add https://github.com/tauri-apps/tauri-plugin-log
then I updated my main() function in src-tauri/src/main.rs:
use tauri_plugin_log::{LogTarget};
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_log::Builder::default().targets([
LogTarget::LogDir,
LogTarget::Stdout,
LogTarget::Webview,
]).build())
.invoke_handler(tauri::generate_handler![greet])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
However, when I attempt to import anything (the line of code below was written inside main.js):
import { trace, info, error, attachConsole } from "tauri-plugin-log-api";
I get the following error:
Uncaught TypeError: Failed to resolve module specifier "tauri-plugin-log-api". Relative references must start with either "/", "./", or "../".
Even imports taken straight from the documentation, such as this one, fail:
import { ask } from '#tauri-apps/api/dialog';
const yes = await ask('Are you sure?', 'Tauri');
and result in the same TypeError:
Uncaught TypeError: Failed to resolve module specifier "#tauri-apps/api/dialog". Relative references must start with either "/", "./", or "../".
despite the fact that I've added the following to tauri.conf.json
{
"tauri": {
"allowlist": {
"dialog": {
"all": true,
"open": true,
"save": true
},
...
}
}
}
The only workaround for the above problem I have found is this:
const { ask } = window.__TAURI__.dialog;
const yes = await ask('Are you sure?', 'Tauri');
which ends up working.
Unfortunately, I remain at a loss trying to use the Plugin-Log described earlier in this post.
I tried using a relative path i.e.
import { trace, info, error, attachConsole } from "../node_modules/tauri-plugin-log-api/dist-js/index.min.js";
but then a new error occurs:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
I even tried reproducing the issue in a fresh VM after installing everything and I end up with the same errors.
Could there be something that I'm missing? Please bear with me as I am a literal Tauri noob.
Thank you in advance for any replies.

Related

Module not found when requiring library submodule in Jest tests

I am currently trying to write some tests for a node-based GCP Cloud Functions application.
At this point I've stripped it down to the bare minimum:
// index.js
const functions = require("#google-cloud/functions-framework");
const testing = require('#google-cloud/functions-framework/testing');
functions.http("updateProvider",
(req, res) => { res.send("OK"); });
My test file follows the sample here:
// index.spec.js
const {getFunction} = require('#google-cloud/functions-framework/testing');
require('../../');
describe("HelloTests", () => {
test("is testable", () => {
});
});
When I run jest I get the following error:
Cannot find module '#google-cloud/functions-framework/testing' from 'spec/unit/index.spec.js'
Some additional observations:
If I put that import statement into index.js and run the application, it imports just fine.
If I comment out the import statement from index.spec.js but leave it in index.js and run jest, I get the same error for the import in index.js.
This leads me to assume that Jest is not properly handling submodules. I've never worked with submodules like this before (that I can remember), so I'm at a complete loss. I did some digging and this is from the functions-framework node module's package.js:
"exports": {
".": {
"types": "./build/src/index.d.ts",
"default": "./build/src/index.js"
},
"./testing": {
"types": "./build/src/testing.d.ts",
"default": "./build/src/testing.js"
}
},
No idea if this is relevant but wanted to include it in case it's useful.
Any idea why I'm getting this error and/or how to resolve it without switching to ESM?
Update: I switched to ESM and get the exact same error.
This apparently got fixed earlier this year:
Issue: https://github.com/facebook/jest/issues/9771
Initial Release: https://github.com/facebook/jest/releases/tag/v28.0.0-alpha.3
I had copied an older (but still fairly recent!) package.json that was stuck on v27 so it wasn't picking up the latest library. Did a clean install and confirmed no further issue with at least v29.3.1.
Rookie mistake.

How to use Metro's config to not look for extension when resolving a file?

I'm trying to modify my metro.config.js file so that it will not ignore an npm package's main module.
This is the error message I receive at runtime:
error: Error: While trying to resolve module `#apollo/client` from file `<project-directory>/src/ApolloProvider.tsx`, the package `<project-directory>/node_modules/#apollo/client/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`<project-directory>/node_modules/#apollo/client/main.cjs`. Indeed, none of these files exist:
* <project-directory>/node_modules/#apollo/client/main.cjs(.native|.ios.jsx|.native.jsx|.jsx|.ios.js|.native.js|.js|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.|.native.|.|.ios.json|.native.json|.json)
* <project-directory>/node_modules/#apollo/client/main.cjs/index(.native|.ios.jsx|.native.jsx|.jsx|.ios.js|.native.js|.js|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.|.native.|.|.ios.json|.native.json|.json)
at DependencyGraph.resolveDependency (<project-directory>/node_modules/metro/src/node-haste/DependencyGraph.js:311:17)
at Object.resolve (<project-directory>/node_modules/metro/src/lib/transformHelpers.js:129:24)
at resolve (<project-directory>/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:33)
at <project-directory>/node_modules/metro/src/DeltaBundler/traverseDependencies.js:412:26
at Array.reduce (<anonymous>)
at resolveDependencies (<project-directory>/node_modules/metro/src/DeltaBundler/traverseDependencies.js:411:33)
at processModule (<project-directory>/node_modules/metro/src/DeltaBundler/traverseDependencies.js:140:31)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at addDependency (<project-directory>/node_modules/metro/src/DeltaBundler/traverseDependencies.js:230:18)
at async Promise.all (index 3)
I can clearly see that <project-directory>/node_modules/#apollo/client/main.cjs exists, but it appears that the resolver is always trying to append an extension (whereas the main.cjs file described above needs no extension).
The following is my metro.config.js file:
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
sourceExts: ['jsx', 'js', 'ts', 'tsx', ''],
},
};
As you can see I've tried adding an empty string to the sourceExts property's Array, but that doesn't solve the issue.
Any idea how to get this Metro to resolve this main.cjs file correctly?
I've recently encountered this error and tried the same solution without success. The reason it doesn't work is because metro will still look for a file named /path/to/file.js and append . followed by the extension defined in the configuration array. Even if it's empty, it appends a . nonetheless.
I'm not sure if this will work for you, but in my case I didn't change anything in the bundler configuration. What fixed my issue was clearing the project's cache for watchman and react-native.
# Clear watchman's cache
yarn watchman watch-del-all
# Clear react-native's cache
yarn react-native start --reset-cache

How to use class when testing with Vue, Cypress and Cucumber?

I am trying to implement something simple: I want my e2e tests run with Cypress and cucumber.
I have an application created with Vue CLI 4.1.1. I added with NPM the package: cypress-cucumber-preprocessor (V1.19.0)
Edit:
After a lot of research and tests, I think I found where the problem comes from, but I don't know how to fix it yet:
The '#vue/cli-plugin-babel/preset' does not seem to be working with
.feature file...
My babel.config.js file is:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
Any idea how I can make cli-plugin-babel working with cucumber cypress?
Original message :
I have a Test.feature file, executing steps defined in test.step.js files.
Here is the content of my test.spec.js
import { When, Then } from 'cypress-cucumber-preprocessor/steps';
import { HomePage } from './pages/home.page';
When(/^I open the Home page$/, () => {
let homePage = new HomePage();
homePage.goTo();
});
Then(/^I see "([^"]*)" in the main heading$/, msg => {
cy.contains('h1', msg)
});
And the content of my PageObject home.page.js:
export class HomePage {
goTo() {
cy.visit("/");
}
}
When I run:
npm run test:e2e
I get the following error:
Oops...we found an error preparing this test file:
tests/e2e/features/Test.feature
The error was:
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:
- A missing file or dependency
- A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.
These errors does not occur when I use:
export function goToHomePage() {
cy.visit("/");
}
You can checkout my project on Github: https://github.com/truar/cloudcmr-v2 (branch master for the passing case, branch pageObject_pattern for the failing case).
I am assuming this is something related to ES6 and cypress... but I clearly don't know what is going on here. Besides, everything I find on the Internet talks about cypress cucumber and Typescript, which I don't use...
What am I missing?
I found the answer. See this PR for more details : https://github.com/cypress-io/cypress/issues/2945
Basically, there is an incompatibility between Babel 7 and Cypress 3. I had to change the babel.config.js file :
module.exports = process.env.CYPRESS_ENV
? {}
: {
presets: ["#vue/cli-plugin-babel/preset"]
};
It is just a workaround, not a real fix. We have to disable babel when running cypress.
Hope will help you !

How to fix "Its dependency 'kotlinx-coroutines-core' was not found."

I followed this tutorial to create a kotlin->js project: https://kotlinlang.org/docs/tutorials/javascript/getting-started-gradle/getting-started-with-gradle.html
Next, I followed these instructions to use coroutines in my code: https://github.com/kotlin/kotlinx.coroutines/blob/master/README.md#using-in-your-projects
Everything was fine to far, no errors marked in the code and I could build my js application without any error messages. However, my js scripts are not running in the browser and I get the above mentioned error message in the browser console.
Does any of you here know what I missed or might have configured wrong?
Here's my build.gradle
group 'de.berlin'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.3.31'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin2js'
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version"
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0-M1"
compile("org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.3.0-M1")
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core-js:1.3.0-M1"
}
compileKotlin2Js.kotlinOptions.sourceMap = true
compileKotlin2Js.kotlinOptions.outputFile = "${projectDir}/web/js/myApp.js"
compileKotlin2Js.kotlinOptions.suppressWarnings = false
compileKotlin2Js.kotlinOptions.verbose = true
build.doLast {
configurations.compile.each { File file ->
copy {
includeEmptyDirs = false
from zipTree(file.absolutePath)
into "${projectDir}/web/js/lib"
include { fileTreeElement ->
def path = fileTreeElement.path
path.endsWith(".js") && (path.startsWith("META-INF/resources/") || !path.startsWith("META-INF/"))
}
}
}
copy {
includeEmptyDirs = false
from "${buildDir}/resources/main"
into "${projectDir}/web"
}
}
clean.doFirst {
delete "${projectDir}/web"
}
Everything compiles without any error message but I get the following error message in the browser console:
""Its dependency 'kotlinx-coroutines-core' was not found. Please, check whether 'kotlinx-coroutines-core' is loaded prior to '(projectname)'."
A more detailled inspection shows that /web/js/lib only contains kotlin.js, shouldn't kotlinx-coroutines-core be also there because it's part of the depencency block and schould be copied in the build.doLast-step?
I also noticed that the comiled js file contains the following:
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'myApp'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'myApp'.");
}
if (typeof this['kotlinx-coroutines-core'] === 'undefined') {
throw new Error("Error loading module 'myApp'. Its dependency 'kotlinx-coroutines-core' was not found. Please, check whether 'kotlinx-coroutines-core' is loaded prior to 'myApp'.");
}
Why is it this['kotlinx-coroutines-core'] and not kotlinx-coroutines-core (like in the line above)?
Why is it this['kotlinx-coroutines-core'] and not kotlinx-coroutines-core (like in the line above)?
Because "kotlinx-coroutines-core" is not a valid JS identifier.
"this['kotlinx-coroutines-core']" is testing whether the module "kotlinx-coroutines-core" has been loaded or not.
if it is undefined, then it means you have not 'loaded' the module prior to the code being executed.
depending how you load JS modules, you will need to "require(....)" or have an html script reference to the "kotlinx-coroutines-core" module
It has been more than a year and a half since the thread was opened but I answer in case someone has the same problem in the future.
You have to download "kotlinx-coroutines-core" from npm. Coroutines JS - install

how to load electron module in typescript

I try to get the ipcRenderer module from electron in typescript to send informations from the current component to the core and to get informations back to the window (electron-chromium-browser).
All I get is a error "Module not found" by transcoding the ts-code to ES5.
const ipc = require('electron').ipcRenderer;`
Update: The Error is switching between the "Module not found" and this one:
ERROR in ./~/electron/index.js
Module build failed: Error: ENOENT, open '/.../node_modules/electron/index.js'
# ./app/components/search/search.ts 12:10-29
That is from the current electron-api. I have also tried to use the import syntax from typescript but the result is the same.
Than I tried to use the electron.ipcRenderer module in a ES5-file, loaded/linked directly in the html-file.
There it worked. Why?
Solved the problem after 10h searching.
Problem was the webpack-transcoder.
https://github.com/chentsulin/webpack-target-electron-renderer
https://github.com/chentsulin/electron-react-boilerplate/blob/master/webpack.config.development.js
Since electron dependency in the browser app is not real, meaning it's not webpacked from node_modules but instead loaded in runtime, the require statement caused errors such as "fs" not found for me.
However you can trick the typescript with this:
if (typeof window['require'] !== "undefined") {
let electron = window['require']("electron");
let ipcRenderer = electron.ipcRenderer;
console.log("ipc renderer", ipcRenderer);
}
Also if you are writing a web app, which only is augmented by electron when it's running inside, this is a better way since you don't have to add electron as a dependency to your webapp just when using the communication parts.
Than I tried to use the electron.ipcRenderer module in a ES5-file, loaded/linked directly in the html-file.
If it works in html but fails in ts it means the error is not in const ipc = require('electron').ipcRenderer;. The error is most likey in the import you have to load your file from html (and not require('electron')).
This solved the problem for me:
You can fix it, just add to the "package.json"
"browser": {
"fs": false,
"path": false,
"os": false }
Source: https://github.com/angular/angular-cli/issues/8272#issuecomment-392777980
You can trick ts with this (dirty hack, but it works):
const { ipcRenderer } = (window as any).require("electron");

Categories