Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack: import + module.exports in the same module caused error

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?

like image 371
juniorgarcia Avatar asked Feb 24 '17 23:02

juniorgarcia


People also ask

What is tree shaking webpack?

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.

Is import better than require?

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 .

Does webpack use CommonJS?

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.

What is an Esmodule?

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.


1 Answers

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; 
like image 94
Matthew Herbst Avatar answered Oct 13 '22 00:10

Matthew Herbst