Rollup Won't Bundle Proptypes Dependency - rollupjs

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

Related

Vite - How do I use a wildcard in Rollupjs build.rollupOptions.external?

I'm using Vite to build a library and I get the following error when building the library:
Rollup failed to resolve import "node:path"
By adding the failed import to the Rollup options I'm able to fix the error but the build continues to complain for each node:* import. In the end I've had to add each one individually to the build.rollupOptions.external:
build: {
rollupOptions: {
external: [
'node:path',
'node:https',
'node:http',
'node:zlib',
...
],
},
While this solves the issue it is time consuming to list each node import individually. Is there instead a way to use some sort of wildcard syntax to automatically resolve all node imports?
build: {
rollupOptions: {
external: [
'node:*' // i.e. this syntax does not work, is there something similar that would work?
],
},
build.rollupOptions.external also accepts regular expressions. The following RegExp matches any string that starts with node::
/^node:.*/
So configure external as follows:
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
build: {
rollupOptions: {
external: [
/^node:.*/,
]
}
}
})

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-plugin-node-resolve not resolving dependency

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?

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