Rollup - incorrect path resolution
Asked Answered
S

2

6

I want to use the library ebnf from NPM and create a bundle using rollup. Since the ebnf is installed to node_modules I also use the rollup plugin rollup-plugin-node-resolve.

The problem is that ebnf contains the code require('..') which - in my case - is resolved to dist in my case. Thus it seems .. is interpreted relative to the output file instead of being relative to the source file.

This is my rollup.config.js (taken from my test repo jneuendorf/rollup-broken-resolve):

import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'


export default {
    input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
        format: 'cjs'
    },
    // name: 'MyModule',
    plugins: [
        resolve(),
        commonjs(),
    ]
}

Is this a problem in rollup-plugin-node-resolve or am I doing something wrong?

Stodgy answered 6/2, 2018 at 22:1 Comment(1)
I'm experiencing a similar problem as well - rollup-plugin-node-resolve is adding a require('../myutilsfile.js') in the bundle which is causing the consumers of the bundled module to throw "cannot resolve '../myutilsfile.js'". Any luck on this?Justness
V
1

Since some of the external libraries needed will still be available only as Common.js modules, you could also convert them to ES-Modules:

"Since most packages in your node_modules folder are probably legacy CommonJS rather than JavaScript modules, you may need to use rollup-plugin-commonjs"

Vestige answered 9/8, 2018 at 22:29 Comment(0)
S
1

Just in case someone searching this issue on how to make @rollup/plugin-node-resolve (previously was rollup-plugin-node-resolve) to work with relative path. I just found the solution:

function resolve(file, origin) {
    // Your way to resolve local include path
}

function pathResolve(options) {
    return {
        resolveId: function(file, origin) {
            // Your local include path must either starts with `./` or `../`
            if (file.startsWith('./') || file.startsWith('../')) {
                // Return an absolute include path
                return resolve(file, origin);
            }
            return null; // Continue to the next plugins!
        }
    };
}

Here is how to combine it with @rollup/plugin-node-resolve:

import {nodeResolve} from '@rollup/plugin-node-resolve';

function pathResolve(options) { /* ... */ }

export default {
  // ...
  plugins: [pathResolve(), nodeResolve()]
};
Stallion answered 30/3, 2022 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.