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
Related
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>
I have a project which doesn't include webpack in the root direct, it's installed in my website folder within root directory.
project
-> src
-> App.js
-> Hello.js
-> index.js
-> website
-> webpack.config.js
-> index.js
-> package.json
and in my webpack.config.js file I added a alias entry to point to my components folder:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
alias: {
'#my-app/components': path.resolve(__dirname, '../src/'),
}
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
}
The problem is: When I try to import my component like this import { Hello } from '#my-app/components'; and I try to npm run build, I get this error message:
ERROR in ../src/Hello.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/.../my-new-proj/src/Hello.js: Unexpected token (4:2)
I'm not sure if this problem is caused just because I'm pointing my components alias in a parent directory which doesn't have its own webpack config or it's something else.
I pushed my code to github so you can see the complete folder structure: https://github.com/osnysantos/my-new-project
Your problem has nothing to do with webpack alias. If you follow the the emitted error, you will see that babel-loader does not recognize the JSX. I see you have added react-presets to your babelrc file, however those seem to be overwritten by your webpack config. Either remove the preset array from the webpack config, or add react preset to them.
I was installing a react startup app and added Webpack, but it says Can't resolve './src/index.js'.
Browser Shows
My Files Path and Package.json Contents
Webpack.config.js Contents
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "public"),
devtool: debug ? "inline-sourcemap" : false,
entry: "./src/index.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2016', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: __dirname + "/public/",
filename: "build.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
Your base URL is path.join(__dirname, "public"), and your entry is ./src/index.js. Webpack tries to find ./src/index.js in public dir; obviously it does not exist. You should modify entry to ../src/index.js.
The other way I find out to fix this problem is to use path.resolve().
const path = require('path');
module.exports = {
mode: "production",
entry: path.resolve(__dirname, 'src') + 'path/to/your/file.js',
output: {
/*Webpack producing results*/
path: path.resolve(__dirname, "../src/dist"),
filename: "app-bundle.js"
}
}
This will make sure, webpack is looking for entry point in src directory.
By the way it's the default entry point. You can also change this entry point to your suitable location. Just replace the src directory with the other directory you want to use.
My webpack.config.js was named Webpack.config.js and the new cli was looking for something case-sensitive.
Webpack does not look for .js files by default. You can configure resolve.extensions to look for .ts. Don't forget to add the default values as well, otherwise most modules will break because they rely on the fact that the .js extension is automatically used.
resolve: {
extensions: ['.js', '.json']
}
The entry path is relative to the context. It's looking for a file in public/src/ when you want it to look for a path in just /src. Looking at the rest of your webpack.config.js it doesn't seem like you need the context line at all.
https://webpack.js.org/configuration/entry-context/
I had the same problem and found that it was caused by having installed create-react-app globally in the past using npm install -g create-react-app.
As create-react-app should now not be installed globally, I needed to uninstall it first using npm uninstall -g create-react-app and then install it in my project directory with npx create-react-app *my-app-name*.
My solution was to put App.js file on a components folder inside the src folder and keep the inde.js just inside the src one
I had same problem. And solutions was really 'at the top' I forgot to add module.exports inside my webpack.prod.js.
So instead of
merge(common, {
...
});
use
module.exports = merge(common, {
...
});
I'm trying to build both minified and unminified versions of my app (js and css) using Webpack.
This can be easily done via command-line interface using -p or --optimize-minimize switch:
webpack
webpack -p
However, I would like to perform these actions with just one command, so I decided to write a small Node.js script which would run both of these Webpack builds:
var webpack = require('webpack');
var config = require('./webpack.config');
webpack(config, callback); // Build unminified version
So the question is: can I pass the aforementioned -p argument to Webpack from the Node.js script in order to build the minified version? Or maybe there is a simpler way of solving my particular problem?
Of course, I can use child_process.exec(), but I don't think it's an authentic Node.js way.
Create your default config to webpack an unminified version. Run webpack with that config. Change the configuration from code and run webpack again. Here is a code example.
var webpack = require('webpack');
//assuming the config looks like this.
var config = {
entry: "./entry.js",
output: {
devtoolLineToLine: true,
sourceMapFilename: "./bundle.js.map",
pathinfo: true,
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
},
plugins: []
};
webpack(config).run(); // Build unminified version
config.output.filename = 'bundle.min.js'
config.plugins = [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})];
webpack(config).run(); // Build minified version
Key p is an alias to setting node environment variable process.env.NODE_ENV="production" as described here
I'm trying to npm link a module to a project using webpack as its bundler. Of course, after trying many things, I keep getting this error:
ERROR in ./src/components/store/TableView.jsx
Module not found: Error: Cannot resolve module 'react-bootstrap-table'
Here are the exact steps I take when doing this:
1.) cd ../forks/react-bootstrap-table
2.) npm link
(success, checked ~/.nvm/.../node_modules/react-bootstrap-table for symlink and it's there)
3.) cd ../../projRoot/
4.) npm link react-bootstrap-table
(no errors thrown?, says successful link)
5.) node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
Solutions I've tried:
- https://webpack.github.io/docs/troubleshooting.html
- How to make a linked component peerDepdencies use the equivalent node_modules of the script being linked to?
- And many purple links on google serps
webpack.config.js
const webpack = require('webpack')
const path = require('path')
const ROOT_PATH = path.resolve(__dirname)
module.exports = {
devtool: process.env.NODE_ENV === 'production' ? '' : 'source-map',
entry: [
'webpack/hot/only-dev-server',
'./src/index.js'
],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot','babel']
},
{
test: /\.scss$/,
loaders: ['style','css','sass'],
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['style','css']
},
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx'],
fallback: path.resolve(__dirname, './node_modules')
},
resolveLoader: {
fallback: path.resolve(__dirname, './node_modules')
},
output: {
path: process.env.NODE_ENV === 'production' ? path.resolve(ROOT_PATH, 'app/dist') : path.resolve(ROOT_PATH, 'app/build'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(ROOT_PATH),
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
stats: 'errors-only',
host: '192.168.1.115'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
Notes:
1. this is the only symlink in the project
2. I run npm install inside forked version (also tried without, doesn't work)
3. I use NVM, but I have used symlinks before without webpack successfully.
I've been at this for a few days now, any help will be much appreciated.
I was facing a similar issue with webpack and ended up by adding this my webpack.config.js:
module.exports = {
resolve: {
symlinks: false
}
};
Here is the link to webpack docs. Since your question there happened a lot to webpack and their api, so I do not know how much relevance my answer still has according to your question. But for people facing this or a similar issue today this could be a solution. As to be seen, there are still people complaining about:
Webpack GitHub Issue 1643
Webpack GitHub Issue 1866
Also make sure you have bundle and yarn installed and executed in the linked package
Okay guys, this is specific to my use case, but make sure to follow all the instructions to completely build the library you are symlinking. Initially, I a npm install and gulp build, but that wasn't enough. I had to run a few extra commands to get the library to fully build.
Now it works! If you are still having issues, go through the documentation for each library you are symlinking, and use my webpack config as a template for resolving external libraries.
Just in case it's useful for others, the solution of adding the resolve.symlinks configuration to false suggested by #Beat was not enough in my case, I had to perform the following steps to solve it:
In the library:
Setup the libraries that are generating issues as peerDependencies in the package.json instead of dependencies or devDependencies, e.g. in my case react:
"peerDependencies": {
"react": "^16.8.6",
...
}
run npm install
build the library (in my case, with a rollup -c npm script
In my main app:
change the version of my library to point to my local project with a relative path in package.json, e.g.
"dependencies": {
"my-library": "file:../../libraries/my-library",
...
}
Add resolve.symlinks = false to my main app's webpack configuration
Add --preserve-symlinks-main and --preserve-symlinks to my package.json start script, e.g:
"scripts": {
"build": "set WEBPACK_CONFIG_FILE=all&& webpack",
"start": "set WEBPACK_CONFIG_FILE=all&& webpack && node --preserve-symlinks-main --preserve-symlinks dist/server.js",
}
run npm install
run npm run start