How to dynamically bundle module/object in RollupJs output? - javascript

How can I dynamically bundle a module/object into my RollupJs output file? I have tried a ton off different options but can not get the expected output I am looking for.
I put together a short sample project below to help illustrate what I am looking for. The expected output should print "Hello John Doe" from the overrideApp object that is dynamically injected as a dependency.
src/app.js
export default {
sayHello: function() {
console.log('Hello Mr.Roboto')
},
sayGoodBye: function() {
console.log('Goodbye Mr.Roboto')
}
}
index.js
import app from './src/app.js'
import overrideApp from 'overrideApp'
export default { ...app, ...overrideApp }.sayHello()
.rollup.config.js
let overrideApp = {
sayHello: function() {
console.log('Hello John Doe')
}
}
export default [
{
input: 'index.js',
external: ['overrideApp'], // This is not working, expecting to pass overrideApp to index.js
output: {
file: './dist/app.js',
format: 'umd',
name: 'bundle',
}
}
]

This is totally correct your mixing here a lot of stuff together that does not work together.
You are looking for a virtual module
Install
npm install #rollup/plugin-virtual --save-dev
Usage
Note. Use this plugin before any others such as node-resolve or commonjs, so they do not alter the output.
Suppose an entry file containing the snippet below exists at src/entry.js, and attempts to load batman and src/robin.js from memory:
// src/entry.js
import batman from 'batman';
import robin from './robin.js';
console.log(batman, robin);
Create a rollup.config.js configuration file and import the plugin:
import virtual from '#rollup/plugin-virtual';
export default {
entry: 'src/entry.js',
// ...
plugins: [
virtual({
batman: `export default 'na na na na na'`,
'src/robin.js': `export default 'batmannnnn'`
})
]
};
https://github.com/rollup/plugins/edit/master/packages/virtual

Related

How to integrate Javascript library in Laravel9 with Vue using Laravel Mix

new to all these modern day frameworks
I'm trying to get this javascript library to work in my Vue component: https://clipboardjs.com
I can see it is integrated into my public/js/app.js file when Mix runs - but I cannot seem to be able to reference it from within my .vue (component) file
Can anyone give me a step by step guide on how to get this to integrate into my project please:
resources/js/app.js file
import './clipboard';
the clipboard.js file is located at:
resources/js/clipboard.js
Mix webpack.mix.js file:
mix.js("resources/js/app.js", "public/js")
.js("resources/js/clipboard.js", "public/js")
.vue()
.postCss("resources/css/app.css", "public/css", [
require("tailwindcss"),
]);
My Vue component (method section):
<script>
export default {
props: ['mediaDetails'],
data() {
return {
}
},
methods: {
copyPassword() {
alert("copy");
var password = document.getElementById('#password');
alert('1');
var clipboard = new ClipboardJS(password);
alert('2');
}
}
the alert('2') never fires due to the clipboard assignemnet failing
First, in your webpack.mix.js file, remove the line .js("resources/js/clipboard.js", "public/js")
Install the clipboard package: npm install clipboard
In your Vue component, import the package in order to use it:
<script>
import ClipboardJS from 'clipboard';
export default {
props: ['mediaDetails'],
data() {
return {
}
},
methods: {
copyPassword() {
alert("copy");
var password = document.getElementById('#password');
alert('1');
var clipboard = new ClipboardJS(password);
alert('2');
}
}
BTW You have a typo error in document.getElementById('#password'), it should be document.getElementById('password')

import QRCode constructor for Javascript through webpack

I want to use the QRCode generator from this repo: https://github.com/davidshimjs/qrcodejs
How do I import the QRCode through webpack? When I installed qrcodejs through npm the index.js contained this code module.exports = 'qrcodejs'; When I use require('qrcodejs'); in my code it returns the string 'qrcodejs', but I want to import the QRCode constructor through webpack. I want to be able to call the constructor in my code like so, after importing it with webpack.
let qrcode = new QRCode("output", {
text: "http://google.com",
width: 100,
height: 100,
colorDark: "#188710",
colorLight: "#ffffff"
});
What do I have to do to accomplish this? I am using ES6 Javascript without any frameworks or other libraries, besides webpack.
UPDATE
index.js inside the qrcodejs folder
module.exports = {
module: {
rules: [
{ test: /qrcode/, loader: 'exports-loader?QRCode' }
]
}
}
myproject.js
import { QRCode } from 'qrcodejs'
export class EditProduct {
openProduct(){
let test = require('qrcodejs'); // returns the module object with the rules array
let test2 = QRCode // returns undefined
}
}
Just as Raz Ronen said, install export-loader.
This will allow us to introduce non-modular js to Webpack.
After installing add the QRCode module as:
import QRCode from 'exports-loader?QRCode!qrcodejs/qrcode'
based on the answer here
Use export-loader to make module.export = <anything you want>
basiclly what you want is to have qrcode.min.js module.export return QRCode.
You can define a rule for it:
module: {
rules: [
{ test: /qrcode/, loader: 'exports-loader?QRCode' }
]
}

Gatsby.js - Typography themes

I'm creating an application based on gatsby framework, but I have problem with initialize gatsby theme. From official documentation:
https://www.gatsbyjs.org/tutorial/part-three/
import Typography from 'typography';
import fairyGateTheme from 'typography-theme-github';
const typography = new Typography(fairyGateTheme);
export const { scale, rhythm, options } = typography;
export default typography;
But typography-theme-github import has dotted underline when I hovered mouse on it I have got this tip:
Could not find a declaration file for module 'typography-theme-github'. '/Users/jozefrzadkosz/Desktop/hello-world/node_modules/typography-theme-github/dist/index.js' implicitly has an 'any' type.
Try npm install #types/typography-theme-github if it exists or add a new declaration (.d.ts) file containing declare module 'typography-theme-github';ts(7016)
When I run gatsby develop I'm getting this error:
Error: Unable to find plugin "undefined". Perhaps you nee d to install its package?
EDIT
I have looked on this file node_modules/typography-theme-github/dist/index.js and I found one similar issue:
var _grayPercentage = require("gray-percentage");
This require has exactly same tip as my theme import.
SECOND EDIT
Gatsby.config.js
module.exports = {
plugins: [
[`gatsby-plugin-sass`],
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography`
}
}
]
};
I notice you placed gatsby-plugin-sass in an array, which is why gatsby didn't recognize it:
module.exports = {
plugins: [
- [`gatsby-plugin-sass`], <-- error
+ `gatsby-plugin-sass`,
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography`
}
}
]
};
This is probably not a problem with gatsby-plugin-typography.

typescript: resolving typeahead.js with typescript and webpack 2

I am getting the following error from webpack.
ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts
Module not found: Error: Can't resolve 'typeahead' in ...
I have the following installed
npm install typeahead.js
npm install #types/typeahead
My typescript is as follows, using node module resolution.
import { module } from "angular";
import "typeahead";
// necessary to import typeahead into JQuery, as otherwise
// typeahead below is not defined.
class TypeAheadController {
foo(e) {
$(e).typeahead(...)
}
}
this generates javascript as follows:
"use strict";
var angular_1 = require("angular");
require("typeahead");
var TypeAheadController = (function () { ...
My webpack.config.js is as follows:
module.exports = {
context: __dirname,
entry: [
"./app.ts",
"./tab.ts",
"./client/clientService.ts",
"./client/clientSearchComponent.ts",
"./infrastructure/messageComponent.ts",
"./infrastructure/typeaheadComponent.ts",
"./url.ts"],
output: {
filename: "./wwwroot/js/admin/admin.js"
},
devtool: "source-map",
module: {
rules: [
{ test: /\.ts$/, use: 'ts-loader' }
]
}
};
imported into a gulp task.
How do I specify that typeahead is located in node_modules/typeahead.js/dist/typeahead.bundle.js
The module is called typeadhead.js so you also need to import typeahead.js, not typeahead.
import "typeahead.js";
The import is always the same as the name you use to install it with npm. And it's not even special, it simple looks into node_modules and finds the directory with the given name. Then it looks into package.json and imports the file specified in the main field. See also Node.js - Folders as Modules.
You could use resolve.alias to change the name of the import, but there is not really a good reason for doing that in this case.
I resolved this by making the following changes.
You need to import Bloodhound and Typeahead seperately. To do this edit your webpack.config.js
resolve: {
extensions: ['.js', '.ts'],
alias: {
typeahead: 'corejs-typeahead/dist/typeahead.jquery.min.js',
bloodhound: 'corejs-typeahead/dist/bloodhound.min.js'
}
},
And then in your .ts file:
import "typeahead";
import * as Bloodhound from "bloodhound";
You could solve this using aliasing. Minimal example of what to change in your webpack.config.js:
module.exports = {
/* ... everything you currently have */
resolve: {
alias: {
typeahead: 'typeahead.js'
}
}
}

How do I create a webpack import alias in React Static Boilerplate?

I have the following import:
// cwd: /project/pages/blog/category/red/index.js
import PageHeader from '../../../components/PageHeader';
And I want to be able to write it this way (anywhere in my project):
// cwd: /project/pages/blog/category/red/index.js
import PageHeader from 'components/PageHeader';
I've tried using webpack resolve option but I can't seem to make it work:
config.resolve = {
alias: {
components: [
path.resolve('../components/')
]
}
};
and
config.resolve = {
root: [
path.resolve('../')
]
};
Am I missing something ?
My app architecture is forked from React Static Boilerplate, so my webpack.config.js looks like this one
config.resolve = {
alias: {
components: path.resolve('../components/')
}
};
alias accepts key value pairs, with value being of type string. I am not sure if it works with array.
To answer more specificly it would good to know where PageHeader and your webpack config is:
assuming:
PageHeader is in /project/pages/components
and your webpack config is at the root level /project
then your resolve would look something like this:
config.resolve = {
alias: {
components: path.resolve('./pages/components')
}
};
again it depends on the path to your webpack config and your components directory. The path.resolve will change corresponding to that.
The problem seems related to React Static Boilerplate, more specifically when the building the static pages.
I found a workaround that does the job for now. I had to prepend a ~ to the alias so it doesn't get "treated" as a node_module..
config.resolve = {
alias: {
"~components": path.resolve(__dirname, '../components'),
"~decorators": path.resolve(__dirname, '../core/scripts/decorators'),
"~helpers": path.resolve(__dirname, '../core/scripts/helpers'),
"~i18n": path.resolve(__dirname, '../core/i18n'),
}
};
Usage:
import fetch from '~helpers/fetch';
import header from '~components/header';
More info about this on this Github issue.

Categories