简体   繁体   English

如何为 next.js 启用树抖动?

[英]How to enable tree shaking for next.js?

Is there something to enable to have next.js perform tree-shaking/removal of dead code from dependencies?是否可以让 next.js 从依赖项中执行摇树/删除死代码? I've exported two objects like this:我已经导出了两个这样的对象:

library.js

export const foo = {foo:"foo"}
export const bar = {bar:"bar"}

And in my next.js app I do like this:在我的 next.js 应用程序中,我这样做:

page.tsx

import { foo } from 'library';
console.log(foo);

So now I'd expect a production-build will not include bar , and indeed something appears to go right because this line is produced:所以现在我希望生产版本包括bar ,并且确实在 go 中出现了一些东西,因为这条线是生产的:

.next/server/chunks/621.js

/* unused harmony exports bar */

But confusingly when I load the app in the browser the network-traffic indicates the unused export is included:但令人困惑的是,当我在浏览器中加载应用程序时,网络流量表明包含使用的导出:

http://localhost:3001/_next/static/chunks/pages/page-0b2b13a7513f2849d855.js

(self.webpackChunk_N_E = self.webpackChunk_N_E || []).push([[3031], {
    80621: function(e, r, n) {
        "use strict";
        ...
        const l = a.object({
            foo: "foo"
        });
        a.object({
            bar: "bar"
        });
    },

Why would the build identify unused exports but not remove them from the payload that's transferred to the browser?为什么构建会识别未使用的导出但不会从传输到浏览器的有效负载中删除它们? Is there a setting Next expects us to enable? Next 是否需要我们启用设置? Some sort of post-processing that actually prunes unused exports?某种实际上修剪未使用的导出的后处理?

I believe the issue with your example is that Next.js is able to tree-shake primitive values (boolean, string, int,...) and object/array's with primitive values.我相信您的示例的问题是 Next.js 能够对原始值(布尔值、字符串、int 等)和具有原始值的对象/数组进行摇晃。

However, webpack, the bundler used in Next.js, isn't able to identify whether a function call has any side-effects.但是,Next.js 中使用的捆绑程序 webpack 无法识别function 调用是否有任何副作用。

From this Github Issue #12557 , some users report that setting "sideEffects:false in the package.json or even modifying webpack in the next.config.js solved this issue. From this Github Issue #12557 , some users report that setting "sideEffects:false in the package.json or even modifying webpack in the next.config.js this issue.

None of those worked for me.这些都不适合我。 Instead, marking function's as side-effect-free using the /*#__PURE__*/ annotation worked.相反,使用/*#__PURE__*/注释将函数标记为无副作用有效。

Example:例子:

const createApi = (message) => {
  console.log(message);
  return () =>{}
}

export const serverApi = /*#__PURE__*/ createApi("I should only be available server side.")

export const clientApi = /*#__PURE__*/ createApi("I should only be available client side.")

It should be noted, that the syntax of the annotation is /*#__PURE__*/ fn() .需要注意的是,注解的语法是/*#__PURE__*/ fn() All other usages won't work.所有其他用法都不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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