next.js 正在收集页面数据,TypeError:styled.div不是函数

q43xntqr  于 2023-05-06  发布在  其他
关注(0)|答案(1)|浏览(132)

我正在使用Vite构建一个包,但是当我在Next.js中使用这个包时,我得到了这个错误:
正在收集页面数据。TypeError:styled.div不是文件中的函数:dist/org-chart-maker.mjs:3:29 atModuleJob.run(node:internal/modules/esm/module_job:194:25)
我可以在Next.js项目中使用styled-components,但由于某种原因,Next.js将我的包中导入的styled-components视为undefined
我想问题出在我的配置上?
vite.config.ts

import { resolve as pathResolve } from 'node:path';
import { defineConfig } from 'vite';
import tsConfigPaths from 'vite-tsconfig-paths';
import svgr from 'vite-plugin-svgr';
import reactPlugin from '@vitejs/plugin-react';
import { peerDependencies } from './package.json';

export default defineConfig({
  plugins: [
    tsConfigPaths(),
    svgr({
      exportAsDefault: true,
    }),
    reactPlugin({
      jsxRuntime: 'classic',
    }),
  ],
  root: pathResolve(__dirname, 'src'),
  publicDir: pathResolve(__dirname, 'public'),
  build: {
    outDir: pathResolve(__dirname, 'dist'),
    emptyOutDir: true,
    copyPublicDir: false,
    sourcemap: true,
    minify: false,
    target: ['esnext'],
    lib: {
      entry: pathResolve(__dirname, 'src', 'index.ts'),
      formats: ['es', 'cjs'],
    },
    rollupOptions: {
      external: [...Object.keys(peerDependencies)],
      output: {
        interop: 'auto',
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM',
          'styled-components': 'styled',
        },
      },
    },
  },
});

组件:

import styled from 'styled-components';
const StyledDiv = styled.div``;
const Test = () => <StyledDiv>hello</StyledDiv>;
export default Test;

输出为org-chart-maker.js

"use strict";
const React = require("react");
const styled = require("styled-components");
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
const React__default = /* @__PURE__ */ _interopDefault(React);
const styled__default = /* @__PURE__ */ _interopDefault(styled);
const StyledDiv = styled__default.default.div``;
const Test = () => /* @__PURE__ */ React__default.default.createElement(StyledDiv, null, "hello");
module.exports = Test;
//# sourceMappingURL=org-chart-maker.js.map

输出为org-chart-maker.mjs

import React from "react";
import styled from "styled-components";
const StyledDiv = styled.div``;
const Test = () => /* @__PURE__ */ React.createElement(StyledDiv, null, "hello");
export {
  Test as default
};
//# sourceMappingURL=org-chart-maker.mjs.map
bvjveswy

bvjveswy1#

问题似乎是:
由于某些原因,当文件以.mjs结尾时,NextJS无法正确解释文件
https://github.com/rollup/rollup/issues/4438#issuecomment-1296908287
修复方法是将build.lib.filename设置为:

(format) => `org-chart-maker.${format}.js`

相关问题