How do I get rollup to compile at runtime with Deno? - rollup

I have the following Deno code...
import rollup from "https://unpkg.com/rollup/dist/es/rollup.js";
const inputOptions = {
input: "./index.mjs"
}
const outputOptions = {
format: "esm",
sourcemap: "inline"
}
const build = async ()=>{
const bundle = await rollup.rollup(inputOptions);
const { output } = await bundle.generate(outputOptions);
for (const chunkOrAsset of output) {
if (chunkOrAsset.type === 'asset') {
console.log('Asset', chunkOrAsset);
} else{
console.log('Chunk', chunkOrAsset.modules);
}
}
}
But when I try to run I get...
error: relative import path "path" not prefixed with / or ./ or ../ Imported from "https://unpkg.com/rollup#2.26.11/dist/es/rollup.js"
I also tried
import rollup from "https://unpkg.com/rollup";
but I get...
error: Uncaught SyntaxError: The requested module 'https://unpkg.com/rollup' does not provide an export named 'default'
finally I tried...
import * as rollup from "https://unpkg.com/rollup";
But I get...
error: Uncaught ReferenceError: exports is not defined
Object.defineProperty(exports, '__esModule', { value: true });
How do I get rollup to work with Deno?

An effort to port rollup to Deno was started in January 2021, so this problem is now solvable. You can import the deno-rollup module and then use it with the same API as rollup.
Here is a version of your original code which runs under Deno:
import { rollup } from "https://deno.land/x/drollup#2.42.3%2B0.17.1/mod.ts";
const bundle = await rollup({
input: "./index.mjs",
});
const { output } = await bundle.generate({
format: "esm",
sourcemap: "inline",
});
for (const chunkOrAsset of output) {
if (chunkOrAsset.type === "asset") {
console.log("Asset", chunkOrAsset);
} else {
console.log("Chunk", chunkOrAsset.modules);
}
}
You can find multiple examples of using the deno-rollup port on their repository: https://github.com/cmorten/deno-rollup
Please note that Deno's runtime compilation API is considered an unstable API, which means that you must use the --unstable flag when running Deno in order to make it available. For example: deno run --unstable --allow-read=. build.ts

Related

Unable to resolve module crypto

I am attempting to implement WalletConnect V1 in my React-Native Wallet app. However, whenever I use the following import:
import WalletConnect from "#walletconnect/client";
I get the following error:
Unable to resolve module crypto from /Users/<my-name>/<company-name>/<client-name>/<app-name>/node_modules/#walletconnect/randombytes/dist/cjs/node/index.js: crypto could not be found within the project or in these directories:
node_modules
I tried following some solutions but installing crypto-js and crypto-js#3.3.0 both did not fix the issue. I also already have react-native-crypto installed in my application.
Any help figuring out what I need to do to resolve this error would be amazing!
Just add custom resolver to your metro config
// metro.config.js
module.exports = {
resolver: {
extraNodeModules: {
crypto: require('react-native-cyrpto'),
},
},
};
Unfortunately crypto depends on other nodejs packages like: net, tls, fs and etc. Recommend using https://github.com/parshap/node-libs-react-native which polyfills node packages inside react-native
Docs
tldr;
nom install node-libs-react-native
// metro.config.js
module.exports = {
resolver: {
extraNodeModules: require('node-libs-react-native'),
},
};
I managed to solve this thanks to this post (https://github.com/parshap/node-libs-react-native/issues/23)
yarn add react-native-get-random-values
const nodelibs = require("node-libs-react-native");
nodelibs.crypto = `${__dirname}/src/crypto.js`;
module.exports = {
resolver: {
extraNodeModules: nodelibs,
},
};
Then created my own crypto.js file
// src/crypto.js
'use strict'
import { Buffer } from 'buffer';
const { NativeModules } = require('react-native');
const randomBytes = (size) => {
if (NativeModules.RNGetRandomValues) {
return Buffer(NativeModules.RNGetRandomValues.getRandomBase64(size));
} else {
throw new Error('Native module not found')
}
};
exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = randomBytes;

how to use rollup to parse cucumber feature files and backing step definition files

I have the following rollup plugin that will include .feature files
export const cucumberRollupPlugin: PluginImpl<CucumberOptions> = pluginOptions => {
let options: CucumberOptions = {
...{
include: '**/*.feature',
cwd: process.cwd(),
},
...pluginOptions,
};
let filter = createFilter(options);
let plugin: Plugin = {
name: 'bigtest-cucumber',
async transform(code, id) {
if (!filter(id)) {
return;
}
let parser = new GherkinParser({ code, uri: id, rootDir: options.cwd });
let result = await parser.parse();
let esm = dataToEsm(result, { namedExports: false });
// TODO: add sourcemap support
let transformResult: TransformResult = { code: esm };
return transformResult;
},
};
return plugin;
};
The problem I have is that to make the feature files work, there are step definition files that actually contain the functionality. So a feature file might look like this
Feature: Visit career guide page in career.guru99.com
Scenario: Visit career.guru99.com
Given: I browse to career.guru99.com
And a step definition file might look like this:
import { Given, When, Then from 'cucumber';
import assert from 'assert';
import{ driver } from '../support/web_driver';
Given(/^browse to web site "([^"]*)"$/, async function(url) {
return driver.get(url);
});
The problem I have with rollup is that there are no import statements for either the step definition files. The way cucumber-js works is that these files are found at runtime.
I think I need to generate an index.js that looks like this to cover the step definitions.
import from './step_definition_1';
import from './step_definition_2';
import from './step_definition_3';
Where would this fit in the rollup pipeline to generate this file so it can get pulled into the rollup pipeline.
You can use this.emitFile to manually process the .feature files and include them in the output. Call this.emitFile for each .feature file in the buildStart hook (each emitted file will get processed through the transform hook you wrote).
Here's an example that uses the globby package (which expands a glob to an array of file paths) to get the file path of each .feature file to pass to this.emitFile:
import globby from 'globby'
export const cucumberRollupPlugin: PluginImpl<CucumberOptions> = pluginOptions => {
let options: CucumberOptions = {
include: '**/*.feature',
cwd: process.cwd(),
...pluginOptions,
};
let filter = createFilter(options);
let plugin: Plugin = {
name: 'bigtest-cucumber',
async buildStart({ include, cwd }) {
const featureFilePaths = await globby(include, { cwd });
for (const featureFilePath of featureFilePaths) {
this.emitFile({
type: 'chunk',
id: featureFilePath
});
}
},
async transform(code, id) {
if (!filter(id)) {
return;
}
let parser = new GherkinParser({ code, uri: id, rootDir: options.cwd });
let result = await parser.parse();
let esm = dataToEsm(result, { namedExports: false });
// TODO: add sourcemap support
let transformResult: TransformResult = { code: esm };
return transformResult;
},
};
return plugin;
};
Let me know if you have any questions!
You need to use the this.emitFile method and befor that lookup the files via glob or anything else inside your plugin
{
plugins: [typescript(),{
name: "emit-additional-files",
async transform(code,id) {
//id === fileName
//code === fileContent
// inspect code or id here then use path.resolve() and fs.readdir to find additional files
this.emitFile()
}
}]
}

Using mocha and chai with import synax in VueJS

I'm trying to add Pact tests to my existing VueJS application but I'm having trouble even with the most basic test setup (using mocha with chai).
This is the basic test to see if things are working at all:
import { should } from "chai";
describe("setup", () => {
it("should work", () => {
var x = true;
x.should.be.equal(true);
});
});
Running this with the following command:
mocha --require #babel/preset-env test/pact/**/*.pact.js
This results in:
import { should } from "chai";
^
SyntaxError: Unexpected token {
From what I understood I need to transpile. After searching for similar issues I added this:
babel.config.js
module.exports = {
presets: ["#vue/app", "#babel/preset-env"]
};
Same effect.
It works when using e.g.
var should = require("chai").should();
describe("setup", () => {
it("should work", () => {
var x = true;
x.should.be.equal(true);
});
});

How to load webassembly file in Vue?

I have compiled the C code using this command emcc add.c -o js_plumbing.js -s -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap'] -s MODULARIZE=1
This is my Vue component code -
public instance:any = {
ready: new Promise(resolve => {
Module({
onRuntimeInitialized() {
this.instance = Object.assign(this, {
ready: Promise.resolve()
});
resolve();
}
});
})
};
public draw_outline() {
this.instance.ready
.then(_ => this.result_web = this.instance.addTwoNumbers(2,2));
}
draw_outline is getting called when I click on a text element.
And this is the error I'm getting -
So after this error I went to generate file and just added export to the module and this error disappears. but now my function in C "addTwoNumbers" is not getting called from instance.
if I print the value of instance I get
Does anyone know how to proceed from here?
I figured that when compiling I needed to use USE_ES6_IMPORT_META=0 flag so that WebAssembly module will use an older version of the import.meta.url line of code for systems that don't recognize the import style. so the command looks like emcc add.c -o js_plumbing.js -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap'] -s ENVIRONMENT='web,worker' -s EXPORT_ES6=1 -s MODULARIZE=1 -s USE_ES6_IMPORT_META=0
This is my updated code -
Module().then(myModule => {
const result = myModule.ccall('addTwoNumbers',
'number',
['number', 'number'],
[4, 6]);
console.log("Value from wasm file", result);
});
My config file -
const path = require('path');
const contentBase = path.resolve(__dirname, '..', '..');
module.exports = {
configureWebpack: config => {
config.devServer = {
before(app) {
// use proper mime-type for wasm files
app.get('*.wasm', function (req, res, next) {
var options = {
root: contentBase,
dotfiles: 'deny',
headers: {
'Content-Type': 'application/wasm'
}
};
res.sendFile(req.url, options, function (err) {
if (err) {
next(err);
}
});
});
}
}
},
}
It is inside a function that I call on a click event . I can elaborate the whole process if someone is interested. It should not take this much time for anyone, I hope it helps others who have been looking for the solution. I realise I have not properly stated the problem in this post, I shall update everything here in a proper way soon.

Difference between import and require in jest

I am writing my first test for a react-native project using react-native-router-flux and react-redux
My code is something like
jest.autoMockOff();
jest.setMock('react-native', {
NativeModules: {}
});
jest.setMock('react-native-router-flux', {
Actions: {}
});
const mockStore = require('../../mock/Store');
const actions = require('../myActions');
...
// Some tests that test if the right actions are dispatched.
The above works, However when I use ES6 import instead of require I have a problem.
If I replace
const actions = require('../myActions');
with
import * as actions from "../myActions"
I get the below error.
Runtime Error
- Error: Cannot find module 'ReactNative' from 'react-native.js'
at Resolver.resolveModule (node_modules/jest-cli/node_modules/jest-resolve/src/index.js:117:17)
at Object.<anonymous> (node_modules/react-native/Libraries/react-native/react-native.js:175:25)
at Object.<anonymous> (node_modules/react-native-router-flux/src/Scene.js:10:18)
While I can work with this, I am curious to understand the reason for failure,
Also note that I am just not able to transpile react-native-router-flux with es2015 presets in .bablerc file and I think I will have to live with that limitation (of not being able to transpile react-native-router-flux).
myActions.js looks like
import {Actions} from 'react-native-router-flux';
export function searchRequest() {
return {
type: "search_request"
}
}
export function searchRequestFailure(error) {
return {
type: "search_request_failure",
error: error.toString()
}
}
export function searchRequestSuccess(payload) {
return {
type: "search_request_success",
payload: payload
}
}
export function search(nameOrAddress) {
return dispatch => {
dispatch(searchRequest())
return fetch("http://localhost:8080/search", {
method: "GET"
}).then((response) => {
return response.json()
}).then((responseData) => {
dispatch(searchRequestSuccess(responseData))
Actions.list() //react-native-router-flux dependency
}).catch(error => {
dispatch(searchRequestFailure(error))
})
}
}
Using react-native 0.26 and jest 12.1.1
That is not the correct ES6 conversion.
const actions = require('../myActions'); // requires the defaultMember of the exported module and
//ES6 (ES2015) equivalent is
import actions from '../myActions';
https://developer.mozilla.org/en/docs/web/javascript/reference/statements/import