我用webpack,react,typescript等创建了boilder版项目,但每当我构建我的项目时,webpack就会在我的入口点抛出这个错误,无法解析其他模块(这只是简单的Login组件)这是我的webpack的错误信息
ERROR in ./src/index.tsx
Module not found: Error: Can't resolve './components/Login' in '/Users/myname/Desktop/Projects/front/src'
@ ./src/index.tsx 6:14-43
这是我的index.tsx文件
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import Login from './components/Login';
ReactDOM.render(
<BrowserRouter>
<Login />
</BrowserRouter>,
document.getElementById('root')
);
这是我的登录组件,webpack无法解析
import * as React from 'react';
export default () => <div>Login</div>;
这是我的webpack配置和package.json的脚本
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader',
options: {
useCache: true,
reportFiles: ['src/**/*.{ts,tsx}']
}
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'template/index.html'
})
],
mode: 'production',
output: {
path: path.resolve(__dirname, 'build/'),
filename: 'bundle.[hash].js'
},
plugins: [new CleanWebpackPlugin()]
};
package.json的脚本
"scripts": {
"build": "webpack"
},
我尝试尽量减少我的项目,以便你可以专注于这个单一的问题,为什么hack我的webpack无法解析普通的组件文件?你可以在https://github.com/sh2045/myproblem找到这个最小化的项目,你可以克隆它,然后运行
npm i
npm run build
你可以看到错误信息,请帮助:(
而不是使用awesome-typescript-loader
为什么不尝试webpack推荐的装载机打字机
要解决您的问题,
安装这个node
包npm install --save-dev typescript ts-loader
。这是执行ts到js转换的加载器。
你需要删除awesome-typescript-loader
并在ts-loader
中使用webpack.config.js
。以下是更新的webpack.config.js
。您可以使用此配置并执行npm run build
并验证您的webpack
是否捆绑了项目而没有错误
修改了webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader'
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
plugins: [
new HtmlWebpackPlugin({
template: 'template/index.html'
})
],
mode: 'production',
output: {
path: path.resolve(__dirname, 'build/'),
filename: 'bundle.[hash].js'
},
plugins: [new CleanWebpackPlugin()]
};
注意当我从你的git下载并设置你的项目时,我认为这个包npm i acorn --save
在你的package.json
中丢失了。所以我不得不手动安装它