MCPcopy
hub / github.com/vercel/next.js / addWithRouterImport

Function addWithRouterImport

packages/next-codemod/transforms/url-to-withrouter.ts:3–46  ·  view source on GitHub ↗
(j, root)

Source from the content-addressed store, hash-verified

1// One-time usage file. You can delete me after running the codemod!
2
3function addWithRouterImport(j, root) {
4 // We create an import specifier, this is the value of an import, eg:
5 // import {withRouter} from 'next/router
6 // The specifier would be `withRouter`
7 const withRouterSpecifier = j.importSpecifier(j.identifier('withRouter'))
8
9 // Check if this file is already import `next/router`
10 // so that we can just attach `withRouter` instead of creating a new `import` node
11 const originalRouterImport = root.find(j.ImportDeclaration, {
12 source: {
13 value: 'next/router',
14 },
15 })
16 if (originalRouterImport.length > 0) {
17 // Check if `withRouter` is already imported. In that case we don't have to do anything
18 if (
19 originalRouterImport.find(j.ImportSpecifier, {
20 imported: { name: 'withRouter' },
21 }).length > 0
22 ) {
23 return
24 }
25
26 // Attach `withRouter` to the existing `next/router` import node
27 originalRouterImport.forEach((node) => {
28 node.value.specifiers.push(withRouterSpecifier)
29 })
30 return
31 }
32
33 // Create import node
34 // import {withRouter} from 'next/router'
35 const withRouterImport = j.importDeclaration(
36 [withRouterSpecifier],
37 j.stringLiteral('next/router')
38 )
39
40 // Find the Program, this is the top level AST node
41 const Program = root.find(j.Program)
42 // Attach the import at the top of the body
43 Program.forEach((node) => {
44 node.value.body.unshift(withRouterImport)
45 })
46}
47
48function getThisPropsUrlNodes(j, tree) {
49 return tree.find(j.MemberExpression, {

Callers 1

transformerFunction · 0.85

Calls 5

pushMethod · 0.65
identifierMethod · 0.45
findMethod · 0.45
forEachMethod · 0.45
unshiftMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…