Rollup Vue2 - build fails - javascript

I got an issue with my rollup + vue 2 setup, and get conflicting information online.
My rollup config:
import vue from 'rollup-plugin-vue';
import postcss from 'rollup-plugin-postcss';
import sass from 'rollup-plugin-sass';
import image from '#rollup/plugin-image';
import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
const plugins = [
vue({
preprocessStyles: true,
css: true,
compileTemplate: true
}),
commonjs({ extensions: ['.js'] }),
postcss(),
sass(),
image(),
resolve({
jsnext: true,
main: true,
browser: true
}),
babel({ exclude: 'node_modules/**', include: '**/*.js' })
];
export default {
input: 'src/main.js',
output: {
dir: 'diss',
format: 'iife',
sourcemap: false
},
plugins
};
With this config I get the following error:
[!] Error: 'resolveComponent' is not exported by node_modules\vue\dist\vue.runtime.esm.js, imported by src\App.vue?vue&type=template&id=7ba5bd90&lang.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
src\App.vue?vue&type=template&id=7ba5bd90&lang.js (1:9)
1: import { resolveComponent as _resolveComponent, createVNode as _createVNode, openBlock as _openBlock, createBlock as _createBlock } from "vue";
^
2: var _hoisted_1 = {
3: id: "app"
Error: 'resolveComponent' is not exported by node_modules\vue\dist\vue.runtime.esm.js, imported by src\App.vue?vue&type=template&id=7ba5bd90&lang.js
If I switch commonjs with vue in the plugin list, since plugin order matters, I get this error:
[!] (plugin commonjs) SyntaxError: Unexpected token (2:1) in D:\current_projects\uploadportal\client\src\App.vue?vue&type=template&id=7ba5bd90&lang.js
src\App.vue?vue&type=template&id=7ba5bd90&lang.js (2:1)
1:
2: <div id="app">
^
3: <router-view />
4: </div>
SyntaxError: Unexpected token (2:1) in D:\current_projects\uploadportal\client\src\App.vue?vue&type=template&id=7ba5bd90&lang.js
It seems like I miss something in the process, but my research went into rabbit holes without any solution.
Can someone see my error?
Thank you!

Related

How do I polyfill the "process" Node module in the Vite dev server?

In my Vite project, I am depending on a module that makes use of the process Node global in one of its functions. I don't call this function from my code, but the Vite dev server still gives me this error when I import the module:
Uncaught ReferenceError: process is not defined
Interestingly, I don't see this error when I create a production build.
How can I polyfill process with a no-op so that the Vite dev server stops failing?
An alternative is adding to your index.html
<script type="module">
import process from 'process';
window.process = process;
</script>
I had the same issue today in a React project using rollup + vite and here's how I solved it, using this Medium piece by Fabiano Taioli.
Vite needs Node.js polyfills
You need to add some polyfill plugins to allow Node globals, such as process. Fortunately, you can simply edit (or create) the vite.config.js.
Example vite.config.js
Below is an example which includes using NodeGlobalsPolyfillPlugin to polyfill process. It also includes many other node globals so remove at your leisure.
import { defineConfig } from 'vite';
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill';
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill';
import ReactPlugin from 'vite-preset-react';
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
// This Rollup aliases are extracted from #esbuild-plugins/node-modules-polyfill,
// see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
// process and buffer are excluded because already managed
// by node-globals-polyfill
util: 'rollup-plugin-node-polyfills/polyfills/util',
sys: 'util',
events: 'rollup-plugin-node-polyfills/polyfills/events',
stream: 'rollup-plugin-node-polyfills/polyfills/stream',
path: 'rollup-plugin-node-polyfills/polyfills/path',
querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
url: 'rollup-plugin-node-polyfills/polyfills/url',
string_decoder: 'rollup-plugin-node-polyfills/polyfills/string-decoder',
http: 'rollup-plugin-node-polyfills/polyfills/http',
https: 'rollup-plugin-node-polyfills/polyfills/http',
os: 'rollup-plugin-node-polyfills/polyfills/os',
assert: 'rollup-plugin-node-polyfills/polyfills/assert',
constants: 'rollup-plugin-node-polyfills/polyfills/constants',
_stream_duplex:
'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
_stream_passthrough:
'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
_stream_readable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
_stream_writable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
_stream_transform:
'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
timers: 'rollup-plugin-node-polyfills/polyfills/timers',
console: 'rollup-plugin-node-polyfills/polyfills/console',
vm: 'rollup-plugin-node-polyfills/polyfills/vm',
zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
tty: 'rollup-plugin-node-polyfills/polyfills/tty',
domain: 'rollup-plugin-node-polyfills/polyfills/domain',
},
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis',
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
}),
NodeModulesPolyfillPlugin(),
],
},
},
plugins: [
ReactPlugin({
injectReact: false,
}),
rollupNodePolyFill(),
],
});
Development dependencies required
To make the above example work as is you'll need to add some dependencies. In particular:
yarn add --dev vite-preset-react
yarn add --dev #esbuild-plugins/node-modules-polyfill
yarn add --dev #esbuild-plugins/node-globals-polyfill
I'm using node-stdlib-browser, and it works really well for me.
And the following is my final vite.config.ts
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import path from 'path'
import nodeStdlibBrowser from 'node-stdlib-browser'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import inject from '#rollup/plugin-inject'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
// https://github.com/antfu/unplugin-auto-import#configuration
AutoImport({
dts: 'src/auto-import.d.ts',
imports: ['vue', 'vue-router'],
eslintrc: {
enabled: true,
},
}),
// https://github.com/antfu/unplugin-vue-components#configuration
Components({
dts: 'src/components.d.ts',
}),
// https://github.com/niksy/node-stdlib-browser#vite
{
...inject({
global: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'global'],
process: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'process'],
Buffer: [require.resolve('node-stdlib-browser/helpers/esbuild/shim'), 'Buffer'],
}),
enforce: 'post',
},
],
resolve: {
alias: { '#': path.resolve(__dirname, 'src'), ...nodeStdlibBrowser },
},
optimizeDeps: {
esbuildOptions: {
target: 'esnext', // Enable Big integer literals
},
},
build: {
target: 'esnext', // Enable Big integer literals
commonjsOptions: {
transformMixedEsModules: true, // Enable #walletconnect/web3-provider which has some code in CommonJS
},
},
})

Including a specific module in rollup build

I'm using Rollup to build a UMD version of my module.
This rollup.config.js successfully builds my module, without including #tensorflow/tfjs:
import path from 'path';
import commonjs from '#rollup/plugin-commonjs';
import { nodeResolve } from '#rollup/plugin-node-resolve';
export default {
input: "dist/tmp/index.js",
output: {
file: "dist/umd/index.js",
format: 'umd',
name: 'Foo',
globals: {
'#tensorflow/tfjs': 'tf',
}
},
context: 'window',
external: ['#tensorflow/tfjs'],
}
However, I rely on a second module (tensor-as-base64) that I do want to include in the bundle. I cannot figure out how to include that specific module.
From a lot of googling it seems like I need to use #rollup/plugin-commonjs and #rollup/plugin-node-resolve, but I can't find any examples for how to scope the includes to a specific folder under node_modules. I've tried something like this:
import commonjs from '#rollup/plugin-commonjs';
import { nodeResolve } from '#rollup/plugin-node-resolve';
export default {
input: "dist/tmp/index.js",
output: {
file: "dist/umd/index.js",
format: 'umd',
name: 'Foo',
globals: {
'#tensorflow/tfjs': 'tf',
}
},
context: 'window',
external: ['#tensorflow/tfjs'],
plugins: [
nodeResolve({
}),
commonjs({
include: [/tensor-as-base64/],
namedExports: {
'tensor-as-base64': ['tensorAsBase64'],
},
}),
]
};
This seems to just hang with no output.
Any tips on how to include a single specific module from the node_modules folder (and ignore everything else in that folder)?
Update 1
I tried this config:
export default {
input: "dist/tmp/index.js",
output: {
file: "dist/umd/index.js",
format: 'umd',
name: 'Foo',
globals: {
'#tensorflow/tfjs': 'tf',
}
},
context: 'window',
external: ['#tensorflow/tfjs'],
plugins: [
nodeResolve({
resolveOnly: [
/^(?!.*(#tensorflow\/tfjs))/,
],
}),
],
})
This produces the following output:
dist/tmp/index.js → dist/umd/index.js...
[!] Error: 'default' is not exported by ../../node_modules/tensor-as-base64/dist/index.js, imported by dist/tmp/upscale.js
Which is accurate in that tensor-as-base64 does not export default.
After including the commonjs plugin, it gets into an infinite loop. I think that's where I'm missing some bit of configuration.
I should add that this is a monorepo, so maybe there's an issue with node_modules being at the root of the folder?

exports is not defined for rollup and svelte

I'm trying to use a package: quoters
this is app.svelte file. the same code works fine for react and other places in JS.
<script>
import Quote from "quoters";
let quote = "";
let category = "QUOTE";
function handleCategory() {
quote = new Quote(category).get();
}
</script>
when I am trying to run the code. i get the following error: "Uncaught ReferenceError: exports is not defined". I checked the line it is referencing to.
it contains definition for exports inside the quoters package.
Object.defineProperty(exports, "__esModule", { value: true });
I've tried everything like babel and commonjs. maybe i am missing something. please can anyone tell me what is the issue and also fix for this issue.
my rollup config file for reference:
import svelte from "rollup-plugin-svelte";
import commonjs from "#rollup/plugin-commonjs";
import resolve from "#rollup/plugin-node-resolve";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
import css from "rollup-plugin-css-only";
import copy from "rollup-plugin-copy";
import json from "#rollup/plugin-json";
import builtins from "rollup-plugin-node-builtins";
import globals from "rollup-plugin-node-globals";
import replace from "#rollup/plugin-replace";
import babel from "#rollup/plugin-babel";
import nodePolyfills from "rollup-plugin-node-polyfills";
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn(
"npm",
["run", "start", "--", "--dev"],
{
stdio: ["ignore", "inherit", "inherit"],
shell: true,
}
);
process.on("SIGTERM", toExit);
process.on("exit", toExit);
},
};
}
export default {
input: "src/main.js",
output: {
sourcemap: true,
format: "iife",
name: "app",
file: "public/build/bundle.js",
exports: "auto",
},
moduleContext: {
"node_modules/quoters/dist/parseData.js": "window",
},
plugins: [
svelte({
compilerOptions: {
// enable run-time checks when not in production
dev: !production,
},
}),
nodePolyfills(),
json(),
copy({
targets: [
{
src: "node_modules/bootstrap/dist/**/*",
dest: "public/vendor/bootstrap",
},
],
}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: "bundle.css" }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
babel({
exclude: "node_modules/**", // only transpile our source code
}),
resolve({
dedupe: ["svelte"],
browser: true,
preferBuiltins: false,
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("public"),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
],
watch: {
clearScreen: false,
},
};

Error when compiling javascript with Vue using Rollup

I'm having issues trying to compile my Vue scripts with rollup. The error I'm getting is
[!] Error: 'openBlock' is not exported by
node_modules/vue/dist/vue.runtime.esm.js, imported by
src/js/components/TestButton.vue?vue&type=template&id=543aba30&lang.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
app.js
import Vue from 'vue/dist/vue'
import Buefy from 'buefy'
Vue.use(Buefy)
import ButtonTest from './components/TestButton.vue'
Vue.component('ssm-button', ButtonTest);
var app = new Vue({
el: '#app',
data: {
message: 'You loaded this page on ' + new Date().toLocaleString()
}
})
TestButton.vue
<template>
<div>
asdf
</div>
</template>
<script>
export default {}
</script>
rollup.config.js
'use strict'
const path = require('path')
const { babel } = require('#rollup/plugin-babel')
const banner = require('./banner.js')
const { nodeResolve } = require('#rollup/plugin-node-resolve')
import multi from '#rollup/plugin-multi-entry'
import vuePlugin from 'rollup-plugin-vue'
import replace from '#rollup/plugin-replace'
import commonjs from '#rollup/plugin-commonjs'
let fileDest = 'app.js'
const external = ['jquery']
const plugins = [
vuePlugin(),
replace({
preventAssignment: true,
'process.env.NODE_ENV': JSON.stringify( 'production' )
}),
babel({
// Only transpile our source code
exclude: 'node_modules/**',
// Include the helpers in the bundle, at most one copy of each
babelHelpers: 'bundled'
}),
nodeResolve(),
multi(),
commonjs(),
]
const globals = {
jquery: 'jQuery', // Ensure we use jQuery which is always available even in noConflict mode
'popper.js': 'Popper'
}
module.exports = [
{
input: [path.resolve(__dirname, '../js/app.js'), path.resolve(__dirname, '../js/custom.js')],
output: {
banner,
file: path.resolve(__dirname, `../../assets/js/${fileDest}`),
format: 'umd',
globals,
name: 'main-javascript'
},
external,
plugins,
},
]
I've tried a lot of different things, but nothing seems to help. However, if I load commonjs before vuePlugin in the config, I get a different error
[!] (plugin commonjs) SyntaxError: Unexpected token (2:4) in
/Users/xxx/Dev/self-storage-manager/wordpress_data/wp-content/themes/Bulmascores/src/js/components/TestButton.vue?vue&type=template&id=543aba30&lang.js
src/js/components/TestButton.vue?vue&type=template&id=543aba30&lang.js
(2:4) 1: 2:
^ 3: asdf 4:
Does anybody have an idea of what is going on? I've been working on this for the past two days now and really can't seem to find a solution.
Finally found a solution
I changed the rollup vue plugin from #rollup/plugin-vue to rollup-plugin-vue2 https://github.com/thgh/rollup-plugin-vue2 and now it works.

Module not founds: Can't resolve 'fs' from dependency packaged with rollup

my rollup config:
import babel from 'rollup-plugin-babel';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
const extensions = ['.js', '.jsx'];
export default {
input: 'src/index.js',
output: [
{
dir: 'lib/cjs',
format: 'cjs',
},
{
dir: 'lib/esm',
format: 'esm',
},
],
external: ['fs'], //i've tried with and without this
plugins: [
babel({
extensions,
exclude: 'node_modules/**',
}),
resolve(),
commonjs(),
],
};
and I bundle up a package that uses import fs from 'fs';
When I pack it as 'my-dep' and try to use it in another project as a dependency, using the cjs
const myDep = require("my-dep")
works but using esm
import myDep from 'my-dep'
throws an error
Module not found: Error: Cannot resolve module 'fs' in <path-to-my-project>/my-dep/lib/cjs

Categories

Resources