A plugin to add extensions to import and export declarations, is very useful when you use Typescript with Babel and don't want to explicity import or export module with extensions.
WARNING
This is a fork ofbabel-plugin-add-import-extension, mainly used to add extensions when importing files in ESM packaging. If you are using an older webpack project, not all imported resources are.js files; they might be.less,.css,.png, or other files. Adding the.js extension directly would cause errors, so we need to add a parameter to ensure that resources that already have an extension won't have the.js extension added again.
npminstall @uiw/babel-plugin-add-import-extension --save-devVia.babelrc orbabel-loader.
{"plugins":[["@uiw/babel-plugin-add-import-extension",{"extension":"js","replace":true,"skipUnlistedExtensions":true,"observedScriptExtensions":["js","ts","jsx","tsx","mjs","cjs"]}]]}{"plugins":[["@uiw/babel-plugin-add-import-extension",{"extension":"js"}]]}// Input Codeimport'./';import'./main';importpngfrom'./logo.png';import{Button}from'uiw';import{Select}from'@uiw/core';export{ oneBackLevel}from'..';// Output ↓ ↓ ↓ ↓ ↓ ↓import'./index.js';import'./main.js';import{Button}from'uiw';import{Select}from'@uiw/core';export{ oneBackLevel}from"../index.js";Output Result
- import './';- import './main';+ import './index.js';+ import './main.js';import png from './logo.png';import { Button } from 'uiw';import { Select } from '@uiw/core';- export { oneBackLevel } from '..';+ export { oneBackLevel } from "../index.js";replacefalseextensionjs.js extension toimport andexport declarations.skipUnlistedExtensionsfalsetrue and a declaration file has an extension that isnot included in theobservedScriptExtensions list, the file will be skipped.observedScriptExtensions['js', 'ts', 'jsx', 'tsx', 'mjs', 'cjs']replace option). Files with extensionsnot in this list will have theextension option's value appended to them.A module import without extension:
import{ add, double}from"./lib/numbers";will be converted to:
import{ add, double}from"./lib/numbers.js";A module export without extension:
export{ add, double}from"./lib/numbers";will be converted to:
export{ add, double}from"./lib/numbers.js";If you add thereplace:true option, extensions will be overwritten like so
import{ add, double}from"./lib/numbers.ts";will be converted to:
import{ add, double}from"./lib/numbers.js";and
export{ add, double}from"./lib/numbers.ts";will be converted to:
export{ add, double}from"./lib/numbers.js";What this plugin does is to check all imported modules and if your module is not onnode_module it will consider that is a project/local module and add the choosed extension, so for node modules it don't add any extension.
As always, thanks to our amazing contributors!
Made withgithub-action-contributors.