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

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'
}
]
})

Related

Cannot set property 'styles' of undefined in NextJs, I'm facing this issue whenever I start server after installing any packages or simply 'npm i'

Reference snapshot of error -->>
Cannot set property 'styles' of undefined, error in nextJs
whenever I installs package or simply doing npm i I face this issue, I have tried
//next.config.js module.exports = withPlugins([...], {webpack5: false,}) and yarn add --dev webpack#webpack-4 less less-loader#5
but none of them solved the issue later on digging on issue came to know that #zeit\next-css have been deprecated, below is the next.config.js reference please let me know how to resolve issue, how to update code in config file so that I can use built-in CSS support of nextJs itself leaving behind the deprecated one, Very very Thanks in Advance.
const withSass = require('#zeit/next-sass');
const withCSS = require('#zeit/next-css');
const path = require('path');
module.exports = withCSS(
withSass({
webpack: (config) => {
config.node = {
fs: 'empty'
};
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
limit: 1000000,
name: '[name].[ext]'
}
},
{
loader: 'url-loader',
options: {
limit: 1000000,
name: '[name].[ext]'
}
}
]
});
module.exports = {
resolve: {
alias: {
TweenLite: path.resolve('node_modules', 'gsap/src/uncompressed/TweenLite.js'),
TweenMax: path.resolve('node_modules', 'gsap/src/uncompressed/TweenMax.js'),
TimelineLite: path.resolve('node_modules', 'gsap/src/uncompressed/TimelineLite.js'),
TimelineMax: path.resolve('node_modules', 'gsap/src/uncompressed/TimelineMax.js'),
ScrollMagic: path.resolve('node_modules', 'scrollmagic/scrollmagic/uncompressed/ScrollMagic.js'),
'animation.gsap': path.resolve(
'node_modules',
'scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js'
),
'debug.addIndicators': path.resolve(
'node_modules',
'scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js'
)
}
}
};
return config;
}
})
);

SyntaxError: Unexpected token '.' - webpack issue

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;
}
}
)

React - Next.js configuration with cssModules and url-loader

I need to configure next.config.js file in order to use in the same time two different loaders.
This is the first:
const withSass = require('#zeit/next-sass');
module.exports = withSass({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
}
})
And this is the second:
const withSass = require('#zeit/next-sass');
const withCSS = require('#zeit/next-css');
module.exports = withCSS(withSass({
webpack (config, options) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000
}
}
})
return config
}
}))
Individually they work great!
But I'm not able to combine them in a single rule so that both can work together.
Thanks for your help!!
You should use next-compose-plugins. Here is a link below for additional reference.
How can I combine multiple loaders (CSS, LESS, ttf, etc) in NextJS config file?
But the code below should solve your issue:
Install
yarn add --dev #zeit/next-css
yarn add --dev #zeit/next-sass file-loader url-loader
Update your next.config.js file
const withPlugins = require('next-compose-plugins');
const sass = require("#zeit/next-sass")
const css = require("#zeit/next-css")
const nextConfig = {
webpack: function (config) {
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}
}
})
return config
}
}
module.exports = withPlugins([
[css],
[sass, {
cssModules: true
}]
], nextConfig);
Note: You should now be able to import scss modules like this:
import styles from 'your-file-name.module.scss'
Note: Watch out for vendors libs that are not formatted properly in that case you should import as follows:
import "slick-carousel/slick/slick-theme.css";
import "slick-carousel/slick/slick.css";

Webpack how to cache bust angular-translate with $translatePartialLoader?

"webpack": "^2.7.0"
I'm trying to add a hash to our translation files in order to cache bust when deploying. I've managed to extract the json and add a hash and output it to a folder and is good with the world.
But, my unhashed json is still under there original folders after building. I understand that we don't need to add a loader for json as it already has means of handling importing, so my question would be how do I clean out the json that's already been processed?
my folder structure is as follows
src/
app/
module-name/
/translations
en.json
fn.json
module-name/
/translations
en.json
fn.json
//ect...
I used the CopyWebpackPlugin to get the json and hash is there maybe an option ive missed that cleans out the process'd files? or maybe i'm approaching this the incorrect way.
const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');
const VersionFile = require('webpack-version-file');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const pkg = require('../package.json');
const autoprefixer = require('autoprefixer');
module.exports = {
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
enforce: 'pre'
},
{
test: /\.(css|scss)$/,
loaders: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader?minimize!resolve-url-loader!sass-loader?sourceMap!postcss-loader'
})
},
{
test: /\.(jpe?g|png|gif|svg)$/,
loader: 'file-loader',
options: {
regExp: /\/([a-z0-9]+)\/[a-z0-9]+\.json$/,
name: '[name]-[hash].[ext]'
}
},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: [
'ng-annotate-loader',
'babel-loader'
]
},
{
test: /\.html$/,
loaders: [
'html-loader'
]
}
]
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
template: conf.path.src('index.html')
}),
new webpack.optimize.UglifyJsPlugin({
output: {comments: false},
compress: {unused: true, dead_code: true, warnings: false} // eslint-disable-line camelcase
}),
new ExtractTextPlugin('index-[contenthash].css'),
new webpack.optimize.CommonsChunkPlugin({name: 'vendor'}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: () => [autoprefixer]
}
}),
new webpack.HashedModuleIdsPlugin(),
new CopyWebpackPlugin([{
from: 'src/app/**/*.json',
to: 'translations/[name]-[hash].[ext]'
}]),
new VersionFile({
output: `${conf.paths.dist}/version.txt`,
verbose: true
})
],
output: {
path: path.join(process.cwd(), conf.paths.dist),
filename: '[name]-[hash].js'
},
entry: {
app: [`./${conf.path.src('app/app.module.js')}`],
vendor: Object.keys(pkg.dependencies)
},
node: {
fs: 'empty',
/* eslint-disable camelcase */
child_process: 'empty'
}
};
Or to similfy the question, how can i add a hash to json files? and the following code doesn't seem to do anything.
{
test: /\.json$/,
loader: 'file-loader',
options: {
name: '[name]-[hash].[ext]'
}
}
EDIT:
so it seems like my json loader doesnt pick up the translation files as they're dynamicly imported like so how:
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: 'app/{part}/translations/{lang}.json'
});
do you handle cases like this?
The main goal you're trying to do here is telling the browser its a new file when releasing a new version and we can do this fairly easily without having to force webpack to know what files are being used.
in your webpack config add this
const pkg = require('../package.json');
//...
new webpack.DefinePlugin({
__VERSION__: JSON.stringify(pkg.version)
})
and where you add your translation files this allows for the browser to know where has been a new release and should update translation files.
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: `app/{part}/translations/{lang}.json?v=${__VERSION__}`
});

Using webpack to simply transpile and concat files?

So i am trying to figure out how to use webpack to replace our current brunch build process. Basically we have an angular 1 app which doesnt utilise requires or imports at all and I want to have webpack just concat+transpile the files (there are both coffee and sass files and ill need to be able to watch and create source maps using the usual settings). This angular app is sitting inside another application which is using webpack extensively.
What is the simplest way to accomplish this? Is this even possible without the app using any form of javascript modules?
Here is my current config:
var webpack = require( "webpack" );
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require("path");
var glob = require("glob");
const exportConfig = {
entry: {
app: glob.sync('./front-end/applications/core/app/**/*.coffee'),
vendor: ['angular']
},
output: {
filename: "app.bundle.js",
path: path.join( __dirname, "../www_root/build" ),
},
debug: true,
module: {
loaders: [
{
test: /\.coffee$/,
loader: "coffee-loader"
},
{
test: /\.sass$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.(jsx|es6)/,
exclude: /(node_modules|www_root\/bower)/,
loader: "babel",
},
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js"),
new ExtractTextPlugin("[name].css", {
allChunks: true
}),
]
}
module.exports = exportConfig
I basically just get an output file with an error for each of the files obviously:
(function webpackMissingModule() { throw new Error("Cannot find module \"./front-end/applications/core/app/components/app/module.coffee\""); }());
Thanks!

Categories