Commit 30ff9a33 authored by Joe Haddad's avatar Joe Haddad Committed by JJ Kasper

Remove Extraneous Imports in Pages (#9627)

* Remove Extraneous Imports in Pages

* Add test

* bump cache key
parent c5dbc1fe
import { NodePath, PluginObj } from '@babel/core'
import * as BabelTypes from '@babel/types'
export default function(): PluginObj<any> {
return {
name: 'dangerously-remove-unused-imports',
visitor: {
Program: {
exit(path: NodePath<BabelTypes.Program>) {
Object.entries(path.scope.bindings).forEach(([k, v]) => {
if (v.referenced || v.kind !== 'module') return
if (
!(
v.path.type === 'ImportDefaultSpecifier' ||
v.path.type === 'ImportSpecifier'
) ||
!(v.path.parent.type === 'ImportDeclaration')
) {
throw new Error(
`invariant: unknown import binding: ${v.path.type} / parent: ${v.path.parent.type}`
)
}
if (v.path.parent.specifiers.length === 1) {
v.path.parentPath.remove()
} else {
v.path.remove()
}
})
},
},
},
}
}
...@@ -7,7 +7,7 @@ const configKeys = new Set(['amp']) ...@@ -7,7 +7,7 @@ const configKeys = new Set(['amp'])
const pageComponentVar = '__NEXT_COMP' const pageComponentVar = '__NEXT_COMP'
// this value can't be optimized by terser so the shorter the better // this value can't be optimized by terser so the shorter the better
const prerenderId = '__NEXT_SPR' const prerenderId = '__NEXT_SPR'
const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps' export const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps'
const EXPORT_NAME_GET_STATIC_PATHS = 'unstable_getStaticPaths' const EXPORT_NAME_GET_STATIC_PATHS = 'unstable_getStaticPaths'
const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__' const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'
...@@ -41,8 +41,10 @@ interface ConfigState { ...@@ -41,8 +41,10 @@ interface ConfigState {
// config to parsing pageConfig for client bundles // config to parsing pageConfig for client bundles
export default function nextPageConfig({ export default function nextPageConfig({
types: t, types: t,
traverse,
}: { }: {
types: typeof BabelTypes types: typeof BabelTypes
traverse: any
}): PluginObj { }): PluginObj {
return { return {
visitor: { visitor: {
...@@ -142,6 +144,13 @@ export default function nextPageConfig({ ...@@ -142,6 +144,13 @@ export default function nextPageConfig({
}, },
state state
) )
if (!state.bundleDropped && state.isPrerender) {
// After we delete a bunch of code, we need to re-compute the scope.
// This is necessary for later code elimination.
traverse.cache.clear()
;(path.scope as any).crawl()
}
}, },
}, },
ExportDefaultDeclaration(path, state: ConfigState) { ExportDefaultDeclaration(path, state: ConfigState) {
......
import hash from 'string-hash' import hash from 'string-hash'
import { join, basename } from 'path' import { join, basename } from 'path'
import babelLoader from 'babel-loader' import babelLoader from 'babel-loader'
import { EXPORT_NAME_GET_STATIC_PROPS } from '../../babel/plugins/next-page-config'
// increment 'e' to invalidate cache // increment 'e' to invalidate cache
// eslint-disable-next-line no-useless-concat // eslint-disable-next-line no-useless-concat
const cacheKey = 'babel-cache-' + 'e' + '-' const cacheKey = 'babel-cache-' + 'f' + '-'
const nextBabelPreset = require('../../babel/preset') const nextBabelPreset = require('../../babel/preset')
const getModernOptions = (babelOptions = {}) => { const getModernOptions = (babelOptions = {}) => {
...@@ -187,6 +188,17 @@ module.exports = babelLoader.custom(babel => { ...@@ -187,6 +188,17 @@ module.exports = babelLoader.custom(babel => {
'next-js-transform-define-instance', 'next-js-transform-define-instance',
]) ])
if (isPageFile) {
if (source.includes(EXPORT_NAME_GET_STATIC_PROPS)) {
options.plugins.push([
require.resolve(
'../../babel/plugins/dangerously-remove-unused-imports'
),
{},
])
}
}
// As next-server/lib has stateful modules we have to transpile commonjs // As next-server/lib has stateful modules we have to transpile commonjs
options.overrides = [ options.overrides = [
...(options.overrides || []), ...(options.overrides || []),
......
import Link from 'next/link' import Link from 'next/link'
import fs from 'fs'
import findUp from 'find-up'
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
export async function unstable_getStaticProps() { export async function unstable_getStaticProps() {
const text = fs
.readFileSync(
findUp.sync('world.txt', {
// prevent webpack from intercepting
// eslint-disable-next-line no-eval
cwd: eval(`__dirname`),
}),
'utf8'
)
.trim()
return { return {
props: { props: {
world: 'world', world: text,
time: new Date().getTime(), time: new Date().getTime(),
}, },
revalidate: 1, revalidate: 1,
......
...@@ -2,6 +2,9 @@ ...@@ -2,6 +2,9 @@
const loader = require('next/dist/build/webpack/loaders/next-babel-loader') const loader = require('next/dist/build/webpack/loaders/next-babel-loader')
const os = require('os') const os = require('os')
const path = require('path')
const dir = path.resolve(os.tmpdir())
const babel = async ( const babel = async (
code, code,
...@@ -40,10 +43,10 @@ const babel = async ( ...@@ -40,10 +43,10 @@ const babel = async (
supportsStaticESM: true, supportsStaticESM: true,
}, },
// loader opts // loader opts
cwd: os.tmpdir(), cwd: dir,
isServer, isServer,
distDir: os.tmpdir(), distDir: path.resolve(dir, '.next'),
pagesDir: os.tmpdir(), pagesDir: path.resolve(dir, 'pages'),
cache: false, cache: false,
babelPresetPlugins: [], babelPresetPlugins: [],
hasModern, hasModern,
...@@ -192,5 +195,102 @@ describe('next-babel-loader', () => { ...@@ -192,5 +195,102 @@ describe('next-babel-loader', () => {
const code = await babel(`if (process.env.NODE_ENV !== 'production') {}`) const code = await babel(`if (process.env.NODE_ENV !== 'production') {}`)
expect(code).toMatchInlineSnapshot(`"if(false){}"`) expect(code).toMatchInlineSnapshot(`"if(false){}"`)
}) })
it('should not drop unused exports by default', async () => {
const code = await babel(
// effectful
`import"core-js";` +
// basic
`import{foo,bar}from"a";import baz from"b";` +
// complex
`import baz2,{yeet}from"c";` +
`import baz3,{cats}from"d";` +
`import{c,d}from"e";` +
`import{e as ee,f as ff}from"f";`
)
expect(code).toMatchInlineSnapshot(
`"import\\"core-js\\";import{foo,bar}from\\"a\\";import baz from\\"b\\";import baz2,{yeet}from\\"c\\";import baz3,{cats}from\\"d\\";import{c,d}from\\"e\\";import{e as ee,f as ff}from\\"f\\";"`
)
})
const pageFile = path.resolve(dir, 'pages', 'index.js')
it('should not drop unused exports by default in a page', async () => {
const code = await babel(
// effectful
`import"core-js";` +
// basic
`import{foo,bar}from"a";import baz from"b";` +
// complex
`import baz2,{yeet}from"c";` +
`import baz3,{cats}from"d";` +
`import{c,d}from"e";` +
`import{e as ee,f as ff}from"f";`,
{ resourcePath: pageFile }
)
expect(code).toMatchInlineSnapshot(
`"import\\"core-js\\";import{foo,bar}from\\"a\\";import baz from\\"b\\";import baz2,{yeet}from\\"c\\";import baz3,{cats}from\\"d\\";import{c,d}from\\"e\\";import{e as ee,f as ff}from\\"f\\";"`
)
})
it('should drop unused exports in a modern-apis page', async () => {
const code = await babel(
// effectful
`import"core-js";` +
// basic
`import{foo,bar}from"a";import baz from"b";` +
// complex
`import baz2,{yeet}from"c";` +
`import baz3,{cats}from"d";` +
`import{c,d}from"e";` +
`import{e as ee,f as ff}from"f";` +
`` +
`export function unstable_getStaticProps() { return { props: {} } }`,
{ resourcePath: pageFile }
)
expect(code).toMatchInlineSnapshot(`"import\\"core-js\\";"`)
})
it('should keep used exports in a modern-apis page (server)', async () => {
const code = await babel(
// effectful
`import"core-js";` +
// basic
`import{foo,bar}from"a";import baz from"b";import ooo from"ooo";` +
// complex
`import baz2,{yeet}from"c";` +
`import baz3,{cats}from"d";` +
`import{c,d}from"e";` +
`import{e as ee,f as ff}from"f";` +
`` +
`export function unstable_getStaticProps() {foo();baz2();ff();ooo(); return { props: {} }}` +
`export default function () { return bar(); }`,
{ resourcePath: pageFile, isServer: true }
)
expect(code).toMatchInlineSnapshot(
`"import\\"core-js\\";import{foo,bar}from\\"a\\";import ooo from\\"ooo\\";import baz2 from\\"c\\";import{f as ff}from\\"f\\";export function unstable_getStaticProps(){foo();baz2();ff();ooo();return{props:{}};}export default function(){return bar();}"`
)
})
it('should keep used exports in a modern-apis page (client)', async () => {
const code = await babel(
// effectful
`import"core-js";` +
// basic
`import{foo,bar}from"a";import baz from"b";import ooo from"ooo";` +
// complex
`import baz2,{yeet}from"c";` +
`import baz3,{cats}from"d";` +
`import{c,d}from"e";` +
`import{e as ee,f as ff}from"f";` +
`` +
`export function unstable_getStaticProps() {foo();baz2();ff();ooo(); return { props: {} }}` +
`export default function () { return cats + bar(); }`,
{ resourcePath: pageFile, isServer: false }
)
expect(code).toMatchInlineSnapshot(
`"import\\"core-js\\";import{bar}from\\"a\\";import{cats}from\\"d\\";const __NEXT_COMP=function(){return cats+bar();};__NEXT_COMP.__NEXT_SPR=true export default __NEXT_COMP;"`
)
})
}) })
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment