Git Product home page Git Product logo

es-modules-middleware's Introduction

es-modules-middleware

This middleware provides a connect-style middleware and a Karma middleware factory for resolving ES-module import and export statements on the fly.

Browsers do not currently support 'bare module specifiers' such as import * from 'chai'. The browser does not know how to resolve 'chai' since its not an absolute URI or a relative URI. So results in this error message:

Uncaught TypeError: Failed to resolve module specifier "chai". Relative references must start with either "/", "./", or "../".

There are several proposals to fix this, one such proposal is import-maps (repo). The workaround to this would involve using relative references for imports, this is fine when you're not using any node_module based dependencies, but when you want to import some external lib you end up having to bundle your modules to resolve these dependencies or import through complete relative paths to your node_modules folder.

This middleware provides an alternative to that by rewriting the import and export statements served on the fly to resolve the paths to a node_module folder. This implementation is based heavily on the es-module-devserver middleware by myfreeweb with some small tweaks to make it compatible with Karma.

In general you would NOT use this middleware in any production service, where it is expected that you would use bundling to resolve these issues. This middleware is intended for development purposes so the complications of a bundled development environment can be avoided and ES-modules can be used natively. Polymers CLI tools also implement this behavior, for additional context see this documentation.

Examples

There is a complete working example projection in the examples folder which implements a web component using the LitElement library as a dependency.

Requirements

  • NodeJS >= 8.10.0

Installation

npm install --save-dev @adobe/es-modules-middleware

Usage

The module can be included and used as a connect middleware by providing it with a map of url base path to file system path from which to serve files. Any files served through the middleware will be processed to resolve import/export paths properly.

const esModuleMiddleware = require('@adobe/es-modules-middleware');
const express = require('express');

const app = express();
const port = 3000;

const rootPath = path.resolve(__dirname);

app.use(
    esModuleMiddleware.middleware({
        paths: {
            '/node_modules': path.join(rootPath, 'node_modules'),
        },
    })
);

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

It can also be used in Karma to aid in testing es-modules in the browser. Here's an example of using this middleware in combination with the karma-web-components framework to test web components using HTML test pages:

const path = require('path');

module.exports = function(config) {
    config.set({
        basePath: '.',
        plugins: ['karma-*', require('@adobe/es-modules-middleware')],
        frameworks: ['mocha', 'chai', 'sinon', 'web-components'],
        middleware: ['es-modules'],
        esModulesMiddleware: {
            // NOTE: add any paths which you wish to be processed and served by the middleware
            paths: {
                '/': __dirname,
                '/node_modules': path.join(__dirname, 'node_modules'),
            },
        },
        files: [
            {
                pattern: '**/*.test.html',
                watched: false,
                included: false,
                served: true,
            },
            {
                pattern: '**/test/*.js',
                watched: true,
                included: false,
                served: false,
            },
        ],
        // NOTE: proxy node_modules paths to base so they get picked up by the middleware
        proxies: {
            '/node_modules/': '/base/node_modules/',
        },
        reporters: ['mocha'],
    });
};

Contributing

We'd be very grateful if you contributed to the project! Check out our contribution guidelines for more information.

es-modules-middleware's People

Contributors

benjamind avatar

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.