Code Monkey home page Code Monkey logo

lasso-require's Introduction

lasso-require

Plugin for the Lasso.js that adds support for transporting Node.js-style modules to the browser.

Installation

This plugin is included as part of the lasso module so it is not necessary to use npm install to add the module to your project. However, if you want to use a specific version of the lasso-require plugin then you can install it using the following command:

npm install lasso-require --save

Usage

This plugin is enabled by default, but if you want to provide your own configuration then you can do that using code similar to the following:

require('lasso').configure({
    require: {
        extensions: ['.js'], // Defaults to ['.js']
        transforms: [ // Browserify compatible transforms
            'deamdify'
        ]
    }
})

The lasso-require plugin introduces two new dependency types that you can use to target Node.js modules for the browser. There usage is shown in the following browser.json file:

{
    "dependencies": [
        "require: jquery",
        "require-run: ./main"
    ]
}

These new dependency types are described in more detail below.

Dependency Types

require

The require dependency type will wrap a Node.js module for delivery to the browser and allow it to be required from another module. For example:

Input modules:

foo.js:

exports.add = function(a, b) {
    return a + b;
}

bar.js:

var foo = require('./foo');

exports.sayHello = function() {
    console.log('Hello World! 2+2=' + foo.add(2, 2));
};

Output Bundles:

After running the following command:

lasso require:./foo require:./bar --name test

The output written to static/test.js will be the following:

$_mod.def("/foo", function(require, exports, module, __filename, __dirname) { exports.add = function(a, b) {
    return a + b;
} });
$_mod.def("/bar", function(require, exports, module, __filename, __dirname) { var foo = require('./foo');

exports.sayHello = function() {
    console.log('Hello World! 2+2=' + foo.add(2, 2));
}; });

NOTE: $_mod is a global introduced by the client-side Node.js module loader. It should never be used directly!. The code that declares $_mod is not shown in the output above for brevity.

require-run

In the previous examples, neither the foo.js or bar.js module will actually run. The require-run dependency type should be used to make a module self-executing. This is the equivalent of the entry point for your application when loaded in the browser.

Continuing with the previous example:

Input modules:

foo.js (see above)

bar.js (see above)

main.js:

require('./bar').sayHello();

Output Bundles:

After running the following command:

lasso require-run:./main --name test

Alternatively:

lasso --main main.js --name test

The output written to static/test.js will be the following:

$_mod.def("/foo", function(require, exports, module, __filename, __dirname) { exports.add = function(a, b) {
    return a + b;
} });

$_mod.def("/bar", function(require, exports, module, __filename, __dirname) { var foo = require('./foo');

exports.sayHello = function() {
    console.log('Hello World! 2+2=' + foo.add(2, 2));
}; });

$_mod.run("/main", function(require, exports, module, __filename, __dirname) { require('./bar').sayHello(); });

Conditional Remap

The lasso-require supports the package.json browser field for remapping a JavaScript module to a different module during client-side bundling. For example:

{
    "browser": {
        "./foo.js": "./foo-browser.js"
    }
}

The lasso-require plugin also allows modules to be conditionally remapped based on the set of enabled flags by adding additional information an browser.json in the same directory as a module. For example:

{
    "dependencies": [
        ...
    ],
    "requireRemap": [
        {
            "from": "./foo.js",
            "to": "./foo-mobile.js",
            "if-flag": "mobile"
        }
    ]
}

If the mobile flag is set during optimization and the foo.js module is required on the client (e.g., require('./foo')) then the returned module will be the exports for foo-mobile.js (not foo.js).

lasso-require's People

Contributors

austinkelleher avatar dylanpiercey avatar leonli avatar mlrawlings avatar patrick-steele-idem avatar philidem avatar rragan avatar senthilp avatar yomed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

lasso-require's Issues

es6 support

Hi,

I have an ES6 file, that I want to bundle with lasso and lasso-require.
I cannot found in the documentation, but I saw that is supported, if I rename my file to .es6.

During the build the lasso was missing the babel-runtime plugin. I installed it, and the build was success. But when I opened it in a browser, I got the following error:
Uncaught Error: Cannot find module "/$/babel-runtime/$/core-js/library/modules/$" from "/$/babel-runtime/$/core-js/library/fn/object"

I tried to understand what can be the problem, but I cannot found. I have some idea, but it is only an idea. Can it make problem, that the babel-runtime has a lot of files with names that contains $ (dollar sign)? Like $.js

I tried to make a workaround and I used the es6ify browserify transform with lasso-require. It worked properly, but when I want to use it for tests (mocha, sinon), I got the error message because I cannot access to caller, callee, etc in strict mode. This happend because the sinon.spy want so access to this attributes, but in strict mode it is not allowed. I would like to disable strict mode, but I cannot know how can I give config parameters to a transform in lasso-require config. If I opened the bundle and remove all "use strict"; lines, it worked propertly. So, can I give config options to a transform in lasso-require config?

Thanks in advance.

getDependencies() in dep-require.js doesn't always return all of the dependencies

It looks like there are a couple of return paths that don't return all of the dependencies that have been collected thus far.

This was the problem return path that affected my project:

if (!requireHandler) {
    // This is not really a dependency that compiles down to a CommonJS module
    // so just add it to the dependency graph
    return [resolved.path];
}

The fix is to add resolved.path to the list of dependencies and then return dependencies (instead of returning a new array). If you return [resolved.path] then there is a chance that the automatically added commonjs-ready and commonjs-runtime dependencies will not be returned.

A couple of other short-circuit return paths seem to have the same problem. I have a fix ready.

require-run dependency code can overwrite actual file when bundle is written

The code for "require-run" doesn't have a getUnbundledTarget method so it gets written to a default bundle according to value returned by getSourceFile() which corresponds to a bundle that is actually associated with require definition module. The circumstances for this happening seem to be related to the order in which pages are built and bundles are written.

The fix is to add this to dependency-run.js:

getUnbundledTarget: function() {
    return 'raptor-modules-meta';
}

inconsistency referenceing files in current directory

{
    "dependencies": [
        "require: jquery",
        "require: ./file.js",
        "require: file.js",  // does not work
        "./file.js",
        "file.js"
    ]
}

Error: Unable to resolve required module "file.js"

Is this behavior intentional? Just a bit odd that it is inconsistent across require and non-require.

Require any json file that contains the word "process" is not possible

I have a project that has a json language file. It contains somewhere the word process as the part of a value. But when I want to require it, I cannot build the project. I got the following error:

WARN lasso-require/lib/inspect-cache: Error parsing JavaScript file config/languages/en.json Error: Error: Line 1: Unexpected token :
    at inspect (node_modules/gulp-lasso/node_modules/lasso/node_modules/lasso-require/lib/util/inspect.js:155:29)
    at node_modules/gulp-lasso/node_modules/lasso/node_modules/lasso-require/lib/inspect-cache.js:62:17
    at DeferredReadable.<anonymous> (node_modules/gulp-lasso/node_modules/lasso/node_modules/lasso-require/lib/util/streamToString.js:11:13)
    at DeferredReadable.emit (events.js:104:17)
    at DeferredReadable.emit (node_modules/gulp-lasso/node_modules/lasso/lib/util/DeferredReadable.js:43:37)
    at _stream_readable.js:908:16
    at process._tickCallback (node.js:355:11)

Source:
-------
{"foo": "bar process baz"}
-------

Maybe I found the source of the bug. In the line 9 of lib/utils/inspect.js file, there is a shourtCircuitRegExp variable that contains some reserved word, but I think it should not be check the json files.

I make a workaround and rename the json to js and insert a module.exports in it, and it's working now, but I would be happy if you could check this issue.

Thanks in advance.

Dependency key for require with custom dependency type collides with normal require

For example:

// Declare that you require file at path ./abc of type "my-type"
require('my-type: ./abc')

// Now declare that you require the JavaScript module ./abc
require('./abc');

These two dependencies create a key that collides because dependencyType is not a part of the key. This is a weird/advanced use case but I have a fix ready.

Wrong path resolve

A had a project that worked before but today it's broken because of some of your modifications.
I cannot find a problem but it can be reproducible easily with the following steps:

npm install intl lasso-cli
echo "require('intl');" > main.js
lasso --main main.js

It said something like this:

Error: File does not exist: /home/user/node_modules/intl/home/user/node_modules/intl/locale-data/complete.js
    at getPathInfo (/home/user/node_modules/lasso-cli/node_modules/lasso/node_modules/raptor-modules/util/lib/getPathInfo.js:63:15)
...

Versions:

  • "intl" : "1.1.0",
  • "lasso-cli": "1.3.0"

We are using lasso to require a lot of npm libraries, but we experienced this issue only with intl. I cannot find any specific problem with this project. It worked in the last week so maybe it is caused by a new modification. Could you check it for me?

Thanks in advance and if you need any other information please let me know.

es6 support should be done using a transform

Currently, ES6 transpilation occurs at the beginning of the require pipeline. All require transforms kick-in after the transpilation.

This means that it is not possible to run a transform (eg, instrument the ES6 code for coverage) before ES6 transpilation.

Creating a transform for ES6 to ES5 transpilation will be more flexible.

Check if require is not node's pseudo global require

lasso-require does not take into account whether require has been redefined in the current scope.

Given the following, we would expect it to bundle up just fine:

require('./bar');
(function() {
    var require = function(name) {
        console.log(name);
    };
    require('some-thing-that-doesnt-exist');
}());

Instead we get:

Error: Module not found: some-thing-that-doesnt-exist

This is important for compatibility with modules that expose a pre-built file as its main (bundled using lasso/browserify/webpack/etc and so has its own require mechanism).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.