WebPack (Next.js) 动态引入 报错 Cannot find module#
npm:ts-project-demo
const CONFIG_PATH = "ts-demo.js";
const config = require(CONFIG_PATH);
export default config;
project:
ts-demo.js
:
export default {
name: "yrobot",
};
/index.ts
:
import config from "ts-project-demo";
结果:
error - Error: Cannot find module '/$path_to_project/ts-demo.js'
原因#
- webpack 对于变量动态引入 不支持
参看Error: Cannot find module with dynamic import
方案#
- 不要用变量作为 path
const config = require("ts-demo.js");
import("./locales/" + locale + ".js");
多 react 实例 导致 报错 Invalid hook call#
在开发 react 组件库或者 hooks 库的时候,刚 link 完本地库,就出现了 Invalid hook call
报错提示。
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-h... for tips about how to debug and fix this problem.
原因#
排除 hooks 使用规范的问题,大概率是因为开发库的 node_modules 里的 react 和项目使用的 react 不是同一个实例导致的,即原因 3。
参看#13991 Hooks + multiple instances of React
方案#
yarn link 相关问题#
参看#1722 Add command to show linked packages
查看当前项目的相关 link#
( ls -l node_modules ; ls -l node_modules/@* ) | grep ^l
查看全局 link 项目#
ls ~/.config/yarn/link
解除全局 link#
rm -rf ~/.config/yarn/link/[node-name]
使用 Rollup 打包 多个 inputs,@rollup/plugin-node-resolve 失效(output 仍包含 require)#
解决方案:每个 input 分到一个独立打包进程#
rollup.config.ts
import ts from "rollup-plugin-ts";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
const inputs = [
{
file1: "src/file1.ts",
},
{
file2: "src/file2.ts",
},
];
export default inputs.map((input) => ({
input,
output: {
dir: "build",
format: "cjs",
entryFileNames: "[name].js",
chunkFileNames: "[name].js",
},
plugins: [
ts({
tsconfig: "tsconfig.json",
}),
resolve(),
commonjs(),
],
}));