尝试导入 ReactToastify.css 时如何修复“TypeError:rule.assign 不是函数”
Posted
技术标签:
【中文标题】尝试导入 ReactToastify.css 时如何修复“TypeError:rule.assign 不是函数”【英文标题】:How to fix "TypeError: rule.assign is not a function" when trying to import ReactToastify.css 【发布时间】:2022-01-18 03:07:30 【问题描述】:我可以import ToastContainer from 'react-toastify
没有问题,但是当我尝试
import 'react-toastify/dist/ReactToastify.css';
,报错:
./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[7].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[7].use[2]!./node_modules/react-toastify/dist/ReactToastify.css
TypeError: rule.assign 不是函数
我正在使用启用了“jit”模式的 next.js 和 tailwind css。
_app.js:
import 'tailwindcss/tailwind.css';
import '../public/css/syles.css';
import NavBar from '../components/NavBar';
// dynamic(
// () =>
// import('!style-loader!css-loader!react-toastify/dist/ReactToastify.css'),
// s-s-r: false <== tried this as a potential fix, but didn't work.
// );
// import dynamic from 'next/dynamic';
import ToastContainer from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function MyApp( Component, pageProps )
return (
<>
<ToastContainer position='top-center' />
<NavBar />
<Component ...pageProps />;
</>
);
export default MyApp;
package.json:
"name": "client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts":
"dev": "node server.js",
"build": "next build",
"start": "next start",
"lint": "next lint"
,
"keywords": [],
"author": "",
"license": "ISC",
"dependencies":
"@headlessui/react": "^1.4.2",
"@heroicons/react": "^1.0.5",
"@tailwindcss/line-clamp": "^0.2.2",
"axios": "^0.24.0",
"bootstrap": "^5.1.3",
"express": "^4.17.1",
"heroicons": "^1.0.5",
"http-proxy-middleware": "^2.0.1",
"next": "^12.0.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-toastify": "^8.1.0"
,
"devDependencies":
"autoprefixer": "^10.4.0",
"postcss": "^8.4.3",
"postcss-preset-env": "^7.0.1",
"tailwindcss": "^2.2.19"
任何建议将不胜感激。谢谢。
【问题讨论】:
我无法重现该问题。您是否尝试过删除.next
文件夹并再次运行应用程序?
@juliomalves 是的,我试过了,但还是一样的错误,除了现在它还显示TypeError: rule.assign is not a function at runMicrotasks (<anonymous>)
【参考方案1】:
好的,所以我通过 injectStyle 解决了它并在 useEffect() 中执行。
我参考了这个页面:https://fkhadra.github.io/react-toastify/how-to-style/#inject-style-on-demand
_app.js:
import 'tailwindcss/tailwind.css';
import '../public/css/syles.css';
import NavBar from '../components/NavBar';
import useEffect from 'react';
import ToastContainer from 'react-toastify';
import injectStyle from 'react-toastify/dist/inject-style';
function MyApp( Component, pageProps )
useEffect(() =>
injectStyle();
, []);
return (
<>
<ToastContainer position='top-center' />
<NavBar />
<Component ...pageProps />;
</>
);
export default MyApp;
【讨论】:
以上是关于尝试导入 ReactToastify.css 时如何修复“TypeError:rule.assign 不是函数”的主要内容,如果未能解决你的问题,请参考以下文章