Using Browserify with a config file instead of long CLI command - javascript

For Babel there is a .babelrc file, which contains all parameters needed for Babel to work, so you can just use babel index.js and this is working like specified in .babelrc, for example:
// .babelrc file
{
"presets": ["react"]
}
smroot#whatever: ~/project $ babel index.js
works the same way as:
smroot#whatever: ~/project $ babel index.js --presets react
Is there something similar to this for Browserify, so:
smroot#whatever: ~/project $ browserify index.js -o bundle/index.js -t [ babelify --presets [ react ] ]
could be replaced with just:
smroot#whatever: ~/project $ browserify index.js
and a config file for this?

#the_cheff 's solution is great, and It's also possible to define the parameters you need directly from package.json file without creating and npm script.
what you need is a new key "browserify" this way
"browserify": {
"transform": [
[
"babelify",
{
"presets": [
"#babel/preset-env"
]
}
]
]
}
and through the CLI just run:
browserify script.js > build/bundle.js

As #azium suggests in the comment you could create a npm script to handle this.
Open you package.json file and find (or create) the scripts section.
Then insert the command here with some name you would like.
"scripts": {
"browserify": "browserify index.js -o bundle/index.js -t [ babelify --presets [ react ] ]"
}
You can now run it with npm run browserify
Otherwise you could use a task runner like gulp to handle this. In general if you have multiple tasks like running bable, browserify, sass, less, or need to move files around, an actual task runner might come in handy.

Related

Babel-CLI set config value correctly

I am trying to add a build command that uses babel CLI to transpile my ES6. I am having difficult pointing it correctly to babelrc.
The file structure is roughly as follows:
root
src
index.js
...
.babelrc
.package.json
In my package.json, I originally tried the following:
"scripts": {
"build": "babel --out-dir dist src",
...
},
But this gave an error because of the array destructuring notation I have used in my code. I think this is because it is not picking up my .babelrc file. Using
babel --presets=#babel/preset-env --out-dir dist src
instead fixes this problem. But I would rather I didn't have to specify plugins etc. here and rely on the .babelrc file instead.
From reading this issue, I get the impression babel looks for a config file in src rather than root . Looking at the documentation it seems there is an option for specifying a config file, but I can't quite get it to work correctly. My attempt:
babel --config-file .babelrc --out-dir dist src
You can use ./node_modules/.bin/babel in place of babel.
Worked for me this week.
Check point 3 in the overview from babel-cli
https://babeljs.io/docs/en/usage
And running this command to compile all your code from the src directory to lib:
./node_modules/.bin/babel src --out-dir lib
You can use the npm package runner that comes with npm#5.2.0 to shorten that command by replacing ./node_modules/.bin/babel with npx babel
For Babel version 7.x, it looks for project-wide configuration in the file with name like this - babel.config.{json|js|cjs|mjs}. Check the documentation here.
In my end,
npx babel src/ -d lib/
Babel should already pick up the .babelrc file automatically. If you want to add that preset, you should specify
{
// ... more .babelrc up here
"presets": ["#babel/preset-env"]
// ... more .babelrc down here
}
in your .babelrc file.
But babel will automatically search for the closest .babelrc file in the directory starting at the entry file and working its way upwards (specified here at the bottom).

Run Jest tests only for current folder

I have Jest installed on my machine and typing jest from terminal results in tests from parent folers also getting executed. I want to run tests only from the current folder.
For e.g. if I go to c:/dev/app in terminal and type some-jest-command, it should only run files with .test.js present in the app folder. Currently, running jest command from app folder runs tests in parent folders too, which is not my desired behaviour.
By default, Jest will try to recursively test everything from whatever folder package.json is located.
Let's say you're in c:/dev/app, and your package.json is in c:. If your basic command to invoke Jest is npm test, then try with run npm test dev/app.
If you want to run the tests from a specific folder user the --testPathPattern jest flag. When setting up the npm script add the path to the folder as well. In your package.json add the flag in you npm scripts. Check the bellow code for an example.
"scripts": {
....
"test:unit": "jest --testPathPattern=src/js/tests/unit-tests",
"test:integration": "jest --testPathPattern=src/js/tests/integration"
....
},
If you want to watch as well for changes, use the watch flag:
{
...
"test:unit": "jest --watch --testPathPattern=src/js/tests/unit-tests",
...
}
After that open, the command line, change the directory where your project is and run the unit test.
npm run test:unit
or integration tests.
npm run test:integration
To only run testing in a specific directory and to coerce Jest to read only certain type of files(my example: 'ExampleComponent.test.js' with new Jest version #24.9.0 you must write exact "testMatch" in jest.config.json || package.json in "jest" part next "testMatch": [ "<rootDir>/src/__tests__/**/*.test.js" ],
This testMatch in my case hits all files with the prefix .test.js in tests/subdirectories/ and skips all other files like 'setupTest.js' and other .js files in 'mocks' subdirectory which is placed inside of 'tests' directory,so,my 'jest.config.json' looks like this
{
"setupFiles": [
"raf/polyfill",
"<rootDir>/setupTests.js"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"moduleNameMapper": {
"^.+\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
"testMatch": [
"<rootDir>/src/__tests__/**/*.test.js"
]
}
Just adapt to your needs 'testMatch' regex.
A little note: This is for jest#24.9.0 && enzyme#3.10.0 if it matters to anyone.
I hope it will be useful to someone, cheers all.
--package.json
"scripts": {
"test": "jest"
}
--jest.config.js
module.exports = {
"testMatch": [
"<rootDir>/tests/unit/*.test.js"
]
}
From the root of your project, you can run jest <substring of files> and it will only run the test files which have the substring you added.
$ jest /libs/components
> [PASS] /libs/components/button.tsx
yarn:
yarn test nameoffolder
npm:
npm test nameoffolder
For example, if you have a folder named widget and you only want to run the tests in the widget folder you would run this command.
yarn:
yarn test widget
npm:
npm test widget

Babili minifies but does not transpile

I am stuck with babili.
I need to transpile, then minify the javascript that is written in ES6. So I installed the package using:
npm install babili --save-dev
and made .babelrc file containing a preset:
{"presets": ["es2015"]}
Now I tried the following command
./node_modules/.bin/babili public/js/rt.socket.js --out-file public/test.min.js
It does give a minified but doesn't transpile. What could be the reason for this?
`
Babili does not use .babelrc. Per the README:
Note that, because the babili command uses the default preset with no-babelrc, you cannot set any non-default options in the preset's plugins with this command. To do this, you can use the babel command with the options set in a .babelrc. See the preset docs for more information on how to do this.
The solution is to instead use Babel with the babel-preset-babili preset, as described in the Babel preset section of the README (which assumes that you've already installed Babel):
Install
npm install babel-preset-babili --save-dev
Usage
You'll most likely want to use it only in the production environment.
Check out the env
docs for more help.
Options specific to a certain environment are merged into and overwrite non-env specific options.
.babelrc:
{
"presets": ["es2015"],
"env": {
"production": {
"presets": ["babili"]
}
}
}
Then you'll need to set the env variable which could be something like
BABEL_ENV=production npm run build

Babel not compiling ES6 to ES5 Javascript [duplicate]

I have this code:
"use strict";
import browserSync from "browser-sync";
import httpProxy from "http-proxy";
let proxy = httpProxy.createProxyServer({});
and I have installed babel-core and babel-cli globally via npm. The point is when I try to compile with this on my terminal:
babel proxy.js --out-file proxified.js
The output file gets copied instead of compiled (I mean, it's the same as the source file).
What am I missing here?
Babel is a transformation framework. Pre-6.x, it enabled certain transformations by default, but with the increased usage of Node versions which natively support many ES6 features, it has become much more important that things be configurable. By default, Babel 6.x does not perform any transformations. You need to tell it what transformations to run:
npm install babel-preset-env
and run
babel --presets env proxy.js --out-file proxified.js
or create a .babelrc file containing
{
"presets": [
"env"
]
}
and run it just like you were before.
env in this case is a preset which basically says to compile all standard ES* behavior to ES5. If you are using Node versions that support some ES6, you may want to consider doing
{
"presets": [
["env", { "targets": { "node": "true" } }],
]
}
to tell the preset to only process things that are not supported by your Node version. You can also include browser versions in your targets if you need browser support.
Most of these answers are obsolete. #babel/preset-env and "#babel/preset-react are what you need (as of July 2019).
I had the same problem with a different cause:
The code I was trying to load was not under the package directory, and Babel does not default to transpiling outside the package directory.
I solved it by moving the imported code, but perhaps I could have also used some inclusion statement in the Babel configuration.
First ensure you have the following node modules:
npm i -D webpack babel-core babel-preset-es2015 babel-preset-stage-2 babel-loader
Next, add this to your Webpack config file (webpack.config.js) :
// webpack.config.js
...
module : {
loaders : [
{
test : /\.js$/,
loader : 'babel',
exclude : /node_modules/,
options : {
presets : [ 'es2015', 'stage-2' ] // stage-2 if required
}
}
]
}
...
References:
https://gist.github.com/Couto/6c6164c24ae031bff935
https://github.com/babel/babel-loader/issues/214
Good Luck!
As of 2020, Jan:
STEP 1: Install the Babel presets:
yarn add -D #babel/preset-env #babel/preset-react
STEP 2: Create a file: babelrc.js and add the presets:
module.exports = {
// ...
presets: ["#babel/preset-env", "#babel/preset-react"],
// ...
}
STEP 3:- Install the babel-loader:
yarn add -D babel-loader
STEP 4:- Add the loader config in your webpack.config.js:
{
//...
module: [
rules: [
test: /\.(js|mjs|jsx|ts|tsx)$/,
loader: require.resolve('babel-loader')
]
]
//...
}
Good Luck...
npm install --save-dev babel-preset-node5
npm install --save-dev babel-preset-react
...and then creating a .babelrc with the presets:
{
"presets": [
"node5",
"react"
]
}
...resolved a very similar issue for me, with babel 3.8.6, and node v5.10.1
https://www.npmjs.com/package/babel-preset-node5
https://www.npmjs.com/package/babel-preset-react
Same error, different cause:
Transpiling had worked before and then suddenly stopped working, with files simply being copied as is.
Turns out I opened the .babelrc at some point and Windows decided to append .txt to the filename. Now that .babelrc.txt wasn't recognized by babel. Removing the .txt suffix fixed that.
fix your .babelrc
{
"presets": [
"react",
"ES2015"
]
}
In year 2018:
Install following packages if you haven't yet:
npm install babel-loader babel-preset-react
webpack.config.js
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015','react'] // <--- !`react` must be part of presets!
}
}
],
}
Ultimate solution
I wasted 3 days on this
import react from 'react' unexpected identifier
I tried modifying webpack.config.js and package.json files, and adding .babelrc, installing & updating packages via npm, I've visited many, many pages but nothing has worked.
What worked? Two words: npm start. That's right.
run the
npm start
command in the terminal to launch a local server
...
(mind that it might not work straight away but perhaps only after you do some work on npm because before trying this out I had deleted all the changes in those files and it worked, so after you're really done, treat it as your last resort)
I found that info on this neat page. It's in Polish but feel free to use Google translate on it.

How do I exclude the "require('react')" from my Browserified bundle?

I'm using Browserify to bundle a ReactJS application.
All my components include a require("react") at the top. This causes Browserify to include the ReactJS source in my bundle. But I'd like to exclude it.
How do I do that? Is this the right thing to do?
#NickTomlin gave this answer, but then deleted it.
You can use external:
browserify --external react src.js > dest.js
An example using the api:
var bundler = browserify('src.js');
bundler.external('react');
bundler.bundle();
This is a viable option. external requires another script to provide the module in a compatible way. You can produce such a script like this:
browserify -r react > react.js
env NODE_ENV=production browserify -r react | uglifyjs -m > react.min.js
And in HTML:
<script src="react.js"></script>
<script src="dest.js"></script>
dest.js is your code except react. react.js is just react and its dependencies.
Need more things external? Just add them in addition to react.
browserify -x react -x react-bootstrap src.js > dest.js
browserify -r react -r react-bootstrap > vendor.js
You could also do something like this in package.json
"browser": {"react": "./react-fake.js"}
// ./react-fake.js
try {
module.exports = require('react');
} catch(e){
module.exports = window.React;
}
And compile with -x react. This allows you to accept a -r react build, and fallback to a global React.
Sounds like you want to use browserify-shim.
In your package.json
"browserify-shim": {
"react": "global:React"
},
"browserify": {
"transform": [ "browserify-shim" ]
},
"dependencies": {
"browserify-shim": "~3.2.0"
}
(untested). This section has more information.
I also wanted to do this, and found a possible solution.
From the browserify -h help:
--ignore, -i Replace a file with an empty stub. Files can be globs.
Just use the ignore feature.
browserify -i react -i react-dom ...
I also added react and react-dom as peer dependencies, cause in my case, the package can be imported in other packages builds.
You can also use the externals section in the webpack.config.js file. eg:-
externals: {
// require('jquery') is loaded externally and avaliable as jQuery
"jquery": "jQuery"
}
See https://webpack.github.io/docs/library-and-externals.html

Categories