error using import in webpack. Uncaught SyntaxError: Unexpected token { - javascript

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

Related

Excluding node_module from being written to the output file in webpack

I am trying to transpile es6 code to es5 using webpack and babel and in the js file I am importing jquery as below:
import $ from 'jquery';
So when I am building the code using webpack, the output file is getting the content of jquery along with the original transpiled code which I don't want to consume. I have added the exclude statement below to webpack.config.js but that doesn't seem to exclude the jquery part from getting appended.
exclude:path.resolve(__dirname, 'node_modules'),
Here's what the webpack.config.js file looks like:
var path = require('path');
module.exports = {
entry: {
copystyles: './src/copystyles.js',
docErrorReporter: './src/docErrorReporter',
},
output: {
path: path.resolve(__dirname, 'lib'),
filename: "[name].js",
},
mode:'none',
module: {
rules: [
{
test: path.join(__dirname, 'src'),
exclude:path.resolve(__dirname, 'node_modules'),
use: ['babel-loader']
}
]
}
};
Can anybody tell me if I am missing something here?
Thanks!

Webpack - [HMR] Hot Module Replacement is disabled

I've looked around, but can't get any of the answers I've seen on stackoverflow to work.
I cannot use the command line for webpack or the webpack dev-server; I am restricted to using the Node API.
Below is how I am using webpack.
webpack.config.js
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:3000',
// i've also tried webpack/hot/dev-server here
'webpack/hot/only-dev-server',
path.join(__dirname, 'src', 'js', 'app.jsx')
],
output: {
path: path.join(__dirname, 'dist', 'js'),
filename: 'script.js',
publicPath: '/dist/'
},
module: {
loaders: [{
test: /\.(js|jsx)$/,
loaders: ['react-hot', 'babel']
}]
},
plugins: []
};
contained in a gulp task "start"
gulp.task('start', function (callback) {
var config = Object.create(require('webpack.config.js'));
config.plugins.push(new webpack.HotModuleReplacementPlugin());
var devServer = new webpackDevServer(webpack(config), {
stats: { colors: true },
contentBase: path.resolve(__dirname, 'dist'),
progress: true,
inline: true,
hot: true
});
});
What I expect
When I run gulp start, I expect the webpack dev server to spin up, allowing me to hit localhost:3000/. This should load an index.html from my project's /dist/ folder. So far so good. I expect that when I make a change to a file (e.g., app.jsx), that the change would be present.
What is actually happening
I am getting the error "[HMR] Hot Module Replacement is disabled", with no further explanation.
Any help would be appreciated. I have been trying to get hot reloading working for a full day.
in your webpack.config.js on the plugins section try this,
plugins: [new webpack.HotModuleReplacementPlugin()]
I know you are pushing the plugin in your gulp task but you have to use --hot --inline on cli or on your npm script
Try to run webpack as
webpack-dev-server --hot --inline in packge.json,
somehow official docs is wrong now.

Webpack missing loader for bootstrap

I'm trying to use bootstrap through webpack and have installed it using npm. I want to use it in my react project so I've done the below settings but I keep getting the below error:
main.js
import React from 'react'
import 'bootstrap/dist/css/bootstrap.css'
const Main = () => (
<div className="container">yo</div>
)
Webpack config
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
'./client/pokeapp'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'client')
},
// CSS
{
test: /\.css$/,
include: path.join(__dirname, 'client'),
loader: 'style-loader!css-loader'
},
{ test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'url'}
]
}
};
Console Error
Module parse failed: /Users/jlei/Desktop/pokeapp/node_modules/bootstrap/dist/css/bootstrap.css Unexpected token (7:5)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (7:5)
at Parser.pp$4.raise (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:2221:15)
at Parser.pp.unexpected (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:603:10)
at Parser.pp.semicolon (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:581:61)
at Parser.pp$1.parseExpressionStatement (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:966:10)
at Parser.pp$1.parseStatement (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:730:24)
at Parser.pp$1.parseTopLevel (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:638:25)
at Parser.parse (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:516:17)
at Object.parse (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:3098:39)
at Parser.parse (/Users/jlei/Desktop/pokeapp/node_modules/webpack/lib/Parser.js:902:15)
at DependenciesBlock.<anonymous> (/Users/jlei/Desktop/pokeapp/node_modules/webpack/lib/NormalModule.js:104:16)
# ./client/components/Main.js 27:0-43
What's the unexpected token? Is that due to my loader not working?
I tested your code and there is nothing wrong with the loader However this line include: path.join(__dirname, 'client') is causing the issue if you remove it you can see bootstrap bundling just fine with webpack.
For getting more from webpack you may want to get a separate css file then you can use ExtractTextPlugin to achieve it.
How it work ?
Installation
npm i extract-text-webpack-plugin
Configure it in webpack
{test: /\.css$/, loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader' })}
and add it in plugin
new ExtractTextPlugin('yourStyle.css')
Now you should have a separate css file in browser instead of every css in style tag
How does it work
It moves every require("style.css") in entry chunks into a separate css output file. So your styles are no longer inlined into the javascript, but separate in a css bundle file (styles.css). If your total stylesheet volume is big, it will be faster because the stylesheet bundle is loaded in parallel to the javascript bundle.
Hope it help you.
you don't have to include bootstrap as an npm module. You can download or use CDN to include bootstrap on your html template. You can then apply it on your component by using 'className' attribute instead of 'class'. Try it.
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'));
and in your html file:
<link rel="stylesheet" href="/css/bootstrap.min.css">
This method is the same as downloading the bootstrap files to improve latency.

Making a library importable using webpack and babel

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.

Webpack throws syntax error for JSX

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>)

Categories