Publish a isomorphic library with two different output

(Mirko) #1

I am building a isomorphic app using JS. Using webpack multiple targets I now have two different files: index.js and index.node.js The first file is supposed to run on the browser and the second on node.

var path = require('path');

const serverConfig = {
    entry: './src/index.ts',
    target: 'node',
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.js']
    },
    module: {
        rules: [
            { test: /.ts$/, loader: 'ts-loader' }
        ]
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index.node.js',
        libraryTarget: "umd", // exposes and know when to use module.exports or exports.,
    }
};

const clientConfig = {
    entry: './src/index.ts',
    target: 'web',
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.js']
    },
    module: {
        rules: [
            { test: /.ts$/, loader: 'ts-loader' }
        ]
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index.js',
        libraryTarget: "umd", // exposes and know when to use module.exports or exports.,
        globalObject: 'this' // bug fix: https://medium.com/@JakeXiao/window-is-undefined-in-umd-library-output-for-webpack4-858af1b881df
    }
};
module.exports = [serverConfig, clientConfig];

How would I publish this library in a way that it automatically recognise what file to import depending on the environment is running on? At the moment if I import it it will automatically default to index.js regardless if its running on browser or node :(

(Lars Willighagen) #2

In what way are you importing the file in the browser?

(Mirko) #3

For now just tested with a library like react and using ES6 imports and works fineimport {//whatever I am exposing} from 'my-library'
Also if I run the index.node.js file in node works just fine but obviously doesn’t run on the browser.

(Lars Willighagen) #4

What I meant is, what thing are you using to import the library that should automatically recognize what variant to use depending on the environment? Are you using a CommonJS implementation for the browser?

(Mirko) #5

Well I am using http requests etc. for example when I try to run the browser version on Node I get

ReferenceError: XMLHttpRequest is not defined

Because obviously that is an object that is exposed only to the browser.

(system) closed #6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.