Webpack 3 Bootstrap 4 Error #media - reactjs

I am trying to use React, Typescript, Webpack 3 and Bootstrap 4 to create a basic working project. When I import bootstrap.css in main .tsx file I am getting error like Unexpected Symbol - # - in /node_modules/bootstrap/dist/css/bootstrap.css.
Below is my webpack.config.js file :
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: './src/app.tsx'
},
output: {
path: path.join(__dirname,'dist'),
filename: '[name].bundle.js'
},
watch:true,
resolve: {
extensions: ['.ts','.tsx','.js']
},
devServer: {
contentBase: path.join(__dirname,'dist'),
port: 3333
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: ['awesome-typescript-loader']
},
{
test: /.html$/,
use: ['raw-loader']
},
{
test: /\.json$/,
use: ['json-loader']
},
{
test: /\.(s)css$/,
exclude: /node_modules/,
use: ['css-loader','style-loader','sass-loader',{
loader: 'postcss-loader', // Run post css actions
options: {
plugins: function () { // post css plugins, can be exported to postcss.config.js
return [
require('precss'),
require('autoprefixer')
];
}
}
},]
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
showErrors: true,
title: 'React TS Webpack App'
}),
]
}
And the below App.tsx file:
import 'bootstrap/dist/css/bootstrap.css';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Greet from './components/Greet';
const techStack = ['React','TypeScript','Webpack','Bootstrap'];
ReactDOM.render(<Greet techs={techStack}/>, document.getElementById('app'));
But I am getting the below error:
ERROR in ./node_modules/bootstrap/dist/css/bootstrap.css
Module parse failed: Unexpected character '#' (7:0)
You may need an appropriate loader to handle this file type.
| * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
| */
| #media print {
| *,
| *::before,
# ./src/app.tsx 1:0-42
# multi (webpack)-dev-server/client?http://localhost:3333 ./src/app.tsx
Could anybody help me how to clear this error and make bootsrap and webpack work?

"Use" style-loader before css-loader...
use: ['style-loader','css-loader','sass-loader',{ ... }..]

Related

React with Webpack, Typescript and Cypress Loader Error

I'm trying to configure cypress with a working configuration of webpack with React and Typescript. It seems to me that the babel-loader is not picking up the cypress/support/components.ts file because my webpack entry is ./src/index.tsx and the cypress folder is on the root not inside src.
Here is the error I'm getting...
========
Error: The following error originated from your test code, not from Cypress.
Module parse failed: Unexpected token (28:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| // Alternatively, can be defined in cypress/support/component.d.ts
| // with a at the top of your spec.
declare global {
| namespace Cypress {
| interface Chainable {
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure.
===========
Here is my cypress.config.ts
import { defineConfig } from 'cypress';
export default defineConfig({
component: {
devServer: {
framework: 'react',
bundler: 'webpack',
webpackConfig: require('./webpack.dev'),
},
includeShadowDom: true,
},
});
Here is my webpack.common.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
entry: {
main: './src/index.tsx',
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
}),
],
module: {
rules: [
{
test: /\.(js|ts)x$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.(png|jpg)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'static/images',
},
},
},
{
test: /\.svg$/,
use: [
{
loader: '#svgr/webpack',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'static/images',
},
},
{
loader: 'file-loader',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'static/images',
},
},
],
},
{
test: /\.(woff|woff2)$/,
type: 'asset/resource',
generator: {
filename: 'static/fonts/[name][ext][query]',
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.jsx', '.js'],
plugins: [new TsconfigPathsPlugin()],
},
};
Here is my webpack.dev.js
const path = require('path');
const { merge } = require('webpack-merge');
const common = require('./webpack.common');
module.exports = merge(common, {
mode: 'development',
devServer: {
port: '9500',
static: {
directory: path.join(__dirname, 'src'),
},
open: false,
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader', // 2) injects styles into DOM
'css-loader', // 1) turns css into commonjs
],
},
],
},
devtool: 'eval-source-map',
});
Again this config is working and will build, the issue I'm have is bringing in Cypress using Typescript for our testing suite.
I've tried all sorts of different configs and using ts-loader with babel-loader, but I feel like I'm just missing how to get webpack to "pick up" the .ts files in the Cypress folder with is outside of my src.
Any suggestions are very much appreciated!

when creating a custom lib react seem to be unavailable

When building I get the following error message:
ERROR in ./node_modules/my-components-lib/src/components/table/Table.js 11:4
Module parse failed: Unexpected token (11:4)
You may need an appropriate loader to handle this file type.
| }) =>
|
> <table>
Table component in node_modules/my-compoenents-lib
import React from 'react';
import PropTypes from 'prop-types';
import {FormattedMessage} from 'react-intl';
const Table = ({ columns, actions, data}) => <table ...> ... // the error is on this line
Usage of table component in src
import Table from "my-components-lib/src/components/table/Table";
...
return (<Table ...>...)
webpack.common.config.js
module.exports = {
entry: [
'./src/index.js'
],
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebPackPlugin({
favicon: './src/assets/favicon.ico',
template: './src/index.html',
filename: './index.html',
envVarsPath: contextPath + constants.envVarsFileName
})
],
output: {
publicPath: '/'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: [/node_modules/],
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name() {
// prod -- path will get "/" before images
const url = 'images/[hash]-[name].[ext]';
return prod ? '/' + url : url;
}
}
}]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
};
webpack.dev.config.js
module.exports = merge(common, {
mode: 'development',
devServer: {
contentBase: './src',
hot: true,
open: true,
historyApiFallback: true
},
devtool: 'inline-source-map'
});
You are importing table component incorrectly. If you are writing directly name of component or folder name without using dots (./), react will try to import this component from node_modules. try to import correctly your component.
I managed to resolve the problem by adding this script:
"scripts": {
"prepare": "rm -rf dist && mkdir dist && babel src/components -d dist/components --copy-files"
},
Looks like it needs to be compiled to JS.

Issue in configure the scss with bootstrap in react project

I am learning react and currently facing the issue in configuring the scss with bootstrap in a project, that was initially built by my friend and now I want to work on it. It works fine when I configure it for bootstrap. But when I try to configure the scss I have the following type error..
1)Here is the terminal error
ERROR in ./client/styles/styles.scss
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #import '~bootstrap/scss/bootstrap.scss';
| $btn-font-weight:bold;
|
# ./client/App.js 17:0-31
# ./client/main.js
# multi react-hot-loader/patch webpack-hot-middleware/client?reload=true ./client/main.js
2/ Here is my webpack.config file:
const path = require('path')
const webpack = require('webpack')
const CURRENT_WORKING_DIR = process.cwd()
const config = {
name: "browser",
mode: "development",
devtool: 'eval-source-map',
entry: [
'react-hot-loader/patch',
'webpack-hot-middleware/client?reload=true',
path.join(CURRENT_WORKING_DIR, 'client/main.js')
],
output: {
path: path.join(CURRENT_WORKING_DIR , '/dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'babel-loader'
]
}, {
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.scss$/,
loaders: [ 'style-loader', 'css-loader', 'sass-loader' ]
},
{
test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/,
use: 'file-loader'
}
]
}, plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
}
module.exports = config
3)Here is my app.js file
import React from 'react'
import MainRouter from './MainRouter'
import {BrowserRouter} from 'react-router-dom'
import './styles/styles.scss';
import { hot } from 'react-hot-loader';
const App = () => (
<BrowserRouter>
<MuiThemeProvider>
<MainRouter/>
</MuiThemeProvider>
</BrowserRouter>
)
export default hot(module)(App)
To achieve expected result, use below option of using loaders in below format
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]

Error while importing font or images file inside scss using Webpack 4 and react js

I am using webpack and react js.
I am getting this error when i try to import image or font file inside my scss file.
I have tried many solutions but none of them solved my problem,
webpack.common.js
enter image description here
const path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: {
main: "./src/index.js",
vendor: "./src/vendor.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(ttf|svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
}
};
Here is another webpack.dev.js
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/template.html"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader", //3. Inject styles into DOM
"css-loader", //2. Turns css into commonjs
"sass-loader" //1. Turns sass into css
]
}
]
}
});
ERROR in ./src/assets/index.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js!./src/assets/index.scss)
Module not found: Error: Can't resolve '../../../src/assets/fonts/icomoon.ttf' in 'C:\Users\jamal\Documents\webpack-demo-app\src\assets'
# ./src/index.js
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js
You need to remember that the import actually takes "place" from the root index.scss file (the one that loads all the other partials). So the path you are using to fetch the asset is not accurate.
You need to use ./fonts/icomoon.ttf instead of ../fonts/icomoon.ttf
your file structure:
assets/
------/fonts
------/images
------/sass
------/---/partial1.scss // while the reference to the image is here
------/index.scss // the actual root of the reference call is here

React, Babel, Webpack not parsing jsx, unexpected token error [duplicate]

This question already has answers here:
babel-loader jsx SyntaxError: Unexpected token [duplicate]
(8 answers)
Closed 6 years ago.
I am trying to build my app using wepback and getting getting stuck at this unexpected token error. All the dependencies for my project are fine and upto date I am using the same project somewhere else and it is building fine but when I try to build my current code which is same it gives the error, below are config.js and error descriptions
Here is my app.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {Router} from 'react-router';
import Routes from '../routes/routes';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { browserHistory } from 'react-router';
require('../Config');
injectTapEventPlugin();
window.EventEmitter = {
_events: {},
dispatch: function (event, data, returnFirstResult) {
if (!this._events[event]) return;
for (var i = 0; i < this._events[event].length; i++)
{
if(this._events[event][i])
{
var r = this._events[event][i](data);
if(returnFirstResult)
return r;
}
}
},
subscribe: function (event, callback, onlyOne) {
if (!this._events[event] || onlyOne) this._events[event] = []; // new event
this._events[event].push(callback);
}
};
// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
Here is my config.js
var webpack = require('webpack');
var path = require('path');
var buildPath = path.resolve(__dirname, '../project/public/js/');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var TransferWebpackPlugin = require('transfer-webpack-plugin');
var config = {
entry: {
app: path.join(__dirname, '/app/entry_points/app.jsx'),
vendor: ['react', 'radium'],
},
resolve: {
extensions: ["", ".js", ".jsx"]
},
devtool: 'source-map',
output: {
path: buildPath,
publicPath: '/js/',
filename: 'mobile.[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("vendor", "mobile.vendor.js"),
new webpack.DefinePlugin({}),
new webpack.NoErrorsPlugin(),
],
module: {
preLoaders: [
{
test: /\.(js|jsx)$/,
loader: 'eslint-loader',
include: [path.resolve(__dirname, "src/app")],
exclude: [nodeModulesPath]
},
],
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath]
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
]
},
eslint: {
configFile: '.eslintrc'
},
};
module.exports = config;
This is the error I get when I try to build:
ERROR in ./app/entry_points/app.jsx
Module build failed: SyntaxError: /home/zeus/Glide/project/project-mobile/app/entry_points/app.jsx: Unexpected token (46:16)
44 | // Render the main app react component into the app div.
45 | // For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
> 46 | ReactDOM.render(<Router history={browserHistory}>{Routes}</Router>, document.getElementById('app'));
| ^
I am using react v0.14.8, react-dom v0.14.8, babel-loader ^6.2.1
i believe you need to specify the presets with babel and install the npm module babel-preset-react
loaders: [
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader'
],
exclude: [nodeModulesPath],
query: {
presets: ['react']
}
},
...
]
you'd also want to add es2015 to that presets array if you're using it.

Resources