Nuxtjs with scrollmagic gives me "window is not defined" - window

I want to use scrollmagic with nuxtjs.
I installed scrollmagic via npm.
npm install scrollmagic
In my nuxt.config.js file i added
build: {
vendor: ['scrollmagic']
},
And in my pages/index.vue file i simply imported it.
import ScrollMagic from 'scrollmagic'
But this results only in this error
[vue-router] Failed to resolve async component default:
ReferenceError: window is not defined [vue-router] uncaught error
during route navigation: ReferenceError: window is not defined
at C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:37:2
at C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:22:20
at Object. (C:\pathto\node_modules\scrollmagic\scrollmagic\uncompressed\ScrollMagic.js:27:2)
How can i fix this?

Add a file to your plugins folder called "scrollmagic.js" and paste the following code into it:
plugins/scrollmagic.js
import ScrollMagic from 'scrollmagic'
Add the plugin to your nuxt.config.js file
nuxt.config.js
module.exports = {
build: {
vendor: ['scrollmagic']
},
plugins: [
// ssr: false to only include it on client-side
{ src: '~/plugins/scrollmagic.js', ssr: false }
]
}
Use it with if (process.client) {}
page or component
<script>
let scrollmagic
if (process.client) {
scrollmagic = require('scrollmagic')
// use scrollmagic
}
</script>
For more information please consult the excellent documentation on this topic: https://nuxtjs.org/guide/plugins/

Related

Vite does not build my #extend rules from bulma-scss

I'm having a build issue with the scss at-rule "extend" using Vite to build out a Vue3 component library using the bulma-scss NPM package.
Using Bluma buttons for example, I would like to import the bulma-scss button.scss file into my tag in my .vue file (or into the button.scss file and then import that into the script tag) like so:
<template/>
<script/>
...
<style lang="scss">
#import 'bulma-scss/elements/button';
</style>
When running $ vite build I get this error from Vite:
File: /Users/my-user/sites/component-library/node_modules/bulma-scss/elements/_button.scss
Error: The target selector was not found.
Use "#extend %control !optional" to avoid this error.
It is specifically this line in the bulma-scss package that it doesn't like (in this example) https://github.com/j1mc/bulma-scss/blob/master/elements/_button.scss#L71
it looks like I can get around this by adding the following preprocessor option to my storybook's vite configs:
css: {
preprocessorOptions: {
scss: {
additionalData: `#import "bulma-scss";`
}
},
},
But that would include the entirety of bulma-scss right? Ideally I would only import the things I need from bulma.
And here is my entire vite config file (sans the css preprocessorOptions)
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import {resolve} from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
lib: {
entry: resolve(__dirname, 'src/index.js'),
name: 'lmsComponentLibrary',
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
resolve: {
alias: {
'bulma-scss/': require('path').join(__dirname, 'node_modules/bulma-scss/'),
}
},
});
I think the problem comes from the bulma-scss package itself. In the file that you are importing there is no %control placeholder. Even its import ../utilities/controls and ../utilities/mixins don't have that placeholder neither. So the error is expected here.
The %control is defined in bulma-scss/utilities/extends so you can fix the problem by importing that file. BUT, it will lead to another problem because in the _extends.scss there are some variables that are not defined. So you need to import all the file that contains these variables.
Luckily, the package has a file containing all the utility variables. So you just need to import it.
#import 'bulma-scss/utilities/all'; <-- Add this line
#import 'bulma-scss/elements/button';

Next-optimized-images: Error Module parse failed, Unexpected character ''"

I'm trying to optimize my nextjs page images with next-optimized-images
This is the next.config.js:
module.exports = {
...
withOptimizedImages: withOptimizedImages({
webpack(config) {
config.resolve.alias.images = path.join(__dirname, 'public')
return config
}
}),
...
Here is how I import image to components:
require(`public/assets/icons/${iconName}`)
My Error:
./public/assets/icons/website/information/hiring-black.svg 1:0
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
I'm using latest version of next-optimized-image and tried different guides but still no luck.
Please help
Next.js now optimize images by default.
Refer: next/image
If you need svg, you need to try adding svgr-webpack loader.
Install: yarn add #svgr/webpack -D
To configure this, update following in next.config.js
module.exports = {
...
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ['#svgr/webpack'],
});
return config;
},
...
};
Use it as following:
...
import Star from './star.svg'
...
<Star />
...

Unresolved dependencies & Missing global variable name when trying to import #mapbox/mapbox-gl-geocoder

I'm beginning with Svelte and I would like to (more or less) reproduce Mapbox store locator tutorial with Svelte & rollup. (Starting from svelte REPL starter kit).
Everything's fine for loading a map and some markers, but as soon as I try to import this package https://github.com/mapbox/mapbox-gl-geocoder, nothing works anymore and I'm not familiar enough with Svelte to figure out how to setup rollup and fix it.
<script>
import { onMount, setContext } from 'svelte'
import mapbox from 'mapbox-gl/dist/mapbox-gl.js';
import MapboxGeocoder from '#mapbox/mapbox-gl-geocoder'; // <<--- Problem here
mapbox.accessToken = 'xxx';
let map;
let geocoder;
onMount(() => {
map = new mapbox.Map({,,,});
geocoder = new MapboxGeocoder({,,,});
});
</script>
terminal :
bundles src/main.js → public/build/bundle.js...
(!) Missing shims for Node.js built-ins
Creating a browser bundle that depends on 'events'. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
events (imported by node_modules/#mapbox/mapbox-gl-geocoder/lib/index.js, events?commonjs-external)
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
events (guessing 'events$1')
created public/build/bundle.js in 2s
browser console :
Uncaught ReferenceError: events$1 is not defined
at main.js:5
Then, I tried to add to my rollup config resolve and polyfills plugins, but have other errors.
rollup.config.js
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import preprocess from 'svelte-preprocess';
import nodeResolve from '#rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
nodeResolve(),
nodePolyfills(),
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write('bundle.css');
},
preprocess: preprocess()
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Gives me this
bundles src/main.js → public/build/bundle.js...
LiveReload enabled
(!) `this` has been rewritten to `undefined`
https://rollupjs.org/guide/en/#error-this-is-undefined
node_modules/base-64/base64.js
163: }
164:
165: }(this));
^
to conclude: I'm a bit lost :D
thanks in advance

Loading D3 with Nuxt/Vue

I am trying to implement D3 in an app I am building with Nuxt. I have successfully imported it into a view in the <script> section with import * as d3 from 'd3' however because the app is being rendered server-side D3's functionality doesn't work (i.e. d3.select(...)) due to the lack of browser. In the Nuxt plugin documentation it suggests a pattern for client-only external plugins:
module.exports = {
plugins: [
{ src: '~plugins/vue-notifications', ssr: false }
]
}
I attempted to implement the pattern in the nuxt.config.js of my project:
module.exports = {
head: {
title: 'My Demo App',
meta: [...],
link: [...]
},
loading: {...},
plugins: [
{ src: '~node_modules/d3/build/d3.js', ssr: false}
]
}
However D3 throws a ReferenceError while looking for document and Nuxt throws a SyntaxError in the console pointing to something in the plugins field of nuxt.config.js.
For reference, demo.vue:
<template>
<div class="demo-container"></div>
</template>
<script>
import * as d3 from 'd3';
d3.select('.demo-container');
</script>
Would someone be able to point to what I'm doing wrong?
For anyone coming to this page looking for a solution,
these suggestions from piyushchauhan2011 here on GitHub sent me in the right direction.
All I needed to do:
import d3 in my single-file component, and then
do any DOM manipulation with d3 only within mounted()
Before all this, I had to of course add d3 to my project with yarn add d3 (or npm install d3).
[Edit: removed link that no longer works. It wasn't that relevant anyway.]
I was getting an error:
Must use import to load ES Module: .../node_modules/d3/src/index.js require() of ES modules is not supported. require() of .../node_modules/d3/src/index.js from .../node_modules/vue-server-renderer/build.dev.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from .../node_modules/d3/package.json.
I solved it by reading this: https://github.com/nuxt/nuxt.js/issues/9223
which indicates you can add this to your nuxt.config.js file:
build: {
standalone: true,
}
This allowed the d3 import to work.
import * as d3 from "d3";
Here's a simple step-by-step tutorial:
Create a new NuxtJS project (Skip this step if you have an existing project)
npm init nuxt-app nuxtjs-d3js-example
Install D3JS
npm install d3
npm install #types/d3 --save-dev
Import D3JS and add a target
HTML:
<p id="d3-target"></p>
JavaScript:
import * as d3 from 'd3'
export default {
name: 'NuxtTutorial',
mounted: function() {
d3.select("#d3-target").text("This text is manipulated by d3.js")
},
}
Fix ES Module error (mentioned by #agm1984)
Error:
require() of ES Module /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/d3/src/index.js from /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/vue-server-renderer/build.dev.js not supported. Instead change the require of index.js in /home/johnson/projects/nuxtjs-d3js-example/nuxtjs-d3js-example/node_modules/vue-server-renderer/build.dev.js to a dynamic import() which is available in all CommonJS modules.
nuxt.config.js:
build: {
standalone: true,
}
A minimal project example can be found at: https://github.com/j3soon/nuxtjs-d3js-example, with each step detailed in the Git commit history.

using d3.js as an external in webpack

I'm using this tutorial to setup a React.js project with webpack. The webpack.config.js below is almost an exact copy (except that I'm using an app and 'dist' folder), and I am also adding d3.js as an external. Because React is added as an external it lets me do require('react') in any of my app files without including it in the bundle. I wish to do the same with d3.js and have installed it as a node_module, and listed it in the externals area of my webpack config, but when I do require('d3') i get an error message that it's not available.
How can I use d3 (or jQuery for that matter) as an external if I have it installed as a node_module?
this is my project setup
/app
/dist
/node_modules
package.json
webpack.config.js
module.exports = {
entry: './app/index.jsx',
output: {
path: './dist',
filename: 'bundle.js', //this is the default name, so you can skip it
//at this directory our bundle file will be available
//make sure port 8090 is used when launching webpack-dev-server
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
}
]
},
externals: {
//don't bundle the 'react' npm package with our bundle.js
//but get it from a global 'React' variable
'react': 'React',
'd3': 'd3'
},
resolve: {
modulesDirectories: ['app', 'node_modules'],
extensions: ['', '.js', '.jsx']
}
}
I know this question has been open a while, but hopefully this answer is still useful!
If you have installed d3 (or jQuery) as a node_module, you can use the webpack ProvidePlugin to tie an arbitrary key to a module.
The key will be then be available to require anywhere in your webpack app.
E.g. webpack.config.js
{
...lots of webpack config here...
...
plugins: [
new webpack.ProvidePlugin({
d3: 'd3',
$: 'jquery'
})
]
...
}
Then in my-file.js
var d3 = require('d3')
Hope that helps!

Resources