Creating a React component library - reactjs

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?

This setup assuming you are using styled-components and have no css/scss.
What's important here is that you have "module": commonJS in your tsconfig and libraryTarget: "commonJS" in your webpack config. Externals tells webpack not bundle you're library with React, or React-DOM or styled-components and instead to look for those packages within the project you're importing into.
you're also going to need to take React, react-dom and styled-components out of your package.json dependencies and put those package in your peer-dependencies
const path = require("path");
const fs = require("fs");
const TerserPlugin = require('terser-webpack-plugin');
const appIndex = path.join(__dirname, "../src/main.tsx");
const appBuild = path.join(__dirname, "../storybook-static");
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');
module.exports = {
context: fs.realpathSync(process.cwd()),
mode: "production",
bail: true,
devtool: false,
entry: appIndex,
output: {
path: appBuild,
filename: "dist/Components.bundle.js",
publicPath: "/",
libraryTarget: "commonjs"
},
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
},
"styled-components": {
root: "styled-components",
commonjs2: "styled-components",
commonjs: "styled-components",
amd: "styled-components"
}
},
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
parse: {
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
comparisons: false,
inline: 2,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
ascii_only: true,
},
},
parallel: true,
cache: true,
sourceMap: false,
})
],
},
resolve: {
extensions: [".web.js", ".mjs", ".js", ".json", ".web.jsx", ".jsx", ".ts", ".tsx"],
alias: {
"react-native": "react-native-web",
},
},
module: {
strictExportPresence: true,
rules: [
{ parser: { requireEnsure: false } },
{
test: /\.(ts|tsx)$/,
loader: require.resolve("tslint-loader"),
enforce: "pre",
},
{
oneOf: [
{
test: /\.(tsx?)$/,
loader: require.resolve('awesome-typescript-loader'),
options: {
configFileName: 'tsconfig.prod.json'
}
},
],
},
],
},
plugins: [
new TsConfigPathsPlugin()
],
node: {
dgram: "empty",
fs: "empty",
net: "empty",
tls: "empty",
child_process: "empty",
},
performance: false,
};
note: it's important that you target a point in you're application as an entry that ONLY has the components you want to export.
I.E For me it's Main.tsx and inside Main.tsx it looks like this.
export { Checkbox } from "./components/Checkbox/Checkbox";
export { ColorUtils } from "./utils/color/color";
export { DataTable } from "./components/DataTable/DataTable";
export { DatePicker } from "./components/DateTimePicker/DatePicker/DatePicker";
export { DateTimePicker } from "./components/DateTimePicker/DateTimePicker/DateTimePicker";
export { Disclosure } from "./components/Disclosure/Disclosure";
This means webpack won't bundle things you're not meaning to export. To test you're bundle works try importing something with require syntax from the bundle to get around typescript typings and turn allowJS true in tsconfig.
something like
const Button = require("../path/to/js/bundle").Button
console.log(Button);

I found create-react-library extremely helpful

You are excluding your node_modules directory (which generally is a good thing):
const tsModules = {
test: /\.(js|jsx|ts|tsx)$/,
include: [path.resolve('src')],
exclude: /node_modules/,
loader: 'babel-loader'
}
Besides explicitely excluding the node_modules folder, you also only allow the content of the src folder to be processed by babel-loader because of your include property in tsModules. So this error:
ERROR in ../node_modules/wtf/index.tsx 4:9 Module parse failed:
Unexpected token (4:9)
makes sense.
You can still exclude node_modules except for a single folder if you remove the tsModules.include property and change your regular expression in tsModules.exclude:
const tsModules = {
// ...
exclude: /node_modules\/(?!my-awesome-lib)\/*/
// ...
}
Or you could, but I haven't tested it yet, add the my-awesome-lib dir to the include array:
const tsModules = {
// ...
include: [
path.resolve(__dirname, './src'),
path.resolve(__dirname, './node-modules/my-awesome-lib')
]
// ...
}
Then files in your node_modules/my-awesome-lib directory will pass the babel-loader which will transform the typescript code.
Edit: I think you confusion is coming from your tsconfig.json file with "include": ["src/**/*", "node_modules/**/*"],. Babel is transpiling your code, not typescript. So having a tsconfig.json file in your root directory may help your IDE (especially if you are using Microsoft's VScode), but has no effect on how babel and #babel/preset-typescript transform your code.

Related

Trying to render Froala Editor in React App, but the app crashes

I'm using React 17 with TypeScript and Webpack 5
and I'm trying to render Froala Editor from 'wysiwyg' package but I get this Error:
'FroalaEditorView' cannot be used as a JSX component. Its instance type 'FroalaEditor' is not a valid JSX element.The types returned by 'render()' are incompatible between these types. Type 'React.ReactNode' is not assignable to type 'import("/Users/Al/Desktop/projects/privateLib/node_modules/#types/react-transition-group/node_modules/#types/react/index").ReactNode. Type '{}' is not assignable to type 'ReactNode'.
Note: When I'm trying to render the Froala Editor in the app that I generate with CRA, I don't have any issue.
Any idea how to solve this problem?
Webpack Config:
const path = require('path');
const webpack = require('webpack');
const svgrLoader = require.resolve('#svgr/webpack');
module.exports = {
mode: "production",
entry: './src/index.ts',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'umd',
clean: true
},
devtool: 'source-map',
resolve: {
extensions: [".tsx", ".ts", ".jsx", ".js", ".json"],
modules: ['node_modules']
},
externals: {
react: "react"
},
module: {
rules: [
{
test: /\.(ts|tsx)?$/,
use:['ts-loader'],
exclude: /node_modules/
},
{
test: /\.(css|s[ac]ss)$/i,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
{
test: /\.svg$/i,
type: 'asset',
resourceQuery: /url/, // *.svg?url
},
{
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
resourceQuery: {not: [/url/]}, // exclude react component if *.svg?url
use: [
{
loader: svgrLoader, options: {
svgoConfig: {
plugins: [
{
name: 'removeViewBox',
active: false
}
]
}
}
},
]
},
{
test: /\.(woff(2)?|eot|ttf|otf|)$/,
type: 'asset/inline',
},
{
test: /\.(?:ico|gif|png|jpg|jpeg|)$/i,
type: 'asset/resource',
},
],
},
plugins: [
new webpack.ProvidePlugin({
FroalaEditor: 'file_name'
})
]
};
TS Config:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"target": "es5",
"module": "es2015",
"jsx": "react",
"strict": true,
"esModuleInterop": true,
"moduleResolution": "node",
"noUnusedLocals": true,
"types": ["node", "mocha", "jest","cypress", "cypress-file-upload","./cypress/support"],
"lib": ["es5","es2015","es2016", "dom","esnext"],
"outDir": "./dist/",
"sourceMap": true,
"declarationMap": true,
"declaration": true,
"resolveJsonModule": true,
},
"include": [
"src",
"node_modules/cypress/types/cypress-global-vars.d.ts"
],
"exclude": ["node_modules", "dist", "**/*.stories.tsx", "**/*.test.tsx"]
}
Render Code:
<FroalaEditorView
tag="textarea"
onModelChange={(newContent: ChangeEvent<HTMLTextAreaElement>) => props.onChange(newContent)}
config={textEditorConfig}
model={props.value}
/>
I’ve had the same issue with the FroalaEditor component in one of my projects (React 17 and Webpack 5). Although Typescript would complain about the component not being JSX, I could still build and run my application just fine. I managed to please Typescript (get rid of the error) by updating #types/react:
yarn add #types/react#latest
For npm it should be (not 100% sure):
npm install –save #types/react

How to make a declared module visible in Enzyme shallow render?

I've been trying to figure out how to have my declared module be found when I shallow render a component using enzyme in my jest unit tests. I have a custom declared module like so:
// index.d.ts
declare module "_aphrodite" {
import {StyleDeclarationValue} from "aphrodite";
type CSSInputType = StyleDeclarationValue | false | null | void;
interface ICSSInputTypesArray extends Array<CSSInputTypes> {}
export type CSSInputTypes = CSSInputType | CSSInputType[] | ICSSInputTypesArray;
}
Which is used by a component of mine called closeButton:
// closeButton.tsx
import {CSSInputTypes} from "_aphrodite";
export interface ICloseButtonProps {
onClick: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
cssStyles?: CSSInputTypes;
}
#injectable()
#observer
#autobind
export class CloseButton extends React.Component<ICloseButtonProps> {
// implementation
}
And a simple unit test that shallow renders a component:
// closeButton.test.tsx
import {shallow} from "enzyme";
import {CloseButton} from "../../common";
import * as React from "react";
describe("Common - Close Button", () => {
it("Shallow Render", () => {
const component = shallow(<CloseButton onClick={null}/>);
console.log(component);
});
});
When I run the test, I get the following error:
Which is strange because the closeButton class doesn't throw any compilation errors and maps the module fine. Same goes with when I run my project locally, it doesn't throw any run time error about not being able to find the _aphrodite module. It seems it's just with testing that this comes up.
Now I've tried to change various settings in my jest.config.json, tsconfig.json, and webpack.config.js settings with no luck. I'm hoping someone with more experience than I would know what needs to be done in order to make my _aphrodite module found when running a shallow render on a component.
Below are the settings for the aforementioned files:
// jest.config.json
{
"verbose": true,
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|svg)$": "<rootDir>/src/components/__tests__/_transformers/fileTransformer.js"
},
"transform": {
"\\.(ts|tsx)$": "ts-jest"
},
"setupFiles": [
"<rootDir>/src/components/__tests__/setup.ts"
],
"testRegex": "(/__tests__/\\.*|(\\.|/)(test))\\.tsx?$",
"testURL": "http://localhost/",
"collectCoverage": false,
"timers": "fake"
}
// tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build/",
"sourceMap": true,
"noImplicitAny": true,
"module": "esnext",
"target": "es2018",
"jsx": "react",
"watch": false,
"removeComments": true,
"preserveConstEnums": true,
"inlineSourceMap": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"lib": [
"dom",
"dom.iterable",
"es2018",
"esnext"
],
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"isolatedModules": false
},
"include": [
"./src/**/*"
],
"exclude": [
"./node_modules"
]
}
// webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require('webpack');
const dotenv = require('dotenv');
const fs = require('fs'); // to check if the file exists
module.exports = () => {
return {
plugins: []
};
};
/**
* DevServer
*/
const devServer = {
inline: true,
host: "localhost",
port: 3000,
stats: "errors-only",
historyApiFallback: true,
watchOptions: {
poll: true
},
};
module.exports.getEnv = () => {
// Create the fallback path (the production .env)
const basePath = __dirname + '/.env';
// We're concatenating the environment name to our filename to specify the correct env file!
const envPath = basePath + ".local";
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
// call dotenv and it will return an Object with a parsed key
const finalEnv = dotenv.config({path: finalPath}).parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(finalEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(finalEnv[next]);
return prev;
}, {});
return new webpack.DefinePlugin(envKeys);
};
/**
* Plugins
*/
const plugins = [
new HtmlWebpackPlugin({
template: "./index.html"
}),
module.exports.getEnv()
];
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/build",
publicPath: "/"
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{test: /\.tsx?$/, loader: "ts-loader"},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{enforce: "pre", test: /\.js$/, loader: "source-map-loader", exclude: [/node_modules/, /build/, /__test__/]},
{test:/\.css$/, use:['style-loader','css-loader'] },
{test:/\.(png|svg)$/, loader: "url-loader"},
{test:/\.mp3$/, loader: "url-loader" }
]
},
plugins: plugins,
devServer: devServer,
mode: "development",
performance: {
hints: false
}
};
And here is my project structure:
Feel free to ask if more information is needed.
Turns out I just needed to add it to the list of setup files in jest.config.json
// jest.config.json
"setupFiles": [
"<rootDir>/src/components/__tests__/setup.ts",
"<rootDir>/src/aphrodite/index.ts"
],

Webpack Dev Server cannot find modules with Typescript if I use custom paths in tsconfig

I'm building a project from scratch on React + TypeScript and using the Webpack Dev server.
I want to use relative paths to components, which will be not strict for a more flexible development.
In my App.tsx, I'm trying to import component:
import EntityTypes from "components/EntityTypes/EntityTypes";
and getting an error
Module not found: Error: Can't resolve 'components/EntityTypes/EntityTypes' in '/home/eugene/prj/work/crud-react/src'
File by this path exists (/src/components/EntityTypes/EntityTypes.js) and exports the class like
export default EntityTypes;
My tsconfig.json:
{
"compilerOptions": {
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "es5",
"lib": [
"es2015",
"es2017",
"dom"
],
"removeComments": true,
"allowSyntheticDefaultImports": false,
"jsx": "react",
"allowJs": true,
"baseUrl": ".",
"paths": {
"components/*": [
"src/components/*"
]
}
}
}
webpack.config.js:
const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const path = require( 'path' );
module.exports = {
context: __dirname,
entry: './src/index.js',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
output: {
path: path.resolve( __dirname, 'dist' ),
filename: 'main.js',
publicPath: '/',
},
devServer: {
historyApiFallback: true
},
module: {
rules: [
{
test: /\.(tsx|ts)?$/,
loader: 'awesome-typescript-loader'
},
{
test: /\.js$/,
use: 'babel-loader',
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|j?g|svg|gif)?$/,
use: 'file-loader'
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: path.resolve( __dirname, 'public/index.html' ),
filename: 'index.html'
})
]
};
I've checked the documentation of typescript about "paths", the file is exists, I don't understand what the problem.
I have sorted out how to use paths for my files and make them flexible, that I can reorganize the project and manage paths easy without a lot of changes of strict relative paths.
The problem was related to configuration of the webpack.
Final configuration is next:
tsconfig.json
{
"compilerOptions": {
// ...
"paths": {
"~/components/*": [
"./src/components/*"
],
"~/services/*": [
"./src/services/*"
],
"~/interfaces/*": [
"./src/interfaces/*"
]
},
}
}
webpack.config.js
const path = require('path');
module.exports = {
// ...
resolve: {
// ...
alias: {
'~/components': path.resolve(process.cwd(), './src/components'),
'~/interfaces': path.resolve(process.cwd(), './src/interfaces'),
'~/services': path.resolve(process.cwd(), './src/services'),
}
},
}
Examples of usage
import {IEntities} from "~/interfaces/entities.interface";
// ...
import EntityForm from "~/components/EntityForm/EntityForm";
Just add tsconfig-paths-webpack-plugin into your webpack configuration:
const { cwd } = require('node:process');
const { resolve } = require('node:path');
const TsconfigPathsWebpackPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
resolve: {
plugins: [
new TsconfigPathsWebpackPlugin({
configFile: resolve(cwd(), './tsconfig.json'),
})
]
}
};
And you don't need to duplicate paths configuration as webpack aliases.
You're using absolute imports, not relative ones. Try import EntityTypes from "./components/EntityTypes/EntityTypes";, assuming the file you're importing it into is on the same level as the components directory.

Webpack+ tsconfig + dynamic import throwing NoEmit error for .d.ts files

I'm having a strange issue understanding how webpack, tsconfig and .d.ts files are working together.
I've the following project structure:
The ScriptsApp contains an #types folder as follows:
My tsconfig.json is as follows:
{
"compilerOptions": {
"target": "ES2018",
"module": "esnext",
"lib": [
"es6",
"dom",
"scripthost",
"es2018",
"es2018.promise"
],
"jsx": "react",
"sourceMap": true,
"outDir": "./.out/",
"noImplicitAny": true,
"strictFunctionTypes": true,
"alwaysStrict": true,
"moduleResolution": "node",
"typeRoots": ["node_modules/#types", "ScriptsApp/#types"]
},
"include": ["./ScriptsApp/**/*.tsx", "./ScriptsApp/**/*.ts", "ScriptsApp/#types"],
"exclude": ["node_modules"],
"files": ["ScriptsApp/indexApp.tsx"]
}
And this is my webpack config:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
module.exports = {
mode: "development",
output: {
filename: "[name].bundle.[hash].js",
path: path.join(__dirname, ".out/"),
chunkFilename: "[name].chunk.js",
publicPath: "/",
hotUpdateChunkFilename: ".hot/hot-update.js",
hotUpdateMainFilename: ".hot/hot-update.json"
},
optimization: {
runtimeChunk: {
name: "manifest"
},
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
priority: -20,
chunks: "all"
}
}
}
},
target: "web",
devServer: {
contentBase: ".out/",
hot: true
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
inject: true,
template: path.join(__dirname, "./index.html")
}),
new ForkTsCheckerWebpackPlugin({
checkSyntacticErrors: true,
tslint: "./tslint.json",
tslintAutoFix: true,
tsconfig: "./tsconfig.json",
async: false,
reportFiles: ["ScriptsApp/**/*"]
})
],
module: {
rules: [
{
test: /\.(png|jpg|ico)$/,
loader: "file-loader",
options: {
name: ".img/[name].[ext]?[hash]",
publicPath: "/"
}
},
{
test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader",
options: {
name: ".fonts/[name].[ext]?[hash]",
publicPath: "/"
}
},
{
test: /\.(ts|tsx)$/,
use:"ts-loader"
},
{
test: /\.js$/,
loader: "source-map-loader"
},
{
test: /\.scss$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader",
options: {
sourceMap: true
}
},
{
loader: "resolve-url-loader"
},
{
loader: "sass-loader",
options: {
sourceMap: true
}
}
]
}
]
},
resolve: {
extensions: [".js", ".ts", ".tsx", ".scss", ".css", ".png", ".ico", ".json"]
},
devtool: "source-map"
};
Now my question:
I'm trying to use dynamic imports in one of my React components as follows:
private loadComponentFromPath(path: string) {
import(`../../ScriptsApp/${path}`).then(component =>
this.setState({
component: component.default
})
);
}
As soon as I added dynamic import, my build started showing this error for all the .d.ts files inside ScriptsApp/#types folder
WARNING in ./ScriptsApp/#types/react-adal.d.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:\code\AzureCXP-Eng\src\Applications\AzureCxpWebSite\WebSite\FeedbackSrc\App\ScriptsApp\#types\react-adal.d.ts.
at makeSourceMapAndFinish (C:\code\AzureCXP-Eng\src\Applications\AzureCxpWebSite\WebSite\FeedbackSrc\App\node_modules\ts-loader\dist\index.js:78:15)
at successLoader (C:\code\AzureCXP-Eng\src\Applications\AzureCxpWebSite\WebSite\FeedbackSrc\App\node_modules\ts-loader\dist\index.js:68:9)
at Object.loader (C:\code\AzureCXP-Eng\src\Applications\AzureCxpWebSite\WebSite\FeedbackSrc\App\node_modules\ts-loader\dist\index.js:22:12)
# ./ScriptsApp lazy ^\.\/.*$ namespace object ./#types/react-adal.d.ts
# ./ScriptsApp/Routes/AppRoutesList.tsx
# ./ScriptsApp/Routes/Routes.tsx
# ./ScriptsApp/Components/App.tsx
# ./ScriptsApp/indexApp.tsx
# ./ScriptsApp/index.tsx
# multi webpack-hot-middleware/client?reload=true ./ScriptsApp/index.tsx
How I can currently make the error go away?
Move #types folder outside the ScriptsApp, or
Not use dynamic imports
Rename all .d.ts files under ScriptsApp/#types to .interface.ts --> most baffling to me
I'm not able to understand why though. I'm also new to the entire technology stack so sorry if I'm missing something obvious. Please explain this behavior. Also, any suggestions on improving the configs are also much appreciated. Thanks.
From another GitHub issue you can do this in your tsconfig.json file.
{
"compilerOptions": {
"target": "ES6",
"jsx": "react",
"noEmit": true
},
"exclude": [
"node_modules",
"dev_server.js"
]
}
Could you try to add the line "noEmit": false.
The following code in tsconfig.json should ensure that the errors from within node_modules will not be reported.
{
compilerOptions: {
skipLibCheck: true
}
}

VS2017: Using JSX components from react theme in ASP.NET Core React Redux web application template

I've created a project using Visual Studio 2017 preview using the ASP.NET Core "React.js and Redux" project type.
I'm now trying to include components from a theme and we're running into some issues I haven't been able to resolve with extensive googling. I suspect I am misunderstanding how to use webpack. I've boiled it down to an extremely simple test case below.
Note: I have "allowJs": true in my tsconfig.json because it complains about not having the --allowJs flag when I try to import a jsx file otherwise.
This issue looks suspiciously similar to this issue: import jsx file in tsx compilation error but I believe this one is distinct and googling hasn't gotten me anywhere.
What I've tried:
setting "jsx" to "react", "react-native", and "preserve"
creating separate rule under sharedConfig in webpack.config.js (probably incorrectly?)
adding a rule for jsx and installing babel-core
Changing settings more or less at random in tsconfig.json and webpack.config.js
Too much googling
the error:
NodeInvocationException: Prerendering failed because of error: Error: Module parse failed: D:\MyProject\ClientApp\components\Card.jsx Unexpected token (5:12)
You may need an appropriate loader to handle this file type.
| render(){
| return (
| <div> Test </div>
| );
| }
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:21692:7)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:8547:64)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:8445:75)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:8498:66)
at __webpack_require__ (D:\MyProject\ClientApp\dist\main-server.js:20:30)
at D:\MyProject\ClientApp\dist\main-server.js:66:18
at Object.<anonymous> (D:\MyProject\ClientApp\dist\main-server.js:69:10)
Current directory is: D:\MyProject
Home.tsx
import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { ApplicationState } from '../store';
import Card from './Card';
type HomeProps = RouteComponentProps<{}>;
export default class Home extends React.Component<RouteComponentProps<{}>, {}> {
public render() {
return <div>
<Card></Card>
</div>
}
}
Card.jsx
import React, { Component } from 'react';
class Card extends Component{
render(){
return (
<div> Test </div>
);
}
}
export default Card;
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const merge = require('webpack-merge');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
// Configuration in common to both client-side and server-side bundles
const sharedConfig = () => ({
stats: { modules: false },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
});
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig(), {
entry: { 'main-client': './ClientApp/boot-client.tsx' },
module: {
rules: [
{ test: /\.css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new ExtractTextPlugin('site.css'),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig(), {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot-server.tsx' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
],
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"jsx": "react",
"experimentalDecorators": true,
"sourceMap": true,
"skipDefaultLibCheck": true,
"strict": true,
"lib": ["es6", "dom"],
"types": [ "webpack-env" ],
"allowJs": true
},
"exclude": [
"bin",
"node_modules"
]
}
To fix this we had to add some stuff to package.json and webpack to support babel loader. This hasn't been working perfectly, but it's gotten us a step closer to having things work properly. This is due to some unresolved typing issues.
Package.json
"babel-core":"6.26.0",
"babel-loader": "7.1.4",
"babel-preset-es2015": "6.24.1",
"babel-preset-react": "6.24.1",
Webpack.config.js:
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.(png|jpg|jpeg|gif)$/, use: 'url-loader?limit=25000' },
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['react', 'es2015']
}
}
]
},

Resources