I have javascript functions I want to run both server-side and client side. The server side uses node.js
and can handle imports just fine.
However, the client side i want a single script tag with inlined javascript. To achieve that goal I understood that I needed a bundler to pull the modules into the main script file. I chose rollup to do that job.
Here's an example of what I've tried. I've made a module test.js
. it's a simple function that returns a string:
// test.js
const test = () => {
return 'testing'
}
module.exports = test
and here's the main javascript file, main.js
. The file I want to pull the test.js
function into:
// main.js
import test from "/test.js"
console.log(test())
Here's what i'd like main.js
to look like after bundling:
// main.js
const test = () => {
return 'testing'
}
console.log(test())
I'd like to simply pull the function into the file.
Instead rollup produces this:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../../../../../../js/test.js')) :
typeof define === 'function' && define.amd ? define(['../../../../../../../js/test'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.test));
}(this, (function (test) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var test__default = /*#__PURE__*/_interopDefaultLegacy(test);
console.log(test__default['default']());
})));
The code is much larger than before, and crucially the module isn't incorporated into the main file. It's still a module, but with different syntax. Rollup has a number of output options, all produce similar results.
Here's my rollup.config.js
file:
// rollup.config.js
export default [
{
input: 'src/scripts/main.js',
output: {
name: 'main',
file: "public/scripts/main.js",
format: 'umd'
}
}
]
Of course, this is the expected output for somebody who understands what's going on. But I don't understand.
How do I merge a javascript into one file at build time?
is there a simpler solution I'm overlooking?
Edit: Using the commonjs
module and setting the output format to iife
results in the following:
// main.js
(function (test) {
'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var test__default = /*#__PURE__*/_interopDefaultLegacy(test);
console.log(test__default['default']());
}(test));
It's different, but the result still doesn't contain the test function.