背景
我想在任意目录下启动vite服务来支持预览。还有test file
:
- 测试文件将由
testFilePlugin
testFilePlugin
包含一些依赖于 commonJS 模块的代码:import { Fragment } from 'react/jsx-runtime'
- 已
react
安装在我的项目中
失败 1
// main.js
import { createServer } from 'vite';
import testFilePlugin from 'testFilePlugin';
createServer({
root: __dirname, // my project root
resolve: {
alias: {
'@root': process.cwd(),
},
},
plugins: [
testFilePlugin(), // handle for testFile
],
});
然后,我这样导入其他项目模块:</p>
import testFile from '@root/xx.test'
然后,我只是main.js
在其他目录中执行。但出现错误:
[vite] Internal server error: Failed to resolve import "react/jsx-runtime" from "xx.test". Does the file exist?
我确认它react
已安装在我的项目目录中。所以这个错误可能是因为vite正在根据其他目录的node_modules寻找模块。</p>
所以我想到了使用@rollup/plugin-node-resolve手动添加moduleDirectories:
失败 2
// main.js
import { createServer } from 'vite';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import testFilePlugin from 'testFilePlugin';
createServer({
root: __dirname, // my project root
resolve: {
alias: {
'@root': process.cwd(),
},
},
plugins: [
nodeResolve({
moduleDirectories: module.paths, // add my project moduleDirectories
}),
testFilePlugin(), // handle for testFile
],
});
重试后不再出现编译错误!但是浏览器出现运行时错误:</p>
Uncaught SyntaxError: The requested module '/@fs/.../myProject/node_modules/react/jsx-runtime' does not provide an export named 'Fragment
所以我想我应该使用@rollup/plugin-commonjs插件来解决这个问题:</p>
失败 3
// main.js
import { createServer } from 'vite';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import testFilePlugin from 'testFilePlugin';
createServer({
root: __dirname, // my project root
resolve: {
alias: {
'@root': process.cwd(),
},
},
plugins: [
nodeResolve({
moduleDirectories: module.paths, // add my project moduleDirectories
}),
commonjs({
include: /node_modules/,
}),
testFilePlugin(), // handle for testFile
],
});
这次终于没有运行时错误了!但是页面总是在加载。
查看网络请求,我发现了 4 个待处理请求:
http://localhost:3000/@id/__x00__/.../myProject/node_modules/react/cjs/react-jsx-runtime.production.min.js?commonjs-proxy
http://localhost:3000/@id/__x00__/.../myProject/node_modules/react/cjs/react-jsx-runtime.development.js?commonjs-proxy
http://localhost:3000/@id/__x00__/.../myProject/node_modules/react/cjs/react-jsx-runtime.development.js?commonjs-proxy
http://localhost:3000/@id/__x00__/.../myProject/node_modules/object-assign/index.js?v=a502bc89?commonjs-proxy
http://localhost:3000/@id/__x00__/.../myProject/node_modules/.vite/react.js?v=a502bc89&es-interop?commonjs-proxy
在上述尝试失败后,我决定放弃Vite插件来解决这个问题!</p>
然后,分享一下我尝试过的一些成功的解决方案:</p>
成功1
还要在目标目录中安装 react。
成功 2
手动添加react/jsx-runtime
到 vite 的pre-bundling 中:
{
...
optimizeDeps: {
include: ['react/jsx-runtime']
},
...
}
成功 3
然后通过我项目中的测试文件导入其他目录中的测试文件:
// index.js in my project
import testFile from './xx.test'
// xx.test in my project
import testFile from '@root/xx.test' // import other directory test file
结尾
- 我想知道这个要求是否有更好的解决方案?
- 失败的原因是
Failed x
什么?