我需要NextJS webpack 配置方面的幫助嗎?
我有一個單一存盤庫并在React-Native和NextJS之間共享代碼。為了拆分特定于作業系統的代碼,我將本機代碼和 Web 代碼分開:( 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
}
}
但它沒有效果。
任何幫助將非常感激。
uj5u.com熱心網友回復:
在閱讀了幾個小時的 webpack 檔案、Github 問題和評論之后,我終于找到了一個超級簡單的解決方案,叫做webpackIgnore
只需將其插入import命令中,我就可以告訴 webpack 在編譯時忽略該檔案:
const LoginComponent = lazy(
() => (Platform.OS === 'web' ?
import('./Login.web'):
import(/* webpackIgnore: true */ './Login.native'))
)
我喜歡這個優雅的解決方案。
現在我只需要告訴我的 Typescript 編譯器不要洗掉這一行。??
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437308.html
