I am creating a modular component library with React and TypeScript with Babel 7.
I want the user of my library to import the components by a syntax similar to this:
import SomeComponent from "my-awesome-lib/SomeComponent"
SomeComponent is a TSX module in my-awesome-lib package:
import * as React from "react";
export default function () {
return <h1>SomeComponent</h1>
}
And main field of the package.json file of my-awesome-component is:
"main": "src/index.ts"
I do not want to publish compiled version of my component library, because I am importing CSS and other assets in my components and I expect all the users of my package to use Webpack with some specific configs.
Now my problem is that `import SomeComponent from "my-awesome-lib/SomeComponent" fails with a parse error:
ERROR in ../node_modules/wtf/index.tsx 4:9
Module parse failed: Unexpected token (4:9)
You may need an appropriate loader to handle this file type.
|
| export default function () {
> return <h1>WTF</h1>
| }
It seems Webpack does not load or transform the TSX files in node_modules.
I use this tsconifg.json at the root of my user app (which imports my-awesome-lib):
{
"compilerOptions": {
"outDir": "./dist",
"module": "commonjs",
"target": "es5",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true,
"downlevelIteration": true,
"lib": ["es5", "es2015", "dom", "scripthost"],
"typeRoots": ["node_modules/@types", "src/@types"],
},
"include": ["src/**/*", "node_modules/**/*"],
"exclude": []
}
And the relevant configurations of Webpack are:
const tsModules = {
test: /\.(js|jsx|ts|tsx)$/,
include: [path.resolve('src')],
exclude: /node_modules/,
loader: 'babel-loader'
}
const resolve = {
alias: {
},
modules: [
'node_modules'
],
extensions: ['.tsx', '.ts', '.js']
}
module.exports = {
...
context: resolve('src'),
resolve: resolve,
module: {
rules: [
tsModules,
...
]
}
}
How can I make Webpack to load and transform TSX modules of my-awesome-lib from node_modules?