SyntaxError: Unexpected token '.' - webpack issue - javascript

I have the following error when trying to use a React grid component (from Glide-Data-Grid) in my NextJS project. The error tells me there is an unexpected token '.' in a file inside the nodes_modules folder.
Yet, I tried to use this component in a new React project, in order to see if I have the same error, and everything works well.
How can I fix it in my NextJS project?
Error message:
Image-overlay-editor.js line 16:
My next.config.js:
const { withExpo } = require('#expo/next-adapter');
const withCSS = require('#zeit/next-css');
const withFonts = require('next-fonts');
const withImages = require('next-images');
const withPlugins = require('next-compose-plugins')
const withTM = require('next-transpile-modules')([
'expo-next-react-navigation',
// you can add other modules that need traspiling here
])
module.exports = withPlugins(
[withTM, withFonts, withCSS, withImages, [withExpo, { projectRoot: __dirname }]],
{
webpack: (config, options) => {
config.module.rules.push({
test: /\.js$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
presets: [
['module:metro-react-native-babel-preset'],
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true }
]
],
plugins: [
['#babel/plugin-transform-flow-strip-types'],
['#babel/plugin-proposal-class-properties']
],
}
});
return config;
}
}
)

Related

NextJS: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type boolean (true)

I am building a webpage with NextJS. Today I updated NextJS to version 11.0.0, typescript to 4.3.2, and react to 17.0.0.
Now I am getting this error:
error - ./pages/_app.tsx
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type boolean (true)
I searched Google up and down, but could not find an answer.
I stripped my custom _app.tsx to the bare minimum:
import App from 'next/app';
import React from 'react';
export default class MyApp extends App {
public render() {
const {Component, pageProps} = this.props;
return (
<Component {...pageProps} />
);
}
}
but that did not work.
I also checked my next.config.js but couldn't find anything wrong with it:
const withImages = require('next-images');
const path = require('path');
const usePolling = process.env.USE_POLLING === 'true';
module.exports = withImages({
webpack: (config, options) => {
config.module.rules.push({
test: /\.(ts|tsx)$/,
exclude: /\.\.\/node_modules/,
use: [
{
loader: 'next-babel-loader',
options: {
...options.defaultLoaders.babel.options,
cacheDirectory: true,
highlightCode: true,
plugins: [
['styled-components', {ssr: true, displayName: true, preprocess: false}],
['inline-react-svg', {ignorePattern: 'noinline.svg$', caseSensitive: true, svgo: false}]
]
}
}
]
});
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
config.module.rules.push({
test: /\.(frag|vert|glsl)$/,
exclude: /\.\.\/node_modules/,
use: ['raw-loader', 'glslify-loader']
});
config.module.rules.push({
test: /\.css$/,
use: 'raw-loader'
});
return config;
},
async headers() {
return [
{
source: '/:all*(svg|jpg|png|js|css)',
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=31536000, must-revalidate'
}
]
}
];
},
webpackDevMiddleware: config => {
config.watchOptions = {
poll: 400,
aggregateTimeout: 100
};
return config;
}
});
I am using Node v14.17.0
I'm slowly losing my mind, did anyone experience the same error?

Require doesn't appear in my code, but webpack keeps throwing the error "require is not defined."

I'm writing an electron app with react. I run the developement version using this command:
webpack-dev-server --hot --host 0.0.0.0 --port 4000 --config=./webpack.dev.config.js
Here is the webpack.dev.config.js file
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { spawn } = require('child_process');
const helpers = require('./config/helpers');
// Config directories
const SRC_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'dist');
// Any directories you will be adding code/files into, need to be added to this array so webpack will pick them up
const defaultInclude = [SRC_DIR];
module.exports = {
entry: SRC_DIR + '/index.js',
output: {
path: OUTPUT_DIR,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
include: defaultInclude
},
{
test: /\.jsx?$/,
use: [{ loader: 'babel-loader' }],
include: defaultInclude
},
{
test: /\.(jpe?g|png|gif)$/,
use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
}
]
},
target: 'electron-renderer',
plugins: [
new HtmlWebpackPlugin({
template: helpers.root('public/index.html'),
inject: 'body'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
devtool: 'cheap-source-map',
devServer: {
contentBase: OUTPUT_DIR,
stats: {
colors: true,
chunks: false,
children: false
},
setup() {
spawn(
'electron',
['.'],
{ shell: true, env: process.env, stdio: 'inherit' }
)
.on('close', code => {
console.error("electron exited with code ", code);
process.exit(0)
})
.on('error', spawnError => console.error(spawnError));
}
}
};
Once the electron browser opens it has the following error in the Dev-Tools console.
Uncaught ReferenceError: require is not defined
at Object.url (index.js:23)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
at Object../node_modules/webpack-dev-server/client/utils/createSocketUrl.js (createSocketUrl.js:4)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
at Object.<anonymous> (client:20)
at Object../node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:4000 (client:176)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
The place where it claims this is occurring is at index.js:23.
Here is the build version of index.js:
import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./components/App";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { ipcRenderer as ipc } from "electron";
import { onUpdate } from "./actions/workerActions";
import { RECEIVED_STATE } from "./actions/types";
import "./assets/css/index.css";
import rootReducer from "./reducers/rootReducer";
import defaultState from "../config/defaultstate"; //Setup redux store
const middleware = [thunk];
const store = createStore(rootReducer, defaultState, applyMiddleware(...middleware));
ipc.on(RECEIVED_STATE, arg => {
console.log("Recieved State: ", arg);
onUpdate(arg)(store.dispatch);
}); // Now we can render our application into it
render(React.createElement(Provider, {
store: store
}, React.createElement(App, null)), document.getElementById("app"));
As you can see require does not appear here and all of the import aside from ipcRender are designed to run client-side, and therefore should not use required. I tried commenting out the ipcRender import but it resulted in the exact same error.
Most puzzlingly of all, I get the exact same error even with the entire index.js file commented out. The console still claiming the block comment contains a reference to require, which is not defined.
If you're using webpack directly then make sure you have the following in the webpack config that targets your renderer code.
// webpack.config.js
...
module.exports = {
...
target: 'web',
...
}
If you're using Vue then you'll need something like the following:
// vue.config.js
...
module.exports = {
...
configureWebpack: {
target: 'web'
},
...
}
Or, in my case I was using vue-cli-plugin-electron-builder and so need the following:
// vue.config.js
...
module.exports = {
...
pluginOptions: {
electronBuilder: {
nodeIntegration: false,
chainWebpackRendererProcess: config => {
config.target('web');
}
}
},
...
}
It turns out that the error is caused by importing electron's ipcRenderer which requires node integration and uses require. The reason that commenting out the import in the index.js didn't fix the error was because it was imported in other files.

Nextjs-Graphql webpack loader: How to integrate Nextjs with Graphql loader

I am trying to integrate Nextjs with graphql-tag/loader, This is my next.config.js file:
const withSass = require('#zeit/next-sass')
const graphqlLoader = require('graphql-tag/loader')
module.exports = withSass({
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
config.module.rules.push({
test: /\.(graphql|gql)$/,
loader: graphqlLoader,
exclude: /node_modules/
})
return config
}
})
I am unable to build, I get the error below:
/HOME/node_modules/graphql-tag/loader.js:43
this.cacheable();
^
TypeError: Cannot read property 'cacheable' of undefined
Please help.
i made it working in my setup as follows. Not sure what is wrong in your code, but you can try it and see if it is working :) You can use next js plugin for it. Maybe the order of plugins matter. Here is my config. There are some additional code, but i am sure, that you will get it what you need from it. As for the libraries version "next": "6.1.1", "next-optimized-images": "1.4.1", "next-plugin-graphql": "^0.0.1",
const withSass = require("#zeit/next-sass");
const webpack = require("webpack");
const withGraphQL = require("next-plugin-graphql");
const withOptimizedImages = require("next-optimized-images");
module.exports = withOptimizedImages(
withGraphQL(
withSass({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]"
},
webpack: config => {
config.plugins.push(
new webpack.ContextReplacementPlugin(
/graphql-language-service-interface[\\/]dist$/,
new RegExp(`^\\./.*\\.js$`)
)
);
return config;
}
})
)
);
If you would prefer just to modify your code and do not install plugins you can inspire yourself from this next-graphql-plugin. The plugin is working for me, the difference from your setup is that they have rule configured as follows
config.module.rules.push({
test: /\.(graphql|gql)$/,
include: [dir],
exclude: /node_modules/,
use: [
{
loader: 'graphql-tag/loader'
}
]
})

Wrong URL for images with React + Typescript + WebPack

I'm referencing an image inside my .JSX file but the generated URL is wrong.
It looks like this : http://localhost:43124/dist/dist/9ee7eb54c0eb428bb30b599ef121fe25.jpg
The folder "dist" exists with the picture but not "dist/dist". I think the problem comes from my Webpack.config.js. Here are the files :
module.d.ts
I instruct Typescript what to do with image files as mentionned here.
declare module '*.jpg'
declare module '*.svg'
Layout.tsx
I reference my logo inside React so it can be packed by Webpack.
/// <reference path="./module.d.ts"/>
import * as React from 'react';
import logo from '../img/logo.svg';
export class Layout extends React.Component<{}, {}> {
public render() {
return <img src="{logo}" width="220" alt="logo" />
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const merge = require('webpack-merge');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
// Configuration in common to both client-side and server-side bundles
const sharedConfig = () => ({
stats: { modules: false },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
});
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig(), {
entry: { 'main-client': './ClientApp/boot-client.tsx' },
module: {
rules: [
{ test: /\.css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new ExtractTextPlugin('style.css'),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
});
return [clientBundleConfig];
};
I used the default Visual Studio ASP.NET Core React + Redux template.

webpack - output.filename error

I know this is a common question for webpack; it's really hard to debug something if it won't give you any information about the cause or location of the error.
I'm getting the error:
Error: 'output.filename' is required, either in config file or as --output-filename
I know it has to do with a syntax error somewhere, but I'm too new to webpack to figure it out.
Here's my config file. It's called "webpack.config.js" in the root folder (i.e. the folder in which I initially ran: npm init).
const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const RewriteImportPlugin = require("less-plugin-rewrite-import");
const root_dir = path.resolve(__dirname)
const src_dir = path.resolve(__dirname, "webpack_src")
const build_dir = path.resolve(__dirname, "webpack_bin")
const node_mod_dir = path.resolve(__dirname, 'node_modules');
const extractLESS = new ExtractTextPlugin('style.css');
const config = {
entry: {
index: path.resolve(src_dir, 'index.js')
},
output: {
path: build_dir,
filename: 'bundle.js'
},
resolve: {
modules: [root_dir, 'node_modules'],
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.(js)$/
},
{
use: extractLESS.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'less-loader',
options: {
paths: [root_dir, node_mod_dir],
plugins: [
new RewriteImportPlugin({
paths: {
'../../theme.config': __dirname + '/semantic_ui/theme.config',
}
})
]
}
}]
}),
test: /\.less$/
},
{
use: ['file-loader'],
test: /\.(png|jpg|gif|woff|svg|eot|ttf|woff2)$/
},
]
},
plugins: [
extractLESS,
new webpack.optimize.ModuleConcatenationPlugin()
]
};
module.exports = {
config
};
You're exporting module.exports = { config }, which means that you are exporting an object with one property, namely config, but webpack expects the object to be your entire config. Webpack requires output.filename, whereas you only provide config.output.filename.
The export should be your config:
module.exports = config;

Categories