Monday, 30 July 2018

Using React within a dynamically loaded es module

I have been loading a native ES Module which can be simplified to src/test.tsx:

export default class Test {
    constructor() {
        console.log('loaded');
    }
}

I can load this in my browser and initialize it great, a la:

import('http://127.0.0.1:8085/').then(m => { 
  const instance = new m.default();
});

However.. if I want to add any external dependency, in this case React, I can't seem to figure out how to target es6 and also bundle React, with tsc. So my dist file contains import React from 'react'; for which the browser has no idea how to resolve, and produces:

(index):1 Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

My tsconfig looks like:

{
    "compilerOptions": {
        "baseUrl": ".",
        "rootDir": "src",
        "module": "es6",
        "target": "es2015",
        "lib": ["es6", "dom"],
        "declaration": true,
        "jsx": "react",
        "outDir": "dist",
        "strict": true,
        "noImplicitAny": false,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "skipLibCheck": true
    },
    "include": ["./src/**/*"]
}

Running node v9.5.0, typescript v2.9.2

I have also attempted to use webpack to bundle everything but cannot figure out how to produce a dynamically importable module that way



from Using React within a dynamically loaded es module

No comments:

Post a Comment