Grunt + Babel successfully runs but doesn't do anything - javascript

I'm rather new to grunt/npm but after reading up the docs. I have made myself a package.json and a Gruntfile.js. Here's my folder structure:
/
|- src
|- myfile.es6
|- anotherfile.es6
|- etc.
|- Gruntfile.js
|- package.json
What I have
Here's my Gruntfile:
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
babel: {
options: {
sourceMap: true,
plugins: ['es2015']
},
dist: {
files: [{
expand: true,
cwd: 'src/',
src: ['*.es6'],
dest: 'dist/',
ext: '.js'
}]
}
}
});
grunt.registerTask('default', ['babel'])
};
And then here's my package.json:
{
"name": "Cheddar",
"version": "0.2.0",
"devDependencies": {
"babel-preset-es2015": "^6.6.0",
"grunt": "^1.0.1",
"grunt-babel": "^6.0.0"
},
"scripts": {
"test": "grunt --verbose"
}
}
What does it do?
I have my src/ folder which contains my source files (*.es6). I want to transpile these to a dist/ directory with grunt.
What I've tried
Then I installed all the dependencies / babel-cli / grunt-cli/ etc. with npm install and npm-update --save
Seems good, so I went ahead and ran grunt:
$ grunt
Running "babel:dist" (babel) task
Done.
$ ls
Gruntfile.js node_modules/ package.json src/
The ls is outputting the exact same thing as before I ran grunt. So nothing is appearing to happen. Where's my output dist? This has been bugging me for the past few hours. I've tried installing babelify, and quite a few other fixes from blogs across the internet but alas, nothing works.

Try using the keyword "presets" instead of "plugins":
babel: {
options: {
sourceMap: true,
presets: ['es2015']
}
...
}
When I use your configuration, grunt seems to error out because it can't find the plugin called "es2015". Everything worked after I made that change.

Try a more literal example from the README like:
grunt.initConfig({
babel: {
options: {
sourceMap: true,
presets: ['es2015']
},
dist: {
files: {
'dist/myfile.js': 'src/myfile.es6'
}
}
} });
After you get that working try specifying *.es6 etc. under files. If you look at the source for the grunt-babel plugin it may be more limited than one would assume.
You can also just use npm scripts and specify the babel command line directly which I feel is simpler than using grunt.

Related

Error when typing cmd grunt jshint.

I am currently going to the Learn how to Program with Steve Foote. I am using ubuntu as the operating system.I have installed Node.js, installed the grunt command-line, and installed the npm install to the correct folder.
I noticed a problem that when I ran node on the specified folder it wouldn't run the js files I have. I even went to the folder with the js files and it didn't work. I then tried node values.js but nothing came up.
This is my code for the package.json file:
{
"name": "kittenbook",
"version": "0.0.1",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-concat": "~0.3.0",
"grunt-contrib-copy": "~0.5.0",
"grunt-contrib-jshint": "~0.6.3"
}
}
And this is the Gruntfile.js
module.exports = function(grunt) {
//Project Configuiration
grunt.initConfig({
/*
* We will configuire our tasks here
*/
concat: {
release: {
src:['js/values.js', 'js/prompt.js'],
dest: 'release/main.js'
}
},
copy: {
release{
src: 'manifest.json',
dest: 'release/manifest.json'
}
},
jshint: {
files: ['js/values.js', 'js/prompt.js']
}
});
//We will load our plugins here
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-jshint');
//We will register our tasks here
grunt.registerTask('default', ['jshint', 'concat', 'copy']);
};
Sorry if the formatting is bad here it genuinely is all lined up on the text file.
When I type grunt jshint a warning comes up saying:
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected token {
Warning: Task "jshint" not found. Use --force to continue.
Aborted due to warnings.
You are missing a colon (:) in your grunt.initConfig object.
copy: {
release{ /*<--Missing colon in between "release" and the opening bracket {*/
src: 'manifest.json',
dest: 'release/manifest.json'
}
},

Setting up Webpack with Babel for ES6 coding [duplicate]

How to use ES6 in webpack.config ?
Like this repo
https://github.com/kriasoft/react-starter-kit
does ?
For instance:
using this
import webpack from 'webpack';
instead of
var webpack = require('webpack');
It is quite a curiosity rather than a need.
Try naming your config as webpack.config.babel.js. You should have babel-register included in the project. Example at react-router-bootstrap.
Webpack relies on interpret internally to make this work.
As an alternative to what #bebraw suggests, you can create a JavaScript automation script with ES6+ syntax:
// tools/bundle.js
import webpack from 'webpack';
import webpackConfig from './webpack.config.js'; // <-- Contains ES6+
const bundler = webpack(webpackConfig);
bundler.run(...);
And execute it with babel:
$ babel-node tools/bundle
P.S.: Calling webpack via JavaScript API might be a better approach (than by calling it via a command line) when you need to implement more complex build steps. E.g. after server-side bundle is ready, startup Node.js app server, and right after Node.js server is started, launch BrowserSync dev server.
See also:
React Starter Kit (package.json/scripts, tools/bundle.js, tools/webpack.config.js)
React Static Boilerplate (run.js, webpack.config.js, node run)
You might not need Gulp.js
Another approach is to have a npm script like this: "webpack": "babel-node ./node_modules/webpack/bin/webpack", and run it like so: npm run webpack.
This is what worked for me using webpack 4:
In package.json:
"scripts": {
"dev": "cross-env APP_ENV=dev webpack-serve --require #babel/register"
},
"devDependencies": {
"#babel/core": "^7.0.0-rc.1",
"#babel/register": "^7.0.0-rc.1",
"#babel/preset-env": "^7.0.0-rc.1",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2"
},
"babel": {
"presets": [
["#babel/preset-env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-es2015-modules-commonjs"
]
}
You can clearly see how each dependency is used, so no surprises there.
Note I am using webpack-serve--require, but if you want to use the webpack command instead, replace it with webpack --config-register. In either case, #babel/register is needed to make this work.
And that's it!
yarn dev
And you are able to use es6 in the config!
For webpack-dev-server, use the --config-register option which is the same as with the webpack command
NOTE:
NO need to rename the config file to webpack.config.babel.js (as suggested by the accepted answer). webpack.config.js will work just fine.
I had a problem getting #Juho's solution running with Webpack 2. The Webpack migration docs suggest you to turn of babel module parsing:
It is important to note that you will want to tell Babel to not parse
these module symbols so webpack can use them. You can do this by
setting the following in your .babelrc or babel-loader options.
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Sadly, this conflicts with the automatic babel register functionality. Removing
{ "modules": false }
from the babel config got things running again. However, this would result in breaking tree-shaking, so a complete solution would involve overwriting the presets in the loader options:
module: {
rules: [
{
test: /\.js$/,
include: path.resolve('src'),
loader: 'babel-loader',
options: {
babelrc: false,
presets: [['env', {modules: false}]]
}
}
]
}
Edit, 13th Nov 2017; updated webpack config snippet to Webpack 3 (thanks to #x-yuri). Old, Webpack 2 snippet:
{
test: /\.js$/,
exclude: ['node_modules'],
loader: 'babel',
query: {
babelrc: false,
presets: [
['es2015', { modules: false }],
],
},
},
This is really easy, but it wasn't obvious to me from any of the answers, so if anyone else is confused like me:
Just append .babel to the part of your filename before the extension (assuming that you have babel-register installed as a dependency).
Example:
mv webpack.config.js webpack.config.babel.js
Configuration for Babel 7 & Webpack 4
package.json
...
"scripts": {
"start": "webpack-dev-server --env.dev",
"build": "webpack --env.prod",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/plugin-proposal-class-properties": "^7.0.0",
"#babel/preset-env": "^7.0.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"babel-loader": "^8.0.0",
...
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0",
"webpack-config-utils": "^2.3.1",
"webpack-dev-server": "^3.1.8"
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-proposal-class-properties"]
}
webpack.config.babel.js
import webpack from 'webpack';
import { resolve } from 'path';
import { getIfUtils, removeEmpty } from 'webpack-config-utils';
export default env => {
const { ifProd, ifNotProd } = getIfUtils(env);
return {
mode: ifProd('production', 'development'),
devtool: ifNotProd('cheap-module-source-map'),
output: {
path: resolve(__dirname, ifProd('prod', 'dev')),
filename: 'bundle.js'
},
For TypeScript: straight from https://webpack.js.org/configuration/configuration-languages/
npm install --save-dev typescript ts-node #types/node #types/webpack
# and, if using webpack-dev-server
npm install --save-dev #types/webpack-dev-server
then proceed to write your, e.g.:
webpack.config.ts
import path from 'path';
import webpack from 'webpack';
const config: webpack.Configuration = {
mode: 'production',
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
}
};
export default config;
Check the link for more details where you can use a plugin to have a separate tsconfig file just for the webpack config if you're not targeting commonjs (which is a req for this to work since it relies on ts-node).
For readers in 2022:
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
Add "type": "module" in package.json
Change the syntax of your webpack.config.js to ESM.
Enjoy.
One more way is to use require argument for node:
node -r babel-register ./node_modules/webpack/bin/webpack
Found this way in electron-react-boilerplate, look at build-main and build-renderer scripts.
Rename webpack.config.js to webpack.config.babel.js.
Then in .babelrc: {"presets": ["es2015"]}
However, if you want to use a different babel config for babel-cli, your .babelrc might look something like this:
{
"env": {
"babel-cli": {
"presets": [["es2015", {"modules": false}]]
},
"production": {
"presets": ["es2015"]
},
"development": {
"presets": ["es2015"]
}
}
}
And in package.json:
{
"scripts": {
"babel": "BABEL_ENV='babel-cli' babel src -d dist/babel --source-maps",
"build-dev": "NODE_ENV='development' webpack -d --progress --profile --colors",
...
},
...
}
It's dumb but the {"modules": false} will break webpack if you don't use different envs.
For more info about .babelrc, check the official docs.
Don't have enough rep to comment, but I wanted to add for any TypeScript users out there a similar solution to #Sandrik above
I have two scripts that I use pointing to webpack configs (JS files) that contain ES6 syntax.
"start-dev": "./node_modules/.bin/ts-node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --config ./webpack/webpack.config.dev.js"
and
"build": "./node_modules/.bin/ts-node ./node_modules/webpack/bin/webpack.js --config webpack/webpack.config.js"
Using Webpack 4 and Babel 7
To setup a webpack configuration file to use ES2015 requires Babel:
Install dev dependencies:
npm i -D webpack \
webpack-cli \
webpack-dev-server \
#babel/core \
#babel/register \
#babel/preset-env
npm i -D html-webpack-plugin
Create a .babelrc file:
{
"presets": ["#babel/preset-env"]
}
Create your webpack config, webpack.config.babel.js:
import { resolve as _resolve } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const config = {
mode: 'development',
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
})
],
resolve: {
modules: [_resolve(__dirname, './src'), 'node_modules']
}
};
export default config;
Create your scripts in package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --open"
},
Run npm run build and npm start.
The webpack config is based on a sample project with the following directory structure:
├── README.md
├── package-lock.json
├── package.json
├── src
│   ├── Greeter.js
│   ├── index.html
│   └── index.js
└── webpack.config.babel.js
Sample project: Webpack Configuration Language Using Babel
My Best approach along with npm script is
node -r babel-register ./node_modules/webpack/bin/webpack
and configure rest of scripts as per your requirement for Babel
After tons of the documents...
Just install es2015 preset (not env !!!) and add it to
.babelrc:
{
"presets": [
["es2015", { "modules": false }]
]
}
Rename your webpack.config.js to webpack.config.babel.js
Adding es6 to webpack is a 3 step process
In webpack.config.js add
module:{
rules:[
{
test: /\.js$/,
loader: 'babel-loader'
}
]
}
Create a .babel.rc and add inside it
{
"presets": ["#babel/env", "#babel/react"],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
]
]
}
in package.json add
npm install #babel/core --save-dev
npm install #babel/preset-env --save-dev
npm install #babel/preset-react --save-dev
npm install #babel/plugin-proposal-class-properties --save-dev
npm install babel-loader --save-dev
Edit: Works as of Feb 2021
https://github.com/webpack/webpack-cli/pull/2381
You can't. You have to convert it to CommonJS, either with babel or esm.
https://github.com/webpack/webpack-cli/issues/282
But you can run webpack -r esm #babel/register

Using babel-polyfill with grunt and browserify

My grunt build system transpiles my javascript (which is using react as well).
Unfortunately it doesn't transpile Promises. For that, I need a polyfill.
I want to include babel-polyfill with my grunt build system.
My build system uses browserify along with babelify and the es2015 preset.
How do I include babel-polyfill into the mix?
Here is what I have...
Inside gruntfile.js, here is where I use browserify
browserify: {
dist: {
options: {
watch: true,
transform: [["babelify", {presets: ['es2015', 'react']}], ["envify", {NODE_ENV: 'development'}]]
},
files: {
'dist/js/app.js' : 'src/js/main.js'
}
},
build: {
options: {
transform: [["babelify", {presets: ['es2015', 'react'], compact: true }], ["envify", {NODE_ENV: 'production'}]]
},
files: {
'dist/js/app.js' : 'src/js/main.js'
}
}
},
Here is my babelrc file
{
"presets": [ "react", "es2015" ]
}
Thanks!
Assuming that babel-polyfill is included as a dependency, at the top of your entry file 'src/js/main.js' add the line:
import "babel-polyfill";
No need to do anything in your GruntFile.js

new to grunt - warning: task "concat, uglify" not found

As the title says I'm new to Grunt. I am following a tutorial located at: http://24ways.org/2013/grunt-is-not-weird-and-hard/. It is an older tutorial but most seems to work the same. I have installed "grunt-contrib-concat" and "grunt-contrib-uglify" and can run both individually. But when I run grunt, I get the following error: Warning: Task "concat, uglify" not found. Use --force to continue. Aborted due to errors. I've been looking around and can't seem to figure it out. My files are as follows:
Gruntfile.js:
module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
dist: {
src: [
'js/libs/*.js', // All JS in the libs folder
'js/controls.js', // This specific file
],
dest: 'dist/built.js',
}
},
uglify: {
build: {
src: 'js/build/production.js',
dest: 'js/build/production.min.js',
}
},
});
// 3. Where we tell Grunt we plan to use this plug-in.
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
// 4. Where we tell Grunt what to do when we type 'grunt' into the terminal.
grunt.registerTask('default', ['concat, uglify']);
};
package.json:
{
"name": "grunt_libsass_example-project",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.1",
"grunt-contrib-concat": "^0.5.1",
"grunt-contrib-uglify": "^0.9.1"
}
}
Your passing in only one string for the registerTask task list. It should be a array with a list of strings like:
grunt.registerTask('default', ['concat', 'uglify']);
You're getting that error because it's looking for a task named 'concat, uglify'.
I had to run:
npm install grunt-contrib-uglify --save-dev

Grunt tasks stuck in endless loop

Working on putting together a base Gruntfile.js for some upcoming projects. Starting in on a new computer so everything has been a fresh build. Installed Node and NPM using Homebrew, and then installed Grunt globally, as well as in my local directory.
Here is my package.json:
{
"name": "timespent-prototype",
"version": "0.1.0",
"devDependencies": {
"assemble": "0.4.37",
"bower": "^1.4.1",
"grunt": "^0.4.5",
"grunt-contrib-concat": "^0.5.1",
"grunt-contrib-sass": "^0.9.2",
"grunt-contrib-watch": "^0.6.1",
"grunt-newer": "^1.1.0",
"grunt-wiredep": "^2.0.0"
}
}
And here is my Gruntfile.js:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
vendor: {
src: ['vendor/**/*.min.js'],
dest: 'build/javascripts/library.js',
}
},
// Takes your scss files and compiles them to css
sass: {
dist: {
options: {
style: 'expanded'
},
files: {
'build/stylesheets/application.css': 'app/stylesheets/application/index.scss'
}
}
},
// Assembles your templates into HTML files
assemble: {
options: {
layoutdir: 'app/views/layouts/',
partials: ['app/views/partials/*.hbs'],
flatten: true,
expand: true
},
pages: {
src: ['app/views/**/*.hbs','!app/views/layouts/*.hbs','!app/views/partials/*.hbs'],
dest: 'build/'
}
},
wiredep: {
task: {
src: ['app/views/layouts/*.hbs']
}
},
// Watches for file changes, runs the default task
watch: {
files: ['app/**/*'],
tasks: ['default'],
options: {
// Start another live reload server on port 1337
livereload: 1337,
}
}
});
// Load the plugins
grunt.loadNpmTasks('assemble');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-wiredep');
// Register the tasks
grunt.registerTask('default', ['sass','assemble']);
grunt.registerTask('watch', ['watch']);
grunt.registerTask('concat', ['concat']);
grunt.registerTask('wiredep', ['wiredep']);
};
The problem that I am seeing is that with multiple tasks, here specifically with wiredep and concat, the task gets stuck in a loop and never ends. Running grunt concat with verbose outputs like this:
Registering "grunt-contrib-concat" local Npm module tasks.
Reading /Users/jacksonlynch/projects/timespent-prototype/node_modules/grunt-contrib-concat/package.json...OK
Parsing /Users/jacksonlynch/projects/timespent-prototype/node_modules/grunt-contrib-concat/package.json...OK
Loading "concat.js" tasks...OK
+ concat
Running tasks: concat
Running "concat" task
Running "concat" task
Running "concat" task
Running "concat" task
Running "concat" task
Running "concat" task
Where Running "concat" task will continue to print until I stop it. As I am seeing this with multiple plugins and tasks this might be a problem with my installation of NPM or Grunt, but I'm having a very hard time debugging this. If anyone has run into this before, please let me know what helped!
Thanks!
Edit: in response to Alireza Ahmadi's comment, here is my file structure:
.
|
|_ app/
|_ assets/
|_ javascript/
|_ stylesheets/
|_ views/
|
|_ build/
|_stylesheets/
|_javascripts/
|
|_ vendor/
|_ bower.json
|_ Gruntfile.js
|_ package.json
In the last 2 lines of your Gruntfile.js you have redeclared the concat and wiredep tasks and when grunt tries to run your code, It stuck in an endless loop because concat refers to an undefined concat task, So you should remove these lines:
grunt.registerTask('concat', ['concat']);
grunt.registerTask('wiredep', ['wiredep']);
In general, When you define a task named foobar with grunt.initConfig, It's defined and does not need to registered using registerTask and it can be accessible by grunt foobar command.

Categories

Resources