unresolved dependencies with rollup - rollup

I have the following rollup config:
import cjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
import json from "rollup-plugin-json";
export default {
input: "lib/state-info.js",
output: {
file: "rolled.js",
format: "cjs"
},
external: ["aws-sdk"],
plugins: [
json(),
cjs({
include: "node_modules/**",
exclude: ["node_modules/aws-sdk/**"]
}),
resolve({
jsnext: true,
main: true,
browser: false,
preferBuiltins: false,
extensions: [".js", ".json"]
})
]
};
And I'm rolling up successfully but warned that there are a lot of unresolved dependencies. The following functions are subset of those missing:
process (imported by lib/vote-smart/get-state-info.js, node_modules/abstracted-admin/lib/db.js, commonjs-external:process)
http (imported by node_modules/axios/lib/adapters/http.js, node_modules/follow-redirects/index.js, commonjs-external:http, node_modules/firebase-admin/lib/auth/credential.js, node_modules/request/request.js, node_modules/request/node_modules/http-signature/lib/signer.js, node_modules/forever-agent/index.js, node_modules/request/node_modules/form-data/lib/form_data.js, node_modules/tunnel-agent/index.js)
https (imported by node_modules/axios/lib/adapters/http.js, node_modules/follow-redirects/index.js, commonjs-external:https, node_modules/firebase-admin/lib/auth/token-generator.js, node_modules/firebase-admin/lib/utils/api-request.js, node_modules/firebase-admin/lib/auth/credential.js, node_modules/request/request.js, node_modules/forever-agent/index.js, node_modules/request/node_modules/form-data/lib/form_data.js, node_modules/tunnel-agent/index.js)
dgram (imported by node_modules/request/node_modules/sntp/lib/index.js, commonjs-external:dgram)
tls (imported by node_modules/forever-agent/index.js, commonjs-external:tls, node_modules/tunnel-agent/index.js)
constants (imported by node_modules/graceful-fs/polyfills.js, commonjs-external:constants)
memcpy (imported by node_modules/bytebuffer/dist/bytebuffer-node.js, commonjs-external:memcpy)
timers (imported by node_modules/google-gax/lib/api_callable.js, commonjs-external:timers)
I'm very new to rollup, am I missing anything obvious?
Note, I presume functions like process and fs which are part of node itself can just be added as "external" and all should be good, right? Functions like memcpy or timers are a mystery on why they're not being detected by static analysis.
UPDATE: I have found that all but two of my unresolved dependencies can be addressed simply by adding the rollup-plugin-node-builtins plugin. The two that remain are:
memcpy and fast-crc32c
I can install fast-crc32c locally to the dependencies and this problem goes away (although I'm not sure why I need to do this) but when I try to do the same for memcpy it fails to install.

Related

Loader is required to be configured to import images using Vite?

I have a vue project which uses Vite in place of Webpack, and when I try to use import x from './src/assets/my/path/to/image.png' to resolve an image to compile-time URL, I am greeted by the following error message:
✘ [ERROR] No loader is configured for ".png" files: src/assets/my/path/to/image.png
The entire project is pretty close to the scaffold project given by npm init vue#latest (using vue3) so my vite.config.js is pretty basic:
export default defineConfig({
plugins: [vue(), VitePWA({})],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
build: {
manifest: true,
polyfillModulePreload: true,
}
});
What am I missing? How can I configure this? I can't find anything in Vite documentation about loaders.
I had a quite similar issue with my project that I couldn't really solve. The issue seemed that only initially loaded png files were added. Because I am new to Vite, my efforts with the vite.config.js were fruitless.
Instead, I found a different solution to import the assets (import img from '/path/to/img.png' ) in respective js files directly instead of vite.config.js. Since I used these assets for replacement images for toggling buttons, it was a quick fix. Maybe it helps you, too.

Web3js fails to import in Vue3 composition api project

I've created a brand new project with npm init vite bar -- --template vue. I've done an npm install web3 and I can see my package-lock.json includes this package. My node_modules directory also includes the web3 modules.
So then I added this line to main.js:
import { createApp } from 'vue'
import App from './App.vue'
import Web3 from 'web3' <-- This line
createApp(App).mount('#app')
And I get the following error:
I don't understand what is going on here. I'm fairly new to using npm so I'm not super sure what to Google. The errors are coming from node_modules/web3/lib/index.js, node_modules/web3-core/lib/index.js, node_modules/web3-core-requestmanager/lib/index.js, and finally node_modules/util/util.js. I suspect it has to do with one of these:
I'm using Vue 3
I'm using Vue 3 Composition API
I'm using Vue 3 Composition API SFC <script setup> tag (but I imported it in main.js so I don't think it is this one)
web3js is in Typescript and my Vue3 project is not configured for Typescript
But as I am fairly new to JavaScript and Vue and Web3 I am not sure how to focus my Googling on this error. My background is Python, Go, Terraform. Basically the back end of the back end. Front end JavaScript is new to me.
How do I go about resolving this issue?
Option 1: Polyfill Node globals/modules
Polyfilling the Node globals and modules enables the web3 import to run in the browser:
Install the ESBuild plugins that polyfill Node globals/modules:
npm i -D #esbuild-plugins/node-globals-polyfill
npm i -D #esbuild-plugins/node-modules-polyfill
Configure optimizeDeps.esbuildOptions to use these ESBuild plugins.
Configure define to replace global with globalThis (the browser equivalent).
import { defineConfig } from 'vite'
import GlobalsPolyfills from '#esbuild-plugins/node-globals-polyfill'
import NodeModulesPolyfills from '#esbuild-plugins/node-modules-polyfill'
export default defineConfig({
⋮
optimizeDeps: {
esbuildOptions: {
2️⃣
plugins: [
NodeModulesPolyfills(),
GlobalsPolyfills({
process: true,
buffer: true,
}),
],
3️⃣
define: {
global: 'globalThis',
},
},
},
})
demo 1
Note: The polyfills add considerable size to the build output.
Option 2: Use pre-bundled script
web3 distributes a bundled script at web3/dist/web3.min.js, which can run in the browser without any configuration (listed as "pure js"). You could configure a resolve.alias to pull in that file:
import { defineConfig } from 'vite'
export default defineConfig({
⋮
resolve: {
alias: {
web3: 'web3/dist/web3.min.js',
},
// or
alias: [
{
find: 'web3',
replacement: 'web3/dist/web3.min.js',
},
],
},
})
demo 2
Note: This option produces 469.4 KiB smaller output than Option 1.
You can avoid the Uncaught ReferenceError: process is not defined error by adding this in your vite config
export default defineConfig({
// ...
define: {
'process.env': process.env
}
})
I found the best solution.
The problem is because you lose window.process variable, and process exists only on node, not the browser.
So you should inject it to browser when the app loads.
Add this line to your app:
window.process = {
...window.process,
};

How to fix "This relative module was not found: * ./src/main.js in multi..." error when trying to npm run serve

When trying to run the application with npm run serve (on iOS), I am getting the following error:
This relative module was not found:
./src/main.js in multi (webpack)-dev-server/client?http://10.0.0.5:8081/sockjs-node ./node_modules/#vue/cli-service/node_modules/webpack/hot/dev-server.js ./src/main.js
Please bear with me, I am new to this.
I have tried a bunch of random stuff like checking for misspelling issues, reinstalling webpack, updating node, and nothing. I have no clue of what this error is about so I am not sure where to look at.
The main.js file looks like this:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/store'
import './registerServiceWorker'
import * as VueGoogleMaps from "vue2-google-maps"
import VeeValidate from 'vee-validate'
import BootstrapVue from 'bootstrap-vue'
Vue.use(VueGoogleMaps, {
load: {
key: "AIzaSyCGiy39IZbj8oxvO4HHqSVjP5RmLSHl7mY",
libraries: "places" // necessary for places input
}
});
Vue.use(VeeValidate);
Vue.use(BootstrapVue);
Vue.config.productionTip = false;
new Vue({
router,
store,
beforeCreate() {
this.$store.commit('initialiseStore');
this.$store.dispatch('commons/initialize');
},
render: h => h(App)
}).$mount('#app')
I expect the live web server to display, but I am getting this compilation error and it is failing.
I faced a similar issue after and spent hours searching.
The issue occurred in my project when I tried to install vuetify using command vue add vuetify. Apparently, the in automatically changes the app entry property in webpack.config automatically.
You can either change the filename itself to main.js or change the webpack config through vue.config.js (by reading the vue cli documentation regararding webpack config).
You can check your webpack.config by using the command vue inspect.
],
entry: {
app: [
'./src/main.js'
]
}
}
I had a similar error, this worked for me but not sure you have the same issue. I found this in one of my webpack configuration files (usually named like webpack.dev.conf.js):
{
test: /\.js$/,
loader: 'babel-loader',
include: [
resolve('src'),
resolve('test'),
resolve('node_modules/webpack-dev-server/client')
]
},
I removed resolve('node_modules/webpack-dev-server/client') and it fixed that issue.
This is an old thread, but I ran across this recently after installing a new module to a Vue project. The problem went away when I updated all my other modules, too.

Field 'browser' doesn't contain a valid alias configuration

I've started using webpack2 (to be precise, v2.3.2) and after re-creating my config I keep running into an issue I can't seem to solve I get (sorry in advance for ugly dump):
ERROR in ./src/main.js
Module not found: Error: Can't resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
Parsed request is a module
using description file: [absolute path to my repo]/package.json (relative path: ./src)
Field 'browser' doesn't contain a valid alias configuration
aliased with mapping 'components': '[absolute path to my repo]/src/components' to '[absolute path to my repo]/src/components/DoISuportIt'
using description file: [absolute path to my repo]/package.json (relative path: ./src)
Field 'browser' doesn't contain a valid alias configuration
after using description file: [absolute path to my repo]/package.json (relative path: ./src)
using description file: [absolute path to my repo]/package.json (relative path: ./src/components/DoISuportIt)
as directory
[absolute path to my repo]/src/components/DoISuportIt doesn't exist
no extension
Field 'browser' doesn't contain a valid alias configuration
[absolute path to my repo]/src/components/DoISuportIt doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
[absolute path to my repo]/src/components/DoISuportIt.js doesn't exist
.jsx
Field 'browser' doesn't contain a valid alias configuration
[absolute path to my repo]/src/components/DoISuportIt.jsx doesn't exist
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt.js]
[[absolute path to my repo]/src/components/DoISuportIt.jsx]
package.json
{
"version": "1.0.0",
"main": "./src/main.js",
"scripts": {
"build": "webpack --progress --display-error-details"
},
"devDependencies": {
...
},
"dependencies": {
...
}
}
In terms of the browser field it's complaining about, the documentation I've been able to find on this is: package-browser-field-spec. There is also webpack documentation for it, but it seems to have it turned on by default: aliasFields: ["browser"]. I tried adding a browser field to my package.json but that didn't seem to do any good.
webpack.config.js
import path from 'path';
const source = path.resolve(__dirname, 'src');
export default {
context: __dirname,
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
resolve: {
alias: {
components: path.resolve(__dirname, 'src/components'),
},
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: source,
use: {
loader: 'babel-loader',
query: {
cacheDirectory: true,
},
},
},
{
test: /\.css$/,
include: source,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
query: {
importLoader: 1,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
modules: true,
},
},
],
},
],
},
};
src/main.js
import DoISuportIt from 'components/DoISuportIt';
src/components/DoISuportIt/index.jsx
export default function() { ... }
For completeness, .babelrc
{
"presets": [
"latest",
"react"
],
"plugins": [
"react-css-modules"
],
"env": {
"production": {
"compact": true,
"comments": false,
"minified": true
}
},
"sourceMaps": true
}
What am I doing wrong/missing?
Turned out to be an issue with Webpack just not resolving an import - talk about horrible horrible error messages :(
// I Had to change:
import DoISuportIt from 'components/DoISuportIt';
// to (notice the missing `./`)
import DoISuportIt from './components/DoISuportIt';
Just for record, because I had similiar problem, and maybe this answer will help someone: in my case I was using library which was using .js files and I didn't had such extension in webpack resolve extensions. Adding proper extension fixed problem:
module.exports = {
(...)
resolve: {
extensions: ['.ts', '.js'],
}
}
I'm building a React server-side renderer and found this can also occur when building a separate server config from scratch. If you're seeing this error, try the following:
Make sure your entry value is properly pathed relative to your context value. Mine was missing the preceeding ./ before the entry file name.
Make sure you have your resolve value included. Your imports on anything in node_modules will default to looking in your context folder, otherwise.
Example:
const serverConfig = {
name: 'server',
context: path.join(__dirname, 'src'),
entry: {serverEntry: ['./server-entry.js']},
output: {
path: path.join(__dirname, 'public'),
filename: 'server.js',
publicPath: 'public/',
libraryTarget: 'commonjs2'
},
module: {
rules: [/*...*/]
},
resolveLoader: {
modules: [
path.join(__dirname, 'node_modules')
]
},
resolve: {
modules: [
path.join(__dirname, 'node_modules')
]
}
};
I encountered this error in a TypeScript project. In my webpack.config.js file I was only resolving TypeScript files i.e.
resolve: {
extensions: [".ts"],
}
However I noticed that the node_module which was causing the error:
Field 'browser' doesn't contain a valid alias configuration
did not have any ".ts" files (which is understandable as the module has been converted to vanilla JS. Doh!).
So to fix the issue I updated the resolve declaration to:
resolve: {
extensions: [".ts", ".js"],
}
I had the same issue, but mine was because of wrong casing in path:
// Wrong - uppercase C in /pathCoordinate/
./path/pathCoordinate/pathCoordinateForm.component
// Correct - lowercase c in /pathcoordinate/
./path/pathcoordinate/pathCoordinateForm.component
Add this to your package.json:
"browser": {
"[module-name]": false
},
Changed my entry to
entry: path.resolve(__dirname, './src/js/index.js'),
and it worked.
This also occurs when the webpack.config.js is simply missing (dockerignore 🤦‍♂️)
In my case it was a package that was installed as a dependency in package.json with a relative path like this:
"dependencies": {
...
"phoenix_html": "file:../deps/phoenix_html"
},
and imported in js/app.js with import "phoenix_html"
This had worked but after an update of node, npm, etc... it failed with the above error-message.
Changing the import line to import "../../deps/phoenix_html" fixed it.
My case was rather embarrassing: I added a typescript binding for a JS library without adding the library itself.
So if you do:
npm install --save #types/lucene
Don't forget to do:
npm install --save lucene
Kinda obvious, but I just totally forgot and that cost me quite some time.
In my case, to the very end of the webpack.config.js, where I should exports the config, there was a typo: export(should be exports), which led to failure with loading webpack.config.js at all.
const path = require('path');
const config = {
mode: 'development',
entry: "./lib/components/Index.js",
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, "node_modules")
}
]
}
}
// pay attention to "export!s!" here
module.exports = config;
I had aliases into tsconfig.json:
{
"compilerOptions": {
"paths": {
"#store/*": ["./src/store/*"]
}
},
}
So I solved this issue by adding aliases to webpack.config also:
module.exports = {
//...
resolve: {
alias: {
'#store': path.resolve(__dirname, '../src/store'),
},
},
};
I got same problem and fixed with adding file extension.
// Old:
import RadioInput from './components/RadioInput'
// New:
import RadioInput from './components/RadioInput.vue'
Also, if you still want to use without extensions, you can add this webpack config: (Thanx for #matthew-herbst for the info)
module.exports = {
//...
resolve: {
extensions: ['.js', '.json', '.wasm'], // Add your extensions here.
},
};
For anyone building an ionic app and trying to upload it. Make sure you added at least one platform to the app. Otherwise you will get this error.
In my experience, this error was as a result of improper naming of aliases in Webpack.
In that I had an alias named redux and webpack tried looking for the redux that comes with the redux package in my alias path.
To fix this, I had to rename the alias to something different like Redux.
In my case, it was due to a broken symlink when trying to npm link a custom angular library to consuming app. After running npm link #authoring/canvas
"#authoring/canvas": "path/to/ui-authoring-canvas/dist"
It appear everything was OK but the module still couldn't be found:
When I corrected the import statement to something that the editor could find Link:
import {CirclePackComponent} from '#authoring/canvas/lib/circle-pack/circle-pack.component';
I received this which is mention in the overflow thread:
To fix this I had to:
cd /usr/local/lib/node_modules/packageName
cd ..
rm -rf packageName
In the root directory of the library, run:
a) rm -rf dist
b) npm run build
c) cd dist
d) npm link
In the consuming app, update the package.json with:
"packageName": "file:/path/to/local/node_module/packageName""
In the root directory of the consuming app run npm link packageName
In my case (lolz),
I was importing a local package (that I was developing, and building with rollup) via NPM/Yarn link, into another package I was developing. The imported package was a load of React components, and was configured to have a peerDependency of react and react-dom.
The consuming package was being built with Webpack and obviously wasn't correctly feeding the installed react and react-dom libraries into my local dependency as it was compiling it.
I adjusted my webpack configuration to indicate it should alias those peer dependencies to the correct dependencies in the consuming package:
/* ... */
resolve: {
extensions: [/* make sure you have them all correct here, as per other answers */],
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom')
}
},
/* ... */
Obviously you need to import path in the webpack.config.js file in order to use the methods seen above.
A more detailed explanation can be found in this article
My case was similar to #witheng's answer.
At some point, I noticed some casing error in some file names in my development environment. For example the file name was
type.ts
and I renamed it to
Type.ts
In my Mac dev environment this didn't register as a change in git so this change didn't go to source control.
In the Linux-based build machine where the filenames are case-sensitive it wasn't able to find the file with different casing.
To avoid issues like this in the future, I ran this command in the repo:
git config core.ignorecase false
In my case, I imported library files like:
import { MyFile } from "my-library/public-api";
After I removed the public-api from the import everything worked fine:
import { MyFile } from "my-library";
MyFile is exported in the public-api file in the library.
In my case,
I have mistakenly removed a library ("mini-create-react-context") from package.json. I added that back, and did yarn install and build the app and it start working properly. So please take a look at your package.json file once.
In my case I had accidentally imported this package while trying to use process.env:
import * as process from 'process';
Removing it fixed the problem.
For everyone with Ionic:
Updating to the latest #ionic/app-scripts version gave a better error message.
npm install #ionic/app-scripts#latest --save-dev
It was a wrong path for styleUrls in a component to a non-existing file.
Strangely it gave no error in development.
In my situation, I did not have an export at the bottom of my webpack.config.js file. Simply adding
export default Config;
solved it.
In my case, it is due to a case-sensitivity typo in import path. For example,
Should be:
import Dashboard from './Dashboard/dashboard';
Instead of:
import Dashboard from './Dashboard/Dashboard';
In my case I was using invalid templateUrl.By correcting it problem solved.
#Component({
selector: 'app-edit-feather-object',
templateUrl: ''
})
I am using single-spa, and encountered this issue with the error
Module not found: Error: Can't resolve '/builds/**/**/src\main.single-spa.ts' in /builds/**/**'
I eventually figured out that in angular.json build options "main" was set to src\\main.single-spa.ts. Changing it to src/main.single-spa.ts fixed it.
Had the same issue with angular was importing
import { Injectable } from "#angular/core/core";
changed it to
import { Injectable } from "#angular/core";
I was getting this error when running a GitHub action. The issue was because I'd listed the package as a peer dependency instead of a dependency.
Since I'm using Rollup, the solution was to install the package both as a peer dependency and a dev dependency, and use rollup-plugin-peer-deps-external to remove the dev dependency from the final build.
For me the issue was, I was importing
.ts files into .js files
changing them to ts as well solved the issue.
In my case, I had a mixture of enum and interface in the index.d.ts file.
I extracted enums into another file and the issue resolved.

Bundle ractive with ractive-load through Rollup

What is the correct way to import ractive and ractive-load to my rollup project? npm or github?
Currently I am using npm to install each one:
npm install --save-dev ractivejs/ractive
And
npm install --save-dev ractivejs/ractive-load
And I'm using rollup-plugin-commonjs with rollup-plugin-node-resolve to corretly bundle them (rollup.config.js in the end of the question):
import Ractive from 'ractive';
import load from 'ractive-load';
...
But it seems that ractive-load also imports other modules in its code, causing this error:
Error parsing /home/.../node_modules/rcu/src/make.js: 'import' and 'export' may only appear at the top level (2:0) in /home/.../node_modules/rcu/src/make.js
How can I correctly use Rollup and which are the right sources for this case (npm or github)?
Here is my rollup.config.js:
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
export default {
entry: 'src/main.js',
plugins: [
nodeResolve({
jsnext: true,
main: true,
browser: true,
}),
commonjs({
sourceMap: false
}),
// uglify()
],
format: 'iife',
moduleName: 'Altiva',
dest: 'altiva.js'
};
ractive-load is intended to "read" link tags in the browser and then do AJAX requests for the component file, then it uses a library called rcu to convert the component files into usable javascript components.
What you need is a utility (that uses rcu or does equivalent work) to turn your component files into javascript files that you can run during build process then hand-off to rollup. Fortunately, it looks like there is a rollup plugin rollup-plugin-ractive designed to do just that:
rollup({
entry: 'src/main.js',
plugins: [
ractive({
// By default, all .html files are compiled
extensions: [ '.html', '.ract' ],
// You can restrict which files are compiled
// using `include` and `exclude`
include: 'src/components/**.html'
})
]
}).then(...)
There's also list of some of the available loaders here, among them are "plain vanilla js" variants as well.