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
2 Answers
Answers 1
Please use tsconfig.json as below :-
{ "compilerOptions": { "baseUrl": ".", "outDir": "build/dist", "module": "esnext", "target": "es5", "lib": ["es6", "dom","esnext.asynciterable"], "sourceMap": true, "allowJs": true, "jsx": "react", "moduleResolution": "node", "rootDir": "src", "forceConsistentCasingInFileNames": true, "noImplicitReturns": true, "noImplicitThis": true, "noImplicitAny": true, "strictNullChecks": true, "suppressImplicitAnyIndexErrors": true, "noUnusedLocals": true, "allowSyntheticDefaultImports": true, //Important for your problem "experimentalDecorators": true, }, "exclude": [ "node_modules", "build", "scripts", "acceptance-tests", "webpack", "jest", "src/setupTests.ts" ] }
Answers 2
With tsc-bundler
, you can use the importAs
switch to make it correctly bundle external references. This switch is not yet available as a tsconfig
option.
E.g.
tsc-bundle --project ./tsconfig.json --importAs react=React,react-dom=ReactDOM
0 comments:
Post a Comment