Importing third party Libraries into a Stenciljs Project - node.js

So Im trying to import the third party npm module 'rss-parser' to my Stenciljs project. I tried it like in the official documentation:
let Parser = require('rss-parser');
let parser = new Parser();
(async () => {
let feed = await parser.parseURL('https://www.reddit.com/.rss');
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})();
I got the Error: Can't find variable: require.
I think I'm somehow missing how I need to install these libraries but I can not figure out how. I've red about moudle bundlers but I thought that comes with the Stenciljs compiler already.
Is it a problem that Im trying to import old JS code in a ES6 project?
Thanks for your help

Stencil components are written in TypeScript, so you use import to pull in dependencies:
import Parser from 'rss-parser';
More on TypeScript's modules here: https://www.typescriptlang.org/docs/handbook/modules.html

var Parser = require('rss-parser') is a requireJS syntax which is not going to work with stencil.
You need to import it using one of the following ways:
import Parser from 'rss-parser';
import { Parser } from 'rss-parser';
import 'rss-parser';
And this purely depends upon how the module has exported the variable.
Another thing you might need to do in your stencil.config.ts file is to set
nodeResolve: true

Related

How to import module based dependencies for firebase cloud functions?

I want to organize my firebase cloud functions in specific files,
and currently, I have these 3:
index.ts
crypto.ts
webscrape.ts
Inside of these files, I have functions that use specific dependencies that are needed nowhere else.
For example, in crypto.ts I need the crypto-js package to encrypt some user data and store it into the database.
So I am importing it like so:
import * as CryptoJS from "crypto-js";
as advised in https://firebase.google.com/docs/functions/handle-dependencies#typescript
On the other hand, when I try to import puppeteer into webscrape.ts like this:
import * as puppeteer from"puppeteer-extra";
then calling puppeteer.launch(); gives me an error :
Property 'launch' does not exist on type 'typeof import("c:/Users/username/Desktop/project/firebasee/functions/node_modules/puppeteer-extra/dist/index")'
and it only works when I do const puppeteer = require("puppeteer-extra");
What's the difference here?
My goal is to keep the dependencies of each functions and file/module as small as possible because I assume that this will also keep the size of each function container small (Is that even true?)
I didn't want to import everything to index.ts even when I trigger a function, that doesn't use this dependency at all.
So what is the correct way of handling these dependencies?
Thanks!
The following import will get the default export from that package.
import puppeteer from "puppeteer-extra"
I looked for the default export in the Github repository and found that.
const defaultExport: PuppeteerExtra = (() => {
return new PuppeteerExtra(...requireVanillaPuppeteer())
})()
export default defaultExport
They have mentioned both ES6 import and require methods here.
// javascript import
const puppeteer = require('puppeteer-extra')
// typescript/es6 module import
import puppeteer from 'puppeteer-extra'
You can read more about import on MDN.

How do I import a rust WASM module in gatsby js?

I'm trying to use my rust module from the rust webassembly book in my gatsby project. When I try to import the module like so:
import { <rust-struct> } from 'rust_wasm_npm_package';
I get the following error:
The module seem to be a WebAssembly module, but module is not flagged as WebAssembly module for
webpack.
BREAKING CHANGE: Since webpack 5 WebAssembly is not enabled by default and flagged as experimental
feature.
You need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true' (based
on async modules) or 'experiments.syncWebAssembly: true' (like webpack 4, deprecated).
For files that transpile to WebAssembly, make sure to set the module type in the 'module.rules'
section of the config (e. g. 'type: "webassembly/async"').
(Source code omitted for this binary file)
I'm unable to add the experiments option to the gatsby config file, so I'm not sure what is the best way to import a wasm-pack rust module into gatsby.
I was able to get this working by adding a gatsby-node.js file with the following code:
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
experiments: {
syncWebAssembly: true,
},
});
};
I was then able to import the web assembly asynchronously. Not sure why I did not need to use asyncWebassembly: true instead, but it works!
// The reason for this useless concatenation
// is to get rid of a really specific issue
// with Webpack and WASM modules being imported
// all in one line.
/*eslint no-useless-concat: "off"*/
const module = await import("path/" + "toJSFile.js");
const memModule = await import("path/" + "toWasmModule.wasm");
const memory = memModule.memory;
setMem(memory);

unable to figure out error from passport-custom

trying to use passport-custom and the very first line, from pseudocode at npmjs, errors out:
import passportCustom from 'passport-custom';
The is no default import in index.js when I open it up under node_modules/passport-custom/lib
I must be missing something fundamental here, don't know what though
Try to use CommonJS const passportCustom = require("passport-custom") You probably have older version of Node.js which does not support ES6 modules.
There is no default export. So you will have to name the items you want to import (put them in curly braces).
//Example:
import { a,b,c,d} from 'youPackage';
//Your case:
import { passportCustom } from 'passport-custom';
Above are called named imports. When a package exports one item by default using: export default passportCustom ;, you could have use your code. You can access the code of the package to have a look for yourself.

How to import node module in TypeScript without type definitions?

When I try to import node.js module in TypeScript like this:
import co = require('co');
import co from 'co';
without providing type definitions, both lines reports same error:
error TS2307: Cannot find module 'co'.
How to import it correctly?
The trick is to use purely JavaScript notation:
const co = require('co');
Your options are to either import it outside TypeScript's module system (by calling a module API like RequireJS or Node directly by hand) so that it doesn't try to validate it, or to add a type definition so that you can use the module system and have it validate correctly. You can stub the type definition though, so this can be very low effort.
Using Node (CommonJS) imports directly:
// Note there's no 'import' statement here.
var loadedModule: any = require('module-name');
// Now use your module however you'd like.
Using RequireJS directly:
define(["module-name"], function (loadedModule: any) {
// Use loadedModule however you'd like
});
Be aware that in either of these cases this may mix weirdly with using real normal TypeScript module imports in the same file (you can end up with two layers of module definition, especially on the RequireJS side, as TypeScript tries to manage modules you're also managing by hand). I'd recommend either using just this approach, or using real type definitions.
Stubbing type definitions:
Getting proper type definitions would be best, and if those are available or you have time to write them yourself you should definitely should.
If not though, you can just give your whole module the any type, and put your module into the module system without having to actually type it:
declare module 'module-name' {
export = <any> {};
}
This should allow you to import module-name and have TypeScript know what you're talking about. You'll still need to ensure that importing module-name does actually load it successfully at runtime with whatever module system you're using, or it will compile but then fail to actually run.
I got an error when I used the "Stubbing type definitions" approach in Tim Perry's answer: error TS2497: Module ''module-name'' resolves to a non-module entity and cannot be imported using this construct.
The solution was to rework the stub .d.ts file slightly:
declare module 'module-name' {
const x: any;
export = x;
}
And then you can import via:
import * as moduleName from 'module-name';
Creating your own stub file lowers the barrier to writing out real declarations as you need them.
Just import the module the following way:
import 'co';

TypeScript 0.8.2 importing Node.js modules in internal modules

Okay, as I can see you would like to use internal modules in your project. Well, there was a workaround in TypeScript 0.8.1.1, you could define non exported module (internal) and add imports above it. In 0.8.2 it seems that this doesn't work anymore. Only option I see here would be to completely omit import syntax and use standard require for node modules. I don't know if this is a good idea but please, share your opinions. I know that using import syntax will make module external (language specification), but that wasn't true in 0.8.1.1, bug maybe?
In TypeScript 0.8.1.1 this worked and doesn't work in 0.8.2 anymore:
import path = module('path');
import fs = module('fs');
module SomeNamespace.Controller {
export class Index {
...
}
}
I could reference file including above code using reference syntax on top of file in other internal modules and normally call:
var ctrl = new SomeNamespace.Controller.Index;
ctrl.index();
It seems that in 0.8.2 this is the only way what it works for internal modules:
var path = require('path');
var fs = require('fs');
module SomeNamespace.Controller {
export class Index {
...
}
}
Are there any other possibilities to mix internal modules with Node.js modules? Is there something wrong with above require usage (it compiles and runs okay ...)?
I think that TypeScript 0.8.2 takes us closer to the specification.
The syntax:
import x = module('SomeModule');
Is specifically an ExternalModuleReference in the TypeScript Language Specification.
An internal module would be imported using:
///<reference path="SomeModule.ts" />
import x = SomeModule;
But importing an internal module won't generate you a require statement in your JavaScript.
Taken from TypeScript Language Specification 0.8 - 9.2.2 Import Declarations
ImportDeclaration:
import Identifier = ModuleReference ;
ModuleReference:
ExternalModuleReference
ModuleName
ExternalModuleReference:
module ( StringLiteral )
Ok, this error is due to the version of the TypeScript.
In TypeScript 0.8.1.1 to import an external module the syntax has to be:
export import <moduleName> = module(“<path>”);
This is a bug identified in the latest version of TypeScript, you can return to the previous version or change the syntax to make it compatible with v0.8.1.1. Have in mind that this is a bug and in future versions, you should be able to use the original syntax.
This is the official thread for this bug:
http://typescript.codeplex.com/discussions/405800

Resources