I'm trying to use javascript ES7 syntax on the server using node.js with webpack and babel-loader (es2015 + stage-0 presets). I've gotten it to work with babel-node but when I run webpack I get the following error at the async keyword (9:22 is after the async keyword):
ERROR in ./src/server.js Module parse failed: C:\dev\node-async-sample\src\server.js
Unexpected token (9:22) You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (9:22)
I've put the code on github at https://github.com/qubitron/node-async-sample, any ideas on how to get this to work?
Here is the relevant snippet from src/server.js:
import express from 'express';
import http from 'request-promise';
let server = express();
server.get('/', async function(request, response) {
let result = await http('http://www.google.com');
response.send(result);
});
.babelrc:
{
"presets": [
"es2015",
"node5",
"stage-0"
],
"plugins": [
"transform-runtime"
]
}
and webpack.config.js:
module.exports = {
entry: [
'babel-polyfill',
'./src/server.js'
],
output: {
path: __dirname + '/dist',
filename: 'server_bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: __dirname + '/src',
loader: 'babel-loader'
}
]
}
};
I saw a similar issue here but it has a different error message and was fixed in babel:master:
ES7 async await functions with babel-loader not working
Your src path was incorrect. You should never (like never :)) join pathes using string concatenation there is path.join for that.
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
loader: 'babel-loader'
}
BTW, this will fix parsing issue but you still gonna need to handle .json file loading by adding corresponding extension to resolve section and using json-loader
{ test: /\.json$/, loader: 'json-loader' }
Also you'll need to handle missing modules warning. For example fs and net.
So I do recommend you to use babel-cli to precompile server code.
babel src --out-dir dist
Related
I have an issue with webpack. im using webpack-dev-server but when i try to run It im having this error SyntaxError: Unexpected token { trying to figure it out since yesterday but no luck.
I already tried to export default on other files still got the same issue when importing.
./sort.js
this is my export
export {descend, ascend};
./index.js
this is my import
import {descend, ascend} from './js/insertion_sort';
./babelrc
this is babel
{
"presets": [["#babel/preset-env"]]
}
webpack.config.js
this my webpack config
const path = require('path');
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{test: /\.scss$/, use: 'scss-loader'},
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
]
},
devServer: {
contentBase: './'
}
};
im not using the bundle btw. im just using index file as my main.
UPDATE
so guys this is so weird. what i did. on my html.index is this i change the script tag to <script src="./src/index.js"></script> to <script src="./bundle.js"></script> then its working. but on my package.json i havent built it yet. i was just running it. "start": "webpack-dev-server --mode development --hot" how would webpack now where to look for bundle.js when its not ceated yet. crazy
I am implementing React JS, with Webpack and Babel. However, I am having trouble getting Fetch to work with IE 11.
I have the following in my .babelrc file:
{
"presets" : ["env", "stage-0", "react"]
}
and the following in my webpack.config.js file:
var webpack = require('webpack');
var path = require('path');
var DIST_DIR = path.resolve(__dirname, 'dist');
var SRC_DIR = path.resolve(__dirname, 'src');
var config = {
entry: {
bundle: [
'babel-polyfill',
SRC_DIR + '/app/index.js',
]
},
output: {
path: DIST_DIR + '/public/js',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: SRC_DIR,
loader: 'babel-loader'
}
]
}
};
module.exports = config;
From my understanding implementing babel-preset-env, stage-0, and babel-polyfill should have allowed for the Fetch API to be transpiled into something older browsers could understand. Is there something else that I am missing?
fetch isn't part of EcmaScript but its part of the web platform. Babel is only a compiler to write the latest Javascript. If you want to use fetch in older browsers you need a polyfill like this one
Fetch API: read more
fetch must be made available by the browser you use and is not included in babel-polyfill. If your browser doesn't support fetch, you can either fall back to using XMLHttpRequest or use a polyfill such as isomorphic-fetch.
I'm trying to find some information about Webpack and relative imports when working with ES6 and Babel.
I have an import line in a simple entry point in my app:
// app.es6
import * as sayHello from 'sayHello';
console.log(sayHello());
sayHello.es6 is the same directory as app.es6. (The contents of sayHello.es6 is not significant).
When I run the Webpack compiler via the command line:
$ webpack
I get the following error:
ERROR in ./app/app.es6
Module not found: Error: Cannot resolve module 'sayHello' in /Users/username/Code/projectname/app
This is solved by setting the path to relative:
// app.es6 - note the ./ in the import
import * as sayHello from './sayHello';
console.log(sayHello());
This is a bit of a pain because it's different to the example es6 code on Babel website under the Modules section.
Here is my Webpack config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'babel-polyfill',
'./app/app.es6'
],
output: {
publicPath: '/',
filename: './dist/app.js'
},
debug: true,
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js|\.es6$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:
{
presets:['es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.es6'],
},
};
Question: Does any one know why there is this difference? Or where the relevant information regarding ES6 module imports is in the Webpack documentation?
This is by design, without prefixing it indicates the module should be loaded from node_modules directory. You can set up an alias in your webpack config which would remove the need for relative module imports
resolve: {
alias: {
sayHello: '/absolute/path/to/sayHello'
},
extensions: ['', '.js', '.es6']
}
Then Webpack would fill in the gaps in your import statements and allow you to omit the relative path and import * as sayHello from 'sayHello'; would work throughout your project
I am trying to publish a package on npm (this one) that I am developing using webpack and babel. My code is written in ES6. I have a file in my sources, index.js, that (for the moment) exports one of my library's core components, it simply goes like this:
import TheGamesDb from './scrapers/thegamesdb';
export { TheGamesDb };
I am using webpack and babel to create a dist index.js that is my package's main file. My webpack.config.js goes like this:
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: {
index: ['babel-polyfill', './src/index.js'],
development: ['babel-polyfill', './src/development.js']
},
output: {
path: '.',
filename: '[name].js',
library: 'rom-scraper',
libraryTarget: 'umd',
umdNamedDefine: true
},
devtool: 'source-map',
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
target: 'node',
externals: [nodeExternals()]
};
Now when I load my package in another project and try to import my export TheGamesDb simply like this
import { TheGamesDb } from 'rom-scraper';
I get the error
Uncaught TypeError: Path must be a string. Received undefined
It is to be noted that I am importing my library in electron.
Update: Electron seems to be the main problem here and it is not even my library but a dependency that throws this error (only in Electron)
The problem wasn't any of the things in my question but node-expat not working in electron. I switched to an alternative library and it's all right now.
When I attempted to use webpack to compile my react jsx code, I received the following error:
ERROR in ./client/index.js
Module parse failed: C:\Users\Gum-Joe\Documents\Projects\bedel/client\index.js Unexpected token (6:11)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (6:11)
at Parser.pp.raise (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:920:13)
at Parser.pp.unexpected (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1483:8)
at Parser.pp.parseExprAtom (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:330:12)
at Parser.pp.parseExprSubscripts (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:225:19)
at Parser.pp.parseMaybeUnary (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:204:17)
at Parser.pp.parseExprOps (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:151:19)
at Parser.pp.parseMaybeConditional (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:133:19)
at Parser.pp.parseMaybeAssign (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:110:19)
at Parser.pp.parseExpression (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:86:19)
at Parser.pp.parseReturnStatement (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1854:26)
at Parser.pp.parseStatement (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1719:19)
at Parser.pp.parseBlock (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1991:21)
at Parser.pp.parseFunctionBody (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:607:22)
at Parser.pp.parseMethod (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:576:8)
at Parser.pp.parseClassMethod (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:2137:23)
at Parser.pp.parseClass (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:2122:10)
# ./client/index.js 1:0-20
.babelrc:
{
"presets": ["es2015", "react"]
}
webpack.config.js:
// Webpack config
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// Use client as our root
context: __dirname + "/client",
// Entry file
entry: "./index.js",
// Resolve
resolve: {
extensions: ['', '.js', '.jsx']
},
// Output to /build
output: {
path: path.join(__dirname, "build", "js"),
filename: "bundle.js"
},
loaders: [
{ test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" }
],
// Plugins
plugins: [
// HTML
new HtmlWebpackPlugin({
title: 'Bedel',
filename: path.join(__dirname, 'views', 'index.ejs'),
template: path.join(__dirname, 'client', 'templates', 'index.ejs')
})
]
};
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render () {
return <p> Hello React</p>;
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
I have installed all the babel presets required, as well as babel-core.
I have looked at the following answers already:
babel-loader jsx SyntaxError: Unexpected token
React, babel, webpack not parsing jsx code
Edit: After commenting out my jsx syntax, the outputting bundle.js does not appear to have been transformed by babel (i.e. I can see ES6 code in it)
Edit: Sorry for the inconvenience, but app.jsx was a solution that I tried that involved putting the logic that should be in index.js into a separate file.
Edit: Here is a list of the solutions I tried that did not work:
Copy .babelrc to client/.babelrc
Change test to test for .js instead of .js
Separate app logic into separate file (app.js)
Put presets to use in webpack config
Also, I have pushed my code to my GitHub repo (https://github.com/Gum-Joe/bedel). Feel free to have a look at it.
You configured the loader to only pass .jsx files through Babel:
test: /\.jsx$/
However, your file has the extension .js. Either rename the file or update the test expression to /\.jsx?$/.
In addition to updating the test, you need to rename .babel.rc to .babelrc (no . before rc). Otherwise Babel thinks that there is no configuration file and won't load any presets.
The loaders property must exist within the module property. Webpack Loaders
module.exports = {
// ...
// Output to /build
output: {
path: path.join(__dirname, "build", "js"),
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" }
]
},
//...
};
You need to use react-preset with babel, like here:
loaders: [{
test: /\.(js|jsx)$/,
loader: 'babel',
query: {
presets: [
'es2015',
'react'
]
}
}]
I'm having this issue as well, and if you're using Windows and Node 6.x, the only workaround I've found for now seems to be to use Node 4 LTS or 5 instead. Without knowing the root cause, the problem seems to stem from some combination of using JSX, Webpack, Babel, Acorn JS, Node 6, and Windows.
https://github.com/coryhouse/pluralsight-redux-starter/issues/2
https://github.com/danmartinez101/babel-preset-react-hmre/issues/32
Can you try wrapping the entire element in brackets "()"?
return (<p>...</p>)