Currently I have two files in my webpack script build, script.js and contact-menu.js. If I create react components on the main script.js file, it translates ok. If create React components in contact-menu.js and try export import it gives the following error:
> ERROR in ./babel/contact-menu.js Module parse failed:
> /Applications/MAMP/htdocs/mcdonalds excavation/themes/mcdonalds/babel/contact-menu.js
> Unexpected token (7:3) You may need an appropriate loader to handle
> this file type. | render(){ | return( | <div
> id="contact-menu-container"> | <div id="contact-menu-btn"> |
> Close # ./babel/script.js 11:19-47
I have tried renaming the files from js to jsx, aswell as changing the entry point on my webpack config
webpack config
var path = require('path');
var debug = process.env.NODE_ENV !== 'production';
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? 'inline-sourcemap' : null,
entry: './babel/script.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'script.js'
},
module: {
loaders: [{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
include: [path.resolve(__dirname, 'babel/script.js')],
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-3'],
plugins: ['transform-react-jsx']
}
}, {
test: /\.scss$/,
include: [path.resolve(__dirname, 'sass')],
loaders: ['style-loader', 'css-loader', 'sass-loader']
}, {
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader"
}]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: false,
sourcemap: false
}),
],
};
package.json
{
"name": "react-kit",
"version": "3.0.0",
"description": "React Build Kit With Webpack.",
"main": "webpack.config.js",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"axios": "^0.15.3",
"babel-cli": "^6.18.0",
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-plugin-transform-react-jsx": "^6.8.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-3": "^6.5.0",
"css-loader": "^0.26.1",
"fetch-jsonp": "^1.0.6",
"history": "^1.17.0",
"node-sass": "^4.5.0",
"react-router": "^3.0.1",
"sass-loader": "^5.0.1",
"style-loader": "^0.13.1",
"webpack": "^2.2.1",
"webpack-dev-server": "^1.14.1"
},
"author": "",
"license": "MIT"
}
script.jsx
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(
<ContactMenu />,
document.getElementById('contact-menu')
)
contact-menu.jsx
import React from 'react'
import ReactDOM from 'react-dom'
export default class ContactMenu extends React.Component{
render(){
return(
<div id="contact-menu-container">
<div id="contact-menu-btn">
Close
</div>
<div id="contact-menu">
</div>
</div>
)
}
}
I believe this line in your webpack configuration is the problem:
include: [path.resolve(__dirname, 'babel/script.js')],
The webpack documentation is fairly sparse, but it appears that if include is specified only the paths in it will be transformed by the loader. If you omit that option, all paths that pass test and aren't listed in exclude should be transformed by the loader, including contact-menu.js.
Related
I am trying to use AWS Amplify UI in a React project. However, I receive the following errors after bundling the project with WebPack: Uncaught SyntaxError: Invalid or unexpected token (in Chrome) & SyntaxError: Invalid character '\u00b0' (in Safari). The error does not appear in Firefox.
This occurs when I load the bundled HTML file, after bundling with the webpack command. However, when using webpack serve, I have observed that the page renders as expected, in all the above browsers, with no errors.
package.json
{
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.17.12",
"babel-jest": "^27.5.1",
"babel-loader": "^8.2.5",
"copy-webpack-plugin": "^10.2.4",
"css-loader": "^6.7.1",
"eslint": "^8.14.0",
"html-webpack-plugin": "^5.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.5.1",
"node-polyfill-webpack-plugin": "^1.1.4",
"pa11y": "^6.2.3",
"style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.3.1",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.8.1"
},
"dependencies": {
"#aws-amplify/ui-react": "^3.0.1",
"#fontsource/poppins": "^4.5.8",
"aws-amplify": "^4.3.26",
"jquery": "^3.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
module.exports = (env, argv) => {
let filename = "[name]-bundle.js";
if (argv.mode == "production") {
filename = "[name]-bundle-[contenthash].js";
}
let config = {
entry: {
app: './src/app.js'
},
output: {
filename,
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
importLoaders: 1,
sourceMap: true
}
}
]
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: "index.html",
chunks: ["app"]
}),
new NodePolyfillPlugin()
],
devtool: 'inline-source-map',
devServer: {
static: './dist',
allowedHosts: "all"
}
};
return config;
};
app.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Button } from '#aws-amplify/ui-react';
import '#aws-amplify/ui-react/styles.css';
import "#fontsource/poppins/index.css";
function App() {
return (
<div>
<p>Testing</p>
<Button variation="primary">Hello world</Button>
</div>
);
}
const domContainer = document.getElementById("container");
const root = ReactDOM.createRoot(domContainer);
root.render(<App />);
This is a character encoding issue.
It worked with the WebPack DevServer because charset=utf-8 is automatically appended to the Content-Type header of the response.
Setting the character encoding in the head of the HTML file, as below, resolved this issue.
<meta charset="utf-8" />
I am trying to set up my reactjs project with webpack, but I get an error when compiling with npm start. Looks like webpack does not understand the tag <Provider .../>. This project worked fine for previous versions of the libraries, but I am updating dependencies to latest ones and it stop working. Any help is appreciated. Next, some snippets of the main file involved.
ERROR in ./src/index.js
Module parse failed: /home/andres/Desarrollo/anube-app-flotas/src/index.js Unexpected token (16:2)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (16:2)
at Parser.pp$4.raise (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
at Parser.pp.unexpected (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:603:10)
at Parser.pp$3.parseExprAtom (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:1822:12)
at Parser.pp$3.parseExprSubscripts (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
at Parser.pp$3.parseMaybeUnary (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
at Parser.pp$3.parseExprOps (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
at Parser.pp$3.parseMaybeConditional (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
at Parser.pp$3.parseMaybeAssign (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
at Parser.pp$3.parseExprList (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:2165:22)
at Parser.pp$3.parseSubscripts (/home/andres/Desarrollo/anube-app-flotas/node_modules/webpack/node_modules/acorn/dist/acorn.js:1741:35)
# multi main
My webpack.config.js looks like this:
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
and the .babelrc is:
{
"presets": ["react", "env"]
}
The index.js where it fails at line 16 is:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';
// ...
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}> // line 16
<BrowserRouter>
<div>
<Switch>
Anyone has any idea about what's happening here?
UPDATE: dependencies in package.json
"devDependencies": {
"babel-core": "^6.2.1",
"babel-loader": "^6.2.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"chai": "^3.5.0",
"chai-jquery": "^2.0.0",
"jquery": "^2.2.1",
"jsdom": "^8.1.0",
"mocha": "^2.4.5",
"react-addons-test-utils": "^0.14.7",
"webpack": "^4.6.0",
"webpack-dev-server": "^3.1.3",
"style-loader": "^0.21.0",
"css-loader": "^0.28.11"
},
"dependencies": {
"babel-preset-stage-1": "^6.1.18",
"lodash": "^3.10.1",
"react": "^16.32.1",
"react-dom": "^16.3.2",
"react-redux": "5.0.7",
"react-router": "^4.2.0",
"redux": "^4.0.0"
}
When you use jsx syntax, the file extenstion for that file should be .jsx you are using .js here. So please rename that file to index.jsx
And adapt that change in your webpack config:
module.exports = {
entry: [
'./src/index.jsx'
],
module: {
rules: [{
test: /\.jsx?$/, // also transpile jsx files
exclude: /node_modules/,
loader: 'babel-loader'
}]
},
}
I can't get the file loader module to work. When running this code I get this error:
"You may need an appropriate loader to handle this file type."
I've been googling a lot on this but can't find a solution. Any ideas?
webpack.config.js:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: "./client/index.html",
filename: "index.html",
inject: "body"
})
module.exports = {
entry: "./client/index.js",
output: {
path: path.resolve("dist"),
filename: "index_bundle.js"
},
module: {
loaders: [
{ test: /\.js$/, loader: "babel-loader", exclude: /node_modules/ },
{
test: /\.(ico|png|gif|jpg|svg)$/i,
loader: "file-loader"
}
]
},
plugins: [
HtmlWebpackPluginConfig
]
}
package.json:
{
"name": "hello-world-react",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --hot",
"build": "webpack -p"
},
"dependencies": {
"html-webpack-plugin": "^2.28.0",
"path": "^0.12.7",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"webpack": "^2.5.0",
"webpack-dev-server": "^2.4.5"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"file-loader": "^0.11.1"
}
}
App.jsx:
import React from "react";
export default class App extends React.Component {
render() {
return (
<div style={{ textAlign: "center" }}>
<h1>Hello World</h1>
<img src={require("./client/dog1.jpg")}/>
</div>
)
}
}
You have a .jsx source file but you're telling Webpack to only use babel-loader for files ending in.js. Fix the test in your Webpack config:
{ test: /\.jsx?$/, loader: "babel-loader", exclude: /node_modules/ },
I get the following error when running:
webpack watch
ERROR in multi ./main.js watch
Module not found: Error: Can't resolve 'watch' in '/Users/name/directory/src'
# multi ./main.js watch
Heres my webpack.config.js file
const path = require('path');
module.exports = {
context: path.join(__dirname, 'src'),
entry: [
'./main.js',
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
use: [
'babel-loader',
],
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
}
],
},
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
},
};
Here is my package.json
{
"name": "name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.4.2",
"react-dom": "^15.4.2",
"webpack-dev-middleware": "^1.10.1"
},
"devDependencies": {
"babel-core": "^6.24.0",
"babel-loader": "^6.4.1",
"babel-preset-es2015": "^6.24.0",
"babel-preset-latest": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-2": "^6.22.0",
"css-loader": "^0.27.3",
"express": "^4.15.2",
"node-sass": "^4.5.0",
"react-helmet": "^4.0.0",
"react-hot-loader": "^1.3.1",
"sass-loader": "^6.0.3",
"style-loader": "^0.14.1",
"webpack": "^2.2.1",
"webpack-dev-middleware": "^1.10.1",
"webpack-dev-server": "^2.4.2"
}
}
Below is my main.js file
import "./styles/stylesheet.scss";
import { Header } from "./components/headercomponent";
import React from "react";
import ReactDOM from "react-dom";
import { render } from "react-dom";
class App extends React.Component {
render(){
return (
<div id="container">
<Header/>
<h1>hello world</h1>
</div>
);
}
}
render(<App/>, window.document.getElementById("app"));
Do you know why I'm getting the webpack error?
Arguments you pass to the webpack CLI will be treated as entry points. You want to use the --watch option, not add watch as an entry. The correct command is:
webpack --watch
I am facing issue due to large webpack bundle size.
The size of my bundle size is nearby 166 kb. I am running webpack with -p flag. Most of the size is due to bundling of react module in my bundle file. So, what I am trying to do is that I am making two bundles: one which contain my app specific code and the other one which contains minified version of the npm which do not change frequently.
My bundle size is now 20 Kb.
Here is my webpack config file :
var path = require('path');
var webpack = require("webpack");
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var config = {
entry: path.resolve(__dirname, 'index.js'),
output: getOutput(),
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
devtool: process.env.NODE_ENV === 'production' ? false : "eval",
module: {
loaders: [
{
test: /\.scss$/,
include: /src/,
loaders: [
'style',
'css',
'autoprefixer?browsers=last 3 versions',
'sass?outputStyle=expanded'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'url?limit=8192',
'img'
]
},
{
test: /\.jsx?$/,
exclude: (node_modules_dir),
loaders: [
'react-hot',
'babel-loader?presets[]=stage-0,presets[]=react,presets[]=es2015',
]
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
}
};
module.exports = config;
function getOutput() {
if (process.env.NODE_ENV === 'production') {
return {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
} else {
return {
publicPath: 'http://localhost:3000/',
filename: 'dist/bundle.js'
}
}
}
and here is my code :
import {connect, Provider} from 'react-redux';
import React from "react"
import {createStore, combineReducers} from 'redux';
import reducers from "./reducers";
import {increment} from "./actions/App.js";
var store = createStore(
combineReducers({
...reducers
})
);
class App extends React.Component {
render() {
return <div>
<span>Value is : {this.props.value}</span>
<div onClick={this.props.increment}><span>Increment</span></div>
</div>
}
}
App = connect((state)=> {
return {value: state.app.value}
}, {increment})(App);
module.exports = React.createClass({
render: ()=> {
return <Provider store={store}><App /></Provider>
}
});
and here is my package.json file
{
"name": "Sample App",
"version": "0.0.1",
"private": true,
"scripts": {
"webpack-server": "webpack-dev-server --hot --progress --colors --port 3000",
"serve-web": "npm run webpack-server",
"deploy": "NODE_ENV=production webpack -p --optimize-minimize"
},
"dependencies": {
"babel-core": "6.9.0",
"babel-loader": "6.2.4",
"babel-plugin-transform-runtime": "6.9.0",
"babel-preset-es2015": "6.9.0",
"babel-preset-react": "6.5.0",
"babel-preset-stage-0": "6.5.0",
"babel-relay-plugin": "^0.9.1",
"babel-runtime": "6.9.0",
"css-loader": "^0.23.0",
"file-loader": "^0.8.5",
"http-server": "^0.8.0",
"img-loader": "^1.3.1",
"node-fetch": "^1.5.3",
"postcss-loader": "^0.8.0",
"react": "15.3.2",
"react-dom": "^15.1.0",
"react-hot-loader": "^1.2.8",
"react-redux": "^4.4.5",
"redux": "^3.6.0",
"source-map-loader": "^0.1.5",
"url-loader": "^0.5.7",
"webpack": "1.13.1",
"webpack-dev-server": "1.14.1"
},
"jest": {
"preset": "jest-react-native"
},
"devDependencies": {
"babel-cli": "6.9.0",
"babel-core": "^6.9.0",
"babel-loader": "^6.2.4"
},
"engines": {
"npm": ">=3"
}
}
So, I have changed
module.exports = require('./lib/React');
to
module.exports = window.React;
in react.js file of react module as other npm like redux is also using react npm.
Is it a good thing to apply this patch in react.js file of react npm?
Is it a good thing to make two bundles like this?
You can use source map explorer to detect what is the problem.
https://www.npmjs.com/package/source-map-explorer