Navigating the waters of importing npm modules with typescript, gulp, and browserify is a skill

I'm facing challenges with performing some fundamental tasks such as importing packages that I installed using NPM. Despite conducting extensive research online and following various tutorials, I have been unable to achieve success. Here is my current configuration - attempting to use Gulp. It seems like I am overlooking something basic. I aim to utilize it directly in the browser, hence I followed a tutorial involving Browserify (although I also experimented with other guides without any luck).

For example, I have installed 'webmidi' via npm, and this is how my folder structure appears:

proj
+--node_modules
    +--module1
    +--module2
    +--webmidi
+--dist
+--src
    +--main.ts
    +--index.html

This is what my Gulpfile consists of:

var gulp = require('gulp');
var webmidi = require('webmidi');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var tsify = require('tsify');
var paths = {
    pages: ['src/*.html']
};

gulp.task('copy-html', function () {
    return gulp.src(paths.pages)
        .pipe(gulp.dest('dist'));
});

gulp.task('default', gulp.series(gulp.parallel('copy-html'), function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/main.ts'],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('dist'));
}));

The content of my main.ts file looks like this:

import * as webmidi from "webmidi";

console.log(WebMidi);
package.json:

{
  "name": "ts4",
  "version": "1.0.0",
  "description": "",
  "main": "./dist/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "browserify": "^16.5.0",
    "gulp": "^4.0.0",
    "gulp-require-modules": "^1.1.4",
    "gulp-typescript": "^6.0.0-alpha.1",
    "tsify": "^4.0.1",
    "typescript": "^3.8.2",
    "vinyl-source-stream": "^2.0.0"
  },
  "dependencies": {
    "webmidi": "^2.5.1"
  }
}

And here is tsconfig.json:

{
    "files": [
        "src/main.ts"
    ],
    "compilerOptions": {
        "noImplicitAny": true,
        "target": "es5"
    }
}

When I run the command 'gulp', I encounter the following error:

>gulp
[23:36:55] Using gulpfile ~\Documents\Projekte\code\ts4\gulpfile.js
[23:36:55] Starting 'default'...
[23:36:55] Starting 'copy-html'...
[23:36:55] Finished 'copy-html' after 39 ms
[23:36:55] Starting '<anonymous>'...
[23:36:57] '<anonymous>' errored after 2.21 s
[23:36:57] Error: TypeScript error: c:/users/username/documents/projekte/code/ts4/src/main.ts(4,13): Error TS2304: Cannot find name 'WebMidi'.
    at formatError (C:\Users\username\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\format-error.js:21:10)
    at Gulp.<anonymous> (C:\Users\username\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\log\events.js:33:15)
    at emitOne (events.js:121:20)
    at Gulp.emit (events.js:211:7)
    ...

As per this discussion on GitHub, the method I am employing to import WebMidi is correct and should work. However, I suspect there might be an oversight on my part. Can anyone provide assistance?

Answer №1

If you're new to using bundlers (which seems to be the case), I recommend giving Parcel a try.

It's incredibly user-friendly and doesn't require much setup at all.

For example, if you have an index.html file like this:

<html>
<head>
  <link rel="stylesheet" href="./style.sass">
</head>
<body></body>
<script src="./index.ts"></script>
</html>

You may notice that I included a typescript and sass file directly in the html. This is one of the reasons why Parcel is so convenient. By installing parcel (following their instructions typically involves global installation), you can simply run parcel index.html and it will handle all your dependencies, providing an auto-reloading page with source maps.

It's quite impressive. When it comes to other npm packages, just use npm i [package] in your project directory, import { [whatever] } from '[package]' in your typescript files, and you're ready to proceed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

issue with webpack-dev-server not refreshing after changes to HTML or Sass files

Here is the layout of my project: \root \webpack.config.js \public \ index.html \ ... \ css \ directives \ views \ dist (webpack output) \app.js ...

Trigger Angular2 EventEmitter in child component to inform parent component

I am having trouble triggering an event from the child component to the parent component. @Component({ template:'<foo></foo>' }) export class ParentComponent{ onDoSomething($event){ //handling logic goes here } } @Compo ...

Resolving redundancy in Typescript Material-UI Table codebases

Apologies for the ambiguous question title, it was difficult to come up with something more specific. I am currently exploring the Typescript implementation of Material-UI tables, specifically focusing on the table section titled "Sorting and selecting". ...

Generating TypeScript Type Definitions for dynamic usage

In my client server application, I use REST calls for communication. To avoid using the wrong types by mistake, I have defined all RestCalls in a common file (excerpt): type def<TConnection extends Connections> = // Authentication ...

The field 'XXX' is not a valid property on the type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>>'

When creating a Vue component with TypeScript, I encountered an error message in the data() and methods() sections: Property 'xxx' does not exist on type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>>& ...

Encountered an issue while attempting to assign a value to a property that is declared as [key in keyof T]

I am currently working on implementing a function that selects specific properties of an object. Here is the current function: const project = function<T>(object: T, projection: Projection<T>): Partial<T> { throw new Error("not imple ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

Parcel js is encountering difficulties running the same project on Ubuntu

I have encountered an issue with my JavaScript project when trying to run it on Ubuntu using parcel 2 bundler. The code works perfectly fine on Windows, but in Ubuntu, I am facing errors. Despite trying various solutions like cleaning the cache and reinsta ...

When trying to check a condition in Angular using a boolean, a TypeError is generated stating that a stream was expected instead of the provided 'false' value

Error: In global-error-handler.ts file at line 42, a TypeError has occurred. It states: "You provided 'false' where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable." Below is the s ...

Is it possible to design a Typescript type that only contains one property from a defined set and is indexable by that set as well?

I have the different types listed below: type OrBranch = { or: Branch[] } type AndBranch = { and: Branch[] } I need a type called Branch that can either be an OrBranch or an AndBranch. I initially attempted this: type Branch = AndBrand | OrBranch ...

Is it possible to determine if an HTML form has been modified?

Is there a way in typescript to determine if a form has been changed and return true or false accordingly? For example, if I have a first name field with the current value of "John" and then change it to "Johny", it should return true. But if I revert it b ...

Challenges with utilizing Ionic Native in a cross-platform application

I am currently developing an application using Ionic 2 that can function both as a website in a browser and as a mobile app on iOS and Android. One key aspect of the app is its use of the SQLite plugin when accessed on mobile devices. However, I have encou ...

What is the most effective method to retrieve the current browser URL in Angular 2 with TypeScript?

Is there a way for me to retrieve the current URL from the browser within my Angular 2 application? Usually in JavaScript, we would use the window object for this task. Can anyone guide me on how to achieve this in Angular 2 using TypeScript? Appreciate a ...

CSS-WHAT Package for Angular Update - Enhance Your Styles!

In my Angular setup, the configurations are as follows: _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | ...

Steps for making a GET request from an API in Angular 7

Currently, I am attempting to retrieve JSON data using HttpClient in Angular 7. The code is functioning properly, but I am exploring the option of fetching the data directly from the API URL instead of relying on the const IMAGES array. import { Injectable ...

The error message "Property '...' is not found on the type 'ServerContextJSONValue'" pops up whenever I try to utilize the useContext() function

After creating a Provider and defining the type, I encountered a TypeScript error when using it with useContext(): "Property '...' does not exist on type 'ServerContextJSONValue'. I'm not sure what I am missing. Can anyone help me ...

Is there a way to resolve the issue of retrieving the processed value directly in NestJS's @OnEvent function?

Due to excessive logic in the API and its slow performance, I have resorted to handling some of the logic with @OnEvent. The problem arises when the frontend runs the @GET API immediately after this API, potentially without waiting for @OnEvent to update. ...

Encountering an unauthorized error during the installation process on a private registry while using

I encountered an npm 128 error code while trying to install a project due to a dependency issue. npm install npm ERR! Error while executing: npm ERR! C:\Program Files\Git\mingw64\bin\git.EXE ls-remote -h -t <a href="/cdn-cgi/l/e ...

What is the proper method to deactivate a hyperlink in Angular 2?

I'm currently developing a web application using Angular2, and I find myself in need of displaying, but making it non-clickable, an <a> element within my HTML. Can anyone guide me on the correct approach to achieve this? Update: Please take no ...

Issue arose following the update from Angular 5 to 6, impacting the VSTS build process

Upon upgrading from Angular 5 to 6, I successfully got it running locally. It builds and compiles with --prod. Integration into an .NET MVC application went smoothly. However, when the build on VSTS is triggered, a series of errors surface: node_modules&b ...