Sapper/Svelte/Rollup external dependencies best practice? - node.js

Smart people!
I’m a bundler-beginner with a bundler slash dependency-question.
On yarn dev run I get the error: "Cannot find module '#sveltejs/svelte-scroller'..."
I have a sapper/svelte/rollup/yarn-suite
the svelte-scroller-plugin
The plugin is by default loaded as an external in rollup.config.js:
{ ..., server: { ..., external: <**package.json-dependencies-arr**> } ... }
And when I use it in a .svelte-component:
import Scroller from '#sveltejs/svelte-scroller';
//...
<Scroller />
...the error slaps my face.
Notes
rollup.config.js is unchanged from the template clone
If I remove the plugin from the dependencies-arr loaded as externals in rollup.config.js the error goes away.
...which tells me that rollup shouldn't load the dependency as an external (assuming the only goal is to make the specified error vanish).
And since svelte-scroller's purpose here is client-interaction-related, I presume it shouldn't be a part of the bundle either way.
Of course cyberspace has related issues, but I can't seem to find a clear best practice example on how to handle this.
My current workaround is therefore:
// in rollup.config.js
import pkg from './package.json';
// filter out those "not external dependencies"
const notExternals = ['#sveltejs/svelte-scroller'];
const externals = Object.keys(pkg.dependencies).filter(plugin =>
notExternals.some(not => not === plugin) ? false : true
);
export default {
// ...,
server: {
// ...,
// bundle filtered externals (along with default built in modules)
external: externals.concat(require('module').builtinModules),
},
// ...
}
And if the error revisits with another dependency, I'll just add it to the notExternals-arr.
Question
Considering the sapper/svelte/rollup-setup, is this approach best practice when handling client-based plugins causing similar errors?
Thanks in advance!
Stack
internal/modules/cjs/loader.js:896
throw err;
^
Error: Cannot find module '#sveltejs/svelte-scroller'
Require stack:
- /.../__sapper__/dev/server/server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:893:15)
at Function.Module._load (internal/modules/cjs/loader.js:743:27)
at Module.require (internal/modules/cjs/loader.js:965:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/.../__sapper__/dev/server/server.js:8:16)
at Module._compile (internal/modules/cjs/loader.js:1076:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:941:32)
at Function.Module._load (internal/modules/cjs/loader.js:782:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/.../__sapper__/dev/server/server.js'
]
}
Reproduce if you dare
template
npx degit "sveltejs/sapper-template#rollup" <app-name>
plugin
yarn add #sveltejs/svelte-scroller
import the plugin to a .svelte-component
<script>
import Scroller from '#sveltejs/svelte-scroller';
</script>
//...
<Scroller />
go
yarn run dev

Because #sveltejs/svelte-scroller is a Svelte component rather than a JS module, it must be processed by the Svelte compiler at build time rather than imported at runtime. In other words, it should be part of your bundle.
The conventional way to do this, if the contents of dependencies are treated as external, is to add the package to devDependencies instead:
yarn add -D #sveltejs/svelte-scroller

Related

NextJS build error - ReferenceError: navigator is not defined

I'm running into this special error message while trying to build a simple NextJS application (using npm run build):
> Build error occurred
ReferenceError: navigator is not defined
at /cdk-next/next-frontend/node_modules/codemirror/lib/codemirror.js:18:19
at /cdk-next/next-frontend/node_modules/codemirror/lib/codemirror.js:11:83
at Object.<anonymous> (/cdk-next/next-frontend/node_modules/codemirror/lib/codemirror.js:14:2)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/cdk-next/next-frontend/node_modules/easymde/src/js/easymde.js:2:18) {
type: 'ReferenceError'
}
info - Collecting page data .
I don't know who codemirror is, or why it's not letting me build my project. From reading around I gather that this issue occurs with NextJS when trying to build a project on the server side instead of the client side, because the project does not have access to a window or navigator. In that case, what should I do? The tutorial I'm following seems to breeze through this step just fine, so should I just look at their package.json and downgrade all of my packages? Any advice would be appreciated.
The error was with my import of import SimpleMDE from "react-simplemde-editor" (located in create-post.js of the repo link above).
I implemented the solution proposed by modikum here: https://github.com/dabit3/next.js-amplify-workshop/issues/21.
Now the project builds successfully.

Erorr running node.js project after moving to a new development machine: [!] SyntaxError: Unexpected token { in rollup.config.js

I have a working node.js development environment created with Anaconda. When I have moved the project to another machine, re-created identical environment, I get error when running npm run build (or npm run dev):
[!] SyntaxError: Unexpected token {
c:\test\myproject\rollup.config.js:1
(function (exports, require, module, __filename, __dirname) { import { nodeResolve } from '#rollup/plugin-node-resolve'
^
SyntaxError: Unexpected token {
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:656:28)
at Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Object.require.extensions.(anonymous function) [as .js] (c:\test\myproject\node_modules\rollup\dist\shared\loadConfigFile.js:560:13)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Module.require (internal/modules/cjs/loader.js:636:17)
This is the top line of my rollup.config.js where the error occurs:
import { nodeResolve } from '#rollup/plugin-node-resolve'
Node version: v10.13.0.
I have compared npm modules installed on both machines, they are identical, with identical versions. I'm truly puzzled. I'll be grateful for any pointers where to look for differences between the two machines and how to make the project working. I've already spent half a day looking at it and I've run out of ideas.
UPDATE:
I copied the whole conda environment to the new machine to mirror the working configuration on the old machine but the error still persists. So now I have identical environments, identical source code but it works on one machine and it doesn't on another.
It turns out rollup doesn't work properly when the project path goes through an NTFS directory junction.
Sample layout:
C:\Home - directory
\Work - directory
\MyProject - directory
C:\Work - junction to C:\Home\Work
Results:
cd C:\Work\MyProject
npm run build
.... results in error
cd C:\Home\Work\MyProject
npm run build
.... everything works OK

Error importing redux:

ERROR:
Error: Cannot find module 'redux'
at Function.Module._resolveFilename (module.js:555:15)
at Function.Module._load (module.js:482:25)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object. (C:\dev\Django
code\portfolio_web\stats_frontend\node_modules\react-
redux\lib\connect\mapDispatchToProps.js:8:14)
at Module._compile (module.js:660:30)
at Module._extensions..js (module.js:671:10)
at Object.require.extensions.(anonymous function) [as .js] (C:\dev\Django
code\portfolio_web\stats_frontend\node_modules\babel-
register\lib\node.js:152:7) at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
The file where I import react-redux is reduxStore.js:
import {createStore} from 'react-redux;
//There is nothing else. The function being imported doesn't change anything`
I'm running the file with babel-node, or with webpack-cli (which is using babel to transpile ES2015. In both cases I get the same error.
Tracing the error I can open the source (
...\stats_frontend\node_modules\react-redux\lib\connect\mapDispatchToProps.js of the error (its from official react-redux dist).
Line 8 (which causes the error) I can see a commonJS import:
var _redux = require('redux');
Upon further inspection I can see that the node search algorithm will not find 'redux' because no such file exists in ./node_modules/react-redux/ or in ./node_modules/
I have installed and updated my react-redux installation with node install --save-dev react-redux with no errors.
I was hoping someone can provide insight on why the error occurs and how to fix it
You are importing createStore from wrong library. import it from redux
import { createStore } from 'redux';

Adding gulp-sass breaks by task runner

I have a basic gulp setup in VS2017 to minify my Javascript. I decided to add gulp-sass (my package.json says I'm on gulp-sass v4.0.1) but it throws this error:
C:\Work\MyProject\MyProject\node_modules\gulp-sass\index.js:66
let sassMap;
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:404:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Work\MyProject\MyProject\gulpfile.js:11:12)
at Module._compile (module.js:397:26)
at Object.Module._extensions..js (module.js:404:10)
My gulpfile looks like this:
var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
gulp.task('minify', function () {
gulp.src('src/**/*.js')
.pipe(uglify({ mangle: false }))
.pipe(concat('scripts.min.js'))
.pipe(gulp.dest('Content'));
});
gulp.task('sass', function () {
gulp.src('src/css/**/*.scss')
.pipe(sass({ outputStyle: 'compressed' }))
.pipe(gulp.dest('Content'));
});
gulp.task('watch', function () {
gulp.watch('src/**/*.js', ['minify']);
});
I did some Googling and a simple fix suggested was to add "use strict" to the top of the offending file, in this case index.js:66. However, after doing that I get:
Failed to run "C:\Work\MyProject\MyProject\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
C:\Work\MyProject\MyProject\node_modules\node-sass\lib\binding.js:15
throw new Error(errors.missingBinary());
^
Error: Missing binding C:\Work\MyProject\MyProject\node_modules\node-sass\vendor\win32-x64-47\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 5.x
Found bindings for the following environments:
- Windows 64-bit with Node.js 6.x
This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass --force` to build the binding for your current environment.
at module.exports (C:\Work\MyProject\MyProject\node_modules\node-sass\lib\binding.js:15:13)
at Object.<anonymous> (C:\Work\MyProject\MyProject\node_modules\node-sass\lib\index.js:14:35)
at Module._compile (module.js:397:26)
at Object.Module._extensions..js (module.js:404:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Work\MyProject\MyProject\node_modules\gulp-sass\index.js:163:21)
at Module._compile (module.js:397:26)
I am running Node.js v6. I'm lost as to why what should be a simple process is giving me these errors. What am I doing wrong?
Update:
I ran the following commands suggested in the comments:
npm install node-sass -f
npm rebuild nose-sass
Both ran successfully. However, I'm still getting this error:
Failed to run "C:\Work\MyProject\MyProject\Gulpfile.js"...
cmd.exe /c gulp --tasks-simple
C:\Work\MyProject\MyProject\node_modules\gulp-sass\index.js:66
let sassMap;
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:404:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Work\MyProject\MyProject\gulpfile.js:8:12)
at Module._compile (module.js:397:26)
at Object.Module._extensions..js (module.js:404:10)
Update 2:
I was advised to add "use strict"; to the top of my gulpfile.js, but the same error occurs. Here's the file contents:
"use strict";
var gulp = require('gulp');
var sass = require('gulp-sass'); // If I comment this out, I can build
gulp.task('sass', function () {
gulp.src('src/css/**/*.scss')
.pipe(sass({ outputStyle: 'compressed' }))
.pipe(gulp.dest('Content'));
});
Most common issue online appears to be Node.js version of < 6.0, but I'm running v6.11.1.
Update 3: (solved)
I finally found the cause & solution; I've added it as an answer down below for any future readers. Enjoy.
Managed to find the problem so I'm answering my own question for future readers.
Whilst I have node.js v6.11.1 installed, Visual Studio 2017 comes bundled with it's own version of node that it uses by default. Even if you run node -v in the VS2017 shell and it tells you it's running v6.11.1, it's actually - by default - running whatever it finds in .\node_mobules\.bin.
The solution is this:
In VS2017, go "Tools > Options > Projects and Solutions > Web Package Management > External Web Tools".
You'll probably see this:
Add the path to your standalone installation of node (default C:\Program Files\nodejs) and, using the arrows, position it above the .\node_modules\bin version, like this:
Hit OK and either refresh the Task Runner Explorer or restart VS2017. Your gulpfile should now build.
In my case, I had to move $(PATH) above $(VSINSTALLDIR)/Web/External to fix the problem.

NodeJS eth-lightwallet doesn't allow different bitcore-lib versions among submodules

Module eth-lightwallet and its' dependencies have some issue with bitcore-lib version guard. I noticed that some of them have version 0.15 and other 0.14. Do you have any solution to this problem? Error that I receive is presented below.
(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"]
Error: More than one instance of bitcore-lib found. Please make sure to require bitcore-lib and check that submodules do not also include their own bitcore-lib dependency.
at Object.bitcore.versionGuard (\GitHub\X\node_modules\eth-lightwallet\node_modules\bitcore-mnemonic\node_modules\bitcore-lib\index.js:12:11)
at Object.<anonymous> (\GitHub\X\node_modules\eth-lightwallet\node_modules\bitcore-mnemonic\node_modules\bitcore-lib\index.js:15:9)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (\GitHub\X\node_modules\eth-lightwallet\node_modules\bitcore-mnemonic\lib\mnemonic.js:3:15)
Process finished with exit code 7`
Full proof solution
In your main file, set _bitcore in global to return undefined on every retrieval of its value. _bitcore is not used for anything other than guarding version in bitcore-lib .
Object.defineProperty(global, '_bitcore', {
get(){
return undefined
},
set(){}
})
The solution provided here worked for me: bitpay/bitcore#1454
Well, this is far from a proper way to solve this issue, but you can
get rid of this error by editing file
~/.nvm/versions/node/v4.8.3/lib/node_modules/bitcore/node_modules/insight-api/node_modules/bitcore-lib/index.js
line 7: bitcore.versionGuard = function(version) { Change it to:
bitcore.versionGuard = function(version) { return;
I did this and so far no problems.
This error causes of version confliction.
I fixed this error by changing the version of
bitcore-lib and bitcore-mnemonic/bitcore-lib by ^0.15.0
(which bitcore-mnemonic/bitcore-lib is ^0.16.0).
Then npm install again.

Resources