webpack - NextJS webpack 配置 - 从编译中排除文件

标签 webpack next.js react-native-web

我需要一些关于 NextJS webpack 配置的帮助吗?

我在 React-NativeNextJS 之间有一个单一的代码库和共享代码。为了拆分特定于操作系统的代码,我将原生代码和网络代码分开,如下所示:(Login.web.tsx & Login.native.tsx)

示例:/Login/index.tsx

import React, { lazy, ReactElement, Suspense } from 'react'
import { Platform, View } from 'react-native'

const LoginComponent = lazy(() => (Platform.OS === 'web' ? import('./Login.web') : import('./Login.native')))

const Login = (props: NavigationProp): ReactElement => {
  return (
    <Suspense fallback={<View />}>
      <LoginComponent {...props} />
    </Suspense>
  )
}

export default Login

此示例代码位于 ui-screens 项目中,将被导入到唯一的 NextJS 页面中

import { Login } from '@monorepo/ui-screens'

export default function App() {
  return (
    <Login />
  )
}

React-Native 完美地处理了这个问题并加载了正确的 Login.native.tsx 页面。但是 NextJS webpack 编译器 仍然看到这个文件 Login.native.tsx 并尝试编译它,这显然会导致错误。

当我像那样更改 /Login/index.tsx 的代码时,出于测试目的,我的网络应用程序运行良好

const LoginComponent = lazy(() => (Platform.OS === 'web' ? import('./Login.web') : import('./Login.web')))

如何让 webpack 排除具有 *.native.* 扩展名的文件?

注意:我试过RemovePlugin:

const withPlugins = require('next-compose-plugins')
const withTM = require('next-transpile-modules')([
  'react-native',
  '@types/react-native',
  '@monorepo/ui-screens'
])
const RemovePlugin = require('remove-files-webpack-plugin')

module.exports = withPlugins([withTM()], {
  enableSvg: true,
  esModule: true,
  images: {
    disableStaticImages: true
  },
  plugins: [
    new RemovePlugin({
      before: {
        include: ['Login.native.tsx']
      }
    })
  ],
  webpack: (config) => {
    config.resolve.alias = {
      ...(config.resolve.alias || {}),
     'react-native$': 'react-native-web',
    }
    config.resolve.extensions = ['.web.js', '.web.jsx', '.web.ts', ...config.resolve.extensions]
    return config
  }
}

但是没有效果。

如有任何帮助,我们将不胜感激。

最佳答案

经过几个小时阅读 webpack 文档、Github 问题和评论,我终于找到了一个 super 简单的解决方案,叫做 webpackIgnore

只需将它插入到 import 命令中,我就可以告诉 webpack 在编译时完全忽略该文件:

const LoginComponent = lazy(
 () => (Platform.OS === 'web' ? 
 import('./Login.web'): 
 import(/* webpackIgnore: true */ './Login.native'))
)

我喜欢这个优雅的解决方案。

现在我只需要告诉我的 Typescript 编译器不要删除这一行。 🤔

关于webpack - NextJS webpack 配置 - 从编译中排除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71304663/

相关文章:

reactjs - react-native-web:编译失败(react-native-vector-icons)

react-native - 在/expo/build/Notifications 中找不到 AsyncStorage 模块

javascript - 如何将 alasql 与 webpack 结合使用?

使用 node.js API 的 Webpack 进度

reactjs - 页面加载时与 _next/webpack-hmr 的连接被中断

reactjs - next.js 和 material-ui - 让它们工作

ios - "Unhandled JS Exception: Can' t 仅在 iOS 中找到变量 setTimeout"

webpack - 如何在 vue.js 应用程序的生产环境中禁用源映射?

javascript - 如何使用 Babel 正确加载 .eot 和 .woff 文件?

javascript - 尝试更改输入 onChange 时遇到状态错误