rollup-plugin-node-resolve not resolving dependency - rollupjs

This is going to be a pretty easy question, but after reading and rereading documentation, and a thousand different trials, I still cannot get my library to resolve my dependencies.
Directory hierarchy is :
root
|-- package.json
|-- rollup.config.js
|-- node_modules
|-- fast-json-patch
|-- fp-rosetree
|-- deep-equal
Rollup config file is :
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import { terser } from "rollup-plugin-terser";
export default {
input: 'src/index.js',
output: {
file: 'dist/transducer.umd.js',
format: 'umd',
name: 'StateTranducer',
},
plugins: [
resolve({
module: true, // Default: true
jsnext: false, // Default: false
main: true, // Default: true
browser: true, // Default: false
extensions: [ '.mjs', '.js', '.jsx', '.json' ],
preferBuiltins: false, // Default: true
// Lock the module search in this path (like a chroot). Module defined
// outside this path will be marked as external
// jail: '/my/jail/path', // Default: '/'
// Set to an array of strings and/or regexps to lock the module search
// to modules that match at least one entry. Modules not matching any
// entry will be marked as external
only: [
/^fp-rosetree$/,
], // Default: null
modulesOnly: false, // Default: false
}),
commonjs({
include: ['node_modules/**', "node_modules/deep-equal/**"],
}),
terser()
]
};
then my code has
import { applyPatch } from "fast-json-patch/"
The fast-json-patch library in its code features a var _equals = require('deep-equal');. In terminal, the error message I get is :
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
deep-equal (guessing 'deepEqual')
As the module deep-equal can be found in node_modules directory, I expect rollup to be able to resolve it. I even ran npm install in node_modules/fast-json-patch to install deep-equal in the node_modules/fast-json-patch/node_modules but that still failed to produce any result.
Note that fp-rosetree is correctly resolved, and fast-json-patch is a commonjs module, as you can guess from the rollup config.
What can I be missing?

Related

Rollup JS build using rollup-plugin-modify plugin not replacing all string instances in the build files (using 'replace-in-file' plugin instead)

I wanted to tackle file cache updating in a Svelte app and wanted this part of the rollup build. I decide to add a querystring parameter to the file references (such as 'index.html?v=0.1') in the distributed build scripts. I created a constant '__cVersion__' in my rollup.config.js script and tried to use the 'rollup-plugin-modify', but that only updated my main.js and App.svelte code (the files being compiled). I also tried the '#rollup/plugin-replace' plugin with the same results. I needed the files I was also copying (not building) from src to public to also to have instances of '__cVersion__' replaced in the scripts.
The following was my initial rollup.config.js export function (the string replacement that did not work):
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
// this only seems to work on the main.js and .svelte files
modify({
'__cVersion__': 'c0.1.19'
}),
svelte({
dev: !production,
css: css => {
css.write('public/build/bundle.css');
}
}),
copy({
targets: [{
src: 'src/bs4.4.1.css',
dest: 'public/'
},
{
src: 'src/sw.js',
dest: 'public/'
},
{
src: 'src/index.html',
dest: 'public/'
},
{
src: 'src/manifest.json',
dest: 'public/'
},
{
src: 'src/images/*',
dest: 'public/images/'
}
]
}),
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// cache files
workbox({
mode: 'injectManifest',
options: {
swSrc: 'src/sw.js',
swDest: 'public/sw.js',
globDirectory: 'public',
globPatterns: [
'**/*.{html,json,js,css,png,map}',
'./manifest.json',
'./images/**',
'./bs4.4.1.css',
'./index.html'
]
}
}),
!production && serve(),
!production && livereload('public'),
production && terser()
],
watch: {
clearScreen: false
}
};
By default, the rollup-plugin-copy plugin will trigger on rollup's buildEnd hook.
Setting the hook to writeBundle fixed this issue for me, like so:
copy({
targets: [
{
src: ...,
dest: ...
},
...
],
hook: "writeBundle",
}),
I decided to take a different approach since I realized the build process needed to complete before I tried to replace '__cVersion__' in the files. After some trial and error I settled on this code:
https://github.com/kuhlaid/svelte2/releases/tag/v0.1.7
If you search the source code for '__cVersion__' you will see where I am adding the file revision string to try and force a file cache update...however, that didn't fully fix the issue.
I then looked at the service worker (sw.js) and realized the Workbox 'injectManifest' was actually handling the file revisions. The only problem with my current setup was that I had added '__cVersion__' constants to my scripts, but Workbox never saw the replacements since Workbox processed the service worker before I replaced the constants.
What I probably need to do is copy the src files to a 'staging directory' where I can replace the 'cache' constants in the scripts and then run the build rollup off of the staging files. This 'should' cause Workbox to treat the files as updated and thus assign them different revision numbers in the service worker file. I will try and update this thread when I have that issue worked out.

Rollup generates (node-resolve plugin) TypeError: Cannot read property 'preserveSymlinks' of undefined Error

I am using rollup for bundling and getting the following error
[!] (node-resolve plugin) TypeError: Cannot read property 'preserveSymlinks' of undefined
I am attaching rollup configuration
// rollup.config.js
import { terser } from "rollup-plugin-terser";
import babel from "rollup-plugin-babel";
import commonjs from "rollup-plugin-commonjs";
import nodeResolve from "rollup-plugin-node-resolve";
import replace from "rollup-plugin-replace";
export default {
input: 'src/sdk.js',
output: [
{ file: './dist/sdk.iife.js', format: 'iife' },
{ file: './dist/sdk.min.js', format: 'cjs' },
{ file: './dist/sdk.esm.js', format: 'es' }
],
plugins: [
nodeResolve({
jsnext: true,
main: true,
browser: true,
preferBuiltins: true
}),
babel(),
commonjs({
include: /node_modules/
}),
terser({
include: [/^.+\.min\.js$/, '*esm*'],
exclude: ['some*'],
compress: {
drop_console: true
}
})
]
};
I have installed rollup and all dependencies as per the rollup configuration mentioned in the site.
I have found the answer.
The issue was I have installed rollup globally and dependencies like rollup-plugin-node-resolve installed locally for the project.
That caused the error.
Solution: Install rollup locally in the project folder solved my issue.
npm install rollup --save
instead of npm install rollup --global

Rollup Won't Bundle Proptypes Dependency

I'm trying to build a component library of react components. I'd like to keep my prop-types in the library as documentation rather than remove them at build time. The problem is that rollup doesn't bundle all of the prop-types functions.
I end up with these lines in my bundle:
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var checkPropTypes = require('./checkPropTypes');
And the consumers of my library can't resolve those packages so it ends up in an error.
My rollup config looks like this:
import babel from "rollup-plugin-babel";
import commonjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
import pkg from "./package.json";
export default {
input: "src/index.js",
output: [
{
file: pkg.main,
format: "cjs",
sourcemap: true
},
{
file: pkg.module,
format: "es",
sourcemap: true
}
],
external: Object.keys(pkg.peerDependencies || {}),
plugins: [
babel(),
resolve(),
commonjs({ include: ["./index.js", "node_modules/**"] })
]
};
How can I force rollup to bundle and expand the require('./lib/ReactPropTypesSecret') call at build time?
It turns out this was due to two problems:
Ordering of Rollup plugins. Resolve should come first, followed by commonjs, and then babel.
Babel should exclude node_modules. Having Babel parse them might leave commonjs and resolve unable to parse them to bundle dependencies.
The final config should be:
import babel from "rollup-plugin-babel";
import commonjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
import pkg from "./package.json";
export default {
input: "src/index.js",
output: [
{
file: pkg.main,
format: "cjs",
sourcemap: true
},
{
file: pkg.module,
format: "es",
sourcemap: true
}
],
external: Object.keys(pkg.peerDependencies || {}),
plugins: [
resolve(),
babel({
exclude: "**/node_modules/**"
}),
commonjs({ include: ["./index.js", "node_modules/**"] })
]
};
In your package.json, include 'prop-types' within 'peerDependencies'
npm install
That fixed my problem:
[!] Error: 'default' is not exported by node_modules\prop-types\index.js, imported by Component

How to skip Javascript output in Webpack 4?

I use Webpack 4 in a project where I only need to compile and bundle styles so far. There's no Javascript.
Here's the config I have:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: {
'css/bundle': path.resolve(__dirname, 'static/scss/index.scss'),
},
output: {
path: path.resolve(__dirname, 'static'),
},
module: {
rules: [
{
test: /\.s[ac]ss$/,
include: path.resolve(__dirname, 'static/scss'),
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
plugins: [
new MiniCssExtractPlugin(),
],
};
The problem is that it outputs two files: bundle.css and bundle.js. Is there a way to configure Webpack so that it doesn't output the Javascript bundle? I tried to navigate the docs, tried a dozen different things, but it didn't really work.
One important note here is that if I remove the css-loader, bundling fails. So while css-loader is most likely responsible for outputting the bundle.js file, I'm not entirely sure how to avoid using it.
webpack-extraneous-file-cleanup-plugin has no effect with webpack 4.12.0.
I can suggest to remove bundle.js manually with on-build-webpack plugin:
var WebpackOnBuildPlugin = require('on-build-webpack');
// ...
plugins: [
// ...
new WebpackOnBuildPlugin(function () {
fs.unlinkSync(path.join('path/to/build', 'bundle.js'));
}),
],
March 2021:
In Webpack 5, on-build-webpack plugin did not work for me.
I found this:
Webpack Shell Plugin Next
The project I’m working on we’re using Webpack 5 as a build tool for a CSS pattern library. Therefore, we didn’t need the main.js in our dist.
Run npm i -D webpack-shell-plugin-next
Then in webpack.config.ts (just showing the pertinent parts):
import WebpackShellPluginNext from "webpack-shell-plugin-next";
module.exports = {
output: {
path: path.resolve(__dirname, "static/dist")
},
plugins: [
// Run commands before or after webpack 5 builds:
new WebpackShellPluginNext({
onBuildEnd: {
scripts: [
() => {
fs.unlinkSync(path.join(config.output.path, "main.js"));
}
]
}
})
]
};
export default config;
Unfortunately, this is just the way that webpack currently works. However, we are not alone in this problem! There's a plugin to cleanup any unwanted files:
install the plugin:
yarn add webpack-extraneous-file-cleanup-plugin -D
and then in your config:
const ExtraneousFileCleanupPlugin = require('webpack-extraneous-file-cleanup-plugin');
plugins: [
new ExtraneousFileCleanupPlugin({
extensions: ['.js'],
minBytes: 1024,
paths: ['./static']
}),
]
I simply delete the unneeded output with rm in package.json:
"scripts": {
"build": "npm run clean && webpack -p && rm ./dist/unneeded.js"
},
The webpack-remove-empty-scripts plugin, compatible with webpack 5, cover the current issue. It remove unexpected empty js file.

Webpack unable to load module for karma

Tyring to use webpack to bundle my depenedencies to be used in karma spec files. But getting:
Module 'fuse' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Fuse is the name of ng-app.
this same setup works when I run on standard tests, but when I try to: beforeEach(module('fuse')); the app breaks with the above error.
Here is my Karma.conf:
// Karma configuration
var webpackConfig = require('./webpack.dev.config.js');
webpackConfig.entry = {};
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
reporters: ['progress'],
port: 9876,
colors: false,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS', 'Chrome'],
singleRun: false,
autoWatchBatchDelay: 300,
// ... normal karma configuration
files: [
'node_modules/jquery/dist/jquery.js',
'./node_modules/angular/angular.js',
'./node_modules/angular-mocks/angular-mocks.js',
// 'public/app/pages/main/**/*.spec.js',
'../../app.js',
'public/app/services/auth/auth_service.spec.js'
],
preprocessors: {
// add webpack as preprocessor
'../../app.js': ['webpack'],
},
webpack: webpackConfig,
webpackMiddleware: {
// webpack-dev-middleware configuration
// i. e.
noInfo: true
},
plugins: [
require("karma-webpack"),
require("karma-jasmine"),
require("karma-chrome-launcher"),
require("karma-phantomjs-launcher")
]
});
};
Any idea what is going on? I've tried so many things and am almost out of ideas, will keep trying to reorder the files being loaded.

Resources