rollup / rollup-plugin-commonjs

This module has moved and is now available at @rollup/plugin-commonjs / https://github.com/rollup/plugins/blob/master/packages/commonjs
MIT License
501 stars 126 forks source link

Native nodejs require #396

Closed lal12 closed 5 years ago

lal12 commented 5 years ago

Hey,

I want to dynamically load a json config and some plugins via require. However rollup-plugin-commonjs replaces all references to require, so it will just throw an error, that dynamic requires are not supported. Is there any way to access the native require function? Webpack has a special variable for this: __non_webpack_require__. Currently I am using eval('require')('my-plugin'), but this doesn't seem to be the nicest solution...

lukastaegert commented 5 years ago

If you know the ids you want to load dynamically, I believe this is what the ignore option is for.

lal12 commented 5 years ago

No I am loading every file in a directory, so I don't know them at compile time.

lal12 commented 5 years ago

Wrote a small plugin which achieves the wished functionality:

const nativeRequire = (plgOpts = {})=>{
    const alias = (plgOpts || {}).alias || "__non_rollup_require__"
    return {
        name: 'native-require',
        renderChunk(code, chunk, options){
            if(!alias.match(/^[_a-zA-Z][_a-zA-Z0-9]+$/))
                this.error("alias '"+alias+"' is not a valid variable name!");
            const addReqAlias = 'const '+alias+' = require;\n';
            let match = code.match(/^['"]use strict['"].*;\s*\n/);
            let map = {mappings: ';;'};
            if(match){
                let useStrict = code.substr(0, match[0].length);
                code = useStrict + addReqAlias + code.substr(match[0].length);
            }else{
                code = addReqAlias + code;
            }
            return {code, map};
        }
    }
};