First of all, I REALLY tried to fix it myself, I found several similar questions here, but none helped me.
Getting this error:
ERROR in ./src/components/App.jsx
Module parse failed: D:\JS projects\habr-app\src\components\App.jsx Unexpected token (54:6)
You may need an appropriate loader to handle this file type.
| render() {
| return (
| <div className='App'>
| <h1>Hello World!</h1>
| <div>
# ./src/client.js 3:0-42
# multi (webpack)-dev-server/client?http://0.0.0.0:8050 webpack/hot/dev-server babel-polyfill ./src/client.js
client.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render ("<App />", document.getElementById('react-view'));
render function in App.jsx looks like this:
render() {
return (
<div className='App'>
<h1>Hello World!</h1>
<div>
<p>Введите Ваше имя:</p>
<div><input onChange={this.handleNameChange} /></div>
{this.renderGreetingWidget()}
</div>
</div>
);
}
webpack.config.js file:
global.Promise = require('bluebird');
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var publicPath = 'http://localhost:8050/public/assets';
var cssName = process.env.NODE_ENV === 'production' ? 'styles-[hash].css' : 'styles.css';
var jsName = process.env.NODE_ENV === 'production' ? 'bundle-[hash].js' : 'bundle.js';
var plugins = [
new webpack.DefinePlugin({
'process.env': {
BROWSER: JSON.stringify(true),
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
}
}),
new ExtractTextPlugin(cssName)
];
if (process.env.NODE_ENV === 'production') {
plugins.push(
new CleanWebpackPlugin([ 'public/assets/' ], {
root: __dirname,
verbose: true,
dry: false
})
);
plugins.push(new webpack.optimize.DedupePlugin());
plugins.push(new webpack.optimize.OccurenceOrderPlugin());
}
module.exports = {
entry: ['babel-polyfill', './src/client.js'],
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new ExtractTextPlugin("styles.css"),
new webpack.LoaderOptionsPlugin({
debug: true,
options: {
eslint: { configFile: '.eslintrc' }
}
})
],
output: {
path: `${__dirname}/public/assets/`,
filename: jsName,
publicPath
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
],
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader!postcss-loader'})
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader!postcss-loader!less-loader'})
},
{ test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif' },
{ test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg' },
{ test: /\.png$/, loader: 'url-loader?limit=10000&mimetype=image/png' },
{ test: /\.svg/, loader: 'url-loader?limit=26000&mimetype=image/svg+xml' },
{ test: /\.(woff|woff2|ttf|eot)/, loader: 'url-loader?limit=1' },
{ test: /\.jsx?$/, loaders: ['react-hot-loader', 'babel-loader?presets[]=react,presets[]=es2015'],
exclude: [/node_modules/, /public/] , query: {presets: ['es2015', 'react', 'react-hot']} },
{ test: /\.json$/, loader: 'json-loader' },
]
},
devtool: process.env.NODE_ENV !== 'production' ? 'source-map' : null,
devServer: {
headers: { 'Access-Control-Allow-Origin': '*' }
}
};
The only way I can fix this problem - is to put quotes around html in render:
render() {
return (
`<div className='App'>
<h1>Hello World!</h1>
<div>
<p>Введите Ваше имя:</p>
<div><input onChange={this.handleNameChange} /></div>
{this.renderGreetingWidget()}
</div>
</div>`
);
}
But after that I'm gettin this error in browser and nodemon:
Invariant Violation: App.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
I checked and rechecked all dependencies, modules and my files.
Still, I cant find an error. Could someone help me, please?
P.S. Sorry for my awful English.
Funny thing. When I start nodemon without those quotes in App.jsx, my page loads, but without css. After that I add quotes in file App.jsx and now webpack-devserver builds everything right, and page gets .css after refresh. JS-script still doesnt work on it, but looks almost like it should... Right until I restart nodemon... It starts to show same error "Invariant Violation: App.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object."
The error tells you that you did not define a loader that can handle JSX, although it might look like you did in your webpack config. The problem is that you define both module.rules and module.loaders. When webpack sees module.rules it ignores module.loaders completely (though it still exists for compatibility reason). The fix is simple, just put all loaders under module.rules.
And there is also a problem in your .jsx? rule, because query (which is also deprecated and replaced with options) cannot be used for an array of loaders, but instead should be defined per loader in the array. Since you did it inline as string you don't need it at all.
To get a working config replace the module section with:
module: {
rules: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader!postcss-loader'})
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract({fallback: 'style-loader', use: 'css-loader!postcss-loader!less-loader'})
},
{ test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif' },
{ test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg' },
{ test: /\.png$/, loader: 'url-loader?limit=10000&mimetype=image/png' },
{ test: /\.svg/, loader: 'url-loader?limit=26000&mimetype=image/svg+xml' },
{ test: /\.(woff|woff2|ttf|eot)/, loader: 'url-loader?limit=1' },
{ test: /\.jsx?$/, use: ['react-hot-loader', 'babel-loader?presets[]=react,presets[]=es2015'],
exclude: [/node_modules/, /public/] },
{ test: /\.json$/, loader: 'json-loader' },
]
},
In case you decide to use options, which is definitely more readable, your .jsx? rule would look like this:
{
test: /\.jsx?$/,
use: [
'react-hot-loader',
{ loader: 'babel-loader', options: { presets: ['react', 'es2015'] } },
],
exclude: [/node_modules/, /public/]
}
As shown in the docs for use.
Related
I have a variable in my vars.scss that I want to access from Javascript in root/app/app.vue.
root/app/scss/vars.scss
:export {
cursor: #fff;
}
root/app/app.vue
<template>
<div id="yes">
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import colors from '#/scss/vars.scss';
export default Vue.extend({
mounted() {
console.log(colors.cursor);
},
});
</script>
<style >
</style>
I have read approximately 30 different stackoverflow questions that appear to be dealing with the similar problem of importing variables into the style block of the .vue file, as well as the identical problem of importing the variables directly into the Javascript code. As a result, my webpack.config.js looks like the following:
root/webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const env = process.env.NODE_ENV
module.exports = {
entry: './app/index.ts',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'staticfiles')
},
resolve: {
extensions: [ '.ts', '.js', '.vue', '.scss', '.sass'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, '/app/')
}
},
plugins: [
new HtmlWebpackPlugin(),
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin(),
new VueLoaderPlugin()
],
module: {
rules: [
{
enforce: 'pre',
test: /\.(js|vue|ts)$/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
}
// other vue-loader options go here
}
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
},
{
test: /\.s(a|c)ss$/,
use: [ {
loader: "style-loader",
options: {
sourceMap: env === 'development',
}
}, {
loader: "css-loader",
options: {
sourceMap: env === 'development',
}
}, {
loader: "sass-loader",
options: {
sourceMap: env === 'development',
}
},
'vue-style-loader'],
}]
}
};
I have also tried, in the test: /\.s(a|c)ss$/ section, to put vue-style-loader at the beginning of the array.
I have tried many combinations of filenames when attempting to import the .scss file, such as relative (../scss/vars.scss), removing the extension, using .css as an extension, etc.
The error I get is:
ERROR in /home/Documents/application/app/app.vue.ts
[tsl] ERROR in /home/Documents/application/app/app.vue.ts(10,28)
TS2307: Cannot find module '#/scss/vars.scss'.
My question:
In a project that uses vue-style-loader and vue-loader to build .vue files with webpack, how can I import .scss variables into the <script> portion of a .vue file? (please note - I am NOT attempting to import them into the <style> section of the .vue file)
An example based on my comment:
SCSS fragment:
$foo: #333;
body {
--variable-foo: $foo;
}
And then anywhere in the JavaScript
const value = document.body.style.getPropertyValue("--variable-foo");
console.log(value); // outputs "#333"
I have added the thumbnail component into my project. I got to see the following error in my project after adding it. The error is shown in the following image.
Here's my webpack.config.js file code which might help you on understanding the issue. There's a loader to be specified there. I don't know what's the specified loader for this. Anyone faced the same issue?
Any help?
**/*webpack.config.js*/**
/* eslint comma-dangle: ["error",
{"functions": "never", "arrays": "only-multiline", "objects":
"only-multiline"} ] */
const webpack = require('webpack');
const pathLib = require('path');
const devBuild = process.env.NODE_ENV !== 'production';
const config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/HelloWorld/startup/registration',
],
output: {
filename: 'webpack-bundle.js',
path: pathLib.resolve(__dirname, '../app/assets/webpack'),
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
],
module: {
rules: [
{
test: require.resolve('react'),
use: {
loader: 'imports-loader',
options: {
shim: 'es5-shim/es5-shim',
sham: 'es5-shim/es5-sham',
}
},
},
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
include: /node_modules/,
loaders: ['style-loader', 'css-loader'],
},
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
And Here's the code where I called the component:
import React, { Component } from 'react';
import Thumbnail from 'react-native-thumbnail-video';
class VideoThumnail extends Component {
render() {
return(
<div>
<Thumbnail url="https://www.youtube.com/watch?v=lgj3D5-jJ74" />
</div>
);
}
}
export default VideoThumnail;
You have a rule only for jsx. Try to add js extension in webpack also
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/,
}
Also i see es6 synax, so try to add .babelrc in project root with this
{
"presets": ["stage-0"]
}
and install babel-preset-env (npm install --save babel-preset-env)
I got this unusual error after webpack installation, Searched whole web tried all solution but nothing works,
//My webpack.config.js file
const webpack = require("webpack");
const path = require("path");
const config = {
entry : path.resolve(__dirname,"src/index.js"),
output : {
path : path.resolve(__dirname,"dist/assets"),
filename : "bundle.js",
publicPath : "assets"
},
devServer : {
inline : true,
contentBase : path.resolve(__dirname,"dist"),
port : 3000
},
module : {
rules : [
{
test : /\.js$/,
exclude : path.resolve(__dirname,"node_modules"),
loader : "babel-loader",
query: {
presets: ["env","latest","react","stage-0","es2015"]
}
},
{
test : /\.css$/,
loader: 'style-loader!css-loader!autoprefixer-loader'
},
{
test : /\.scss$/,
loader: 'style-loader!css-loader!autoprefixer-loader!sass-loader'
}
]
}
};
module.exports = config;
My babelrc file
{
"presets" : ["env","latest","react","stage-0","es2015"]
}
Index.js file
import React from 'react'
import ReactDOM from 'react-dom'
import { hello, goodbye } from './lib'
ReactDOM.render(
<div>
{hello}
{goodbye}
</div>,
document.getElementById('root')
);
lib.js file
import React from 'react'
import text from './titles.json'
import './stylesheets/hello.css'
import './stylesheets/goodbye.scss'
export const hello = (
<h1 id="title"
className="hello">
{text.hello}
</h1>
);
export const goodbye = (
<h2 id="goodbye"
className="goodbye">
{text.bye}
</h2>
);
titles.json
{
"hello" : "Bonjour",
"bye" : "Au Revoir"
}
i didnot include json loader in webpack.config file as i found out that json loader is added in webpack by default and when i check in browser in console i get this error -> ReferenceError: ReactDOM is not defined.
Error that i get in CLI
//Folder Structure
The solution seems to be around removing the autoprefixer-loader, I don't know for sure, but it may no longer be necessary to include it because it is included as part of one of the loaders or is built into newer versions of webpack. Again I'm just speculating here.
The current bang (!) argument separated syntax seems to still work
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader',
}
But the webpack documentation seems to prefer the broken out style as below
webpack sass-loader
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env', 'react'],
},
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
},
],
},
ERROR in ./client/index.js
Module build failed: SyntaxError: Unexpected token (31:4)
const Root = () => {
return (
<ApolloProvider client={client}>
^
<Router history={hashHistory}>
My Webpack config file below:
const path = require('path'),
webpack = require("webpack"),
clientPath = path.join(__dirname, 'client'),
HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.join(clientPath, 'index.js'),
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader'
}
],
loaders: [
{ test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" }
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html'
})
]
};
I am not able to build , it throws Unexpected token error while I have no syntactical mistake in code, Its just not able to recognise react code style
I have tried changing js to jsx inside webpack config at this place
{
use: 'babel-loader',
test: /\.jsx$/,
exclude: /node_modules/
}
Then it throws different error like
Module parse failed: /client/index.js Unexpected token (31:4)
You may need an appropriate loader to handle this file type.
It was my mistake only, ".babelrc" file was missing in my directory so I have created a file inside my app directory at root level and put this content into that file
.babelrc
{
"presets": ["env", "react"]
}
And tried with npm run-script build....succeeded!!!!
I see two possible causes:
1) loaders: [
{ test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" }
] will do nothing as loaders should be specified in module.rules so nothing is handling jsx files. This can be done to handle both js and jsx files using regex /\.jsx?/
2) The babel loader has no presets so unless they are specified in a .babelrc ypou arent showing, then you need to add the necessary presets to the loader
These should both be remedied by...
npm install babel-preset-react babel-preset-es2015
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'react']
}
}
},
//...
}
I'm building a React application that will require font-awesome CSS to be imported, but I'm getting an error saying that the module cannot parse the woff2 files.
Below is my code:
import React from 'react';
import ReactDOM from 'react-dom';
require('css!../node_modules/bootstrap/dist/css/bootstrap.css')
require('css!../node_modules/font-awesome/css/font-awesome.css')
import '../node_modules/bootstrap/dist/js/bootstrap.js'
import Dashboard from './components/Dashboard/Dashboard';
ReactDOM.render(
<Dashboard/>,
document.getElementById('react-container')
);
This is the error I'm getting in the browser:
When running on browser I'm getting the following error:
bundle.js:669 ./~/font-awesome/fonts/fontawesome-webfont.woff2?v=4.7.0
Module parse failed: D:\DEV\airwaysprj\node_modules\font-awesome\fonts\fontawesome-webfont.woff2?v=4.7.0 Unexpected character '' (1:4)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '' (1:4)
at Parser.pp$4.raise (D:\DEV\airwaysprj\node_modules\acorn\dist\acorn.js:2221:15)
at Parser.pp$7.getTokenFromCode (D:\DEV\airwaysprj\node_modules\acorn\dist\acorn.js:2756:10)
at Parser.pp$7.readToken (D:\DEV\airwaysprj\node_modules\acorn\dist\acorn.js:2477:17)
at Parser.pp$7.nextToken (D:\DEV\airwaysprj\node_modules\acorn\dist\acorn.js:2468:15)
at Parser.pp$7.next (D:\DEV\airwaysprj\node_modules\acorn\dist\acorn.js:2413:10)
at Parser.pp$3.parseIdent (D:\DEV\airwaysprj\fways\node_modules\acorn\dist\acorn.js:2191:10)
at Parser.pp$3.parseExprAtom (D:\DEV\airwaysprj\fways\node_modules\acorn\dist\acorn.js:1774:21)
at Parser.pp$3.parseExprSubscripts (D:\DEV\airwaysprj\fways\node_modules\acorn\dist\acorn.js:1715:21)
at Parser.pp$3.parseMaybeUnary (D:\DEV\airwaysprj\fways\node_modules\acorn\dist\acorn.js:1692:19)
at Parser.pp$3.parseExprOps (D:\DEV\airwaysprj\fways\node_modules\acorn\dist\acorn.js:1637:21)
at Parser.pp$3.parseMaybeConditional (D:\DEV\airwaysprj\fways\node_modules\acorn\dist\acorn.js:1620:21)
at Parser.pp$3.parseMaybeAssign (D:\DEV\airwaysprj\fways\node_modules\acorn\dist\acorn.js:1597:21)
# ./~/css-loader!./~/font-awesome/css/font-awesome.css 6:479-532
[1]: https://webpack.github.io/docs/stylesheets.html
And my webpack.config.js file:
var path = require('path');
module.exports = {
entry: "./client/app.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js",
publicPath: "/dist"
},
module: {
loaders: [
{
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
},
],
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader']
},
{
test: /images\/.*\.(png|jpg|svg|gif)$/,
loader: 'url-loader?limit=10000&name="[name]-[hash].[ext]"',
},
{
test: /fonts\/.*\.(woff|woff2|eot|ttf|svg)$/,
loader: 'file-loader?name="[name]-[hash].[ext]"',
}
]
},
watch: true
}
Help appreciated to solve this issue.
This configuration for webpack.config.js from here solved the problem:
var config = {
entry: './app.js',
output: {
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css?sourceMap'
}, {
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file"
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
}]
}
};
module.exports = config;
You'll need to remove ?v=4.7.0
You can see that your current regex does not match the end part ?v=4.7.0. So either you can remove that end part or modify your regex to allow it at the end.
/fonts\/.*\.(woff|woff2|eot|ttf|svg)?(\?v=[0-9]\.[0-9]\.[0-9])?$
Above regex will allow versions at the end.
Optionally, You can also write the above regex like this,
/fonts\/.*\.(woff(2)?|eot|ttf|svg)?(\?v=[0-9]\.[0-9]\.[0-9])?$
I think your /fonts\/.*\.(woff|woff2|eot|ttf|svg)$/ can not match /fonts/fontawesome-webfont.woff2?v=4.7.0. the end of the font file path is ?v4.7.0. try to remove the $.