This question already has answers here:
Importing an external module in TS causes "ReferenceError: require is not defined"
(2 answers)
Closed 6 years ago.
I have 3 typescript files: main.ts, print.ts, log.ts
I installed node modules and used typescript compiler - tsc main.ts - to compile .ts files.
After that, I tried to run index.html with npm start, but console.log says require is not defined. Am I still missing something? I use Visual Studio Code editor.
INDEX.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this is the title</title>
<style type="text/css">
</style>
</head>
<body>
<div id="wrapper">
</div>
<script type='text/javascript' src='main.js'></script>
</body>
</html>
MAIN.TS
import log = require('./log')
import print = require('./print')
log.logMessage();
print.printMessage();
PRINT.TS
export function printMessage() {
console.log('print');
}
LOG.TS
export function logMessage() {
console.log('log');
}
Console.log should say 'log' and 'print', but it doesn't.
Your code is fine. The important part of your question is
but console.log says require is not defined
require is used in node's module system, called CommonJS. Browsers do not understand this system by default. You have to use a bundler, like webpack or fuse-box
TypeScript can not really bundle your application :-/
Related
For some reason, I find myself in a situation where I need to compile one file (main entry point), which depends on multiple other modules in other files, into a single-bundle-file. It must be able to run in the browser.
I must use the TypeScript compiler, and only that tool (i.e. not Webpack, Babel, etc.).
I am currently compiling using the --outFile option with --module set to either System or AMD (which are the only ones allowed for --outFile).
For System, something along the lines of the following gets generated:
[some more modules ...]
System.register("index", [...], function (exports, context) {
[...]
});
When I try to stick this in an HTML file like this:
<!doctype html>
<html>
<head>
<title></title>
<meta content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/6.1.7/system.js"></script>
</head>
<body>
<script>
[some more modules ...]
System.register("index", [...], function (exports, context) {
[...]
});
System.import("index").then(function (m) {
new m.run();
});
</script>
</body>
</html>
I get:
Error: Unable to resolve specifier 'index' from [...]
What am I doing wrong with System?
Also, which is better for my purpose? AMD or System?
I am just getting started with TypeScript (and front end development in general) coming from a c# background so sorry if this is a really basic question, but I can't figure out where I'm going wrong...
What I'm trying to do for now is create a really basic program to retrieve some sample data from a url in JSON format, parse to TS classes, and display it on the page.
In order to get the json response I found this answer that recommends using a node package. I got it installed and it seems to be ok (at least TS doesn't give me any errors).
I also figured out that I need to compile (not sure if that's the right term?) with Browserify to make it browser compatible since it's using a node module. I did that but now when I try to run in a browser it's telling me my method is not defined.
export class Keynote {
KeyValue: string;
Description: string;
Parent: string;
}
Retrieval class is:
import {Keynote} from "./Keynote";
import * as request from "request-promise-native";
function GetKeynotes(): Array<Keynote> {
const baseUrl = 'https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteProvider.php';
var options = {uri: baseUrl};
const result = JSON.parse(request.get(options));
return result;
}
and html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Keynotes Testing</title>
<script src="bundle.js"></script>
<script>
function Retrieve() {
var notes = GetKeynotes();
document.getElementById('container').innerText = JSON.stringify(notes);
}
</script>
</head>
<body>
<div>
<button content="Get some notes" onclick="Retrieve()">Get some notes</button>
</div>
<div id="container">
</div>
</body>
</html>
Browserify is really long so I didn't want to copy here but you can see it at https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteDisplay.html in the source if you want.
When I click the button I get this error in the browser:
KeynoteDisplay.html:9 Uncaught ReferenceError: GetKeynotes is not defined
at Retrieve (KeynoteDisplay.html:9)
at HTMLButtonElement.onclick (KeynoteDisplay.html:16)
Retrieve # KeynoteDisplay.html:9
onclick # KeynoteDisplay.html:16
GetKeynotes is defined in my typescript, and on the 5th line of bundle.js I see a function with that name... Why is it undefined?
UPDATE
Ok I have played with jspm and SystemJs but I still don't have something right. I referenced the module with jspm and did a bundle to build.js and uploaded the whole thing just to make sure everything is there. Here are the tags in my html for scripts:
<script src="../../jspm_packages/system.js"></script>
<script src="../../config.js"></script>
<script src="build.js"></script>
<script>
System.import("Sandbox/TypeScript/build.js")
function Retrieve() {
System.import("Sandbox/TypeScript/build.js")
var notes = GetKeynotes();
document.getElementById('container').innerText = JSON.stringify(notes);
}
</script>
When I press the button I can debug in my function, but it still gives the error, 'GetKeynotes is not defined' just like before... Again I can see a function with that name in the build.js file so I don't understand why it's not finding it.
I also tried System.import("Sandbox/TypeScript/KeynoteRetrieval.js") but it gives the error:
Uncaught (in promise) Error: (SystemJS) Node tls module not supported in browsers.
Error loading https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteRetrieval.js
I'm trying to port my JavaScript source code to JavaScript ES6. To acomplish this I have so far:
1) installed Babel to my project folder
2) created .babelrc file
3) defined the file watcher in my WebStorm to auto transpile JavaScript files.
Transpiling seems to work well, the "older" syntax JavaScript files get created in a dist folder. However, when I try to run my transpiled code (added in a .html file) the alert test doesn't show up when using import statement.
Here's the source code:
arquivo.js
let test = 'Alert from Arquivo.js';
export {test};
main.js
import {test} from "./arquivo";
alert(test);
After auto transpile:
arquivo.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var test = 'Alert from Arquivo.js';
exports.test = test;
//# sourceMappingURL=arquivo.js.map
main.js
"use strict";
var _arquivo = require("./arquivo");
alert(_arquivo.test);
//# sourceMappingURL=main.js.map
This is my index.html file inside same transpiled JavaScript files folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<!--
main.js is the after
transpiled code
-->
<script src="main.js"></script>
</head>
<body>
</body>
</html>
Browser console reports this:
Uncaught ReferenceError: require is not defined
at main.js:3
How to avoid this problem?
The following Angular application is working correctly, but I need to achieve some requirements that don't depend on me:
GitHub Repo: git#github.com:napolev/napolev.pr02.git
[1] need to move: main.ts from: /src/ to: /src/app/
[2] need to get rid of the file: tsconfig.app.json.
Probably this file is partially referenced on the file: .angular-cli.json (with ext: .spec.json instead of: .app.json, why?)
I tried to remove it but then I get a build error:
> ng build
ENOENT: no such file or directory, stat 'D:\wamp64\www\ionic2\cli-angular-counter\src\tsconfig.app.json'
Error: ENOENT: no such file or directory, stat 'D:\wamp64\www\ionic2\cli-angular-counter\src\tsconfig.app.json'
at Error (native)
at Object.fs.statSync (fs.js:987:18)
at AotPlugin._setupOptions (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#ngtools\webpack\src\plugin.js:58:16)
at new AotPlugin (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#ngtools\webpack\src\plugin.js:26:14)
at _createAotPlugin (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\models\webpack-configs\typescript.js:55:12)
at Object.exports.getNonAotConfig (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\models\webpack-configs\typescript.js:70:19)
at NgCliWebpackConfig.buildConfig (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\models\webpack-config.js:27:37)
at Class.run (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\tasks\build.js:26:92)
at Class.run (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\commands\build.js:143:26)
at Class.<anonymous> (D:\wamp64\www\ionic2\cli-angular-counter\node_modules\#angular\cli\ember-cli\lib\models\command.js:134:17)
at process._tickCallback (internal/process/next_tick.js:103:7)
One question:
[3] For the rendered html file, where is specified the inclusion of the following files?
inline.bundle.js
polyfills.bundle.js
vendor.bundle.js
main.bundle.js
This is the rendered code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular Counter</title>
</head>
<body>
<app-root>Loading...</app-root>
<script type="text/javascript" src="inline.bundle.js"></script>
<script type="text/javascript" src="polyfills.bundle.js"></script>
<script type="text/javascript" src="vendor.bundle.js"></script>
<script type="text/javascript" src="main.bundle.js"></script>
</body>
</html>
Please, if possible, use the reference numbers above (inside square brackets) in your answers. If possible maybe you could provide me the modified code?. I tried to put this code on: plnkr.co/edit/ with no success.
[EDIT]
I solved the points [1] and [2] by doing the following changes:
http://github.com/napolev/napolev.pr02/commit/068d0884e360a2ec438032f209601b6b26ec5398
going from: [Commit 1] to [Commit 2][2], but now the lint test tool doesn't work properly because it doesn't detect a violation of a tslint.json declared rule. For example,
https://github.com/napolev/napolev.pr02/blob/068d0884e360a2ec438032f209601b6b26ec5398/src/app/counter.component.ts#L55
There you can see a line with a tab character (illegal based on my declared rules on the tslint.json file). On the previous commit it would be detected.
How can I make the lint tool work again?
I am trying to use express-babelify-middleware
with FeathersJS and the error shows up in the browser console:
ReferenceError: main_run is not defined
I take this to mean that babelify is not working or I am using it incorrectly as main_run is in the global namespace of the src in my html file.
Here is my setup using the structure from feathers generate:
public/index.html:
<!DOCTYPE html>
<html>
<head>
<title>babelify test</title>
<script src="main.js"></script>
<script>
main_run()
</script>
</head><body>
<p>Testing feathers with babelify</p>
</body></html>
public/main.js
const external_module = require('./test')
function main_run(){
external_module()
}
public/test.js
module.exports = function(){
console.log("Hello world for an external module")
}
among the .uses of src/app.js:
...
const babelify = require('express-babelify-middleware')
...
app.use(compress())
.options('*', cors())
.use(cors())
//the line that is not working:
.use('/main.js', babelify( path.join(app.get('public'), 'main.js') ))
.use(favicon( path.join(app.get('public'), 'favicon.ico') ))
.use('/', serveStatic( app.get('public') ))
When I visit localhost:3030/main.js I can see the file, but the functions look to be in a function of their own, so I don't know how to get into that function.
Silly problem, one can't access browserified code in the html file that calls it. So public/index.html can't access main_run unless it is attached to the window object. There is a similar question
here.
Other than that, my code works perfectly.
In main.js place the following code at the bottom:
window.main_run = main_run
Then in index.html replace the main_run() line with:
window.main_run()
This will write the contents of test.js to the console.