Webpack not recognize jsx only from package module - reactjs

I have a package that exports react components.
When I install the package and a component, and run site I am getting an error from webpack:
Module parse failed: Unexpected token (84:24)
You may need an appropriate loader to handle this file type,
This error refers to a line containing a jsx element.
When I copied the component, and imported it worked ok.
This is my webpack.config.js (no .babelrc file, I also tried with .bablerc file):
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env", "#babel/preset-react"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: { extensions: ["*", ".js", ".jsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
}
};

Try indicating libraryTarget in output.
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
libraryTarget: "commonjs2",
},
libraryTarget specifies how your component will be exported. Refer to the docs for details: https://webpack.js.org/configuration/output/#outputlibrarytarget

Related

webpack options has an unknown property 'hotOnly'. Invalid options object. Dev Server has been initialized using an options object

I am running the command npx webpack-dev-server --mode development in my react application and getting the preceding error.
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options has an unknown property 'hotOnly'. These properties are valid:
Below is my webpack.config.js file.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "babel-loader",
options: {
presets: ["#babel/env"],
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "https://localhost:3000/dist/",
hotOnly: true,
},
plugins: [new webpack.HotModuleReplacementPlugin()],
};
Any idea what is causing this issue?
So devServer|Webpack config is related to Options for webpack-dev-server
If your webpack is using webpack-dev-server version 4 you should use this migration guide
// your v3 config
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "https://localhost:3000/dist/",
hotOnly: true,
},
in v4 will be
devServer: {
// contentBase
static : {
directory : path.join(__dirname, "public/")
},
port: 3000,
// publicPath
devMiddleware:{
publicPath: "https://localhost:3000/dist/",
}
// hotOnly
hot: "only",
},
It seems like the updated version of webpack doesn't support the property hotOnly, we should use the option hot instead. You can see a GitHub issue associated with this here.
devServer: {
hot: "only", // hot:true
},
The latest versions automatically apply HotModuleReplacementPlugin plugin when you set hot: true, so please check you don't have HotModuleReplacementPlugin in your plugins if you have hot: true/hot: "only". You will get a warning as " [webpack-dev-server] "hot: true" automatically applies HMR plugin, you don't have to add it manually to your webpack configuration." if you have the preceding settings.
plugins: [new webpack.HotModuleReplacementPlugin()],
If you are getting error "static heartbeatInterval = 1000; SyntaxError: Unexpected token =", make sure to use the node version is >= 12.13.0 as per the guide here.
If everything is done, you should be able to see an output as preceding when you run npx webpack-dev-server --mode development.
Thanks, #Tushar Mistry for providing the migration guide.
Below is my completed webpack.config.js file.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "babel-loader",
options: {
presets: ["#babel/env"],
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
},
devServer: {
static: {
directory: path.join(__dirname, "public/"),
},
port: 3000,
devMiddleware: {
publicPath: "https://localhost:3000/dist/",
},
hot: "only",
},
};
Or you can also use the old version as below.
"webpack": "4.41.5",
"webpack-cli": "3.3.10",
"webpack-dev-server": "3.10.1"
For me, comma was missing after devMiddleware property causing error.
Solved by installing an older version of webpack
"webpack-dev-server": "3.10.1"

Unexpected token when #import -ing scss file into another scss file

I have a main style.scss file which attempts to import other .scss files into itself. when I compile the code using npm start, I get this error:
ERROR in ./style/style.scss
Module build failed: SyntaxError: C:/Users/XYZ/React/react-project/style/style.scss:
Unexpected token, expected ( (1:8)
#import "_base";
^
I've tried putting it in brackets:
#import("_base");
and
#import("_base.scss");
and I get this error:
ERROR in ./style/style.scss Module build failed:
SyntaxError: C:/Users/XYZ/React/react-project/style/style.scss:
Leading decorators must be attached to a class declaration (1:21)
> 1 | #import("_base.scss");
^
Here is my webpack.config.js:
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
],
rules: [{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS
]
}]
},
resolve: {
extensions: ['', '.js', '.jsx', '.scss']
},
devServer: {
historyApiFallback: true,
contentBase: './',
host: 'localhost',
port: 8080
}
};
I am new to scss and all of the tutorials I have found online tell me to import the files this way. What could be wrong?
Fixed the issue - I migrated to Webpack 2 and changed my webpack.config.js to:
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', ["es2015", { "modules": false }], 'stage-1']
}
},
{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS
]
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.scss']
},
devServer: {
historyApiFallback: true,
contentBase: './',
host: 'localhost',
port: 8080
}
};

"Modules" is not allowed Error

Webpack 2 comes with the new resolve setting and when I try to modify the setting in config, as follows, webpackValidator throws an error saying
"Modules" is not allowed"
const config = webpackValidator({
context: resolve('src'),
entry: './app.js',
output: {
filename: 'bundle.js',
path: resolve('dist'),
publicPath: '/dist/',
pathinfo: ifNotProd(),
},
devtool: ifProd('source-map', 'eval'),
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js'],
modules: [
resolve(__dirname, 'src'),
resolve(__dirname, 'node_modules')
]
},
plugins: [
new DashboardPlugin()
]
})
As mentioned on the webpack-validator project's readme (npm & github), you should seriously consider giving up the use of this package...
Note: webpack v2 has built-in validation for configuration. Due to this, webpack-validator is unlikely to make significant changes. While pull requests will be reviewed and can be merged, project maintainers are unlikely to put a lot of much effort into the maintenance of the project.
I had the same issue and finally gave up its use : Webpack 2 introduced breaking changes that surely won't be followed by the webpack-validator project.
The new built-in validation for configuration in Webpack 2 is now good enough.
By the way, your config may need a few improvements :
const config = {
context: resolve('src'),
entry: './app.js',
output: {
filename: 'bundle.js',
path: resolve('dist'),
publicPath: '/dist/',
pathinfo: ifNotProd(),
},
devtool: ifProd('source-map', 'eval'),
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader'],
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js'],
modules: [
resolve(__dirname, 'src'),
resolve(__dirname, 'node_modules')
]
},
plugins: [
new DashboardPlugin()
]
}
module.loaders becomes module.rules
module.loaders.loaders becomes module.rules.use
You can't use the shortcut 'babel' instead of 'babel-loader' any more, unless you specify it (resolveLoader.moduleTemplates property).

Webpack defaulting to /public directory

I have a React app I'm porting to Webpack, and I can successfully launch it using webpack-dev-server.
Unfortunately I have to navigate to the public directory to load the app:
localhost:10000/public/
...which interferes with React router. Is it possible to have it mount to / instead? I.e:
localhost:10000/
The publicPath directive in output doesn't seem to influence this.
// webpack.config.js
module.exports = {
devServer: {
inline: true,
port: 10000 // Defaults to 8080
},
entry: {
app: ['./src/app.jsx']
},
devtool: 'source-map',
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: path.resolve(__dirname, "public/scripts"),
publicPath: '/scripts/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: [
"es2015",
"stage-0",
"react"
],
plugins: [
"transform-flow-strip-types"
]
}
}
]
}
};
Try setting the contentBase to public folder
https://webpack.github.io/docs/configuration.html#devserver

require is working jsx file but url() resolve is not wroking in sass file - webpack

I am facing this strange issue with Webpack. After spending hours couldn't find solution.
In my jsx file when I a try to set image source via this
let img = require('../../../img/imgN.png');
It is working perfectly but when I try to set the background image using scss via
$bg-img: url('../img/bg-img.png');
Image is not getting loading by webpack.
This is my webpack file
module.exports = {
devtool: 'source-map',
entry: {
main: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./src/index.js'
]
},
output: {
path: path.join(__dirname, 'public'),
publicPath: '/public/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
loader: 'react-hot!babel'
},
{
test: /\.scss$/,
include: path.join(__dirname, 'sass'),
loaders: ["style", "css?sourceMap", "sass?sourceMap"]
},
{
test: /\.(png|jpg)$/,
include: path.join(__dirname, 'img'),
loader: 'url-loader?limit=30000'
} // inline base64 URLs for <=30k images, direct URLs for the rest
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
}
Problem was occurring because of using sourceMap with style-loader.
There is some issue on github for the same problem.
Solution:
1 . While source-maps is enabled
Style-loader uses a Blob, so it requires absolute urls to work.
Changed publicPath: '/public/', to
publicPath: 'http://localhost:8080/public/',
It worked.
Without source-maps
Just remove source map from style loaders.
Now style-loader will use an inline style tag, so there is no problem.
{
test: /\.scss$/,
include: path.join(__dirname, 'sass'),
loaders: ["style", "css", "sass"]
},
Can you try to see if $bg-img: url('~/img/bg-img.png'); would work? When I was trying out webpack in my bootstrap.scss files I had to modify the font url's using ~ (I think I read it somewhere but ya just giving you something to try)

Resources