Challenges faced while setting up a closure-compiler/typescript front end workflow

My current focus is on creating an effective workflow that involves using Gulp, Closure Compiler, and TypeScript with npm modules stored in a private Sinopia repository.

The ultimate objective is as follows:

  • To develop projects with browserify and TypeScript, then publish the shared code to the private npm repository.

  • To subsequently enhance a web application project using Closure Compiler.

(Closure Compiler isn't optional; UglifyJS doesn't provide the level of optimizations I require in terms of file size and performance)

Everything works smoothly when my project is self-contained within my source tree (i.e., without npm-installed modules). Here's the functional gulpfile:

var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var size = require('gulp-size');
var server = require('gulp-live-server');
var typescript = require('gulp-typescript');
var closureCompiler = require('gulp-closure-compiler');

/** No minification */
gulp.task('compile-dev', function() {
    console.log("compile-dev at "+new Date())
    var b = browserify({baseDir: "src", debug: true})
        .add("src/main.ts")
        .plugin('tsify', { noImplicitAny: true, target: "es6"});
    b.bundle()
    .on('error', function(error) {
        console.error(error.toString());
    })
    .pipe(source("out.js"))
    .pipe(gulp.dest("www"))
})

/* Minify with Closure */
gulp.task('compile-closure', function () {
    gulp.src('src/**/*.ts')
    .pipe(typescript({target: "es6"}))
    .pipe(gulp.dest("build"))
    .pipe(closureCompiler({
        fileName: "out.js",
        compilerFlags: {
            language_in: "ES6",
            language_out: "ES5",
            compilation_level: "ADVANCED_OPTIMIZATIONS"
        }
    }))
    .pipe(gulp.dest("www"))
    .pipe(size({gzip: true, showFiles: true }))
});

However, when integrating modules into the project, I encounter three intertwined issues:

  • Publishing the npm package and compiling the top-level project with TypeScript's target: "es6" triggers a 'ParseError: 'import' and 'export' may appear only with 'sourceType: module'' error in Browserify under the compile-dev task. Compiling the module with TypeScript target: "es5" resolves this issue but limits functionality to targeting "es5" across the board.

  • Transitioning to "es5" leads to Closure Compiler raising an error like '

    Error: build/main.js:2: WARNING - dangerous use of the global this object
    var __extends = (this && this.__extends) || function (d, b) {'
    . This indicates that Closure Compiler struggles with consuming the es5 output from TypeScript.

  • If I persist with "es6" as the TypeScript target, both Browserify (compile-dev) and Closure continue to face issues. Closure, understandably, cannot find my library because it doesn't search node_modules for import Foo from "bar".

So, how can I:

  • Instruct Closure Compiler to look in node_modules when importing external libraries (without requiring './')?
  • Enable Browserify to process these es6 modules from npm effectively?

Answer №1

Currently, closure compiler does not support referencing named modules directly. One workaround is to utilize a bundler that can remove named module references before compiling.

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

Assign the image source to the file path located in the data directory

Is there a way to dynamically set the src attribute of an <img> tag in an HTML file using a string path from a file? The path is retrieved from the cordova.file.dataDirectory Cordova plugin within Ionic2 (TypeScript) and it typically looks like this ...

Troubleshooting an angular problem with setting up a dynamic slideshow

I am currently working on building a slideshow using plain HTML, CSS, and JavaScript. I referred to the following example for guidance: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto However, despite implementing the code prov ...

Unlocking the power of vscode webview with acquireVsCodeApi in a React project

Currently, I am in the process of creating a new extension for Visual Studio Code using Webview. However, I am encountering difficulties with sending messages from the client to the extension. To kickstart the project, I decided to utilize this awesome rep ...

The data type 'unknown' cannot be assigned to the type 'any[]', 'Iterable<any>', or (Iterable<any> & any[])

I have been working on creating a custom search filter in my Angular project, and it was functioning properly. However, I encountered an error in my Visual Studio Code. In my previous project, everything was working fine until I updated my CLI, which resul ...

Why does TypeScript require a generic type parameter when arguments have already been provided?

When I attempted to use the argument p to infer type P, TypeScript still prompted me to provide type P. Why is that? const numberStringConverter = <T extends string | number,P extends {x: any}>(p: P): T => { if(typeof p.x === 'string') ...

Display a dynamic array within an Angular2 view

I have a dynamic array that I need to display in the view of a component whenever items are added or removed from it. The array is displayed using the ngOnInit() method in my App Component (ts): import { Component, OnInit } from '@angular/core' ...

What is the best way to set up jest on my system?

Having some difficulties installing jest using the following command: npm i --global jest and encountering these messages: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="17657264787b61723a62657b57273925392 ...

Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up: Defining the observable for the image amount: public imageAmount: KnockoutObserva ...

The attempt to install the "now" package using npm on OSX 10

Looking for some assistance here as I'm running into issues trying to install 'nowjs' using npm on my OSX ML 10.8. Just to clarify, I have xCode installed and command line utilities set up. Below are the lines from npm-log showing the error ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

Can ng-content be utilized within the app-root component?

I have successfully developed an Angular application, and now I am looking to integrate it with a content management system that generates static pages. In order to achieve this, I need to utilize content projection from the main index.html file. The desi ...

Troubleshooting problem with event triggering in Angular's ngSelect dropdown menu items

Hello, I am currently utilizing ngSelect but encountering an issue. Whenever a user hovers over an option in ngSelection, I would like to trigger an event that is created in my typescript file. I am using Angular 13, so I am unsure how to achieve this. Is ...

Unleashing the power of dynamic data imports in a Node.js application

My goal is to utilize the require function in a node/express application with typescript to import a json file. Here's how I attempted it: const url = `./data/${resource}.json`; const data = require(url); However, I encountered the error Cannot find ...

Exploring Angular2: The Router Event NavigationCancel occurring prior to the resolution of the Route Guard

My application has routes protected by an AuthGuard that implements CanActivate. This guard first checks if the user is logged in and then verifies if certain configuration variables are set before allowing access to the route. If the user is authenticated ...

Broaden the current category within the MUI Theme

I am attempting to enhance the current options within MUI's theme palette by adding a couple of properties. Take a look at this example: declare module @material-ui/core/styles/createMuiTheme { interface CustomOptions extends SimplePaletteColorOptio ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

Issue with rendering PDF document using react-pdf library

I am a newcomer to the world of react, and I'm attempting to showcase a pdf file in a browser. Unfortunately, I keep encountering an error stating failed to load PDF. I'm following the example program provided at https://www.npmjs.com/package/rea ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Dynamically load current components in Angular 2's final release

In my quest to dynamically load a component in the upcoming release version 2.0.0, I encountered some challenges. Previously, in RC5, I utilized the following code for loading: I created a directive responsible for loading the controls: import { Check ...

"Encountered a type error while trying to execute the 'ionic

An issue arose while trying to run your Ionic application: TypeError: Unable to access property 'hasOwnProperty' of undefined at C:\Users\Administrator\AppData\Roaming\npm\node_modules\ionic\l ...