Related
I'm trying to run a dev server with TypeScript and an Angular application without transpiling ts files every time.
What I found is that I can run .ts files with ts-node but I want also to watch .ts files and reload my app/server. An example of this is the command gulp watch.
You can now simply npm install --save-dev ts-node nodemon and then run nodemon with a .ts file and it will Just Work:
nodemon app.ts
Previous versions:
I was struggling with the same thing for my development environment until I noticed that nodemon's API allows us to change its default behaviour in order to execute a custom command.
For example, for the most recent version of nodemon:
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "ts-node src/index.ts"
Or create a nodemon.json file with the following content:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/index.ts" // or "npx ts-node src/index.ts"
}
and then run nodemon with no arguments.
By virtue of doing this, you'll be able to live-reload a ts-node process without having to worry about the underlying implementation.
And with even older versions of nodemon:
nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec 'ts-node' src/index.ts
Or even better: externalize nodemon's config to a nodemon.json file with the following content, and then just run nodemon, as Sandokan suggested:
{
"watch": ["src/**/*.ts"],
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./index.ts"
}
I've dumped nodemon and ts-node in favor of a much better alternative, ts-node-dev
https://github.com/whitecolor/ts-node-dev
Just run ts-node-dev src/index.ts
[EDIT]
Since I wrote this answer, nodemon has improved a lot, the required config is much lighter now and performance is much better. I currently use both (on different projects, obviously), and am satisfied with both.
Here's an alternative to the HeberLZ's answer, using npm scripts.
My package.json:
"scripts": {
"watch": "nodemon -e ts -w ./src -x npm run watch:serve",
"watch:serve": "ts-node --inspect src/index.ts"
},
-e flag sets the extenstions to look for,
-w sets the watched directory,
-x executes the script.
--inspect in the watch:serve script is actually a node.js flag, it just enables debugging protocol.
This works for me:
nodemon src/index.ts
Apparently thanks to since this pull request: https://github.com/remy/nodemon/pull/1552
Summary of options from other answers
nodemon plus ts-node is pretty stable but needs to be explicitly configured and is somewhat slow
node-dev plus ts-node requires much less configuration than nodemon but is still slow
ts-node-dev is fast but unreliable
Note that tsx (which uses ESBuild under the hood) and swc don't do type checking; this should be acceptable since most editors have type checking built-in, and type checking should still be part of your build process. You can also do type checking separately alongside your tests or as a pre-push hook via tsc --noEmit.
(Recommended) tsx
ⓘ TL;DR: fastest with minimal configuration
As of 2023-02-01, tsx seems to be the best combination of speed and minimal configuration:
Install tsx
npm install --save-dev tsx
Update your package.json, e.g.
"scripts: {
"dev": "tsx watch src/index.ts",
Run it
npm run dev
(Adjust these steps if you just want to install tsx globally and run it directly)
Alternative 1: nodemon/node-dev + ts-node + swc
ⓘ TL;DR: as fast as tsx but with more configuration
An alternative option that combines the reliability of nodemon/node-dev with the speed of ts-node-dev is to use ts-node with swc, a TypeScript-compatible transpiler implemented in Rust which is an "order of magnitude faster" than the TypeScript transpiler.
Install nodemon or node-dev (whichever you prefer)
nodemon
npm install --save-dev nodemon
node-dev
npm install --save-dev node-dev
Set up ts-node with swc integration
https://github.com/TypeStrong/ts-node#swc-1
Install necessary packages
npm install --save-dev ts-node #swc/core #swc/helpers regenerator-runtime
Add this to tsconfig.json
"ts-node": {
"swc": true
}
Run nodemon or node-dev, e.g
nodemon --watch src src/index.ts
or:
node-dev src/index.ts
Alternative 2: nodemon/node-dev + ts-node transpileOnly
ⓘ TL;DR: fast, reliable
Here's an alternative that's slower than the previous option because it uses the standard TypeScript transpiler, but in my testing it's still faster than nodemon/node-dev + ts-node.
Basically it's the same as the previous option but without swc. It's faster than out-of-the-box ts-node by disabling type checking (see notes above regarding why this should be acceptable).
Install nodemon/node-dev as above
Install ts-node
npm install --save-dev ts-node
Modify your tsconfig.json to enable transpileOnly for ts-node
"ts-node": {
"transpileOnly": true
}
Call nodemon/node-dev as above
Alternative 3: nodemon + tsc --incremental
ⓘ TL;DR: fast, reliable, type checking, more finicky
This is nearly the same speed as the previous alternative. The only real advantage of this over the other options is that it does type checking.
In terms of downsides, it can be a bit more finicky; in my testing, I'm using dotenv to pick up my .env file for local development. But depending how your tsc build is configured in tsconfig.json, you may have to do some acrobatics to get it working.
But it's good to have options, so here it is:
Install nodemon as above
(It's possible that this may work with node-dev as well, but I didn't see an exec option for node-dev)
Configure tsconfig.json to transpile your TypeScript to JavaScript
In particular, noEmit should not be set to true
Configure nodemon to run the TypeScript compiler to do an incremental transpilation any time a TypeScript file is changed, e.g.
"dev": "nodemon -e ts --watch src .env --exec \"tsc --incremental && node src/index.js\"",
You can even remove --incremental to further simplify it, but it will end up being much slower, comparable to nodemon/node-dev + ts-node.
you could use ts-node-dev
It restarts target node process when any of required files changes (as standard node-dev) but shares Typescript compilation process between restarts.
Install
yarn add ts-node-dev --dev
and your package.json could be like this
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"dev": "ts-node-dev --respawn --transpileOnly ./src/index.ts",
"prod": "tsc && node ./build/index.js"
}
Specifically for this issue I've created the tsc-watch library. you can find it on npm.
Obvious use case would be:
tsc-watch server.ts --outDir ./dist --onSuccess "node ./dist/server.js"
Add "watch": "nodemon --exec ts-node -- ./src/index.ts" to scripts section of your package.json.
i did with
"start": "nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec ts-node src/index.ts"
and yarn start.. ts-node not like 'ts-node'
I would prefer to not use ts-node and always run from dist folder.
To do that, just setup your package.json with default config:
....
"main": "dist/server.js",
"scripts": {
"build": "tsc",
"prestart": "npm run build",
"start": "node .",
"dev": "nodemon"
},
....
and then add nodemon.json config file:
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "npm restart"
}
Here, i use "exec": "npm restart"
So all ts file will re-compile to js file and then restart the server.
To run while in dev environment,
npm run dev
Using this setup I will always run from the distributed files and no need for ts-node.
add this to your package.json file
scripts {
"dev": "nodemon --watch '**/*.ts' --exec 'ts-node' index.ts"
}
and to make this work you also need to install ts-node as dev-dependency
yarn add ts-node -D
run yarn dev to start the dev server
Another way could be to compile the code first in watch mode with tsc -w and then use nodemon over javascript. This method is similar in speed to ts-node-dev and has the advantage of being more production-like.
"scripts": {
"watch": "tsc -w",
"dev": "nodemon dist/index.js"
},
The first step - Install the below packages in deDependencies
npm i -D #types/express #types/node nodemon ts-node tsc typescript
or using yarn
yarn add -D #types/express #types/node nodemon ts-node tsc typescript
The second step - using this configuration in your tsconfig.json file
{
"compilerOptions": {
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"lib": [
"DOM",
"ES2017"
] /* Specify library files to be included in the compilation. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
"strict": true /* Enable all strict type-checking options. */,
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": ["node_modules"],
"include": ["./src"]
}
The third step - using these scripts in your package.json file
"scripts": {
"start": "node ./dist/server.js",
"dev": "nodemon -L ./src/server.ts && tsc -w"
},
STEP 1: You can simple install nodemon and ts-node (skip if you already done)
npm install --save-dev nodemon ts-node
STEP 2: You can configure the start script in package.json
"start": "nodemon ./src/app.ts"
As now nodemon automatically identify the typescript from the project now and use ts-node command by itself. Use npm start and it will automatically compile/watch and reload.
If you get any errors like typescript module not found in the project. simple use this command in the project folder.
npm link typescript
Just update these 3 packages
nodemon, ts-node, typescript
yarn global add nodemon ts-node typescript
or
npm install -g nodemon ts-node typescript
and now you can run this, problem solved
nodemon <filename>.ts
Clear logs of the console after changing
Javascript:
"start": "nodemon -x \"cls && node\" index.js",
Typescript:
"start": "nodemon -x \"cls && ts-node\" index.ts",
If you are having issues when using "type": "module" in package.json (described in https://github.com/TypeStrong/ts-node/issues/1007) use the following config:
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --loader ts-node/esm --experimental-specifier-resolution ./src/index.ts"
}
or in the command line
nodemon --watch "src/**" --ext "ts,json" --ignore "src/**/*.spec.ts" --exec "node --loader ts-node/esm --experimental-specifier-resolution src/index.ts"
With nodemon and ts-node:
nodemon --watch source --ext ts,json --exec "node --loader ts-node/esm ./source/index.ts"
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
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
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");
Question: How can I write my gulp file in ES6 so I can use import instead of require and use => syntax over function()?
I can use io.js or node any version.
gulpfile.js:
import gulp from "./node_modules/gulp/index.js";
gulp.task('hello-world', =>{
console.log('hello world');
});
Errors:
import gulp from "./node_modules/gulp/index.js";
^^^^^^
SyntaxError: Unexpected reserved word
gulp.task('hello-world', =>{
^^
SyntaxError: Unexpected token =>
Inside the node_modules/gulp/bin/gulp.js i've changed the first line to #!/usr/bin/env node --harmony as asked in this stack
Yes, you can by using babel.
Make sure you've got the latest version of the gulp-cli.
npm install -g gulp-cli
Install babel as a dependency of the project.
npm install --save-dev babel
Rename gulpfile.js to gulpfile.babel.js
Your gulpfile might look something like this:
import gulp from 'gulp';
gulp.task('default', () => {
// do something
});
Update for Babel 6.0+
As correctly pointed out by Eric Bronniman, there are a few extra steps involved in getting this to work with the latest version of babel. Here are those instructions:
Again, make sure you've got the latest version of gulp-cli
npm install -g gulp-cli
Then install gulp, babel core, and the es2015 presets
npm install --save-dev gulp babel-core babel-preset-es2015
Then, either add the following to a .babelrc file or to your package.json
"babel": {
"presets": [
"es2015"
]
}
Your gulpfile.js should be named gulpfile.babel.js
Note you can now use many/most ES6 features in Node.js v4.0.0 without babel. However apparently 'import' is still not supported. See: https://nodejs.org/en/docs/es6/
Edit: Most of the popular ES6 features (including destructuring and spread) are supported by default in NodeJS 5.0 (see above link.) The only major missing feature appears to be ES6 modules as far as I can tell.
If you have the latest versions of gulp & node, you can simply create a gulpfile as gulpfile.mjs instead of gulpfile.js and it should work without needing to use Babel or any other transpiler.
.mjs is a special format used by node which allows usage of ES Modules.
References :-
https://nodejs.org/api/esm.html#esm_enabling
https://nodejs.org/api/packages.html#packages_determining_module_system
Example :-
// Filename: gulpfile.mjs
import gulp from 'gulp';
export default task;
function task()
{
return (
gulp.src(`./src/js/**/*.js`)
.pipe(gulp.dest(`./dist/Static/js`)
);
}
I use babel-node and native gulp.
Install babel and gulp as devDependencies.
Write gulpfile.js with ES6 syntax.
Use command ./node_modules/.bin/babel-node ./node_modules/.bin/gulp to run gulp
In package.json scripts section, you can skip the first ./node_modules/.bin/ part - as babel-node ./node_modules/.bin/gulp.
The advantage of this appoach is, one day when the node.js support all ES6 features one day, all you need to opt-out babel runtime is to replace babel-node with node. That is all.
If you're using the most modern version of Gulp and the Gulp CLI, you can just do Gulpfile.babel.js and it will understand and transpile your ES6 gulpfile with BabelJS by default.
It is also important to have the BabelJS transpiler installed under devDependencies as is Gulp:
npm install --save-dev babel
Also note that to require gulp in this context, you do not have to import the index.js, you can just:
import gulp from 'gulp';
Basically, what you need to install using npm is gulp, gulp-babel and babel-resent-env, add "env" to your .babelrc presets array, and use a gulpfile.babel.js file.
npm install gulp-babel --save-dev
Some of the answers mentioned babel-core, babel-preset-es2015, etc. The Babel official setup guide with Gulp is to use gulp-babel only, while gulp-babel has dependencies modules including babel-core so you don't need to install it separately.
About preset, you need to use a preset to make Babel actually do something, which is called Preset Env that automatically determines the Babel plugins you need based on your supported environments.
npm install babel-preset-env --save-dev
and in .babelrc file
{
"presets": ["env"]
}
/*
* Steps
* 1. Rename your gulpfile.js to gulpfile.babel.js
* 2. Add babel to your package.json (npm install -D babel)
* 3. Start writing ES6 in your gulpfile!
*/
import gulp from 'gulp'; // ES6 imports!
import sass from 'gulp-sass';
const sassOpts = { outputStyle: 'compressed', errLogToConsole: true }; // "let" and "const"!!
gulp.task('sass', () = > { // Arrow functions!!
gulp.src('./**/*.scss')
.pipe(sass(sassOpts))
.pipe(gulp.dest('./'));
});
gulp.task('default', ['sass'], () => { // Arrow functions!!
gulp.watch('./src/sass/**/*.scss', ['sass'])
.on('change', (e) => { // Arrow functions!!
console.log(`File ${e.path} was ${e.type}, running Sass task...`); // Template strings and interpolation!!
});
});
Steps I followed for developing the code for gulpfile in es6:
npm install gulp && sudo npm install gulp -g.
Please make sure that you you are using the updated version of Gulp.
The current version at the time of writing this answer was 3.9.1. To check which version of gulp is installed, type gulp -v
npm install babel-core babel-preset-es2015-without-strict --save-dev
Type touch .babelrc in the terminal
In the .babelrc file, add this code
{
"presets": ["es2015-without-strict"]
}
Created the gulp config file with the name gulpfile.babel.js
Voila!!! You can now write the config code for gulp in ES6.
Source: Using ES6 with Gulp - Mark Goodyear
I have just had the same problem and
solved as following:
Windows 10
node version: 14.15.4
npm version: 6.14.10
gulp version: 4.0.2
using yarn v1
Renamed gulpfile.js as gulpfile.babel.js
Added these packages as devdependency:
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/register": "^7.12.10",
"gulp-babel": "^8.0.0",
Added babel.config.json
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "10",
"edge": "17",
"firefox": "60",
"chrome": "70",
"safari": "11.1"
}
}
]
]
}
Finally I deleted yarn.lock file and node_modules folder and installed all packages.
yarn install
This is how my gulpfile.babel.js file looks like:
import { src, dest, parallel, series, watch } from 'gulp';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import concat from 'gulp-concat';
import postcss from 'gulp-postcss';
import replace from 'gulp-replace';
import sass from 'gulp-sass';
import { init, write } from 'gulp-sourcemaps';
import uglify from 'gulp-uglify';
import babel from "gulp-babel";
//....
const _default = series(
parallel(scssTask, jsTask),
cacheBustTask,
watchTask
);
export { _default as default };
Note:
yarn gulp command runs properly but I still have that warning:
Requiring external module #babel/register