TLDR I am targeting the browser. Using VSCode to write typescript and consume a (sample) npm package. I checked as best I can but I get an uncaught error in browser console saying
Uncaught ReferenceError: require is not defined
Longer version:
I am trying to work in my typescript project with the a package named Graphemer, but I had a similar issue with another package so I think this is my issue, not the packages. I am writing my code in VScode, target is the browser. Here is my tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "ES6",
"moduleResolution": "node",
"outDir": "./dist",
"strict": true,
"skipLibCheck": true
}
node -v gives version v16.17.0 tsc -v gives Version 4.9.3 Chrome browser is Version 111.0.5563.65 (Official Build) (64-bit)
So...
I install Graphemer into the project folder /node_modules folder via $ npm i graphemer.
The docs in Graphemer github say I can then, in my own TS file, do
import Graphemer from 'graphemer';
const splitter = new Graphemer();
import Graphemer from "Graphemer";
function test() {
const splitter = new Graphemer();
}
main.js:6 Uncaught ReferenceError: require is not defined
at main.js:6:21
And I look in the /dist/main.js file to see
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Graphemer_1 = __importDefault(require("Graphemer"));
function test() {
const splitter = new Graphemer_1.default();
}
Where of course there is a line referencing require...
const Graphemer_1 = __importDefault(require("Graphemer"));
Question - what is the proper configuration of TSC, when targeting the browser, to get the JS generated to simply work with ES6 import/export module syntax?
Supplementary info:
The content of the Graphemer file /node_modules/Grapheme /lib/indexjs is
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Graphemer_1 = __importDefault(require("./Graphemer"));
exports.default = Graphemer_1.default;
console.log('exports',exports)
To use npm
modules in a browser-hosted application, you'll need to use a bundler like Vite, Webpack, Rollup, Browserify, etc. That's because you won't provide the entire node_modules
directory in script
tags in your application. The purpose of the bundler in this situation is to wrap up your code along with code from node_modules
and put it into "bundles" that you then include in your browser application.
Alternatively, you can use some npm
modules directly via https://unpkg.com, and many of them may also be available with UMD builds (so they work in various environments, including browsers) on CDNs like https://cdnjs.com/ where you can directly reference them in your script tags.