I'm developing a website with webpack. When I have a code like this:
import $ from 'jquery'; function foo() {}; module.exports = foo;
I got the error Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
.
Turns out that changing import $ from 'jquery'
to var $ = require('jquery')
don't cause any errors.
Why import with module.exports causes this error? Is anything wrong in using require instead?
Tree shaking is a term commonly used within a JavaScript context to describe the removal of dead code. It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with .
As you may know, webpack supports a couple of module types out of the box, including both CommonJS and ES modules. Webpack also works on both client- and server-side JavaScript, so with webpack, we can also easily handle assets and resources like images, fonts, stylesheets, and so on.
ES modules are the standard for JavaScript, while CommonJS is the default in Node. js. The ES module format was created to standardize the JavaScript module system. It has become the standard format for encapsulating JavaScript code for reuse. The CommonJS module system, on the other hand, is built into Node.
You can't mix import
and module.exports
. In the import
world, you need to export things.
// Change this module.exports = foo; // To this export default foo;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With