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.
Related
I'm testing replacing Webpack 5 with esbuild. How do you export globals in a bundle? I have a single dependency, jQuery, but I will have more in the future. My esbuild script is:
// build.js
const esbuild = require('esbuild');
esbuild
.build({
bundle: true,
entryNames: "[dir]/[name].[hash]",
entryPoints: {
libs: "src/libs.js",
},
outbase: "src",
outdir: "dist",
platform: 'browser',
})
.catch(() => process.exit(1));
And the libs.js that indicates dependencies to bundle is:
// src/libs.js
import 'jquery';
And here's my package.json:
{
// ...
"dependencies": {
"jquery": "~3.6.0"
},
"devDependencies": {
"esbuild": "^0.14.23"
},
// ...
}
Running the build script will properly bundle jQuery in dist/libs.{hash}.js but including this in a webpage via a script tag exposes neither window.$ nor window.jQuery. How do I get these to export?
In Webpack 5, I would use expose-loader to achieve this:
module.exports = {
module: {
rules: [
{
test: require.resolve('jquery'),
loader: 'expose-loader',
options: {exposes: ["$", "jQuery"]},
},
],
},
};
In order to get this to work with esbuild, you have to import an object from the module, and set the object on window. E.g.,
// Import module.
import * as module from 'module';
// Export module on window.
window.module = module;
jQuery exports the jQuery object as the default value. To export it as a global you have to do:
// Import jQuery.
import {default as jQuery} from 'jquery';
// Which can be shortened to.
import jQuery from 'jquery';
// Then export jQuery.
window.$ = jQuery;
window.jQuery = jQuery;
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,
},
};
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!
EDIT: I gave up with my own Webpack setup and just used react-scripts and now it compiles just fine. So must have been my Webpack/Babel setup, though still can't find out what
I'm trying to play around with the module effector, which has a React binding effector-react. I copy pasted a basic (working) code sandbox example, but I'm getting a webpack error which makes me think my build configuration isn't right.
My simple component is as follows:
import React from "react";
import { useStore } from "effector-react";
import { s_counter } from "stores/counter";
function Count () {
const counter = useStore(s_counter);
return ( <div>{counter}</div> );
};
export default Count;
and my effector counter store is as follows:
import { createStore, createEvent } from "effector";
// Store
const s_counter = createStore(0);
export { s_counter };
I think the issue is with my Webpack/Babel config, which are as follows:
webpack.config.js
const path = require("path");
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/src/dist',
publicPath: '/',
filename: 'bundle.js'
},
resolve: {
alias: {
components: path.resolve(__dirname, 'src/components/'),
stores: path.resolve(__dirname, 'src/stores/'),
},
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
I'm using webpack 4, and when I build by just running webpack my app doesn't load and I get the console error:
effector.es.js:35 Uncaught SyntaxError: Invalid or unexpected token
at Object../node_modules/effector/effector.es.js (bundle.js:109)
at __webpack_require__ (bundle.js:20)
at eval (effector-react.es.js:13)
at Module../node_modules/effector-react/effector-react.es.js (bundle.js:97)
at __webpack_require__ (bundle.js:20)
at eval (Count.jsx:4)
at Module../src/components/Count.jsx (bundle.js:311)
at __webpack_require__ (bundle.js:20)
at eval (App.jsx:4)
at Module../src/components/App.jsx (bundle.js:299)
The actual error is caused by importing things from effector-react, specifically this line:
import { useStore } from "effector-react";
doesn't matter what module I import from effector-react, I get that console error. Any ideas for what's going wrong are welcome.
EDIT: same kind of problem if importing from effector itself too
Tested on npm#6.4.1, webpack4.30.0 & node#10.13.0
Try this,
Did you download effector separately as a npm dependency.
I believe you are not able to resolve this module specifically.
I tried using the same modules using.
npm install effector
npm install effector-react
Adding the above two dependencies. It works fine.
Adding a sample of my module property from webpack
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}]
}
Hope this helps.
I am giving a try to Webpack, and am giving a try to the instructions in this tutorial, give or take a few custom things.
This is simple code, really, but I'm quite puzzled about this error, and feel this is something silly that I missed.
I defined two ES6 classes, each corresponding to a Handlebars template, and my app's entrypoint is supposed to replace the placeholder HTML in the index file by their contents:
Entrypoint:
import './bloj.less'
// If we have a link, render the Button component on it
if (document.querySelectorAll('a').length) {
require.ensure([], () => {
const Button = require('./Components/Button.js');
const button = new Button('9gag.com');
button.render('a');
}, 'button');
}
// If we have a title, render the Header component on it
if (document.querySelectorAll('h1').length) {
require.ensure([], () => {
const Header = require('./Components/Header.js');
new Header().render('h1');
}, 'header');
}
Index:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My title</h1>
<a>Click me</a>
<script src="build/bloj.js"></script>
</body>
</html>
Button:
import $ from 'jquery';
import './Button.less';
export default class Button {
constructor(link) {
this.link = link;
}
onClick(event) {
event.preventDefault();
alert(this.link);
}
render(node) {
const text = $(node).text();
var compiled = require('./Button.hbs');
// Render our button
$(node).html(
compiled({"text": text, "link": this.link})
);
// Attach our listeners
$('.button').click(this.onClick.bind(this));
}
}
Header:
import $ from 'jquery';
import './Header.less';
export default class Header {
render(node) {
const text = $(node).text();
var compiled = require('./Header.hbs');
// Render the header
$(node).html(
compiled({"text": text})
);
}
}
Sadly, it does not work, and I get both these errors when displaying the page:
Uncaught TypeError: Header is not a constructor
Uncaught TypeError: Button is not a constructor
What could I be missing?
Here is my webpack configuration:
var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractPlugin = require('extract-text-webpack-plugin');
var production = process.env.NODE_ENV === 'production';
var appName = 'bloj';
var entryPoint = './src/bloj.js';
var outputDir = './build/';
var publicDir = './build/';
// ************************************************************************** //
var plugins = [
//new ExtractPlugin(appName + '.css', {allChunks: true}),
new CleanPlugin(outputDir),
new webpack.optimize.CommonsChunkPlugin({
name: 'main',
children: true,
minChunks: 2
})
];
if (production) {
plugins = plugins.concat([
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.MinChunkSizePlugin({
minChunkSize: 51200 // 50ko
}),
new webpack.optimize.UglifyJsPlugin({
mangle: true,
compress: {
warnings: false // Suppress uglification warnings
}
}),
new webpack.DefinePlugin({
__SERVER__: false,
__DEVELOPMENT__: false,
__DEVTOOLS__: false,
'process.env': {
BABEL_ENV: JSON.stringify(process.env.NODE_ENV)
}
})
]);
}
module.exports = {
entry: entryPoint,
output: {
path: outputDir,
filename: appName + '.js',
chunkFilename: '[name].js',
publicPath: publicDir
},
debug: !production,
devtool: production ? false : 'eval',
module: {
loaders: [
{
test: /\.js/,
loader: "babel",
include: path.resolve(__dirname, 'src'),
query: {
presets: ['es2015']
}
},
{
test: /\.less/,
//loader: ExtractPlugin.extract('style', 'css!less')
loader: "style!css!less"
},
{
test: /\.html/,
loader: 'html'
},
{
test: /\.hbs/,
loader: "handlebars-template-loader"
}
]
},
plugins: plugins,
node: {
fs: "empty" // Avoids Handlebars error messages
}
};
What could I be missing?
Babel assigns default exports to the default property. So if you use require to import ES6 modules, you need to access the default property:
const Button = require('./Components/Button.js').default;
I realize that you already have an answer. However I had a similar issue to which I found an answer. Starting my own question and answering it seems weird.
So I'm just going to leave this here.
I had the same error as you got. However, I managed to solve it by changing my
export default {Class}
to
export default Class
I don't know why I wrapped the Class in an object but I remember having seen it somewhere so I just started using it.
So instead of the default returning a Class it returned an object like this {Class: Class}.
This is completely valid yet it will break webpack+babel.
EDIT: I've since come to know why this probably breaks babel+webpack. The export default is meant to only have 1 export. A javascript-object can contain many properties. Which means it can have more than 1 export. (See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export).
For multiple exports use: export {definition1, definition2}.
Use-case: I've used this in a situation where I've created a library which exported different types of an editor (while the underlying code was the same, the appearance of the editor changes depending on which export you use).
You can just put export var __useDefault = true; just after exporting your Class.
export default class Header {
...
}
export var __useDefault = true;
I was able to fix this by adding babel-plugin-add-module-exports to the .babelrc file
npm install babel-plugin-add-module-exports --save-dev
{
"presets": ["#babel/env"],
"plugins": ["add-module-exports"]
}
this adds
module.exports = exports.default;
to the last line when compiling the class with babel.
Although this is not the cause of your particular issue, I ran into a very similar problem when trying to rip babel out of an existing node app that was using ES6's import and export syntax, so this post is to help out anyone else struggling with this in the future.
Babel will resolve any circular dependencies between one module and another, so you can use ES6's import and export with reckless abandon. However, if you need to get rid of babel and use native node, you will need to replace any import and exports with require. This can reintroduce a latent circular reference issues that babel was taking care of in the background. If you find yourself in this situation, look for an area in your code that looks like this:
File A:
const B = require('B');
class A {
constructor() {
this.b = new B();
}
}
module.exports = A;
File B:
const A = require('A'); // this line causes the error
class B {
constructor() {
this.a = new A();
}
}
module.exports = B;
There are several different ways to resolve this issue depending on how you structured your code. The easiest way is probably to pass B a reference to A instead of creating a new instance of class A. You could also dynamically resolve the reference when loading A. There are a myriad of other alternatives, but this is a good place to get started.
It's not the problem in this particular question, but for some reasons, babel does not hoist classes in the same file.
So if you declare your class Token at the top of the file, and write later new Token(), it will run.
If you declare your class after the constructor call, you will have the xxx is not a constructor error
I had the same error message and discovered that the cause was circular import statements. That is: I had two files that imported each other, wherein one file contained an export default class that contained a method that was dependent upon an export function from the other file.
My solution was to move one of the dependencies (functions) out of the class and into a utils.js file, which was a more appropriate place for it anyway!
This is the way I am using / importing my classes:
Utils.class.js
export default class Utils {
somefunction(val) {
return val
}
}
Using Utils into my controllers:
import {default as U} from '../helpers/Utils.class';
const Utils = new U();
console.log(Utils.somefunction(123));