在nuxtjs项目之间共享代码的5个技巧

Many companies have multiple portals, and having them share common code is certainly the scenario we’d prefer, so what are the challenges to sharing code between Nuxt projects?

许多公司都有多个门户,让它们共享通用代码无疑是我们首选的方案,那么在Nuxt项目之间共享代码有哪些挑战?

Normally shared code is in the form of an npm package with importable components, and that can be done with Nuxt, but the thing about Nuxt is that it offers some lovely features that are exclusively tied to its directory structure, and it only allows for one such structure.

通常,共享代码采用带有可导入组件的npm软件包的形式,并且可以使用Nuxt完成,但是Nuxt的事情是,它提供了一些仅与目录结构相关的可爱功能,并且仅允许一个这样的结构。

What if we want to share pages, layouts or components between projects? Let’s setup a sample project and walk through some ways to do that.

如果我们想在项目之间共享页面,布局或组件该怎么办? 让我们设置一个示例项目,并逐步完成该操作。

1)莱娜 (1) Lerna)

While not necessary, a lerna mono repo is easy to setup and means a great developer experience. We can make modifications in common code while running a portal and get hot reloading.

虽然不是必需的,但lerna mono repo易于设置,并且意味着出色的开发人员经验。 我们可以在运行门户网站时对通用代码进行修改并进行热重载。

Within a new folder let’s create a 2 package repo:

在一个新文件夹中,我们创建一个2软件包仓库:

> 
> lerna init
> lerna create portal-one --dependencies nuxt --yes
> lerna create portal-two --dependencies nuxt portal-one --yes
> lerna bootstrap

The empty packages can be started like this:

空包可以这样启动:

> cd packages/portal-one
> npx nuxt

Now the dev server is running and showing the default page.

现在,开发服务器正在运行并显示默认页面。

2)页数 (2) Pages)

In the first package we are going to create the first page.

在第一个包中,我们将创建第一页。

> mkdir pages
> cd pages
> echo '<template><div>Simple page</div></template' > one.vue

Now view http://localhost:3000/one (note the root page will no longer be generated)

现在查看http:// localhost:3000 / one (注意将不再生成根页面)

In order to get this page to be included in portal-two, we will package it as a Nuxt module. So in the root of portal-one create a file called module.js with the following:

为了使此页面包含在portal-two ,我们将其包装为Nuxt模块。 因此,在portal-one的根目录中创建一个名为module.js的文件, module.js包含以下内容:

// Nuxt exposes its default route builder logic here
import { createRoutes } from '@nuxt/utils'// with a lot of pages it might be worth considering a folder pass
// to dynamically create this list

const pages = ['pages/one.vue']export default function NuxtModule() {
const { routeNameSplitter, trailingSlash } = this.options.router this.extendRoutes((routes) => {
routes.push(...createRoutes({
files: pages,
srcDir: __dirname,
pagesDir: 'pages',
routeNameSplitter,
trailingSlash,
}))
})
}

Nuxt modules have a convenient extendRoutes helper exposed, coupling this with the Nuxt page-to-route generation (createRoutes), the code to inject the page routes is short and straight-forward.

Nuxt模块公开了一个方便的extendRoutes帮助器,将其与Nuxt页面到路由生成( createRoutes )结合使用,注入页面路由的代码简短明了。

In portal-two add a nuxt.config.js file with:

portal-two添加带有以下内容的nuxt.config.js文件:

export default {
modules: ['portal-one/module']
}

This could be configured as a build only module, but we might need more options later.

可以将其配置为仅构建模块,但是稍后我们可能需要更多选项。

Now stop the portal-one nuxt server and start one in portal-two(npx nuxt).

现在,停止portal-one nuxt服务器,并在portal-two ( npx nuxt )中启动一npx nuxt

View http://localhost:3000/one to confirm the page route was added successfully.

查看http:// localhost:3000 / one以确认页面路由已成功添加。

3)布局 (3) Layouts)

Back to portal-one and we will create a default layout:

回到portal-one ,我们将创建一个默认布局:

> mkdir layouts
> cd layouts
> echo '<template><center><nuxt/></center></template>' > default.vue

In module.js add :

module.js添加:

import { createRoutes, relativeTo } from '@nuxt/utils'
import path from 'path'...// at the end of the NuxtModule functionconst layoutPath = (file) =>
relativeTo(
this.options.buildDir,
path.resolve(__dirname, 'layouts', file),
)
this.nuxt.hook('build:templates', ({ templateVars }) => {
templateVars.layouts.default = layoutPath('default.vue')
})

Here we are using a hook to provide layouts at the right time in the build process. The layoutPath function will provide a path to the dependency layout files relative to the project build directory.

在这里,我们使用挂钩在构建过程中的正确时间提供布局。 layoutPath函数将提供相对于项目构建目录的依赖项布局文件的路径。

Refresh http://localhost:3000/one and the new default layout should be applied.

刷新http:// localhost:3000 / one ,应应用新的默认布局。

4)静态内容 (4) Static content)

In portal-one, we create a static robots file:

portal-one ,我们创建一个静态机械手文件:

> mkdir static
> cd static
> echo 'User-agent: *' > robots.txt

In module.js add :

module.js添加:

import serveStatic from 'serve-static'...// at the end of the NuxtModule functionthis.addServerMiddleware(
serveStatic(path.resolve(__dirname, 'static')),
)

This is the same middleware Nuxt uses internally for a local static folder, we just configure an additional one connected to the module’s static content.

这与Nuxt内部用于本地静态文件夹的中间件相同,我们只配置了一个附加到模块静态内容的中间件。

Restart the portal-two Nuxt server and view http://localhost:3000/robots.txt

重新启动portal-two Nuxt服务器并查看http:// localhost:3000 / robots.txt

5)组件 (5) Components)

As already mentioned, components can easily be imported from an npm package, but there is a nice feature in recent Nuxt versions, which discovers components. There are extension patterns out of the box, but here is another.

如前所述,可以很容易地从npm包中导入组件,但是在最新的Nuxt版本中有一个很好的功能,可以发现组件。 开箱即用的扩展模式,但这是另一个。

First let’s create our component and a page in portal-one:

首先,让我们在portal-one创建组件和页面:

> mkdir components
> cd components
> echo '<template><div>Simple Component</div></template>' > comp.vue
> cd ../pages
> echo '<template><comp/></template>' > compPage.vue

and if you want to test it in portal-one(from package root):

如果要在portal-one (从软件包根目录)中进行测试,请执行以下操作:

> echo 'export default { components: true }' > nuxt.config.js
> npx nuxt

View http://localhost:3000/compPage.

查看http:// localhost:3000 / compPage

Now to provide the same component and page in the module.js:

现在在module.js提供相同的组件和页面:

// update pages array
const pages = ['pages/one.vue', 'pages/compPage.vue']....// at the end of the NuxtModule functionthis.nuxt.hook('components:dirs', (dirs) => {
dirs.unshift({ path: path.resolve(__dirname, 'components') })
})

This is a hook specifically provided to extend the folders for components, however most examples specify a prefix and I have intentionally left it out.

这是专门提供的用于扩展组件文件夹的钩子,但是大多数示例都指定了前缀,而我故意将其省略。

Back in portal-two, add the components: true to the nuxt config, and run the server. http://localhost:3000/compPage should work here too.

返回portal-two ,将components: true添加到nuxt config,然后运行服务器。 http:// localhost:3000 / compPage也应该在这里工作。

One last thing, back to portal-one’s module.js and add:

最后一件事,回到门户网站一个的module.js并添加:

// at the end of the NuxtModule functionthis.nuxt.hook('components:extend', (components) => {
// If there are duplicates, give last the priority
const noDupes = Object.values(
components.reduce(
(map, comp) => ({ ...map, [comp.pascalName]: comp }),
{}
)
)
components.length = 0
components.push(...noDupes)
})

This code will remove duplicate components from the discovery process, giving the latter defined ones priority. This works in conjunction with the unshift in the dirs hook to ensure the local project components take priority.

此代码将从发现过程中删除重复的组件,并为后者定义的组件赋予优先级。 这与dirs钩中的unshift结合使用,以确保本地项目组件具有优先权。

Now from portal-two:

现在从第二portal-two

> mkdir components
> cd components

Create comp.vue and add:

创建comp.vue并添加:

<template>
<comp class="overridden"/>
</template><style>
.overridden { text-transform: uppercase; }
</style><script>
import comp from 'portal-one/components/comp.vue'export default {
components: { comp },
}
</script>

Back to http://localhost:3000/compPage and the local override should be applied. This pattern allows the local project to override common components (as a proxy if required) and provide them not only locally, but in common code also (the compPage in this case).

返回http:// localhost:3000 / compPage ,应应用本地替代。 这种模式允许本地项目覆盖公共组件(如果需要,可以作为代理),并且不仅在本地提供它们,还以公共代码(在这种情况下为compPage)提供它们。

That wraps it up, hope you find them helpful.

总结一下,希望对您有所帮助。

翻译自: https://medium.com/dailyjs/5-tips-for-sharing-code-between-nuxtjs-projects-6ffb5b7f8a25

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值