deep-import-loader
Introduce
When building with webpack, it will find the final file which import
refers to, then replace the path following by from
. This will avoid importing the whole package, to reduce size of js bundle.

Difference with webpack tree-shaking
Although webpack supports elimination of unused export
, it will NOT work if you transform your project to commonjs such as @babel/plugin-transform-modules-commonjs or babel-plugin-transform-es2015-modules-commonjs. Perhaps, lots of your dependencies does NOT have sideEffects: false
in package.json
file, which will also stop the elimination, even if we know they have no sideEffects. A way is to write code like import Foo from 'somemodule/lib/foo'
, but it is not convenient.
How it works
Load the file before other loaders, analyze import ... from ...
. If a module comes from a deeper file, transform the path. For example:
// Before
import { Foo, Bar } from 'module1';
import { Foo as myFoo } from 'module2';`
// After
// Foo is default export in foo.js
import Foo from 'module/path/foo.js';
// Bar is an export in utils.js
import { Bar } from 'module/path2/utils.js';`
// Support as, tsx and others
import myFoo from 'module/path3/foo.tsx';`
How to use
-
Install deep-import-loader:
npm install deep-import-loader
or yarn add deep-import-loader
-
Add this rule at the END of rules
in webpack config, an example in webpack@4:
rules: [{
test: /\.(js|jsx|ts|tsx)$/,
use: [
// ... other rules
{
loader: 'deep-import-loader',
options: {
blackList: ['adirtymodule'],
whiteList: ['somemodule', 'anothermodule'],
log: true,
warn: true
}
}
]
}]
Why at the end ? Rule
run from last to first, so deep-import-loader will transform the import
before other loaders make it unrecognizable.
options:
Props | Default | Description |
---|
blackList | [] | Package blacklist, import from these packages will never be transformed. |
whiteList | [] | Package whitelist, import from these package will always be transformed. Otherwise will obey the option in package.json. Transform only happens if sideEffects is false. Set to '*' means always transform. |
log | false | Show the modules and new path during webpack. |
warn | false | Show the modules that fail during webpack. |
-
If you are using vue file, include VueLoaderPlugin in plugins. Not to modify test
above. See https://vue-loader.vuejs.org/guide/#webpack-configuration for more information.