I am building a very basic React app by including the React library script tags in my html page, and loading my components in script tags. I am not using modules or create-react-app. My components looks like this:
TIPS.JS
class Tips extends React.Component {
constructor() {
super()
}
render() {
return (
<div>
<h1>Hello World</h1>
</div>
)
}
}
I have installed the babel transpolar:
npm install babel-cli#6 babel-preset-react-app#3
And now I can transpile my JSX component to normal JS with:
npx babel --watch src --out-dir . --presets react-app/prod
This is fine, but now I want to ALSO compile Typescript TSX, but these docs are a bit unclear on how to combine these. They refer to the Microsoft Typescript React Starter, but that uses Webpack, so it's not the same setup.
Typescript setup
nom install typescript
npx tsc --init
TSCONFIG.json
{
"compilerOptions": {
"rootDir": "src",
"outDir": "build"
},
}
Now I should be able to run npm run build but I can't find the settings for package.json.
Should I use tsc watch or babel watch ? Or can I just discard babel when using typescript?
In other words, what's the most basic setup to compile TSX components to javascript without using modules and webpack?
You can compile Typescript using Babel with #babel/preset-typescript.
npm install --save-dev #babel/preset-typescript
// .babelrc
{
"presets": ["#babel/preset-typescript"]
}
So just add this preset & add tsconfig.json to your project and you will able to transpile TS.
For more info
Related
New to Next.js/React here. I followed the Tailwind CSS for Next.js tutorial and added Tailwind to my project like so:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Then, per those instructions, modified the generated tailwind.config.js like so:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,jsx}",
"./components/**/*.{js,jsx}",
],
theme: {
extend: {},
},
plugins: [],
}
and globals.css like so:
#tailwind base;
#tailwind components;
#tailwind utilities;
...rest of my CSS styles are down here (there are many)
When I started up the dev server (npm run dev) I got errors complaining about it detecting nested CSS which led me to eventually find this article on fixing CSS nesting in Tailwind.
So I updated postcss.config.js to look like:
module.exports = {
plugins: {
'postcss-import': {},
'tailwindcss/nesting': {},
tailwindcss: {},
autoprefixer: {},
}
}
And now I am seeing these errors:
wait - compiling...
wait - compiling /404 (client and server)...
warn - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[2]!./styles/globals.css
Warning
(42:5) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin *before* Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
warn - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[2]!./styles/globals.css
Warning
(42:5) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin *before* Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
warn - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[2]!./styles/globals.css
Warning
(42:5) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin *before* Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
<w> [webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|/Users/myuser/workspace/myapp/node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!/Users/myuser/workspace/myapp/node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[2]!/Users/myuser/workspace/myapp/styles/globals.css': No serializer registered for Warning
<w> while serializing webpack/lib/cache/PackFileCacheStrategy.PackContentItems -> webpack/lib/NormalModule -> Array { 1 items } -> webpack/lib/ModuleWarning -> Warning
What is going on here, why am I seeing these errors/warnings and how can I fix them?
It seems like you've missed the last step. Step-4. Run the following command
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch
step 1
npm install -D tailwindcss
npx tailwindcss init
step 2
Add the paths to all of your template files in your tailwind.config.js file.
module.exports = {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {},
},
plugins: [],
}
step 3
Add the #tailwind directives for each of Tailwind’s layers to your main CSS file
#tailwind base;
#tailwind components;
#tailwind utilities;
step 4
Start the Tailwind CLI build process
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch
I cleared up the nested CSS violations in my global.css file and Tailwind is now working perfectly.
I have a React component library that is used in a React app. The component library is setup using Styleguidist and webpack. I've setup webpack to use absolute paths using:
webpackConfig: {
resolve: {
modules: [path.resolve(__dirname, 'src/'), 'node_modules'],
}
}
This works within the context of the component library. When I build the component library, the package looks like this:
/core
/components
/Table
/Row
When I import the components into my app, I get an error:
Module not found: Can't resolve components/Row in /Users/myusername/Sites/mysite/node_modules/#mypackage/core/components/Table
I understand why the paths don't match in the context of node_modules, but I would've expected Webpack to transform those import paths during the build process. Is there something I'm missing? Or is this not possible?
While Styleguidist uses webpack, it turns out the build script we were using does not, so the webpack config is irrelevant. Instead, our build script (https://www.npmjs.com/package/cod-scripts) uses babel.
We ended up having to add a separate babel.config.js file to define absolute paths for babel using the babel-plugin-module-resolver package.
npm install babel-plugin-module-resolver --saveDev
npm install #babel/preset-react --saveDev
babel.config.js
module.exports = {
plugins: [
[
'module-resolver',
{
root: ['./src'],
},
],
],
presets: ['#babel/preset-react'],
};
I created a module using CRA (Create-React-App) - typescript and published the same to npm.
My goal is to add the module as a component in another CRA created typescript project. When I try to import the module it fails with below error.
Cannot find module: 'fbdemots'. Make sure this package is installed.
I do see the modules in the path "node_modules\fbdemots".
I tried the below which did not help
Creating declaration files(d.ts) both in the module and the project which uses the module
Updating the TSConfig as mentioned in below link
Below links does not help, as I cannot change the
"module": "esnext", --> to "CommonJS" since CRA (Create-React-App) does not allow me to.
"moduleResolution": "node", "esModuleInterop" : "true"
`Cannot find module` for my own TypeScript module
Wait! Why I see the fbdemots of node_modules is a project, not component, and it can't be exported at all
If you want to publish a component, you can follow these common steps, of course there are other methods you can try.
If you don't want to use rollup/webpack or feel a bit complicated, you can just export your plain component, and then publish it.
1. Create a component and export it
// index.tsx
import React from 'react'
const Test = (props: {a: string})=> <div>{props.a}</div>
export default Test
2. Using rollup or Webpack to build it to make sure it would be usable for JS modules
Install some necessary modules
yarn add --dev rollup rollup-plugin-typescript2
Then create rollup.config.js file at root, if there are other files like '.css', '.scss', then you should install and add some plugins like rollup-plugin-sass or rollup-plugin-css-only...
// rollup.config.js
import typescript from 'rollup-plugin-typescript2';
// import sass from 'rollup-plugin-sass';
export default {
input: 'index.tsx', // the path of your source file
output: [
{
dir: 'lib',
format: 'cjs',
exports: 'named',
sourcemap: false,
strict: false,
},
],
plugins: [typescript()],
// plugins: [sass({ insert: true }), typescript()],
external: ['react', 'react-dom'],
};
3. Create lib
Using the command of rollup to build it
npx rollup -c
And then prepare package.json, LICENSE, README.md... into lib dir,
finally you can publish it
npm publish ./lib --access public
The end of the last, you can add it as a component in another CRA created typescript project!
I am developing a Web application using React and Laravel. I want both to be in the same project. So in the Laravel application, I installed react using preset (php artisan preset react) following this link, https://appdividend.com/2017/08/31/laravel-5-5-reactjs-tutorial/. My set up was working. At some point, I installed the react bootstrap as well running this command.
npm install react-bootstrap --save
Then I used the bootstrap Button component like this in my project.
import React, {Component} from 'react';
import Button from 'react-bootstrap/lib/Button';
class CreateItem extends Component {
render() {
return (
<div>
<h1>Create An Item</h1>
<form>
<Button>Submit</Button>
</form>
</div>
)
}
}
export default CreateItem;
It was still working fine. Then, I used the es6 syntax in my component like this.
class CreateItem extends Component {
addItem = () => {
}
//other code
}
export default CreateItem;
When I run it was throwing error because I used the es6 syntax. So, to solve the errors, I installed the required babel packages running the following command.
npm install --save babel-loader babel-core babel-preset-es2015 babel-preset-react --dev
When I run "npm run watch", it is throwing this error.
ERROR in ./node_modules/react-bootstrap/lib/utils/bootstrapUtils.js
Module not found: Error: Can't resolve '#babel/runtime/core-js/object/entries' in '/Applications/MAMP/htdocs/react_integration/node_modules/react-bootstrap/lib/utils'
# ./node_modules/react-bootstrap/lib/utils/bootstrapUtils.js 13:38-86
# ./node_modules/react-bootstrap/lib/Button.js
# ./resources/assets/js/components/CreateItem.js
# ./resources/assets/js/app.js
# multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss
ERROR in ./node_modules/react-bootstrap/lib/Button.js
Module not found: Error: Can't resolve '#babel/runtime/core-js/object/values' in '/Applications/MAMP/htdocs/react_integration/node_modules/react-bootstrap/lib'
# ./node_modules/react-bootstrap/lib/Button.js 8:37-84
# ./resources/assets/js/components/CreateItem.js
# ./resources/assets/js/app.js
# multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss
Basically, it does not like the bootstrap. This line
import Button from 'react-bootstrap/lib/Button';
When I remove it, it does not support the es6 syntax as well. Now, I cannot use both es6 (babel) and the bootstrap in my project. I tried adding the .babelrc file into my project root folder with the following content as well.
{
"presets": [
["es2015", {
"modules": false
}],
"react"
]
}
It is still throwing the same error. So, what went wrong? How can I use React with babel and react-bootstrap inside a Laravel project together? How can I fix this error?
In the browser console, I got this error.
Uncaught Error: Cannot find module "#babel/runtime/core-js/object/values"
at webpackMissingModule (app.js:60211)
at Object.module.exports (app.js:60211)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:59878)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:15646)
at __webpack_require__ (app.js:20)
at Object.defineProperty.value (app.js:15631)
at __webpack_require__ (app.js:20)
at app.js:63
This is a recently introduced bug you are hitting, making the 0.32.2 version of react-bootstrap incompatible with the babel version used:
https://github.com/react-bootstrap/react-bootstrap/issues/3231
We temporarily fixed the react-bootstrap version to 0.32.1 as a workaround.
When I try to import Jquery like
import $ from 'jquery';
inside test file
or like
import $ from 'jquery'; global.$ = global.jQuery = $;
inside the Jest setup file, I get error as
● Runtime Error- SyntaxError: Unexpected identifier
at new Function (<anonymous>)
at createMockFunction (node_modules/jest-mock/build/index.js:179:10)
at Array.forEach (<anonymous>)
at Array.forEach (<anonymous>)
How to fix this issue? Checked the path and node_modules for Jquery both are fine. using Jest version "^14.1.0".
I have a newer version of Jest (v24.7.0), so I'm not sure this answer works with the Jest version used in the question.
From a note on Jest documentation:
Note: babel-jest is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project.
I found the solution on the Jest documentation itself:
Install these dependencies: npm install --save-dev babel-jest #babel/core #babel/preset-env
Add a configuration file for Babel similar to this one in your project's root directory:
// babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
Try using #babel/preset-env. Here's an example .babelrc:
{
"env": {
"test": {
"presets": [["#babel/preset-env"]]
}
}
}
You can add additional configuration options, of course; the important part is that #babel/preset-env is set as a preset in your env.test object.