How to create and publish a Vuejs component on NPM - javascript

I started working a lot with vue and started to use it in all the projects in the company where I work. And with that, I ended up creating some components, in general autocomplete, I know that there are many, I have already used some, but none have supplied all my needs. However, whenever I go to work on a new project and use the same component, either I recreates it, or I copy and paste it.
So I came to doubt How to create my component, upload to npmjs for whenever I use it, just give a npm install -save ..., and also be able to contribute a bit with the community.

update
With the release of vue-loader 15.x this answer will no longer work. Please use this instead https://medium.freecodecamp.org/how-to-create-a-vue-js-app-using-single-file-components-without-the-cli-7e73e5b8244f
Here is one way you can create/publish a Vuejs library/component from scratch.
As I am going to write down every step and command, make sure to follow the entire guide and you will be able to create and publish your own Vuejs component on NPM.
After you publish it, like most libraries you can install it using ex:
npm install --save your-component
And then import the component inside your app using
import something from 'your-component'
To start creating our first component, first create a folder called vuejs-hello-app (or any other name) and inside it, run:
npm init
Just hit enter until the interactive question ends and then npm will generate a file named package.json in that folder containing the following code.
(Note: I changed the description and version from 1.0.0 to 0.1.0 here is the result.)
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
After this, we'll need to install the dependencies for our library.
These dependencies are divided into two types: dependency and devDependency
dependency:
is the external library or libraries that our own component runs on. When someone installs your component, npm will make sure this dependency exists or gets installed first. Since we are creating a component for vue, we need to make sure vue is required. So, install it using:
npm install --save vue
devDependency:
is a bunch of libraries that we need only for development purposes. These libraries will help us build and/or transpile.
We install dev dependencies using the method above by adding the the suffix -dev to --save
Now, let us install the minimum dev dependencies we need for our component:
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env
npm install --save-dev cross-env
npm install --save-dev css-loader
npm install --save-dev file-loader
npm install --save-dev node-sass
npm install --save-dev sass-loader
npm install --save-dev vue-loader
npm install --save-dev vue-template-compiler
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
At this point the libraries will be installed and the package.json will be updated to look like following.
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"node-sass": "^4.7.2",
"sass-loader": "^6.0.6",
"vue-loader": "^13.5.0",
"vue-template-compiler": "^2.5.9",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"vue": "^2.5.9"
}
}
(note: I have added "build": "webpack -p" to build our lib with webpack)
Now, since our code needs to be built and transpiled, we need a folder to store the build version. Go ahead and create a folder inside our root folder and call it: dist and in the same place a configuration file for webpack and name it webpack.config.js
All of the files we have so far created are for configuring and stuff. For the actual app that people are going to use, we need to create at least two files inside our src/ directory.
A main.js and VuejsHelloApp.vue put them as:
./src/main.js and ./src/components/VuejsHelloApp.vue
I have mine structured like this:
dist
node_modules
src
main.js
components
VuejsHelloApp.vue
.babelrc
.eslintignore
.gitignore
.npmignore
.travis.yml
CONTRIBUTING
LICENSE
package.json
README.md
webpack.config.js
I will just go through the files listed and describe what each file does in-case anyone is curious:
/dist is where a build (transpiled), minified, non-ES6 version of your code will be stores
node_modules I think we know this already, let's ignore it
src/ this is root dir of your library.
.babelrc is where your babel options are kept, so add this to disable presets on modules
{
"presets": [
[
"env",
{
"modules": false
}
]
]
}
.eslintignore This is where you tell ESLINT to ignore linting so put this inside:
build/*.js
.gitignore
add files you want to ignore (from git)
.npmignore same as .gitignore for NPM
.travis.yml if you need CI check examples from travis and configure it
CONTRIBUTING not required
LICENSE not required
package.json ignore for now
README.md not required
webpack.config.js This is the important file that let's you create a build, browser compatible version of your code.
So, according to our app, here is a minimal example of what it should look like:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
module: {
rules: [
// use babel-loader for js files
{ test: /\.js$/, use: 'babel-loader' },
// use vue-loader for .vue files
{ test: /\.vue$/, use: 'vue-loader' }
]
},
// default for pretty much every project
context: __dirname,
// specify your entry/main file
output: {
// specify your output directory...
path: path.resolve(__dirname, './dist'),
// and filename
filename: 'vuejs-hello-app.js'
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Note that the important directives here are entry and output. You can check webpack docs to learn more if you want to fully customize your app.
But basically, we're telling webpack to get the ./src/main.js (our app) and output it as ./dist/vuejs-hello-app.js
Now, we are almost finished setting up everything except the actual app.
Go to /src/components/VuejsHelloApp.vue and dump this simple app, which will move a button right or left when you hover on it
<template>
<div>
<button #mouseover='move($event)'> I'm alive </button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
move (event) {
let pos = event.target.style.float;
if(pos === 'left'){
event.target.style.float = 'right'
}else{
event.target.style.float = 'left'
}
}
}
}
</script>
<style scoped>
</style>
And not but not least, got to ./src/main.js and export your app like:
import VuejsHelloApp from './components/VuejsHelloApp.vue'
export default VuejsHelloApp
Now go to your package.json file replace the "main: "index.js", with "main": "src/main.js",
After this, simply run these commands to build and publish your app:
npm run build
git add .
git commit -m "initial commit"
git push -u origin master
npm login
npm publish
Importing and using the library.
If everything went smoothly, then simply install your app like this:
npm install --save vuejs-hello-app
And use it in vue like this:
<template>
<div>
<VuejsHelloApp> </VuejsHelloApp>
</div>
</template>
<script>
import VuejsHelloApp from 'vuejs-hello-app'
export default {
name: 'HelloWorld',
components: { VuejsHelloApp }
}
</script>
I made this app https://github.com/samayo/vuejs-hello-app while writing the answer, it might help to better understand the code

Related

Web3 Issue : React Application not compiling

I am facing issue with React application while compilation.
Please find the issue below and screenshot.
ERROR in ./node_modules/web3-providers-http/lib/index.js 30:11-26
Module not found: Error: Can't resolve 'http' in '/Users/rohit/Downloads/Personal/web3/react-minting-website/node_modules/web3-providers-http/lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
- install 'stream-http'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "http": false }
# ./node_modules/web3-core-requestmanager/lib/index.js 56:16-46
# ./node_modules/web3-core/lib/index.js 23:23-58
# ./node_modules/web3/lib/index.js 32:11-31
# ./src/index.js 10:0-24 14:13-17
On scrutiny, I found out Issue is with web3 related dependencies :
https://www.npmjs.com/package/web3
https://www.npmjs.com/package/#web3-react/core
https://www.npmjs.com/package/#web3-react/injected-connector
Can someone please help me with the same? I am using LTS versions, What are stable versions of these?
web3.js has updated their readme to included troubleshooting steps. Ref. link.
Web3 and Create-react-app
If you are using create-react-app version >=5 you may run into issues building. This is because NodeJS polyfills are not included in the latest version of create-react-app.
Solution
Install react-app-rewired and the missing modules
If you are using yarn:
yarn add --dev react-app-rewired process crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer
If you are using npm:
npm install --save-dev react-app-rewired crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer process
Create config-overrides.js in the root of your project folder with the content:
const webpack = require('webpack');
module.exports = function override(config) {
const fallback = config.resolve.fallback || {};
Object.assign(fallback, {
"crypto": require.resolve("crypto-browserify"),
"stream": require.resolve("stream-browserify"),
"assert": require.resolve("assert"),
"http": require.resolve("stream-http"),
"https": require.resolve("https-browserify"),
"os": require.resolve("os-browserify"),
"url": require.resolve("url")
})
config.resolve.fallback = fallback;
config.plugins = (config.plugins || []).concat([
new webpack.ProvidePlugin({
process: 'process/browser',
Buffer: ['buffer', 'Buffer']
})
])
return config;
}
Within package.json change the scripts field for start, build and test. Instead of react-scripts replace it with react-app-rewired
before:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
after:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
The missing Nodejs polyfills should be included now and your app should be functional with web3.
If you want to hide the warnings created by the console:
In config-overrides.js within the override function, add:
config.ignoreWarnings = [/Failed to parse source map/];
If you are using create-react-app version >=5 you may run into issues building. This is because NodeJS polyfills are not included in the latest version of create-react-app.
Currently CRA ships react-scripts with version 5.0.0. Instead of ejecting CRA, just downgrade react-scripts to version 4.0.3. I was facing the same issue, downgrading worked for me.
First remove old version
npm uninstall react-scripts
Then run the following:
npm i react-scripts#4.0.3
as webpack grows in size, they removed the polyfills in webpack5. Looks like you are using create-react-app (CRA) and webpack configuration is not exposed to the user in CRA. you can expose it using eject. you might have this script in package.json:
"eject": "react-scripts eject"
so run npm run eject. This is not recommended because it means that you will no longer benefit from the updates of CRA.
you can handle ejecting with either rewire or craco.
After you get the webpack configuration, you need to add resolve property to webpack config and install all those required packages :
resolve: {
extensions: [".js", ".css"],
alias: {
// add as many aliases as you like!
// optional
components: path.resolve(__dirname, "src/components"),
},
fallback: {
// path: require.resolve("path-browserify"),
fs: false,
assert: require.resolve("assert/"),
os: require.resolve("os-browserify/browser"),
constants: require.resolve("constants-browserify"),
stream: require.resolve("stream-browserify"),
crypto: require.resolve("crypto-browserify"),
http: require.resolve("stream-http"),
https: require.resolve("https-browserify"),
},
},
I have webpac5 Boilerplate. you can use it if you want:
Since there are too many polyfills, instead of manually installing all, you can use node-polyfill-webpack-plugin package. instead of fallback property
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
plugins: [
new HtmlWebpackPlugin({
title: "esBUild",
template: "src/index.html",
}),
// instead of fallback
new NodePolyfillPlugin(),
new webpack.ProvidePlugin({
process: "process/browser",
Buffer: ["buffer", "Buffer"],
React: "react",
}),
],
webpack5 boilerplate github repo
Web3 and Create-react-app
If you are using create-react-app version >=5 you may run into issues building. This is because NodeJS polyfills are not included in the latest version of create-react-app.
Refer the Solution in the Below link
https://github.com/ChainSafe/web3.js#troubleshooting-and-known-issues

Mocha not using babel when it should be? [duplicate]

For a library written in ES6/7, I want to compile (to ES5) the library to a dist/ folder. I also want to run the tests (written in ES6/7) for this lib.
My dev dependencies look like this (package.json):
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/register": "^7.4.4",
"chai": "^4.2.0",
"mocha": "^6.1.4",
"sinon": "^7.3.2"
},
My build and test scripts looks like this (package.json):
"scripts": {
"test": "mocha --require #babel/register",
"build": "babel src -d dist --presets=#babel/preset-env"
},
Running npm run build works well. The dist/ folder gets populated with transpiled files.
Running npm run test does not seem to work - this is my problem.
> mocha --require #babel/register
/Users/dro/Repos/lib/node_modules/yargs/yargs.js:1163
else throw err
^
ReferenceError: regeneratorRuntime is not defined
Initially I got an import error, which was resolved by adding .babelrc file.
Below is my .babelrc file content.
{
"presets": ["#babel/preset-env"]
}
I was reading about regeneratorRuntime and it got me to this link about babel-polyfill where they explain I shouldn't need that polyfill.
This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool.
What is needed to set this up properly?
I am not using webpack.
Testing in ES6 with Mocha and Babel 7. Look here: https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei or http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/
npm install --save #babel/runtime
npm install --save-dev #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/transform-runtime"]
]
}
Look at the project documentation:
npm install --save-dev babel-register
In your package.json file make the following changes:
{
"scripts": {
"test": "mocha --require babel-register"
}
}
Some features will require a polyfill:
npm install --save-dev babel-polyfill
{
"scripts": {
"test": "mocha --require babel-polyfill --require babel-register"
}
}
Below steps are for applying Babel transformations & core-js polyfills for your tests file:
💡 All transformations are only done per current environment, so only what is needed to be transpiled/polyfilled, will be. Target environments may be defined from a .browserslist file or as a property in package.json file. (read more here)
Step 1: Install packages:
#babel/core (read why)
#babel/preset-env (read why)
#babel/register (read why)
core-js (read why)
Note that #babel/polyfill exists and uses core-js under the hood. However, it was deprecated in favor of using core-js directly.
Step 2: Create a Babel configuration file babel.config.js
(used to be .babelrc.js or a .json file).
Create this file at the root-level of your code.
The most basic configuration (for just testing and not bundling) would look like this:
module.exports = {
presets: [
['#babel/preset-env', {
"corejs": "3.26",
"useBuiltIns": "usage"
}],
};
corejs - This is the polyfills library and should be specified with the minor version, otherwise x.0 will be used.
It is needed when testing code on rather "old" Node versions, which do not support all of the language methods. This ofc depends on your own usage of such javascript methods. (for example String.prototype.replaceAll).
useBuiltIns - must be set in order for the corejs polyfills to be applied. Read about it in the official docs.
By default, #babel/preset-env will compile your code for the current environment, but you can specify a different environment by setting the "targets" option in the configuration.
Ofc, you can add more presets like #babel/preset-react for example, if your code it written in React, or any other plugins which are specifically needed for your code.
Step 3: Connect mocha to the babel configuration:
In your package.json file
Under the scripts section, simply write something like this:
"test": "mocha \"src/**/*.test.js\""
Create a .mocharc.json file with this content:
{
"exit": true,
"color": true,
"require": ["#babel/register"],
"ignore": "node_modules"
}
This will apply Babel transformations to all of your test files.
If you need need to apply some special global javascript before/to all of your tests, you can add another file to the require setting, for example, fixtures.cjs:
"require": ["#babel/register", "fixtures.cjs"],
fixtures.cjs:
Below example applies a chai (popular alongside Mocha) plugin for testing DOM-related code:
var chai = require('chai'),
chaiDOM = require('chai-dom');
// https://stackoverflow.com/questions/62255953/chai-usechaihttp-once-or-in-every-test-file
// https://mochajs.org/#global-teardown-fixtures
exports.mochaGlobalSetup = function () {
chai.use(chaiDOM);
}
Interesting reads:
Babel vs babel-core vs babel-runtime
How does mocha / babel transpile my test code on the fly?

How to use babel with npm package that will be used by react

Trying to do what I thought was a simple thing.
I have a node package that uses advanced js syntax. I want to depend on it in a react project.
So I installed babel packages via --save-dev, and added a .babelrc:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread"]
}
That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:
{
"name": "bla",
"version": "1.0.0",
"scripts": {
"postinstall": "babel src --out-dir lib"
},
"main": "lib/index.js",
"dependencies": {},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react-native": "^4.0.0"
}
}
When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.
Why is this so difficult? What am I doing wrong?
sh: 1: babel: not found is from your shell not finding the babel binary file (normally under ./node_modules/.bin/babel)
You'd want to compile before you publish to npm, so anyone who installs your package has the built files. But, for Github try something like:
"postinstall": "npx babel src --out-dir lib"
This hack worked instead of the postinstall:
...
"preinstall": "npm install --ignore-scripts && babel src --out-dir lib",
...
Source: https://github.com/Financial-Times/structured-google-docs-client/commit/891180db742ed00cace0139b201850f79d337098
Also relevant: https://github.com/npm/npm/issues/10366
I am not sure I understand the need here correctly, but could you not just run the babel call in prepare or prepublish scripts? That way only local npm install calls would pick that up.
See more about npm scripts lifecycle: https://docs.npmjs.com/misc/scripts

React Js Environment setup

I'm new to react js and I'm trying to set up the environment for it and I followed the steps mentioned in https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm.
But after doing all the things mentioned there I'm getting this error:
'webpack-dev-server' is not recognized as an internal or external command, operable program or batch file
If you want to develop an application using babel, webpack, etc. You need to follow following steps. No doubt there are much better tutorial available over the internet but it will give you some idea.
1.Webpack:
In browsers you can not require or import modules as you usually do while writing node.js code. With the help of a module bundler, maybe Webpack, you can write code that uses require/import in the same way that you would use it in node environment. I am assuming you will use webpack considering its popularity.
2. Install dependencies (es6)
These are minimal dependencies you need in your project (package.json) to get it working. You can directly copy paste the following text into a new file named "package.json". run the following set of commands in you EMPTY project directory:
install the node package manager
npm init [follow the command prompt to fill in meta data of your project like name, author,etc.]
install global packages
npm install -g babel babel-cli
[this will install transpiler(babel) into your global environment]
install module bundler
npm install webpack webpack-dev-server --save
install babel plugins
npm install babel-core babel-loader babel-preset-react babel-preset-es2015
After this command set, your package.json will start looking like as following:
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "No Command Written Yet"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
3.Write your webpack-config.js file
A sample webpack config file should like this. Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. Just remember the fact that
Webpack is a module bundler that bundles javascript and other assets for the browser.
var config = {
entry: './main.js',
output: {
path:'/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
4.Set up entry point for your application
src->index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<App />
, document.querySelector('.init')
);
5.Setup index.html in your project root
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Welcome to ReactJs</title>
</head>
<body>
<div class="init"></div>
</body>
<script src="./public/bundle.js"></script>
</html>
6.Running
A slight change is needed in your package.json
replace:
"scripts": {
"test": "No Command Written Yet"
},
with
"scripts": {
"dev": "webpack-dev-server --hot"
},
[this will change the script you will run to execute the app bundled by webpack]
Now, whenever you want to run the project, just be in the project root directory and call:
npm run dev
DONE, Have Fun!
Run:
npm install webpack-dev-server --save-dev
And try again. You got the error because webpack-dev-server couldn't be found in your devDependencies inside of your package.json file
This is happening because you don't have webpack-dev-server installed as a global package, that's why you can execute directly.
The recommended way is installing it locally, in this way you'll avoid this problem.
Here you can find the steps to make it run.
Good luck

"unexpected token import" in Nodejs5 and babel?

In js file, i used import to instead of require
import co from 'co';
And tried to run it directly by nodejs since it said import is 'shipping features' and support without any runtime flag (https://nodejs.org/en/docs/es6/), but i got an error
import co from 'co';
^^^^^^
SyntaxError: Unexpected token import
Then i tried to use babel
npm install -g babel-core
npm install -g babel-cli
npm install babel-core //install to babel locally, is it necessary?
and run by
babel-node js.js
still got same error, unexpected token import?
How could I get rid of it?
From the babel 6 Release notes:
Since Babel is focusing on being a platform for JavaScript tooling and not an ES2015 transpiler, we’ve decided to make all of the plugins opt-in. This means when you install Babel it will no longer transpile your ES2015 code by default.
In my setup I installed the es2015 preset
npm install --save-dev babel-preset-es2015
or with yarn
yarn add babel-preset-es2015 --dev
and enabled the preset in my .babelrc
{
"presets": ["es2015"]
}
Until modules are implemented you can use the Babel "transpiler" to run your code:
npm install --save babel-cli babel-preset-node6
and then
./node_modules/babel-cli/bin/babel-node.js --presets node6 ./your_script.js
If you dont want to type --presets node6 you can save it .babelrc file by:
{
"presets": [
"node6"
]
}
See https://www.npmjs.com/package/babel-preset-node6 and https://babeljs.io/docs/usage/cli/
Install packages: babel-core, babel-polyfill, babel-preset-es2015
Create .babelrc with contents: { "presets": ["es2015"] }
Do not put import statement in your main entry file, use another file eg: app.js and your main entry file should required babel-core/register and babel-polyfill to make babel works separately at the first place before anything else. Then you can require app.js where import statement.
Example:
index.js
require('babel-core/register');
require('babel-polyfill');
require('./app');
app.js
import co from 'co';
It should works with node index.js.
babel-preset-es2015 is now deprecated and you'll get a warning if you try to use Laurence's solution.
To get this working with Babel 6.24.1+, use babel-preset-env instead:
npm install babel-preset-env --save-dev
Then add env to your presets in your .babelrc:
{
"presets": ["env"]
}
See the Babel docs for more info.
if you use the preset for react-native it accepts the import
npm i babel-preset-react-native --save-dev
and put it inside your .babelrc file
{
"presets": ["react-native"]
}
in your project root directory
https://www.npmjs.com/package/babel-preset-react-native
It may be that you're running uncompiled files. Let's start clean!
In your work directory create:
Two folders. One for precompiled es2015 code. The other for babel's
output. We'll name them "src" and "lib" respectively.
A package.json file with the following object:
{
"scripts": {
"transpile-es2015": "babel src -d lib"
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-preset-latest": "^6.16.0"
}
}
A file named ".babelrc" with the following instructions:
{"presets": ["latest"]}
Lastly, write test code in your src/index.js file. In your case:
import co from 'co'.
Through your console:
Install your packages:
npm install
Transpile your source directory to your output directory with the -d (aka --out-dir) flag as, already, specified in our package.json:
npm run transpile-es2015
Run your code from the output directory!
node lib/index.js
Current method is to use:
npm install --save-dev babel-cli babel-preset-env
And then in in .babelrc
{
"presets": ["env"]
}
this install Babel support for latest version of js (es2015 and beyond)
Check out babeljs
Do not forget to add babel-node to your scripts inside package.json use when running your js file as follows.
"scripts": {
"test": "mocha",
//Add this line to your scripts
"populate": "node_modules/babel-cli/bin/babel-node.js"
},
Now you can npm populate yourfile.js inside terminal.
If you are running windows and running error internal or external command not recognized, use node infront of the script as follow
node node_modules/babel-cli/bin/babel-node.js
Then npm run populate
You have to use babel-preset-env and nodemon for hot-reload.
Then create .babelrc file with below content:
{
"presets": ["env"]
}
Finally, create script in package.json:
"scripts": {
"babel-node": "babel-node --presets=env",
"start": "nodemon --exec npm run babel-node -- ./index.js",
"build": "babel src -d dist"
}
Or just use this boilerplate:
Boilerplate: node-es6
install --> "npm i --save-dev babel-cli babel-preset-es2015
babel-preset-stage-0"
next in package.json file add in scripts "start": "babel-node server.js"
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"lodash": "^4.17.4",
"mongoose": "^5.0.1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "babel-node server.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
and create file for babel , in root
".babelrc"
{
"presets":[
"es2015",
"stage-0"
]
}
and run npm start in terminal
Involve following steps to resolve the issue:
1) Install the CLI and env preset
$ npm install --save-dev babel-cli babel-preset-env
2) Create a .babelrc file
{
"presets": ["env"]
}
3) configure npm start in package.json
"scripts": {
"start": "babel-node ./server/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
4) then start app
$ npm start
I have done the following to overcome the problem (ex.js script)
problem
$ cat ex.js
import { Stack } from 'es-collections';
console.log("Successfully Imported");
$ node ex.js
/Users/nsaboo/ex.js:1
(function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:152:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:194:16)
at bootstrap_node.js:618:3
solution
# npm package installation
npm install --save-dev babel-preset-env babel-cli es-collections
# .babelrc setup
$ cat .babelrc
{
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
]
}
# execution with node
$ npx babel ex.js --out-file ex-new.js
$ node ex-new.js
Successfully Imported
# or execution with babel-node
$ babel-node ex.js
Successfully Imported
#jovi all you need to do is add .babelrc file like this:
{
"plugins": [
"transform-strict-mode",
"transform-es2015-modules-commonjs",
"transform-es2015-spread",
"transform-es2015-destructuring",
"transform-es2015-parameters"
]
}
and install these plugins as devdependences with npm.
then try babel-node ***.js again. hope this can help you.
In your app, you must declare your require() modules, not using the 'import' keyword:
const app = require("example_dependency");
Then, create a .babelrc file:
{
"presets": [
["es2015", { "modules": false }]
]
}
Then, in your gulpfile, be sure to declare your require() modules:
var gulp = require("gulp");

Categories