Is there a way to set up Babel to continuously transpile and/or minify a src folder to a compiled folder? - babeljs

Starting with an empty directory, is it possible to do that? Should I use stage-0 like it is on the Babel REPL?
I hope to transpile it just like how ReactJS does it. For some reason, I always got an error for just a file containing:
let obj = { a: 1 };
let newObj = {
...obj,
ha: 3
};
Other times, I can transpile a file, but if I transpile a folder, it'd say:
foo.js: Cannot read property 'contexts' of null
The commands I tried included:
npx babel src --out-dir compiled --presets=es2015,react,minify --watch
but the errors I mentioned above appeared. Also, when I do
npm install babel-minify
it reported
found 2489 vulnerabilities (849 low, 306 moderate, 1329 high, 5 critical)
There is also a notice
As of v7.0.0-beta.55, we've removed Babel's Stage presets.
Please consider reading our blog post on this decision at
https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
for more details. TL;DR is that it's more beneficial in the
long run to explicitly add which proposals to use.
and I wonder what should be done.
Is it possible to
just continuously minify a folder
transpile some ES6 or ES7, 8 syntax that are not yet commonly supported
transpile JSX as well
?

I have found some reliable ways to make it work, although I am not sure when I should use babel.config.json and when to use .babelrc.json or .babelrc. It seems I have to run babel as ./node_modules/.bin/babel and is it true if I don't npm install babel using the -g option.
Here is what works:
create a folder, such as TryBabel
cd TryBabel
Go to https://babeljs.io/setup.html and click "CLI"
You need a package.json, so use npm init and just press Enter a few times
It should lead you to install
a. npm install --save-dev #babel/core #babel/cli
b. now look at your package.json. Remove the script about test but use this: "build": "babel src -d lib"
Now npm run build or ./node_modules/.bin/babel src -d lib should work, but make sure you have some .js files in the src folder. The transpiled result will be in the lib folder.
Now to transpile things into "pre ES6", just follow the #babel/preset-env instructions:
a. npm install #babel/preset-env --save-dev
b. make your babel.config.json to contain { "presets": ["#babel/preset-env"] }
Now you can use npm run build to transpile once, or use ./node_modules/.bin/babel src -d lib --watch to keep on running it and "watch" the src folder and transpile files in it when the files change.
To do minification or make it work with JSX/React, see
https://babeljs.io/docs/en/babel-preset-minify
and
https://babeljs.io/docs/en/babel-preset-react
and make sure your babel.config.json file looks like:
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "entry"
}
],
["#babel/preset-react"],
["minify"]
]
}
and remove minify if you don't want the code to be minified.

Related

babel-loader not transpiling packages in node_modules even after specifying in exclude block to ignore the package (lerna)

So I am trying out monorepo design with lerna for our react applications.
the idea is to create one repo which will have all the react projects as lerna packages as well as some common modules/components which are shared across the applications.
now all these common modules/components are es6 modules. which are not transpiled. because there is continuous development going on the common modules as well. and if we build/transpile them I am sure react HMR will not work after that (a wild guess). following is my directory structure
package.json
lerna.json
|--packages
|--common
|--react-app
|--constants
|--utilities
common contains common react elements like table,accordion etc. which are exported as default es6 modules.
react-app imports common as dependency. react-app has webpack build configuration set.
now when i import common module into my react-app babel transform fails with this error
Button.component.jsx 7:19
Module parse failed: Unexpected token (7:19)
You may need an appropriate loader to handle this file type.
| const { Search } = Input;
| class TextBoxWithButton extends React.Component {
> static propTypes = {
| placeholder: PropTypes.string.isRequired,
| onAction: PropTypes.func.isRequired,
# ./src/App/Modules/Todo/Components/Header/Header.component.jsx 10:0-111 16:25-41
# ./src/App/Modules/Todo/Todo.component.jsx
# ./src/App/Router/index.jsx
# ./src/App/Layout/index.jsx
# ./src/App/index.jsx
# ./src/App.hot.js
# ./src/index.jsx
which means babel-loader is unable to parse and transpile whats in the node_nodules folder which makes sense because all dependencies are expected to be already transpiled. but not always. if you manage local dependencies you cannot keep them build all the time (that's what i think)
now I have found some solutions online that enable 1bable-loader not to exclude node_modules or ignoring #mypackagein exclude regex. but nothing is working in my case.
here is what i have tried so far.
remove exlucde: /node_modules/ from babel-loader => not working
use require.resolve('babel-loader') => not working
add resolve.symlinks= false.
add resolve.modules='node_modules' or
path.resove(__dirname,'node_modules') => not working
add packages path to babel-loader include include: [srcPath, lernaPackagesPath],
nothing seem to work.
is there something that i am missing ?
here is the link to my git test repo.
babel-loader by default will not transpile anything that is in node_modules. you can explicitly say what to transpile in node_modules but after #babel7.0.0 that doesn't seem to work either.
there is also a scope of .babelrc which was introduced in #babel7.0.0.
according to the research i did in under normal circumstances node_modules expect to have transpiled commonjs or umd modules. which can be imported by any application. in my case my packages/components where all es6 modules which needed to be transpiled. and my webpack build was failing because babel-loader was simply ignoring them.
so i decided to use #babel/cli to transpile each package where my components reside i had to add .babelrc along with other configurations to my component packages and build them with #babel/cli
here is the scripts in my package.json
"scripts": {
"start": "babel src --watch --out-dir dist --source-maps inline --copy-files --ignore spec.js,spec.jsx"
},
and my package.json looks something like this after that
{
"name": "#pkg/components",
"version": "1.0.1",
"description": "a repository for react common components. may or may not be dependent on elements",
"main": "dist/index.js",
"author": "hannad rehman",
"license": "MIT",
"scripts": {
"start": "babel src --watch --out-dir dist --source-maps inline --copy-files --ignore spec.js,spec.jsx"
},
"dependencies": {
"#pkg/constants": "^1.0.1",
"#pkg/elements": "^1.0.1"
},
"peerDependencies": {
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-router-dom": "^4.3.1"
}
}
with this approach. all of my common packages will be unit tested, linted and built before any application can import them. babel has a watch mode which will make sure transpilation happens always when a change occurs.
lastly and most importantly react HMR works as expected.
UPDATE
the above solution definitely works but after months i changed it by using include property in the babel loader
{
test: /\.js(x?)$/,
include: [/node_modules\/#pkg/],
use: [
'thread-loader',
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
configFile: path.resolve(
__dirname,
'../../../../',
`${env.appConfig.folderSrc}/babel.config.js`,
),
},
},
],
}

BabelJS: Doesn't find all .js files in directory

Babel doesn't find all of my .js/.es6 files in my directory.
I have this directory structure:
src/
assets/
sample/
models.es6
scripts/
playground.es6
If I run babel src --out-dir dist --source-maps --copy-files --presets env, it only transpiles /src/assets/sample/models.es6 and doesnt go through src/scripts/playground.es6.
What am I doing wrong?
Looking forward to your response!
You can do like below :
babel src/** --out-dir lib
more at official doc
Compile Directories
Compile the entire src directory and output it to the lib directory. You may use --out-dir or -d. This doesn’t overwrite any other files or directories in lib.
if you still stuck, you can use gulp or grunt or webpack to load/transpile mupltiple directives from different locations.
Hope it helps
I found the problem. It has barely to do with Babel.
Inside the src/assets/** is my Realm database sample.realm (https://realm.io). The file itself doesnt cause the problem. But if you open the sample.realm file with Realm Studio on MacOSX, a file called sample.realm.note gets created. This file causes babel to not exit the transpile task.

vscode automatic type acquisition for jest

I have vscode 1.9 and I want to have intellisense for jest tests. The problem is that describe, it, expect etc are globally available in jest and you don't need to import them in your test files. So vscode will not show intellisense for them.
Is there any configuration for globals for automatic type acquisition?
You have a few options in this case:
Add jest to your package.json:
"dependencies": {
"jest": "^18.1.0"
}
This only works if you are working JavaScript and do not have a tsconfig.json.
Install #types/jest
$ npm install -D #types/jest
This should work for both JavaScript and TypeScript projects. However #types but may be disabled by a jsconfig.json/tsconfig.json: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html
Create a jsconfig.json file in the root of your workspace to specifically include jest:
{
"typeAcquisition": {
"include": [
"jest"
]
}
}
This will only work for JavaScript projects when automatic typings acquisition is enabled.
All of these should allow VSCode to pick up jest's typings without an import or require
I tried installing the #types/jest, and it did work, but the problem is that it resulted in the jest suggestions appearing in my .js files as well. I couldn't figure out how to get global suggestions for test, expect, etc. in only .test.js files but not .js files.
So I decided to just manually import each jest global I was going to use in each .test.js file, which allowed the suggestions to appear with types but avoided having the suggestions appear in the .js files:
import { test, expect } from '#jest/globals'
npm install -D #types/jest
edit jest.config.js
typeAcquisition: {
include: ['jest'],
},

React Serverside rendering Unexpected token, JSX and Babel

I'm having trouble finding the correct way to use babel to allow me to use jsx in serverside.
Node-jsx was deprecated for babel. It seems like babel-core/register is whats supposed to be used but I still get unexpected token issues.
I created a repo with the problem im having.
https://github.com/pk1m/Stackoverflow-helpme
When I run node app or npm run watch-js I keep getting unexpected token referring to the JSX code '<'.
How do I get babel to transpile JSX, or am I completely off, thanks.
You need to use babel-register (npm i babel-register --save). And run on your server:
require('babel-register')({
stage: 0
});
You can omit stage 0 if you aren't using experimental babel features. Also you might prefer to put those options in .babelrc instead.
Note that it will only work for files required AFTER calling that (so it would not have an effect on the file you include it in).
You could also have the presets and other options in a .babelrc file.
For babel 6x:
npm i babel-register babel-preset-es2015 babel-preset-react --save
require('babel-register')({
presets: ['es2015', 'react']
});
Note: there are also stage 0-2 presets.
For watching as you've written in your package.json you could try a CLI command like the one facebook are suggesting in the note here (or use webpack):
babel --presets react es2015 --watch app/ --out-dir build/

How can I setup webpack to minify and combine scss and javascript like CodeKit?

I'm having trouble using webpack instead of Codekit v1.9.3. I started working to move from CodeKit to Grunt and Gulp, and then learned about webpack which sounds very cool. I just can't seem to get it working correctly.
"Like Codekit" means I can:
Write javascript with the coffeescript syntax
Have all script source files and libraries minified / uglified and combined into one file
Selectively include components of the bootstrap-sass (scss) framework as needed
Maintain a small file with bootstrap customizations via sass variables, like $brand-primary
Use webpack --watch to compile both scripts and styles automatically when they are changed
End up with one css file and one script file that can be included with a stylesheet and script tag.
Codekit Project Setup
Bower resources:
I'm currently storing these globally, outside of the project:
~/bower_components/twbs-bootstrap-sass/vendor/assets/stylesheets
Because CodeKit supports compass, I've got this in my config.rb file:
add_import_path "~/bower_components/twbs-bootstrap-sass/vendor/assets/stylesheets"
Project Structure
js/fancybox.js
js/main.js <-- currently the compiled js 'output' file
js/main.coffee
css/styles.css <-- currently the compiled css 'output' file
scss/styles.scss
scss/modules/_bootstrap-customizations.scss
scss/modules/_typography.scss
scss/partials/_header.scss
scss/partials/_footer.scss
Contents of styles.scss
#import "modules/bootstrap-customizations"; # local customizations
#import "bootstrap/variables";
#import "bootstrap/mixins";
... # load bootstrap files as required
#import "bootstrap/wells";
System Setup:
system: OS X 10.9
node - v0.10.32
npm - v2.1.7
zsh - zsh 5.0.7 (x86_64-apple-darwin13.4.0)
node was installed with homebrew's brew install node and seems to be working fine otherwise.
What I've Tried
I've read over these pages:
http://webpack.github.io/docs/configuration.html
https://github.com/petehunt/webpack-howto
http://webpack.github.io/docs/tutorials/getting-started/
https://www.npmjs.org/package/bootstrap-sass-webpack
I've attempted to create a webpack.config.js file several times, my latest attempt was several versions of this:
module.exports = {
entry: [
"./node_modules/bootstrap-sass-webpack!./bootstrap-sass.config.js",
"./js/main.coffee"
],
output: {
path: __dirname,
filename: "main.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
}
};
Webpack Error
When I run webpack I get this:
ERROR in ./~/bootstrap-sass-webpack/~/css-loader!/Users/cwd/~/sass-loader!./~/bootstrap-sass-webpack/bootstrap-sass-styles.loader.js!./bootstrap-sass.config.js
stdin:1: file to import not found or unreadable: "~bootstrap-sass/assets/stylesheets/bootstrap/variables
NPM Error
I get an error when attempting to npm install bootstrap-sass, and not had any luck when searching for a solution. I'm not even sure I need this module.
npm ERR! Darwin 13.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "bootstrap-sass"
npm ERR! node v0.10.32
npm ERR! npm v2.1.7
npm ERR! code EPEERINVALID
npm ERR! peerinvalid The package bootstrap-sass does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer bootstrap-sass-webpack#0.0.3 wants bootstrap-sass#~3.2.0
npm ERR! Please include the following file with any support request:
npm ERR! /Users/cwd/webpack-test/npm-debug.log
Sources of Confusion
The most confusing parts of webpack for me are:
Where should things like require("bootstrap-sass-webpack") be added - is it in the webpack.config.js file, or in the js/main.js file?
Should modules like this available to webpack as soon as they are installed with npm install ?
I thought that I should do npm install webpack -g so that webpack was installed globally, and use npm install without the -g for the other modules. However, I don't see any node_modules folder being created in my project. Shouldn't there be one?
How are the search paths determined / specified for things like require("bootstrap-sass-webpack") ?
What node modules should I install to be able to do this? And what should my webpack.config.js look like?
Introduction
Webpack is mainly a JavaScript-bundler. Its "native" language is JavaScript and every other source requires a loader which transforms it to JavaScript. If you require() an html-file for example...
var template = require("./some-template.html");
...you'll need the html-loader. It turns...
<div>
<img src="./assets/img.png">
</div>
...into...
module.exports = "<div>\n <img src=\"" + require("./assets/img.png") + "\">\n</div>";
If a loader doesn't return JavaScript, it needs to be "piped" to another loader.
How to load SASS-files
Configure loaders
In order to use SASS you'll need at least the sass-loader and the css-loader. The css-loader returns a JavaScript string. If you want to import the returned JavaScript string as StyleSheet, you'll also need the style-loader.
Run npm i sass-loader css-loader style-loader --save
Now you need to apply these loaders on all files that match /\.scss$/:
// webpack.config.js
...
module: {
loaders: [
// the loaders will be applied from right to left
{ test: /\.scss$/, loader: "style!css!sass" }
]
}
...
You can also pass options to node-sass as query parameters:
{
test: /\.scss$/, loader: "style!css!sass?includePaths[]=" +
path.resolve(__dirname, "./bower_components/bootstrap-sass/assets/stylesheets/"
}
Since bootstrap references icons via the url() statement, the css-loader will try to include these assets into the bundle and will throw an exception otherwise. That's why you'll also need the file-loader:
// webpack.config.js
...
module: {
loaders: [
{ test: /\.scss$/, loader: "style!css!sass" },
{ test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/, loader: "file" },
]
}
...
Configure entry
To include bootstrap into your bundle there are several ways. One is via the multi-entry option as you've already tried. I recommend to use a single entry where you require() your main sass-file:
// main.js
require("./main.scss");
Given that your includePaths are configured then you can do:
// main.scss
// Set the font path so that url() points to the actual file
$icon-font-path: "../../../fonts/bootstrap";
#import "bootstrap";
Please note that import statements inside scss-files are not touched by webpack because libsass has no api (yet) to provide custom resolvers.
To prevent code duplication it's also important to have a single main sass-file, because webpack compiles every sass-file individually.
With the coffee-loader installed via npm your final webpack.config.js should look like:
module.exports = {
entry: "./js/main.coffee",
output: {
path: __dirname,
filename: "main.js"
},
module: {
loaders: [
{ test: /\.scss$/, loader: "style!css!sass" },
{ test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/, loader: "file" },
{ test: /\.coffee$/, loader: "coffee" }
]
}
};
Webpack globally?
It's best not to install webpack globally, because it's a dependency of your project and thus should be controlled via npm. You can use the scripts-section of your package.json:
{
...
"scripts": {
"start": "webpack --config path/to/webpack.config.js & node server.js"
}
}
Then you just need to run npm start