简体   繁体   中英

ES6 module, what counts as the first import?

Here's my module:

console.log("module imported");
export function call(){};

In main.ts:

import * as mod from './module';

// other code that doesn't use mod.

I would have expected this to log "module imported" to the console. In fact, the example seems pretty much the same as this one . And they say:

A module code is evaluated only the first time when imported

But there are no console logs. However, after the following edits to main.ts the log message appears:

import * as mod from './module';

if(false){
  mod.call();
}

It would make sense if only the first time the module is actually used counted as the first import. But here the log message seems to be based on static analysis alone. The code path that uses the module is never executed.

How does this work? What counts as the first import of an ES6 module?

Also, my gut feeling says that this might be about the bundler. Does it optimize away an unused import like this? I'm running these code snippets in a react app, created with:

npx create-react-app my-app --template typescript
cd my-app
# add the module and import it to index.tsx
npm i
npm run start
# browser opens, check the console

On the other hand, the typescript react app also has imports like './index.css' and they are only there for the bundler to package them. It seems common to import something only for its side-effects.

I have searched for related questions but so far haven't found something with this specific problem:

The last of these looks like a duplicate, but it is about a specific syntax error in the module resolution.

Your guess is correct, it's happening because of bundler. Its a feature of bundler known as Dead code elimination . To know more about it, search for Tree Shaking or Dead code elimination .

If you are not going to use anything from imported module, source code of module will not be included in your build.

I think create-react-app use Webpack for bundling. If you want to disable the feature, starting the app in development mode may solve it. BTW, its good to remove unused code while building.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM