我用npm安装了第三方库。例如,我想在页面“ https://github.com/xkeshi/image-compressor”上导入库。但是我在页面开始处写的“从'image-compressor.js导入ImageCompressor”错误显示了“未定义窗口”错误。
如何在NextJS中获取第三方库?
答案 0 :(得分:0)
您可以使用next.config.js这样的设置
const path = require('path')
const withImages = require('next-images')
const withTM = require('next-transpile-modules')
const withTypescript = require('@zeit/next-typescript')
module.exports = withImages(
withTypescript(
withTM({
transpileModules: [
'react-native-elements',
'react-native-paper',
'react-native-ratings',
'react-native-safe-area-view',
'react-native-status-bar-height',
'react-native-vector-icons',
],
webpack(config, options) {
return {
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.ttf$/,
loader: 'url-loader', // or directly file-loader
include: path.resolve(
__dirname,
'node_modules/react-native-vector-icons'
),
},
],
},
resolve: {
...config.resolve,
extensions: [
'.web.ts',
'.web.tsx',
'.ts',
'.tsx',
'.web.js',
'.web.jsx',
'.js',
'.jsx',
...config.resolve.extensions,
],
alias: {
...config.resolve.alias,
'mobx-react/native$': 'mobx-react',
'react-native$': 'react-native-web',
},
},
}
},
})
)
)
或类似的东西
const withSass = require('@zeit/next-sass')
module.exports = withSass()
注意:这些是我从next.js存储库中提取的示例
答案 1 :(得分:0)
您需要为使用第3方库的组件进行动态导入。
// components/my-awesome.component.js
// import the library that use `window` object
import grapesjs from 'grapesjs';
export default function MyAwesomeComponent() {
// Initialize your component or do whatever you need to do
...
}
在页面定义中,使用dynamic
导入组件并禁用SSR
// import dynamic method from next
import dynamic from 'next/dynamic';
// import your component with dynamic and disable SSR
const MyAwesomeComponent = dynamic(
() => import('../components/my-awesome.component'),
{ssr: false}
);
// use your component
export default function () {
return <MyAwesomeComponent />;
}