How to import node modules in simple typescript

Viewed 1901

I'm new to TypeScript and I'm just trying to include a module that imports from a node module. I'm not using webpack or any other build tools as I'm trying to keep this as basic as possible to understand.

This is my structure:

/node_modules    -- contains node modules I want to import in main.ts
/scripts/ts/main.ts
/scripts/main.js -- the transpiled main.ts file
/index.html      -- includes the module script tag for scripts/main.js
/package.json
/tsconfig.json

This is my tsconfig.json:

{
    "compilerOptions": {
        "target": "ES6",
        "module": "ES2015",
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "outDir": "scripts",
        "moduleResolution": "Node",
        "experimentalDecorators": true
    },
    "$schema": "https://json.schemastore.org/tsconfig",
    "exclude": [],
    "include": [
        "scripts/ts/**/*"
    ]
}

My main.ts file has these imports:

import { css, html, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';

The main.ts file gets transpiled and main.js is loaded successfully. But I get this error:

Uncaught TypeError: Failed to resolve module specifier "lit". Relative references must start with either "/", "./", or "../".

The import statements are transpiled "as is". They look exactly the same in the transpiled file so I imagine the issue is that the module path is wrong: The browser does not know that "lit" is in "node_modules/lit" and when I manually change the path in the transpiled file to ../node_modules/lit/index.js then I get another error which is

Uncaught TypeError: Failed to resolve module specifier "@lit/reactive-element". Relative references must start with either "/", "./", or "../".

Which I imagine is a module imported down the heirarchy by other lit modules. Basically my import paths are not transpiled properly and I don't know what to do. Any help would be great!

1 Answers

Thanks to @cdimitroulas for making me think about this.

ES6 imports need to have an absolute or relative path - "plain node imports" simply don't work and these paths need to be resolved somehow not only for the main module's imports but for every other module's imports down the dependency graph.

The Typescript compiler does not handle this and so the current setup was missing a tool that would resolve these paths (like web-dev-server) or bundle the modules and all their dependencies in one file (like webpack) thereby eliminating the need to resolve the paths.

Related