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

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:.*/,
]
}
}
})

Related

Cannot get webpack --watch or dev server to work using Lando to run a local Drupal environment

I've scoured the internet and have bits and pieces but nothing is coming together for me. I have a local Drupal environment running with Lando. I've successfully installed and configured webpack. Everything is working except when I try to watch or hot reload.
When I run lando npm run build-dev (that currently uses webpack --watch I can see my changes compiled successfully into the correct folder. However, when I refresh my Drupal site, I do not see that changes. The only time I see my updated JS changes are when I run lando drush cr to clear cache. Same things are happening when I try to configure the webpack-dev-server. I can get everything to watch for changes and compile correctly but I cannot get my browser to reload my files, they stay cached. I'm at a loss.
I've tried configuring a proxy in my .lando.yml , and have tried different things with the config options for devServer. I'm just not getting a concise answer, and I just don't have the knowledge to understand exactly what is happening. I believe it has to do with Docker containers not being exposed to webpack (??) but I don't understand how to configure this properly.
These are the scripts I have set up in my package.json , build outputs my production ready files into i_screamz/js/dist, build-dev starts a watch and compiles non-minified versions to i_screamz/js/dist-dev - start I have in here from trying to get the devServer to work. I'd like to get webpack-dev-server running as I'd love to have reloading working.
"scripts": {
"start": "npm run build:dev",
"build:dev": "webpack --watch --progress --config webpack.config.js",
"build": "NODE_ENV=production webpack --progress --config webpack.config.js"
},
This is my webpack.config.js - no sass yet, this is just a working modular js build at this point.
const path = require("path");
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const isDevMode = process.env.NODE_ENV !== 'production';
module.exports = {
mode: isDevMode ? 'development' : 'production',
devtool: isDevMode ? 'source-map' : false,
entry: {
main: ['./src/index.js']
},
output: {
filename: isDevMode ? 'main-dev.js' : 'main.js',
path: isDevMode ? path.resolve(__dirname, 'js/dist-dev') : path.resolve(__dirname, 'js/dist'),
publicPath: '/web/themes/custom/[MYSITE]/js/dist-dev'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new BrowserSyncPlugin({
proxy: {
target: 'http://[MYSITE].lndo.site/',
proxyReq: [
function(proxyReq) {
proxyReq.setHeader('Cache-Control', 'no-cache, no-store');
}
]
},
open: false,
https: false,
files: [
{
match: ['**/*.css', '**/*.js'],
fn: (event, file) => {
if (event == 'change') {
const bs = require("browser-sync").get("bs-webpack-plugin");
if (file.split('.').pop()=='js') {
bs.reload();
} else {
bs.stream();
}
}
}
}
]
}, {
// prevent BrowserSync from reloading the page
// and let Webpack Dev Server take care of this
reload: false,
injectCss: true,
name: 'bs-webpack-plugin'
}),
],
watchOptions: {
aggregateTimeout: 300,
ignored: ['**/*.woff', '**/*.json', '**/*.woff2', '**/*.jpg', '**/*.png', '**/*.svg', 'node_modules'],
}
};
And here is the config I have setup in my .lando.yml - I did have the proxy key in here but it's been removed as I couldn't get it setup right.
name: [MYSITE]
recipe: pantheon
config:
framework: drupal8
site: [MYPANTHEONSITE]
services:
node:
type: node
build:
- npm install
tooling:
drush:
service: appserver
env:
DRUSH_OPTIONS_URI: "http://[MYSITE].lndo.site"
npm:
service: node
settings.local.php
<?php
/**
* Disable CSS and JS aggregation.
*/
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
I've updated my code files above to reflect reflect a final working setup with webpack. The main answer was a setting in
/web/sites/default/settings.local.php
**Disable CSS & JS aggregation. **
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
I found a working setup from saschaeggi and just tinkered around until I found this setting. So thank you! I also found more about what this means here. This issue took me way longer than I want to admit and it was so simple. I don't know why the 'Disabling Caching css/js aggregation' page never came up when I was furiously googling a caching issue. Hopefully this answer helps anyone else in this very edge case predicament.
I have webpack setup within my theme root folder with my Drupal theme files. I run everything with Lando, including NPM. I found a nifty trick to switch the dist-dev and dist libraries for development / production builds from thinkshout.
I should note my setup does not include hot-reloading but I can at least compile my files and refresh immediately and see my changes. The issue I was having before is that I would have to stop my watches to drush cr and that workflow was ridiculous. I've never gotten hot reloading to work with with either BrowserSync or Webpack Dev Server and I might try to again but I need to move on with my life at this point.
I've also note included sass yet, so these files paths will change to include compilation and output for both .scss and .js files but this is the basic bare min setup working.

svelte - Environment Variables not working

I am trying to set the env variables in my app using https://medium.com/dev-cafe/how-to-setup-env-variables-to-your-svelte-js-app-c1579430f032
import {config} from 'dotenv';
import replace from '#rollup/plugin-replace';
plugins: [
//Environment varialbes
replace({
// stringify the object
__myapp: JSON.stringify({
env: {
isProd: production,
...config().parsed // attached the .env config
}
}),
}),
But when I try to access the env variables using "__myapp.env.API_ID", I get the following error in the dev tool - Uncaught Reference Error: __myapp is not defined"
Only way I could make it work is
import {config} from 'dotenv';
import replace from '#rollup/plugin-replace';
config()
plugins: [
//Environment varialbes
replace({
API_ID: JSON.stringify(process.env.API_ID)
}),

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

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?

Clarification on grunt-protractor-coverage syntax for rails app backend?

Background
I'm trying to use the grunt-protractor-coverage in my grunt script to get code coverage for protractor functional e2e tests. To get started, I utilized this tutorial, with some minor modifications and it works perfectly. Using this as a guide, I created a new gruntfile, substituting the "express" app with a rails app backend.
The Problem
When running my gruntfile, I get the following stack trace:
../dummy/node_modules/grunt-protractor-coverage/node_modules/protractor/node_modules/glob/glob.js:130
throw new Error("must provide pattern")
^
Error: must provide pattern
at new Glob (../dummy/node_modules/grunt-protractor-coverage/node_modules/protractor/node_modules/glob/glob.js:130:11)
at glob ../dummy/node_modules/grunt-protractor-coverage/node_modules/protractor/node_modules/glob/glob.js:57:11)
at Function.globSync [as sync] (../dummy/node_modules/grunt-protractor-coverage/node_modules/protractor/node_modules/glob/glob.js:76:10)
at Function.ConfigParser.resolveFilePatterns (../dummy/node_modules/grunt-protractor-coverage/node_modules/protractor/lib/configParser.js:89:26)
at Runner.run (../dummy/node_modules/grunt-protractor-coverage/node_modules/protractor/lib/runner.js:323:24)
at process.<anonymous> (../dummy/node_modules/grunt-protractor-coverage/node_modules/protractor/lib/runFromLauncher.js:32:14)
at process.EventEmitter.emit (events.js:98:17)
at handleMessage (child_process.js:318:10)
at Pipe.channel.onread (child_process.js:345:11)
[launcher] Runner Process Exited With Error Code: 8
Tracing through the code in grunt's task.js file via [node-inspector] (https://github.com/node-inspector/node-inspector), it seems there are two possible issues:
I'm missing some parameter from my config file which would correctly retrieve the files needed
There is a syntax issue
Any idea why it's throwing this error?
My Config File
protractor_coverage: {
options: {
configFile: '/usr/local/lib/node_modules/protractor/referenceConf.js', // Default config file
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false, // If true, protractor will not use colors in its output.
coverageDir: '<%= dirs.instrumentedE2E %>',
args: {}
},
phantom: {
options: {
args: {
baseUrl: 'http://localhost:3000/',
// Arguments passed to the command
'browser': 'phantomjs'
}
}
},
chrome: {
options: {
args: {
baseUrl: 'http://localhost:3000/',
// Arguments passed to the command
'browser': 'chrome'
}
}
}
},
This error means that the plugin was unable to locate your spec files. There were a couple of bugs related to this that have been fixed in recent releases.
You'll generally want your protractorConf.js to be part of your projects. I generally put it in a directory called 'tests'.
So your options would then look like:
options: {
configFile: 'tests/protractorConf.js',
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false, // If true, protractor will not use colors in its output.
coverageDir: '<%= dirs.instrumentedE2E %>',
args: {}
},
You could then put your specs in a 'tests/specs' directory, and in this protractorConf.js, reference them as:
specs: [
'tests/specs/**/*.spec.js',
'!**/exclude.spec.js'
],
This would get any file that ends with .spec.js in /tests/specs and any subdirectories therein, unless the file is named exclude.spec.js.
I had this issue also, for me in my protractorConf file I had to change where my path was.
I originally had
specs: [
'./e2e/**/*.spec.js'
],
which worked fine with protractor, and grunt-protractor-runner
But for some reason, the protractor-coverage, this did not run. I changed it to
specs: [
'test/e2e/**/*.spec.js'
],
and this solved my issue. Basically protractor-coverage looks at the path from the base rather then from the config file.

Resources