2016-12-25 88 views
5

我剛剛開始使用React.js,無法導入組件。React無法導入組件 - 找不到模塊

我有這樣的結構,其次是this tutorial (YouTube link)

-- src 
----| index.html 
----| app 
------| index.js 
------| components 
--------| MyCompontent.js 

這是我index.js

import React from 'react'; 
import { render } from 'react-dom'; 

import { MyCompontent } from "./components/MyCompontent"; 

class App extends React.Component { 
    render() { 
     return (
      <div> 
       <h1>Foo</h1> 
       <MyCompontent/> 
      </div> 
     ); 
    } 
} 

render(<App />, window.document.getElementById('app')); 

這是MyComponent.js

import React from "react"; 

export class MyCompontent extends React.Component { 
    render(){ 
    return(
     <div>MyCompontent</div> 
    ); 
    } 
} 

我使用this webpack file (GitHub link)

但是,當我運行這個,我的模塊無法加載。

我得到這個錯誤在瀏覽器控制檯:

Error: Cannot find module "./components/MyCompontent"

[WDS] Hot Module Replacement enabled. bundle.js:631:11 
[WDS] Errors while compiling. bundle.js:631:11 
./src/app/index.js 
Module not found: Error: Cannot resolve 'file' or 'directory' ./components/MyCompontent in /home/kuno/code/react-hoteli/src/app 
resolve file 
    /home/kuno/code/react-hoteli/src/app/components/MyCompontent doesn't exist 
    /home/kuno/code/react-hoteli/src/app/components/MyCompontent.webpack.js doesn't exist 
    /home/kuno/code/react-hoteli/src/app/components/MyCompontent.web.js doesn't exist 
    /home/kuno/code/react-hoteli/src/app/components/MyCompontent.js doesn't exist 
    /home/kuno/code/react-hoteli/src/app/components/MyCompontent.json doesn't exist 
resolve directory 
    /home/kuno/code/react-hoteli/src/app/components/MyCompontent/package.json doesn't exist (directory description file) 
    /home/kuno/code/react-hoteli/src/app/components/MyCompontent doesn't exist (directory default file) 
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent] 
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.webpack.js] 
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.web.js] 
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.js] 
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.json] 
@ ./src/app/index.js 11:20-56 bundle.js:669:5 

想不通了什麼錯在這裏。

回答

3

您的導入中有錯字。您要求MyCompontent。更改爲:

import MyComponent from "./components/MyComponent"; 

還有所有錯別字。

+0

還是有同樣的錯誤; '錯誤:無法找到模塊「./components/MyCompontent」' – Kunok

+1

你有一個錯字,可能是相關的:'MyCompontent'而不是'MyComponent' –

+0

是的,這是一個錯字。對不起。 – Kunok

1

你可以嘗試從 「./components/MyCompontent.js」

這樣

import MyCompontent from "./components/MyCompontent.js"; 
0

你寫了一個文件名是MyComponent.js導入MyCompontent。

因此,您的導入應該像

import { MyCompontent } from './components/MyComponent.js' 
12

對於任何人來到這裏沒有一個錯字,並正在使用的WebPack,一定要檢查是否有這樣的條款:

resolve: { 
    extensions: [".jsx", ".js"] 
}, 

在您的webpack.config.js

這告訴你transpiler來解決類似的語句:

import Setup from './components/Setup' 

import Setup from './components/Setup.jsx' 

這樣,你不需要擴展。