Module API require with dynamic load module causes variable not defined

bug?
Is the module context error?
In the code, why throw error ‘Uncaught ReferenceError’.

index.js

import data from './data';
import dynamic from './dynamic';

const _dynamic = {
  dynamic: 'dynamic',
};

console.log('data', data);
console.log('dynamic', dynamic);

console.log('require', require('./dynamic.js').default);
console.log('require _dynamic', require(`./${_dynamic.dynamic}.js`).default);
console.log('require dynamic', require(`./${data.dynamic}.js`).default); // throw Error Uncaught ReferenceError: data is not defined

data.js

export default {
  dynamic: 'dynamic',
};

dynamic.js

export default {
  key: 'value',
};

Chrome console
2017-07-12 5 41 59

If use the babel module, it will not report the error.

Chrome 59
Node.js 6.10.1
webpack 2.6.1

Author: Fantashit

1 thought on “Module API require with dynamic load module causes variable not defined

  1. You can stick with CommonJS imports as a workaround until it’s fixed. It’s not even that dirty 🙂.

    // import data from './data'
    const data = require('./data').default;
    
    console.log('require dynamic', require(`./${data.dynamic}.js`).default); // this works

    It works because a CommonJS module is treated like a regular object and its fields don’t get renamed by webpack.

Comments are closed.