React, Webpacks and Babel: "You may need an appropriate loader to handle this file type." [duplicate] - parsing

I am trying to use Webpack with Babel to compile ES6 assets, but I am getting the following error message:
You may need an appropriate loader to handle this file type.
| import React from 'react';
| /*
| import { render } from 'react-dom'
Here is what my Webpack config looks like:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
Here is the middleware step that makes use of Webpack:
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var config = require('./webpack.config');
var express = require('express');
var app = express();
var port = 3000;
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.listen(port, function(err) {
console.log('Server started on http://localhost:%s', port);
});
All my index.js file is doing is importing react, but it seems like the 'babel-loader' is not working.
I am using 'babel-loader' 6.0.0.

You need to install the es2015 preset:
npm install babel-preset-es2015
and then configure babel-loader:
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
}

Make sure you have the es2015 babel preset installed.
An example package.json devDependencies is:
"devDependencies": {
"babel-core": "^6.0.20",
"babel-loader": "^6.0.1",
"babel-preset-es2015": "^6.0.15",
"babel-preset-react": "^6.0.15",
"babel-preset-stage-0": "^6.0.15",
"webpack": "^1.9.6",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.0.0"
},
Now configure babel-loader in your webpack config:
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
add a .babelrc file to the root of your project where the node modules are:
{
"presets": ["es2015", "stage-0", "react"]
}
More info:
babeljs.io - using babel with webpack
babeljs.io - docs on .babelrc
react-webpack-cookbook - configure react with webpack
a react-webpack-example repo

If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.
var path = require('path');
let webpack = require("webpack");
module.exports = {
entry: {
app: './app/App.js',
vendor: ["react","react-dom"]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '../public')
},
module: {
rules: [{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory=true',
}
}]
}
};
This picks up its configuration from my .babelrc file:
{
"presets": [
[
"env",
{
"targets": {
"browsers":["last 2 versions"],
"node":"current"
}
}
],["react"]
]
}

BABEL TEAM UPDATE:
We're super 😸 excited that you're trying to use ES2015 syntax, but instead of continuing yearly presets, the team recommends using babel-preset-env. By default, it has the same behavior as previous presets to compile ES2015+ to ES5
If you are using Babel version 7 you will need to run npm install #babel/preset-env and have "presets": ["#babel/preset-env"] in your .babelrc configuration.
This will compile all latest features to es5 transpiled code:
Prerequisites:
Webpack 4+
Babel 7+
Step-1:: npm install --save-dev #babel/preset-env
Step-2: In order to compile JSX code to es5 babel provides #babel/preset-react package to convert reactjsx extension file to native browser understandable code.
Step-3: npm install --save-dev #babel/preset-react
Step-4: create .babelrc file inside root path path of your project where webpack.config.js exists.
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
Step-5: webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src/index.js'),
output: {
path: path.resolve(__dirname, 'output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html"
})
]
}

In my case, I had such error since import path was wrong:
Wrong:
import Select from "react-select/src/Select"; // it was auto-generated by IDE ;)
Correct:
import Select from "react-select";

Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
NB: you have to make sure you have the above #babel/preset-env & #babel/preset-react installed in your package.json dependencies

You probably forgot to add .js extension to your file.
Component -> Component.js

This makes me feel stupid, but I want to share for anyone that got frustrated like me: I used webpack.dev.js but didn't specify that as the config file! When running Webpack run with:
webpack --config webpack.dev.js
And it suddenly worked ;)

Just adding on another reason such error showed up in Angular.. was because I checked for html file in list of styles:
#Component({
selector: ...,
templateUrls: 'xyz.html',
stylesUrls: ['xyz.html'] // problem
})
Addressing wrong file type raises this error

As question doesn't specify if it was for angular, react, or react-native. I am posting this for react-native and it may be implied on others too. The reason was that it wasn't able to understand the syntax specified by loader. e.g. tsx, jsx. One solution I found in this article after lots of exploration. When we use external library that was using jsx and you configured your project with tsx, it won't understand jsx and will give you to add appropriate loader. So, you can fix that by following code in your app.json file.
"web": {
"build": {
"babel": {
"include": [
"name-of-my-shared-package-here"
]
}
}
}
By replacing name-of-my-shared-package-here with your package name that is causing the issue will solve this issue. You can check the package name in error that is causing this issue.

Outdated babel packages on Jan 3, 2023
Please install these list of packages for configuration with babel.
$ npm add -D #babel/core babel-loader #babel/preset-env #babel/preset-react
and add below code .babelrc file
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
I used #khizer webpack configuration in my application
Credit goes to This answer. As I have have been gone through the best answer of this solution and it tooks my 2-3 hours. I hope other don't waste same amount of time.

When using Typescript:
In my case I used the newer syntax of webpack v3.11 from their documentation page
I just copied the css and style loaders configuration form their website.
The commented out code (newer API) causes this error, see below.
module: {
loaders: [{
test: /\.ts$/,
loaders: ['ts-loader']
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader'
]
}
]
// ,
// rules: [{
// test: /\.css$/,
// use: [
// 'style-loader',
// 'css-loader'
// ]
// }]
}
The right way is to put this:
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader'
]
}
in the array of the loaders property.

This one throw me for a spin.
Angular 7, Webpack
I found this article so I want to give credit to the Article
https://www.edc4it.com/blog/web/helloworld-angular2.html
What the solution is:
//on your component file. use template as webpack will treat it as text
template: require('./process.component.html')
for karma to interpret it
npm install add html-loader --save-dev
{
test: /.html$/,
use: "html-loader"
},
Hope this helps somebody

Just add this code webpackmix.js
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
require('tailwindcss'),
]).vue();

Related

Using <style lang="scss"> in vue component gives error

I am trying to use vue js in rails.
Everything works, except when I tried to use <style> inside .vue component
The exact error is:
./app/javascript/layouts/dashboard.vue?vue&type=style&index=0&lang=scss& (./node_modules/css-loader/dist/cjs.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/sass-loader/dist/cjs.js??ref--1-2!./node_modules/style-loader/dist!./node_modules/css-loader/dist/cjs.js??ref--5-1!./node_modules/postcss-loader/src??ref--5-2!./node_modules/sass-loader/dist/cjs.js??ref--5-3!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/layouts/dashboard.vue?vue&type=style&index=0&lang=scss&)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Expected newline.
My environment.js file
const { environment } = require('#rails/webpacker')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoader = require('./loaders/vueLoader')
const vuetifyLoader = require('./loaders/vuetifyLoader')
environment.plugins.prepend('VueLoaderPlugin', new VueLoaderPlugin())
environment.loaders.prepend('vue', vueLoader)
environment.loaders.prepend('vuetify', vuetifyLoader)
const resolver = {
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
}
environment.config.merge(resolver)
module.exports = environment
VuetifyLoader.js file
module.exports = {
test: /\.s(c|a)ss$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'sass-loader',
// Requires sass-loader#^7.0.0
options: {
implementation: require('sass'),
fiber: require('fibers'),
indentedSyntax: true // optional
},
// Requires sass-loader#^8.0.0
options: {
implementation: require('sass'),
sassOptions: {
fiber: require('fibers'),
indentedSyntax: true // optional
},
},
},
],
}
install these two plugins.
npm install --save node-sass
npm install --save sass-loader
So, the problem was with fiber and indentedSyntax. After removing those two, everything works as expected. I was getting lots of error related to scss like
like
expected new line
in sass files inside node_modules. I don't know, why vuetify recommends to use fiber in sass loader.

Load fonts from node_modules in react-rails application with webpack

I have a react-rails application set up with webpacker.
I am trying to load font-awesome-pro with it's fonts from node_modules.
I assume this is a trivial task but I can't seem to find any good documentation on how to do this.
This is what I have so far:
package.json dependencies:
"dependencies": {
"#rails/webpacker": "3.5",
"babel-preset-react": "^6.24.1",
"bootstrap": "^4.1.3",
"prop-types": "^15.6.2",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-slick": "^0.23.1",
"react_ujs": "^2.4.4",
"slick-carousel": "^1.8.1",
"tachyons-z-index": "^1.0.9"
},
"devDependencies": {
"#fortawesome/fontawesome-pro": "^5.2.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"file-loader": "^2.0.0",
"path": "^0.12.7",
"webpack-dev-server": "2.11.2"
}
file.js:
var path = require('path');
module.exports = {
test: /\.(woff(2)?|eot|otf|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
exclude: path.resolve(__dirname, '../../app/assets'),
use: {
loader: 'file-loader',
options: {
outputPath: 'fonts/',
useRelativePath: false
}
}
}
environment.js
const { environment } = require('#rails/webpacker')
const file = require('./file')
environment.loaders.prepend('file', file)
module.exports = environment
application.scss:
#import '#fortawesome/fontawesome-pro/scss/fontawesome.scss';
application.rb:
config.assets.paths << Rails.root.join('node_modules')
What am I missing? From what I can gather, webpack should be looking at the node_modules directory, finding font files based on the webpack test and putting the assets into the output directory: fonts/.
FontAwesome with webfonts:
For me with the free version the example below is working well. I don't know the pro version, but if I'm not mistaken, you just have to rename fontawesome-free to fontawesome-pro in the paths.
application.scss:
$fa-font-path: "~#fortawesome/fontawesome-free/webfonts";
#import "~#fortawesome/fontawesome-free/scss/fontawesome.scss";
#import "~#fortawesome/fontawesome-free/scss/solid.scss";
#import "~#fortawesome/fontawesome-free/scss/regular.scss";
#import "~#fortawesome/fontawesome-free/scss/brands.scss";
In SCSS ~ (tilde import) means that look for the nearest node_modules directory. Not all SASS compilers supports it, but node-sass does, and this is the common for Webpack.
This way in your html you only have to use your application.css. There's no need to include any other FontAwesome css files.
Your font loader config seems OK (tested, worked). With that Webpack should resolve the font files and then copy them to your desired output as you wanted. This needs that your css-loader be configured with url: true but I that is the default.
A minimal/usual config for the loaders in your Webpack config file:
module: {
rules: [
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader, // optional (the most common way to export css)
"css-loader", // its url option must be true, but that is the default
"sass-loader"
]
},
{
// find these extensions in our css, copy the files to the outputPath,
// and rewrite the url() in our css to point them to the new (copied) location
test: /\.(woff(2)?|eot|otf|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: {
loader: 'file-loader',
options: {
outputPath: 'fonts/'
}
}
}
]
},
Loading only the needed fonts (the new way with JS and SVGs)
Again, I will demonstrate it with the free version because I don't have the pro version.
This way your generated bundle will only contain those icons what you need, resulting in a much smaller size which means faster page loads. (I'm using this in my projects)
The needed packages:
#fortawesome/fontawesome-svg-core
#fortawesome/free-brands-svg-icons
#fortawesome/free-regular-svg-icons
#fortawesome/free-solid-svg-icons
Include this in your scss file:
#import "~#fortawesome/fontawesome-svg-core/styles";
Create a new file, name it fontawesome.js:
import { library, dom, config } from '#fortawesome/fontawesome-svg-core';
config.autoAddCss = false;
config.keepOriginalSource = false;
config.autoReplaceSvg = true;
config.observeMutations = true;
// this is the 100% working way (deep imports)
import { faUser } from '#fortawesome/free-solid-svg-icons/faUser';
import { faHome } from '#fortawesome/free-solid-svg-icons/faHome';
import { faFacebook } from '#fortawesome/free-brands-svg-icons/faFacebook';
import { faYoutube } from '#fortawesome/free-brands-svg-icons/faYoutube';
// this is the treeshaking way (better, but read about it below)
import { faUser, faHome } from '#fortawesome/free-solid-svg-icons';
import { faFacebook, faYoutube } from '#fortawesome/free-brands-svg-icons';
library.add(faUser, faHome, faFacebook, faYoutube);
dom.watch();
.. and then require it somewhere in your js:
require('./fontawesome');
That's all. If you want to read more on this, start with understanding SVG JavaScript Core, have a look on its configuration and read the documantation of treeshaking.

Webpack2 cannot resolve: config.context absolute path

I am trying to run my webpack config file (see below), but I am still getting certain type of errors that reffers to a paths I use in my webpack settings:
- config.context
- config.module.rules
- config.output
My idea was, that I set up my config.context path absolutely (as it is written in docs), otherwise my webpack.config files reffers to node_modules in parents directory. But still, when I run webpack -w --env.dev command, it throws following errors:
It seems to me, that config.context cant handle absolute path as it should. Any help how to set up paths correctly? Thank you!
My webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractText = require('extract-text-webpack-plugin');
module.exports = function (env) {
var project = {
env: env.prod ? 'prod' : 'dev',
jsBase: './routesMap/',
cssBase: './src/css/'
}
var config = {
context: path.resolve(__dirname),
entry: {
'routesMap': project.jsBase + 'main.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: '[name].js'
},
plugins: [
new ExtractText({
filename: 'styles.min.css',
disable: false,
allChunks: true
})
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, '/routesMap'),
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['es2015'],
plugins: ["transform-runtime"]
}
}
]
}
};
return config;
}
That's an issue with the latest webpack version. Try using uppercase drive letters in shell, e.g. C:/ instead c:/.
More info https://github.com/webpack/webpack/issues/4530.
I uninstalled latest webpack version (I had webpack 2.3.0) and installed version of 2.2.0, problem solved! As #zemirco stated in his answer, it has something to do with casesensitive letters in absolute path. Unfortunatelly changing small letter to big one doesnt help for me, so I just changed webpack version.

Travis CI - Builds are timing out

My .travis.yml
language: node_js
node_js:
- "0.12"
before_install:
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
I have only added a few very simple tests so far (checking that class attributes exist).
I can see the tests are executed.
Then, the last few lines in the Travis output are this:
WARN [web-server]: 404: /css/style.min.css?1435068425.642
No output has been received in the last 10 minutes, this potentially indicates a stalled build or something wrong with the build itself.
The build has been terminated
If the tests are running, then the build and dependencies must have been installed already?
So why is the process not finishing once all tests are executed?
karma.config:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: [
'jasmine',
'requirejs'
],
// list of files / patterns to load in the browser
files: [
{pattern: 'js/vendor/**/*.js', included: false},
{pattern: 'js/*.js', watched: true, included: false},
{pattern: 'test/**/*Spec.js', watched: true, included: false},
{pattern: 'css/**/*.css', included: false},
'test/test-main.js'
],
// list of files to exclude
exclude: [
'test/lib/**/*.js',
'js/vendor/**/test/*.js', //do not include the vendor tests
'js/_admin.js'
],
preprocessors: {
},
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Firefox'], //'Chrome', 'PhantomJS', 'PhantomJS_custom'
singleRun: false,
});//config.set
};//module.exports
test-main.js in folder test:
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(file);
}
//console.log('test files:', allTestFiles);
});
require.config({
baseUrl: '/base',
paths: {
'jquery': './js/vendor/jquery/jquery-2.1.4.min',
'jquery-ui': './js/vendor/jquery-ui-1.11.4.custom/jquery-ui.min',
'underscore': './js/vendor/underscore/underscore-min',
'backbone': './js/vendor/backbone/backbone-min',
'mustache': './js/vendor/mustache/mustache.min',
'domReady': './js/vendor/requirejs/plugins/domReady/domReady',
'text': './js/vendor/requirejs/plugins/text/text',
//------------------------------------
//custom requireJS application modules
'my': './js/my',
'my-CSS': './js/my-CSS'
},
shim: {
'underscore': {
exports: '_'
}
},
deps: allTestFiles,
callback: window.__karma__.start
});
The my-CSS module loads the css like this:
//custom requireJS module to hold the crowdUI class
define(["my"], function (my) { //prerequisites
'use strict';
//load the CSS definitions
document.head.appendChild(
my.createElement('link', {
attribute: {
id: 'my-CSS',
href: './css/style.min.css?' + crowdUI.TIMESTAMP,
rel: 'stylesheet',
type: 'text/css'
}
})
);
});
If the issue is just that your task requires more than 10 minutes during which it produces no output, the fix is simple: prepend your command with travis_wait.
For instance travis_wait myCommand instead of just myCommand.

Getting Karma, 6to5ify and Istanbul to play ball

I have Browserify, 6to5ify and Karma to play nice, successfully running my specs. When I add code coverage however, things go south. I've tried several approaches:
Add browserify-istanbul transform to my karma.conf.js. However, this results in it trying to run instrumentation on my spec-files as well it would appear.
Run coverage preprocessor on my source files. But because istanbul (even douglasduteil/karma-coverage#next) doesn't read my 6to5ify browserify transform, this crashes immediately on the first file it tries to parse (because of the import statement), or when I use karma-coverage#next, it doesn't respect the browser mapping in my package.json (mobile project, mapped Backbone to Exoskeleton).
Right now my karma.conf.js looks like this:
module.exports = function(karma){
karma.set({
frameworks: ["browserify", "mocha", "chai-sinon"],
browserify: {
debug: true,
extensions: [".js", ".hbs"],
transform: ["6to5ify", "hbsfy"]
},
reporters: ["dots", "osx", "junit", "coverage"],
coverageReporter: {
type: "text"
},
junitReporter: {
outputFile: "spec/reports/test-results.xml"
},
preprocessors: {
"src/javascript/**/*": ["coverage"],
"spec/**/*": ["browserify"]
},
browsers: ["PhantomJS"],
files: ["spec/unit/**/*Spec.js"],
logLevel: "LOG_DEBUG",
autoWatch: true
});
};
I'm kind of lost how to get this all working together. I tried following these instructions, but that didn't work because it didn't follow my browser node in package.json. Any help would be greatly appreciated.
So, apparently I need browserify-istanbul, and I need the browserify configure hook, like so:
var to5ify = require('6to5ify');
var hbsfy = require('hbsfy');
var cover = require('browserify-istanbul');
var coverOptions = {
ignore: ['**/*Spec.js', '**/lib/*.js', '**/fixtures/*.hbs'],
defaultIgnore: true
}
module.exports = function(karma){
karma.set({
frameworks: ["browserify", "mocha", "chai-sinon"],
browserify: {
debug: false,
extensions: [".js", ".hbs"],
configure: function(bundle){
bundle.on('prebundle', function(){
bundle
.transform(to5ify)
.transform(hbsfy)
.transform(cover(coverOptions));
});
}
},
reporters: ["dots", "osx", "junit", "coverage"],
coverageReporter: {
type: "text"
},
junitReporter: {
outputFile: "spec/reports/test-results.xml"
},
preprocessors: {
"spec/**/*": ["browserify"]
},
browsers: ["PhantomJS"],
files: ["spec/unit/**/*Spec.js"],
logLevel: "LOG_DEBUG",
autoWatch: true
});
};

Resources