![](/img/trans.png)
[英]Babel 7.18 doesn't transpile components outside the project root directory
[英]Import components outside the root folder with babel
我在 monorepo 中有多個項目: app1
app2
app3
,每個應用程序都是用 webpack 和 babel 構建的。
我想在應用程序之間創建一個包含共享組件的共享目錄,所以我在 monorepo 中創建了另一個目錄shared
。
(我在每個項目中執行npm i../shared
)
但是,當我從其中一個應用程序的shared
中導入組件時,babel 會引發異常: Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation. If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation. If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
注意:如果我從shared
導入簡單功能,它可以工作,只有在導入組件時它才不起作用。
我可以添加什么配置,以便可以使用共享組件創建共享目錄?
我在每個應用程序中的.babelrc
文件看起來像這樣
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"browsers": ["chrome >= 50"]
},
"useBuiltIns": "usage",
"corejs": 3
}
],
"@babel/preset-react",
"@babel/preset-typescript"
],
"plugins": ["@babel/plugin-syntax-jsx", "@babel/plugin-transform-react-jsx", "@babel/plugin-transform-runtime"]
}
您可以創建指向外部 package 的鏈接:
使用 npm 安裝本地模塊
如果您在團隊中工作,另一種可能性是更復雜的方法:
通過Git獲取npm模塊
至於插件的聲明,請參閱文檔(您需要一個“插件”數組,請參閱鏈接):
babel js 插件
看來,這更像是webpack
而不是babel
問題。 錯誤彈出,因為您的babel-loader
配置不正確。
在構建中添加“外部文件夾/模塊”時,您通常需要執行(或至少檢查)以下操作:
shared
文件夾的src
文件夾添加到您的babel-loader
的include
(如果尚未包含)
preset-react
實際上會起作用)。node_modules
文件夾,否則事情會非常緩慢)。shared
文件夾添加到您的babel-loader
的babelrcRoots ,因為否則,它將忽略其.babelrc.js
文件(如果它與您的babel-loader
的默認配置不同),因此只能使用默認設置,忽略您的preset-react
。shared
文件夾的src
文件夾添加到 webpack.config 的resolve.modules
中:
webpack
在該文件夾中執行它的解析魔法。node_modules
,也將其添加到resolve.modules
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.