我在尝试将Typescript应用到我的项目中时遇到了一些问题。
- 使用Webpack和Babel进行文件的转译和打包
- 使用
babel-loader
与@babel/preset-typescript
- 不使用
tsc
这是我的配置文件。
webpack.dev.js
const config = {
// (...) BUNCH OF OTHER CONFIG LINES
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/, // USE THE babel-loader FOR THESE FILE EXTENSIONS
include: path.resolve(__dirname, "src"),
use: ['babel-loader']
}
]
}
}
module.exports = config;
babel.config.js
module.exports = function (api) {
let presets = [];
let plugins = [];
presets = [ // NOTE: PRESET ORDER IS LAST TO FIRST
[
"@babel/preset-env",
{
targets: "> 0.25%, not dead"
}
],
"@babel/preset-react",
"@babel/preset-typescript"
];
plugins = [
"react-hot-loader/babel",
"babel-plugin-styled-components"
];
return ({
presets,
plugins,
// overrides
});
};
index.tsx
import React from "react";
import ReactDOM from "react-dom";
import firebase from './firebase/firebase';
import App from './App';
ReactDOM.render(
<App
firebase={firebase}
/>
,document.getElementById("root")
);
App.tsx
import React from "react";
import firebase from "firebase/app";
interface App_PROPS{
firebase: firebase.app.App | null;
};
const App: React.FC<App_PROPS> = () => {
return(
<div>App</div>
)
};
export default App;
注意:firebase.ts
是一个导出 firebase 应用对象
的 .ts
文件。
当我执行 npm start
命令时,我会遇到以下错误:
ERROR in ./src/index.tsx
Module not found: Error: Can't resolve './App'
ERROR in ./src/index.tsx
Module not found: Error: Can't resolve './firebase/firebase'
这个配置对于
JS
文件可以正常工作。