Failed to resolve module specifier "babel-runtime/regenerator" - javascript

I'm following the instructions for this link. https://reactjs.org/docs/add-react-to-a-website.html
I have the following code and it works:
const domContainers = document.querySelectorAll('[name="uiattr"]');
domContainers.forEach((element) => {
const id = element.id.split("-")[1];
ReactDOM.render(e(LikeButton), element);
});
If i change it to this code and add async to it:
const domContainers = document.querySelectorAll('[name="uiattr"]');
domContainers.forEach(async (element) => {
const id = element.id.split("-")[1];
const attr = await getAttr(id);
ReactDOM.render(e(LikeButton), element);
});
i get the following error in the console with nothing else: Failed to resolve module specifier "babel-runtime/regenerator"
I installed bable like this: npm install babel-cli#6 babel-preset-react-app#3
and i deploy with this command: js-dev$ npx babel --watch src --out-dir ../prj/static/prj/js/ --presets react-app/prod
I am new to the babel world, i'm assuming i need something else, but have no idea. I'm assuming the syntax is correct, only because its compiling without error. Something i've seen babel fail on when i have it wrong.

The React tutorial is indeed very confusing and doesn't cover all aspects.
I would suggest to just install react & react-dom: npm install --save react react-dom
You will need webpack to bundle your code and babel + a couple of plugins to compile your JSX, use async functions, ...: npm install --save-dev #babel/core #babel/preset-env #babel/preset-react #babel/plugin-transform-runtime babel-loader webpack webpack-cli.
Create a webpack.config.js file in your root folder:
const path = require('path');
module.exports = {
mode: "development", // or production
entry: {
app1: './react/app1/index.js'
},
watch: true,
output: {
filename: "[name].js",
path: path.join(__dirname, "public/react")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
}
]
}
};
Create a .babelrc file in your root folder:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-transform-runtime"]
}
Example react/app1/index.js file:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("myContainer"));
Write your react code in ./react/app1/index.js (you can import other React files, modules, ...)
Then in your html just put a script tag: <script src="public/react/app1.js"></script>

Related

Unable to build jQuery ui with webpack

I'm unable to successfully include jQuery UI in my project using webpack. jQuery has been working, but when I visit a page of my app that requires jQuery-UI I get the following warning:
jQuery.Deferred exception: $(...).draggable is not a function TypeError: $(...).draggable is not a function
And error:
jquery.js:4055 Uncaught TypeError: $(...).draggable is not a function
I'm nearly brand new to building javascript code using webpack/node, so it's very possible I've made a naive mistake.
This is my config file:
config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/js/index.js',
mode: 'development',
output: {
filename: 'index.js',
path: 'path/js',
},
module: {
rules: [
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.js$/,
enforce: 'pre',
use: ['source-map-loader'],
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '../css/index.css',
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
})
],
resolve : {
alias: {
// bind version of jquery-ui
"jquery-ui": "jquery-ui/jquery-ui.js",
// bind to modules;
modules: path.join(__dirname, "node_modules"),
}
},
}
My entrypoint:
index.js
import '../sass/index.scss';
const $ = require("jquery");
require('webpack-jquery-ui');
require('webpack-jquery-ui/draggable');
global.$ = global.jQuery = $;
import 'bootstrap';
Each time I make a change I run the command:
npx webpack --config config.js
There are no errors output from this.
Where am I going wrong?
Update
Upon Chris G suggestion in comments I've tried the following:
import '../sass/index.scss';
const $ = require('webpack-jquery-ui');
global.$ = global.jQuery = $;
import 'bootstrap';
Upon rebuilding I get a series of errors in the console such as:
ERROR in (webpack)-jquery-ui/index.js
Module not found: Error: Can't resolve 'jquery-
ui/themes/base/autocomplete.css' in
'.../webpack/node_modules/webpack-jquery-ui'
# (webpack)-jquery-ui/index.js 57:0-49
# ./src/js/index.js
This is what's returned when running "npm install --save jquery jquery-ui"
npm WARN saveError ENOENT: no such file or directory, open '.../webpack/package.json'
npm WARN enoent ENOENT: no such file or directory, open '.../webpack/package.json'
npm WARN webpack No description
npm WARN webpack No repository field.
npm WARN webpack No README data
npm WARN webpack No license field.
Could this now be an install problem?
From my understanding, there are couple of things you need to do:
All you need to do is to only install webpack-jquery-ui.
I don't think you should are now resolving the correct jquery-ui in your webpack.config.js, just remove that alias of "jquery-ui"
resolve: {
alias: {
// bind to modules;
modules: path.join(__dirname, "node_modules"),
}
},
Finally, I don't think webpack-jquery-ui exports a jquery object for you so don't assign and export it in global anymore since it's currently available in your module with ProvidePlugin. So just simply write like following:
import '../sass/index.scss';
require('webpack-jquery-ui');
require('webpack-jquery-ui/draggable');
// $ is available in the module via `ProvidePlugin`
global.$ = global.jQuery = $;
import 'bootstrap';

How to make an import shortcut/alias in create-react-app?

How to set import shortcuts/aliases in create-react-app?
From this:
import { Layout } from '../../Components/Layout'
to this:
import { Layout } from '#Components/Layout'
I have a webpack 4.42.0 version.
I don't have a webpack.config.js file in the root directory. I've tried to create one myself with this code inside:
const path = require('path')
module.exports = {
resolve: {
alias: {
'#': path.resolve(__dirname, 'src/'),
}
}
};
But it doesn't seem to work. I've seen the NODE_PATH=. variant in .env file. But I believe, it is deprecated - better not to use. And also, I have a posstcss.config.js file. Because I've installed the TailwindCss and I import the CSS library there. I've tried to paste the same code there, but it also didn't work.
It is finally possible with Create React App v.3
Just put:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
into jsconfig.json or tsconfig.json if you use Typescript
Here is wonderful article about this.
Simplest way to archive this follow below steps. (same way as #DennisVash showed as but in simple form)
Installation - install and setup CRACO.
yarn add #craco/craco
# OR
npm install #craco/craco --save
Create a craco.config.js file in the root directory and configure CRACO:
/* craco.config.js */
const path = require(`path`);
module.exports = {
webpack: {
alias: {
'#': path.resolve(__dirname, 'src/'),
'#Components': path.resolve(__dirname, 'src/components'),
'#So_on': path.resolve(__dirname, 'src/so_on'),
}
},
};
Update the existing calls to react-scripts in the scripts section of your package.json file to use the craco CLI:
/* package.json */
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
}
Done! Setup is completed.
Now let's test it.
// Before
import Button from "./form/Button"
import { Layout } from '../../Components/Layout'
// After
import Button from "#/form/Button"
import { Layout } from '#Components/Layout'
Documentation Craco
Thank you. :)
// Absolute path: paths which are relative to a specific path
import Input from 'components' // src/components
import UsersUtils from 'page/users/utils' // src/page/users/utils
// Alias path: other naming to specific path
import Input from '#components' // src/components
import UsersUtils from '#userUtils' // src/page/users/utils
In order for webpack's aliases to work, you need to configure the default webpack.config.js of create-react-app.
The official way is to use the eject script.
But the recommended way is to use a library without ejecting (find the most modern library for that).
VSCode IntelliSense
In addition, you should add jsconfig.json file for path IntelliSense in VSCode (or tsconfig.json), see followup question.
Now such code with IntelliSense will work:
// NOTE THAT THOSE ARE ALIASES, NOT ABSOLUTE PATHS
// AutoComplete and redirection works
import {ColorBox} from '#atoms';
import {RECOIL_STATE} from '#state';
If you want to use:
// this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of this:
import MyUtilFn from '../../../../utils/MyUtilFn';
use the node module plugin for resolving the urls https://www.npmjs.com/package/babel-plugin-module-resolver. By installing it and adding it to your webpack/babel.rc file.
Step 1
yarn add --dev babel-plugin-module-resolver
add this plugin
Step 2
in babel.config.js file
ALIAS NAME ALIAS PATH
#navigation ./src/navigation
#components ./src/components
#assets ./assets
[
"module-resolver",
{
root: ["./src"],
alias: {
"^~(.+)": "./src/\\1",
},
extensions: [
".ios.js",
".android.js",
".js",
".jsx",
".json",
".tsx",
".ts",
".native.js",
],
},
];
Step 3
import example
import SomeComponent from '#components/SomeComponent.js';
Step 4
restart server
yarn start
Reference link: How to use import aliases with React native and VSCode

How to use LESS in React 16.7 with webpack 4.29?

I am just start to learn React, and I want to use less in React. I did some research about it , and they said I should write the config in webpack.config.dev.js but , after I run npm run eject I only got one file :webpack.config.js .
I think maybe that's because the update , the new version maybe combined webpack.config.dev.js and webpack.config.prod.js to `webpack.config.js .
and I checked the homepage of webpack , it says:
// webpack.config.js
module.exports = {
...
module: {
rules: [{
test: /\.js$/,
issuer: /\.less$/,
use: [{
loader: 'js-to-less-loader'
}]
}]
}
};
but I don't know where to insert these code. I did not find any code like that.so I want a simple example for how to support less in React.
Thanks.
You need to do the following steps after ejecting to use less in react
1. Go to webpack.config.js file and search for cssRegex change it from /\.css$/ to /\.(?:le|c)ss$/
2. install less and less loader using npm install -S less less-loader
3. search for getStyleLoaders method in webpack config file and add the following object to array of loaders specified over there
{
loader: require.resolve('less-loader'),
options: {
importLoaders: 1,
},
}
Then you will be good to go, feel free to ask for clarifications if any
I believe you are using the create-react-app starter kit.
Well its good but if you want to add more features to your setup, Starter kits come with their own complications.
You can learn to setup react instead of letting the starter kit handling it for you.
Anyways you can try this,
You will need babel depedencies for handling transpilation:
npm install babel-core babel-loader babel-preset-env babel-preset-react --save-dev
Setup your react dependencies like so:
npm i react react-dom --save-dev
Once you are done with this setup, include your .bablerc file with the following code:
{
"presets" : [
"env",
"react"
]
}
Setup dependencies to load your css/less files.
This will fetch all the loaders you require for css and less.
npm install less less-loader style-loader css-loader --save--dev
Now you will need an HTML plugin and a template .html file for webpack to serve your react.
npm i html-webpack-plugin html-loader --save-dev
The template file (save this as src/index.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<style>
* {
box-sizing: border-box;
}
</style>
<body>
<div class='content' id='app'></div>
</body>
</html>
You will now need a webpack devServer for serving the generated index.html
npm install webpack-dev-server --save-dev
Add the following to your package.json file
"scripts": {
"start": "webpack --mode development",
"build": "webpack --mode production"
}
By now you should be having a webpack.config.js file, which fairly looks like this.
const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
const {
mode
} = argv;
return {
module: {
entry: path.join(__dirname, 'src', 'app.js'),
watch: mode !== 'production',
output: {
path: path.join(__dirname, 'dist'),
filename: mode === 'production' ? 'bundle.min.js' : 'bundle.js'
},
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
}
],
plugins: [
new HtmlWebPackPlugin({
title: 'App',
template: "./src/index.html",
filename: "./index.html"
})
]
},
devServer: {
contentBase: path.join(__dirname, 'dist')
}
};
}
And a app.js file in your src folder like so,
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/style.less'
ReactDOM.render( <div> Hello from react! </div>, document.getElementById("app"));
Use npm start to run the dev version.
Hope this helps. Let me know if you face any issues.
I agree this is tedious work for the first time. But it does help in the long run to scale with features.

Configure Webpack 4 with aliases, Babel 7 to build React components library

I'm trying to create two React projects:
React components library (only components without working application)
SPA application which uses created components (examples application)
I would like to achieve a folders structure like:
./src - directory with React components
./example - contains SPA app which uses ./src components
There are configuration files in example directory (simplest React + webpack config without HMR and other stuff):
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const aliases = require('./aliases.js');
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
}
]
},
resolve: {
alias: aliases
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
aliases.js
var path = require('path');
module.exports = {
'webpack-alias-react': path.resolve(__dirname, '../src')
};
babel.rc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
VSCode alias config is in jsconfig.json file.
And there is my problem.
When ./src/SimpleComponent contains code like that:
const SimpleComponent = () => {
return 'string';
};
Running npm run build command builds working application.
But when ./src/SimpleComponent returns:
const SimpleComponent = () => {
return <div>abc</div>;
};
npm run buid command throws exception:
ERROR in ../src/SimpleComponent.js Module build failed (from
./node_modules/babel-loader/lib/index.js): SyntaxError:
D:\Tranzystor\webpack-alias-react\src\SimpleComponent.js: Unexpected
token (4:9)
How to solve this webpack/Babel configuration issue?
Why is it possible to write <div> in App.js?
Is that right approach?
Whole code is here available.
I've solved that issues with Babel 7 and extended solution for that kind of issues is there:
github
It's ready to use webpack 4 + React + Babel 7 + eslint configuration.
It can be helpful for monorepo solutions.
Publishing your own components library to npm can be another application. As I mentioned above ./src directory contains small react components (content which you want to publish on npm). In ./demo directory there is spa application which shows how to use supplied components (it can be storybook for example).

How to use babel-polyfill in gulpfile.js

In Babel docs they just say that to include import "babel-polyfill"; so that I can use ES6 generators but after I included that line in my gulpfile.js I still gen an exception : Uncaught ReferenceError: regeneratorRuntime is not defined
This is my gulpfile.js
import 'babel-polyfill';
var gulp = require("gulp"),
babel = require("gulp-babel"),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify');
gulp.task("babel", function() {
return gulp.src(jsSrc)
.pipe(concat('Main.js'))
.pipe(babel())
.pipe(gulp.dest(jsDest))
.pipe(rename('Main-min.js'))
.pipe(uglify())
.pipe(gulp.dest(jsDest));
});
jsSrc have maines6.js and other .js files. In maines6.js here is my generator:
function* anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
I don't know how to use this.. can you help me?
Since you're just using gulp and not some sort of module bundler(webpack for e.g)
You should follow this guide https://github.com/babel/gulp-babel#runtime
npm install --save-dev babel-plugin-transform-runtime
and then use it like this
.pipe(babel({
plugins: ['transform-runtime']
}))
Should do the trick :)
EDIT:
Seems that babel-plugin-transform-runtime add require calls to the transformed file, so I guess you'll need to use a module loader. I would suggest webpack, although there are alternative like browserify and jspm.
You'll need
npm install -g webpack
npm install babel-loader babel-core babel-polyfill babel-preset-es2015 --save-dev
Then you'll need to create a webpack.config.js file. Here's a very primitive setup.
module.exports = {
context: __dirname + '/app',
entry: ['babel-polyfill', './entries/index.js'],
output: {
path: 'dist',
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
}
};
With the config above the file structure should looke like this
project/
node_modules/
app/
entries/
main.js
dist/
main.js
webpack.config.js
package.json
Then just run webpack from your command line. If you want to get the minified version run webpack -p
to include the polyfill you need to require it at the top of the entry point to your application.
import 'babel/polyfill' would need to go at the top of your jsSrc entry file

Categories

Resources