Edit - Answer: encapsulating the imports work as required:
# index.js
var myLibrary {
ProfileApp: require('./components/ProfileApp.react'),
ProfileStore: require('./stores/ProfileStore'),
}
module.exports = myLibrary;
I can now do
var lib = require('myLibrary');
var ProfileApp = lib.ProfileApp;
End of edit
I have developped a react/flux libray which I need to package using webpack. I do this for the first time and my exports seem wrong... (the library itself works well).
My (simplified) index.js file is
# index.js
module.exports = require('./components/ProfileApp.react');
module.exports = require('./stores/ProfileStore');
...
The code is correctly compiled and installed in node_modules, but does not work when imported.
# whatever.file.doing.imports
var myLibrary = require('myLibrary'); # works well
var ProfileApp = myLibrary.ProfileApp; # works only if I call it --> myLibrary.ProfileApp()
var ProfileStore = myLibrary.ProfileStore; # does not work and myLibrary.ProfileStore() raises "is not a function error"
I think my exports in index.js should use another syntax. For instance, React Router (https://github.com/rackt/react-router/blob/master/modules/index.js) uses
export Router from './Router';
# which can be simply instantiated writing
var Router = ReactRouter.Router;
This syntax raises an error when used in my library. Do you know if I have to use plugin to be able to use this syntax, or if I can write it differently?
Thank you very much!
The special export syntax that React Router uses is from ES6 and is "transpiled" by the Babel loader that you see in use in the webpack config on line 23. Also note that that line only applies to files that have a ".js" extension. Since you have files with ".react" extensions, you may need to change that line.
Unfortunately that does not explain your issue with having to call ProfileApp as a function. Maybe if you posted the code for the ProfileApp and ProfileStore, that would help.
Related
We are trying a POC of adding Typescript and Webpack to our Angularjs project.
I am able to get my webpack bundle to generate, however at runtime the program cannot find the various functions in my validator.js. Can you please offer some advice?
login-view.components.ts
declare var findFormNode: any; //function in validator.js
//LogInUser
self.login = function ($event, command) {
if (findFormNode($event.target.id)) {
...
}
}
main.ts is importing the file
import "./../../../CommonStaticFiles/include/js/Validators.js";
bundle.js
eval("/* WEBPACK VAR INJECTION */(function($) {/*\r\n\r\n VALIDATORS\r\n\r\n ... n\n\nfunction findFormNode(
error
ReferenceError: findFormNode is not defined
at LoginController.self.login (login-view.component.ts:28)
at fn (eval at compile (angular.js:NaN), <anonymous>:4:267)
at callback (angular.js:29019)
In order for your functions to be properly imported, there are few things that you have to make sure of.
First, make sure you are exporting your functions correctly. Here's an example of how to export a function from Validator.js:
export const validateFunc1 = ():void => {};
Next, you have to make sure you are using proper import syntax. In order to import the function above, you would do the following:
import {validateFunc1} from "./../../../CommonStaticFiles/include/js/Validators.js";
Alternatively, if you want to import all exported functions at once, then you can use this syntax:
import * as validatorFuncs from "./../../../CommonStaticFiles/include/js/Validators.js";
Lastly, check that the location of Validators.js is correct. It's a common mistake to be looking in the wrong directory. Your code editor can usually help you find the right path to use.
So I have a node module which seems to use a versioning system. Using nodejs I simply used
const Package = require('package-name').V1;
which worked without issues. Typescript however does not like the .V1 so I use
import { Package } from 'package-name';
which complies fine but the typescript output to javascript is
const package_name_1 = require("package-name");
Which means that any function or properties of package_name_1 are undefined since the module doesn't seem to load V1.js file (i assume that is how it works..)
So I tried
import * as Package from 'package-name';
But it outputs the same javascript as before..
The actual folder structure of the package I am using is
-node_modules
--package-name
---client
----v1
----v1.js
with the v1.js file looking like
var PackageV1 = {}
PackageV1.CONSTANTS = require('./v1/constants');
PackageV1.Request = require('./v1/request');
PackageV1.Session = require('./v1/session');
...
module.exports = PackageV1;
Of course things like
const Package = require('package-name.V1');
do not work
Error: Cannot find module 'package-name.V1'
How can I require this V1.js file / directory using the typescript method?
As was hinted at in the comments
import * as Package from 'package-name';
is fine but when using the package I had to use
Package.V1.Request()
rather than
Package.Request()
Is it not possible to access already 'built' components within the html file that the build is linked to?
I am trying the following -
In bundle.js
var React = require('react');
var ReactDOM = require('react-dom');
var Titles = React.createClass({
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
});
In my html page -
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<div id="con"></div>
<script type="text/javascript" src="/public/bundle.js'"></script>
<script type="text/jsx">
ReactDOM.render(<Titles headerProp = "Header from props..." contentProp = "Content
from props..."/>, document.getElementById('con'));
</script>
But console outputs React is not defined.
I have even tried to set react globally within the bundle -
window.React = React;
And calling it with window. prefixed but yields the same result.
Because you're mentiong a bundle.js file with a snippet containing commonjs style imports, I'm assuming you're using Webpack.
I have some considerations about your code.
bundle.js file will not expose any module as global. That includes React and any other module you might require inside the bundle. There isn't goint to be window.ModuleName. However, these module are accessible in the Browser via require.js because Webpack will export modules as UMD, that is, they will be accessible through either commonjs or AMD (Require.js).
I'm pretty sure that, if in the entry point of your webpack configuration file, you do something like var React = require("react"); window.React = React, that's actually going to work.
There's a Webpack module meant to expose modules globally (like in window.x) in a more ellegant way than (2) called expose-loader. You should take a look at it.
You should really try to avoid doing what you're trying to do. In your entry.js file (the entry point of your webpack configuration) should be responsible for doing something like ReactDOM.render(..., document.getElementById("#app")). So that, just by including your bundle, the app will render automatically. This is what everybody does.
JSXTransformer.js as well as the <script type="text/jsx"> have been deprecated a long time ago. Now you're supposed to use Babel to compile React.
I'm building an Angular 2 (rc.4) app with TypeScript and I would like to use D3.
I've installed D3 through npm install, but this is a js module without .d.ts file. However, I've found a .d.ts file here.
What I do now (a component):
import d3 from 'node_modules/d3/build/d3.min.js';
//<reference path="../declaration/d3.d.ts" />
//[...]
export class Test {
constructor() {
this.object = this.d3.select(...);
}
}
If I set a break-point on that line in the TS file, I can execute everything just fine. However, the mapped .js version of this file was converted to:
var d3_min_js_1 = require('node_modules/d3/build/d3.min.js');
[...]
this.object = d3_min_js_1.default.select(...);
The d3_min_js_1 object exists, but there is no 'default', so it throws a undefined exception...
How can I get this mapping right (I'm pretty sure d3.d.ts does nothing) or how can a use the plain javascript in the TS-file (without it getting f*cked up by the compiler)?
I hope this plunker will help you: https://embed.plnkr.co/qM3qrk3swvalQFBh1Db1/
Can someone explain how would this look in TypeScript. Can it be done via imports?
JS:
var casper = require('casper').create({})
CoffeeScript:
casper = require("casper").create()
Visual Studio error: Error 1 The name ''casper'' does not exist in the current scope
import something = module('something');
var somevar = something.create({});
The point to note here I think is that TS today doesn't allow dotting off of module('something') so you have to break your statement into two.
I've put together a blog on using require.js with Typescript.
http://blorkfish.wordpress.com/2012/10/23/typescript-organizing-your-code-with-amd-modules-and-require-js/
You will be able to write code like this:
require["casper", (casper) => {
var item = casper.create();
};
If you use a module flag when you compile your TypeScript:
--module commonjs
Or
--module amd
It will convert imports into the appropriate module loading statement:
import something = module('something');
var somevar = something.create();
If that casper thing is something written in JavaScript, you need to declare a module for it too (or else it won't compile).
By convention, you put such declaration in a separate file named casper.d.ts:
declare module casper {
export class SomeClassInCasper {
}
export function someFunctionInCasper();
}
And you would include a reference to that casper.d.ts at the top above your import/module:
/// <reference path="casper.d.js" />
import casper = import("casper");
casper is installed through npm on the global scope.
typings install dt~casperjs --global --save
declare var casper; (on your code)
A short casper with typescript how to can be seen here:
https://medium.com/#guyavraham/smoke-tests-casper-js-with-typescript-8b01b504f3a4
I wrote a fairly comprehensive post on using Require in TypeScript. My approach does NOT require you to use the ugly
require(['dependency'], function() {
}
syntax. Instead, in TypeScript you get to use the convenient import x = module("x") syntax.