Webpack dynamic require throwing error - javascript

I have the following piece of code that works well:
require.ensure(['./core/sample-form.js'], require => {
require('./core/sample-form.js');
});
Now if I put that string into a variable:
const ajaxJs = './core/sample-form.js';
require.ensure([ajaxJs], require => {
require(ajaxJs); // eslint-disable-line import/no-dynamic-require
});
It throws the following error:
Uncaught (in promise) Error: Cannot find module "." at webpackMissingModule
Is there any way I can use a variable for that require?

Take a look at Webpack's Context Module.
Apparently, when you attempt to dynamicly require a module, Webpack will try to parse the input expression to a context.
Try the following code (haven't tested this):
const ajaxJs = './sample-form.js';
core = require.context('./core', true, /^\.\/.*\.js$/);
require.ensure([], () => {
core(ajaxJs);
});

Webpack can't figure out which modules to bundle when the name is dynamic variable. You can't use variable name in require. You'll have to do something like :
require.ensure(['./core/sample-form.js'], require => {
require('./core/sample-form.js'); // eslint-disable-line import/no-dynamic-require
});
This answer can help.

Related

I cannot fix this error: Uncaught ReferenceError: module is not defined

I am exporting my js file, so I can use import into my unit test file. Here is my js file:
function getComputerChoice() {
//stuff here
}
function playRound(playerSelection, computerSelection) {
//stuff here
}
function game() {
// stuff
}
module.exports = {
getComputerChoice,
playRound,
game,
};
And in my test file, I am importing it this way:
const rockPaperScissors = require('../rockPaperScissors');
test('Verify the case for tie', () => {
expect(rockPaperScissors.playRound('rock', 'rock')).toBe('TIE');
});
test('Verify the case for win', () => {
expect(rockPaperScissors.playRound('rock', 'scissors')).toBe('WIN');
});
test('Verify the case for lose', () => {
expect(rockPaperScissors.playRound('rock', 'paper')).toBe('LOSE');
});
The only way I can get my test file to work, is by exporting in the above format, but when I run the index.html in for this page, I see Uncaught ReferenceError: module is not defined.
require and module.exports are part of the CommonJS module system which is Node.js' default module system.
Browsers have no support for CommonJS so if you want to use code written using it you will need to convert it to a format that browsers do support. Typically this is done using a bundler such as Webpack or Parcel.
Browsers do support standard JavaScript modules (so long as you load them with <script type="module">) which use import and export so you could also rewrite your modules to use that.

Rendering a twig template in a Chrome extension

I'm trying to render a twig (with twigjs) template within a chrome extension. I'm currently compiling the following typescript with a browserify build script.
import * as twig from "twig"
const MAIN_TEMPLATE: string = chrome.runtime.getURL("twig/main.html.twig");
document.addEventListener("DOMContentLoaded", () => {
twig.renderFile(MAIN_TEMPLATE, (err: Error, html: string) => {
document.querySelector("body").innerHTML = html;
});
});
I've made sure to include the files in my manifest.json, as such.
...
"web_accessible_resources": [
"twig/*.html.twig"
]
...
However, upon running this, I get the following stacktrace. I'm not really sure what to do, as the URL that chrome.runtime.getURL returns does resolve if I punch it into my address bar.
Uncaught TypeError: t.stat is not a function
at Object.<anonymous> (twig.js:1)
at Object.e.Templates.loadRemote (twig.js:1)
at Object.e.exports.twig (twig.js:1)
at Object.e.exports.renderFile (twig.js:1)
at HTMLDocument.<anonymous> (browser-action.ts:7)
Digging through some of the twigjs source code, it looks like it was a mistake of mine to use the renderFile helper. This is more correct.
const MAIN_TEMPLATE_URI: string = chrome.runtime.getURL("twig/main.html.twig");
const MAIN_TEMPLATE: twig.Template = twig.twig({href: MAIN_TEMPLATE_URI, async: false};
document.querySelector("body").innerHTML = MAIN_TEMPLATE.render({tabs, tabListTemplate: TAB_LIST_TEMPLATE_URI});
I used async false since it's only going to be getting from a local connection, so there really shouldn't be any lag loading the template synchronously.

Dojo Build System - using async plugin with google maps api

I'm trying to build a dojo app and am encountering one error that I can't seem to fix.
The app runs without error unbuilt and I am trying to use the Dojo Build System to optimize the files into one layer.
The error is related to the following import:
define([
'plugins/async!//maps.google.com/maps/api/js?v=3'
//...
The error is
error(308) Failed to evaluate AMD define function.
module: gis/dijit/StreetView; text:
'gis/plugins/async!
error: SyntaxError: Unexpected token ILLEGAL
error(352) Optimizer reported errors; consult build report for details.
The async plugin looks something like this:
define(function () {
var cb = '_asyncApiLoaderCallback';
return {
load: function (param, req, loadCallback) {
if (!cb) {
return;
} else {
window.dojoConfig[cb] = function () {
delete window.dojoConfig[cb];
cb = null;
loadCallback();
};
require([param + '&callback=dojoConfig.' + cb]);
}
}
};
});
The solution to this problem was to switch to the google maps loader from bower/npm.
https://github.com/Carrooi/Js-GoogleMapsLoader
The dojo build system appears to treat the // in the path like a comment, which makes paths like
'my/plugin!http://www.google.com'
show up as
'my/plugin!http:
This causes an error because everything after the // is a comment now and there's no apostrophe.. In addition the path www.google.com is obviously missing.

How to properly load local AMD modules with jspm/system.js

I am having a really hard time using local AMD modules in an Aurelia project that uses es6, JSPM, and system.js. I am hoping someone out there can help me configure my project to enable me to import/load my AMD modules and use them in my project. The local AMD style modules are in a format similar to the following:
define
(['require',
'lib/alerts/STARTSTOP',
'lib/alerts/STOPPED',
...
],
function( require, STARTSTOP, STOPPED, ... ) {
return {
alert: function( data ) {
var type = data.type;
var ev = data.event;
var cls = require( 'lib/alerts/' + ev );
return new cls( data );
}
};
});
When I try to import/load this module into an es6 module I am running into the following error: Uncaught TypeError: Unexpected anonymous AMD define.. I get this error when trying to load the module in either of the following ways:
System.import('lib/alerts/AlertFactory').then( (m) => {
console.log( m );
});
or
import AlertFactory from 'lib/alerts/AlertFactory.js';
I have also made sure to add the following script to my index.html:
<script>
window.define = System.amdDefine;
window.require = window.requirejs = System.amdRequire;
</script>
In addition to the above I have also added a meta format property to my config.js file, but that hasn't seemed to help either.
meta: {
...
"lib/alerts/*.js": {
"format": "amd"
}
}
Does anyone have any ideas on why I am running into the error I am seeing and how to properly load my modules? I appreciate any help/insight you can offer.
UPDATE
I finally realized that the main issue here is that I'm trying to use existing AMD modules in and Aurelia project, and the default Aurelia gulp build assumes that all code is written in ES6 and not mixed with AMD. That's why I'm having issues. Vanilla jspm/system.js handle a mix of module formats, but Aurelia does not out of the box.
Just put your AMD modules out of src so babel will not be able to transpile it. Here is working solution I use to import jquery modules:
First, I have local_packages folder in project root and I have jquery module local_packages/somelib/js/mymodule.js
Then in config.js
paths: {
...
"local/*": "local_packages/*",
}
map: {
...
"somelib": "local/somelib",
"somelib1": "/local_packages/somelib1",
}
And finally my import looks like: import 'somelib/js/mymodule';

Importing other .js files in Buster.js tests

I'm making my first attempt at Javascript testing, with Buster.js
I've followed the instructions at the Buster site to run "states the obvious" test. However, I haven't been able to import any of my existing .js files into the tests.
For instance, I have a file js/testLibrary.js, containing:
function addTwo(inp) {
return inp+2;
}
and a file test/first-test.js, containing:
// Node.js tests
var buster = require("buster");
var testLibrary = require("../js/testLibrary.js");
var assert = buster.referee.assert;
buster.testCase("A module", {
"Test The Library": function() {
result = addTwo(3);
console.log(result);
assert(true, 'a message for you');
}
});
Running buster-test gives:
Error: A module Test The Library
ReferenceError: addTwo is not defined
[...]
Replacing result = addTwo(3); with result = testLibrary.addTwo(3); gives:
Error: A module Test The Library
TypeError: Object #<Object> has no method 'addTwo'
[...]
I'm probably missing something really basic, but at present, I'm completely stumped. Can someone point me in the right direction?
That is because you are not exporting this function from the module.
Take a look at that:
http://nodejs.org/api/modules.html#modules_module_exports

Categories

Resources