Webpack 4 error - Module parse failed: Unexpected character '#' - reactjs

I am trying to build a react app and am getting this error from webpack: 'ERROR in ./src/App.css 1:0
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.' The first line in App.css where the error occurs is this: #import url('https://fonts.googleapis.com/css?family=Alata|Comfortaa:400,600,700|Roboto&display=swap');
I am using the url-loader I learned about in a thread I read online that was supposed to fix it.
And here is my full web.config.js:
/* eslint-env node */
const webpack = require('webpack');
// eslint-disable-next-line #typescript-eslint/no-var-requires
const path = require('path');
module.exports = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: [/node_modules/],
loader: ['babel-loader', 'eslint-loader']
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
exclude: /node_modules/,
use: [
{
loader: 'url-loader?limit=100000',
options: {
name: '[name].[ext]',
limit: 1024,
publicPath: 'dist/assets/',
outputPath: 'dist/assets/'
}
}
]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
// path: __dirname + '/dist',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: 'bundle.js'
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: './dist',
hot: true
}
};

It appears you are using SASS inside of a .css file (#import url(foo) is not valid CSS, it is SASS, thus Webpack does not know to handle this line). Since you are trying to compile a SASS file, you need to configure your Webpack build to handle this type of file. You should install the sass-loader plugin and add configuration for it.
See the plugin README https://github.com/webpack-contrib/sass-loader
Additionally, you should rename your src/App.css to src/App.scss so that Webpack knows to use the sass-loader plugin for this file.

Related

How can I resolve this issue about Storybook and Sass?

I have an issue about Storybook. I can't start storybook and I have an error about my SCSS file.
Here is the error:
ModuleParseError: Module parse failed: Unexpected token (1:0)
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
.h1 {
| color: red;
| }
at handleParseError (/myproject/node_modules/#storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:469:19)
I mean this is juste a simple class. But when the file is empty, the compilation is okay, so I don't understand how I can resolve this.
My SCSS file
.h1 {
color: red;
}
My Webpack file
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, './src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.scss?$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: path.resolve(__dirname, './dist'),
hot: true,
},
};
My main.js file in the .storybook folder
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)",
"../src/**/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
]
}
Is anyone has a solution please?
Thanks by advance
Finally, I have solved my problem, so here is how I did it.
First of all, I uninstalled the storybook (How to remove storybook from the react project), then the reinstalled via webpack (https://storybook.js.org/blog/storybook-for-webpack-5/).
For once with Webpack it works whereas installing it with NPM (or Yarn for my part) brought me to the complications that I had posted above. My guess is that it works for Webpack 5, whereas with NPM, I was getting an error about the css-loader loader that told me about Webpack 4.
Storybook worked, but I was still worried about .scss files. My terminal told me that I did not have a specific loader. So I took a loader for this type of file by adding a webpack.config.js in the .storybook folder created when we install Storybook. I used the instructions found here: https://storybook.js.org/docs/react/configure/webpack
About Sass files: Storybook is case sensitive, and also doesn't take into account files starting with _, so not possible to use partials
I hope you don't have this kind of problem, but if you do, maybe these answers will help you ^^

Migration Webpack from version 1 to 2

I want to convert webpack 1 configuration file to webpack 2 version.
In addition, I want to exclude node modules from bundle.
I got following Exception
Using removed Babel 5 option: base.modules - Use the corresponding module transform plugin in the plugins option. Check out http://babeljs.io/docs/plugins/#modules
In addition, I get another error
ERROR in ./index.js
Module parse failed: Unexpected token (9:16)
You may need an appropriate loader to handle this file type.
The errors seem informative but I can't find what is wrong.
Do I miss something from migration guide?
Version 1
const config = {
entry: './index.js',
output: {
path: '/',
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
module.exports = config;
Version 2
const config = {
entry: './index.js',
output: {
path:'/',
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
rules:[
{
test:/\.jsx?$/,
use:[
{
loader:'babel-loader',
options:{
only:['/node_modules/'],
presets:['es2015', 'react']
},
}
]
}
]
}
};
module.exports = config;
For the first error with Babel, you likely have a dependency that still uses Babel 5 and it contains a config that is no longer allowed in Babel 6. That probably happens because you're trying to transpile your node_modules, as you have removed the exclude option, which has not been changed in webpack 2. Babel always uses the closest config it can find.
For the second error, you are using some syntax that requires Babel, presumably JSX. But you have set the only option on babel-loader, which tells Babel to only transpile files that match the given path. Hence, it's only applied to the node_modules, not the rest of your project. That is exactly the opposite of what you wanted.
Your .jsx rule should be:
{
test:/\.jsx?$/,
exclude:/node_modules/,
use:[
{
loader:'babel-loader',
options:{
presets:['es2015', 'react']
},
}
]
}
You are also setting the output.path to /. That is the root of your file system, not the root of your project. To use the directory where the webpack config is, you can use Node's __dirname, which is the absolute path to the directory of the currently executed file (i.e. webpack.config.js).
output: {
path: __dirname,
filename: 'bundle.js',
},

Webpack production build file paths are off

I'm running this command to try & generate a production webpack build:
rimraf ./build/* && webpack -p --progress --config webpack.production.js
However, when I open up the build/index.html, it's failing to load a lot of files because the locations are off.
It fails to put the correct location for the bundle.js file. It loads it like this: /bundle.js. However the bundle.js file is actually in the same directory as the index.html file in the build folder so it should load it like this ./bundle.js
If I correct the bundle.js path, it's still putting an incorrect route for the assets:
What's interesting is that my app currently works with the webpack dev server when I run: webpack-dev-server --inline --progress --config webpack.dev.js.
Here is what my current webpack.production.js file looks like:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'source-map',
devServer: {
historyApiFallback: true, // This will make the server understand "/some-link" routs instead of "/#/some-link"
},
entry: [
'./src/scripts' // This is where Webpack will be looking for the entry index.js file
],
output: {
path: path.join(__dirname, 'build'), // This is used to specify folder for producion bundle
filename: 'bundle.js', // Filename for production bundle
publicPath: '/'
},
resolve: {
modules: [
'node_modules',
'src',
path.resolve(__dirname, 'src/scripts'),
path.resolve(__dirname, 'node_modules')
], // Folders where Webpack is going to look for files to bundle together
extensions: ['.jsx', '.js'] // Extensions that Webpack is going to expect
},
module: {
// Loaders allow you to preprocess files as you require() or “load” them.
// Loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle frontend build steps.
loaders: [
{
test: /\.jsx?$/, // Here we're going to use JS for react components but including JSX in case this extension is preferable
include: [
path.resolve(__dirname, "src"),
],
loader: ['react-hot-loader']
},
{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
include: [
path.resolve(__dirname, "src"),
],
// Only run `.js` and `.jsx` files through Babel
test: /\.jsx?$/,
// Options to configure babel with
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0', 'react'],
}
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
}
]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(), // Webpack will let you know if there are any errors
// Declare global variables
new webpack.ProvidePlugin({
React: 'react',
ReactDOM: 'react-dom',
_: 'lodash'
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
hash: true
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
]
}
And just in case, this is what my current webpack.dev.js file looks like:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-source-map',
devServer: {
historyApiFallback: true, // This will make the server understand "/some-link" routs instead of "/#/some-link"
},
entry: [
'babel-polyfill',
'webpack-dev-server/client?http://127.0.0.1:8080/', // Specify the local server port
'webpack/hot/only-dev-server', // Enable hot reloading
'./src/scripts' // This is where Webpack will be looking for the entry index.js file
],
output: {
path: path.join(__dirname, 'build'), // This is used to specify folder for producion bundle
filename: 'bundle.js', // Filename for production bundle
publicPath: '/'
},
resolve: {
modules: [
'node_modules',
'src',
path.resolve(__dirname, 'src/scripts'),
path.resolve(__dirname, 'node_modules')
], // Folders where Webpack is going to look for files to bundle together
extensions: ['.jsx', '.js'] // Extensions that Webpack is going to expect
},
module: {
// Loaders allow you to preprocess files as you require() or “load” them.
// Loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle frontend build steps.
loaders: [
{
test: /\.jsx?$/, // Here we're going to use JS for react components but including JSX in case this extension is preferable
include: [
path.resolve(__dirname, "src"),
],
loader: ['react-hot-loader']
},
{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
include: [
path.resolve(__dirname, "src"),
],
// Only run `.js` and `.jsx` files through Babel
test: /\.jsx?$/,
// Options to configure babel with
query: {
plugins: ['transform-runtime', 'transform-decorators-legacy'],
presets: ['es2015', 'stage-0', 'react'],
}
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // Hot reloading
new webpack.NoEmitOnErrorsPlugin(), // Webpack will let you know if there are any errors
// Declare global variables
new webpack.ProvidePlugin({
React: 'react',
ReactDOM: 'react-dom',
_: 'lodash'
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
hash: false
})
]
}
Any ideas what I'm doing wrong?
faced a similar issue. setting output.publicPath: "/" in webpack.dev.js and output.publicPath: "./" in webpack.prod.js, did the trick for me.
Got the same error when running npm run watch, local dev still worked, but after deploying to demo server the app crashed on wrong js-file url.
Cause:
Some changes in my webpack.mix.js started compiling a index.html file that was found by the browser, instead of the app.blade I was using.
Fixed the paths by setting: publicPath: './public/'
(Note that it's a relative path). Also, I removed the generated url by setting inject: false, in the HtmlWebpackPlugin({ section and used the asset('/...') logic.

Webpack with babel-loader for react corrupts image files

I am using webpack with babel-loader to transform .jsx react files.
However, adding a file-loader or style- and css-loader does not correctly process the images required() in the react components or style sheets.
They get recognized by webpack and copied to the dist folder. The path to the image file is correct, I've verified this in the css and js output.
The server is also able to display the files, I've checked with some manually copied ones.
What is happening is that the images themselves get corrupted. No image viewer nor the browser can display the image which results in an invisible image in the browser.
What I've tried so far:
using only babel-loader as suggested in: https://github.com/webpack/file-loader/issues/35, results in Error: No handler for file type.
using file-loader directly
using image-webpack-loader (which seems to be using file-loader under the hood)
using IsomorphicLoaderPlugin (https://github.com/jchip/isomorphic-loader) which seems to be a simpler alternative to webpack-isomorphic-tools
using css background-images with url() and ExtractTextPlugin('style-loader", 'css-loader')
All of the above steps resulted in either errors with webpack not finding an appropriate handler or corrupted image files.
Here is my current webpack config for reference (I've included all of it in case there are any problems/conflicts I am overlooking):
var ExtractTextPlugin = require('extract-text-webpack-plugin'),
webpack = require('webpack');
IsomorphicLoaderPlugin = require("isomorphic-loader/lib/webpack-plugin");
module.exports = {
context: __dirname + '/client',
entry: ['babel-polyfill', './index.jsx'],
output: {
filename: 'app.js',
path: __dirname + '/dist',
publicPath: '/'
},
resolve: {
ignore: /node_modules/,
extensions: ['', '.js', '.jsx']
},
devtool: 'source-map',
plugins: [
new ExtractTextPlugin('styles.css'),
new IsomorphicLoaderPlugin({ keepExistingConfig: false }),
new webpack.DefinePlugin({
"process.env": {
BROWSER: JSON.stringify(true)
}
})
],
module: {
preLoaders: [
{
loaders: ['isomorphine']
}
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
plugins: ['transform-runtime', 'transform-decorators-legacy', 'transform-class-properties', 'transform-object-rest-spread'],
presets: ['react', 'es2015', 'stage-0']
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file!isomorphic"
}
]
}
};

ES6 not compiling

Does anyone see what I'm doing wrong here in my webpack.config.js file? The browser gives me an error saying "unexpected token 'import' " which means it is not recognizing ES6 syntax. Am I doing something wrong with the loaders? I've installed and reinstalled dependencies multiple times, so I don't think that's where the issue lies.
webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./public/index.jsx'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
root: __dirname,
alias: {
App: 'public/components/App.jsx',
Home: 'public/components/Home.jsx',
Footer: 'public/components/Footer.jsx',
Inventory: 'public/components/Inventory.jsx',
Login: 'public/components/nav/Login.jsx',
Navbar: 'public/components/nav/Navbar.jsx',
ProductSearch: 'public/components/Product-Search.jsx',
SingleProduct: 'public/components/Single-Product.jsx',
Product: 'public/components/Product.jsx',
Signup: 'public/components/Signup.jsx',
LandingNavbar: 'public/components/nav/LandingNavbar.jsx',
ProductSearch: 'public/components/ProductSearch.jsx',
Examples: 'public/components/Examples.jsx',
Pricing: 'public/components/Pricing.jsx',
Profile: 'public/components/Profile.jsx',
Checkout: 'public/components/Checkout.jsx',
Receipt: 'public/components/Receipt.jsx',
RequireAuth: 'public/components/auth/require_auth.jsx',
Signout: 'public/components/Signout.jsx',
Tour: 'public/components/tour/Tour.jsx',
BusinessTypes: 'public/components/tour/BusinessTypes.jsx',
Customers: 'public/components/tour/Customers.jsx',
Features: 'public/components/tour/Features.jsx',
GettingStarted: 'public/components/tour/GettingStarted.jsx',
MultiStore: 'public/components/tour/MultiStore.jsx',
Support: 'public/components/tour/Support.jsx',
Actions: 'public/actions/index.js'
},
extensions: ['', '.js', '.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.jsx$/,
loaders: ['react-hot','babel-loader', 'babel?presets[]=es2015,presets[]=stage-0,presets[]=react'],
include: path.join(__dirname, 'public')
}]
}
};
You have the babel loader twice. Just remove 'babel-loader' from your array of loaders. This is because "babel?..." is calling the loader already.
Your package.json must have babel-loader in it. So make sure you run:
npm install babel-loader babel-core babel-preset-es2015 babel-preset-react babel-preset-stage-0 --save-dev
Then this in your webpack config file:
module: {
loaders: [{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'stage-0', 'react']
},
include: path.join(__dirname, 'public')
}]
}
If that works, then try adding 'react-hot' to your list of loaders.
What file gives you this error? public/actions/index.js? You are not passing your .js files to babel.
And you are calling babel-loader twice. First as "babel-loader" without any preset and second as "babel" with presets.
Correct loaders would be:
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel?presets[]=es2015,presets[]=stage-0,presets[]=react'],
include: path.join(__dirname, 'public')
}]
Note changed test regexp. Now it covers .js and .jsx files. And I suggest moving presets into .babelrc file

Resources