我正在尝试使用 webpack 和 webpack-dev-server 在 React 组件中显示图像,作为项目的一部分。
到目前为止我已经完成了以下步骤:
- 使用 npm 安装文件加载器
- 更新了 webpack.config.js 以添加图像文件加载器
- 将我想要的图像导入到我的组件中
- 在我的 img 标签中使用了导入
采取这些步骤后,webpack 无法编译并出现“找不到模块”错误:
ERROR in [at-loader] ./src/components/App.tsx:4:26
TS2307: Cannot find module '../images/kitten-header.jpg'.
我的文件夹结构如下:
/dist
/images
kitten-header.jpg
bundle.js
bundle.js.map
/node_modules
(content ignored for brevity)
/src
/components
App.tsx
/images
kitten-header.jpg
/styles
App.less
index.tsx
index.html
package.json
tsconfig.json
webpack.config.js
我添加到 webpack.config.js 的新加载器是:
test: /\.(jpe?g|gif|png|svg)$/, loader: "file-loader?name=./images/[name].[ext]"
我已经在 App.tsx 中导入了图像文件,如下所示:
import kittenHeader from '../images/kitten-header.jpg';
...并在 img 标签中使用导入,如下所示:
<img src={ kittenHeader } />
Note:提供了 webpack.config.js 和 App.tsx 的全文,直到我更接近答案并意识到它们不相关(请参阅更新 1)。
我假设我在导入中的相对路径方面犯了一些非常微不足道的错误。正如你可以想象的,我尝试了各种替代方案。
任何人都可以提供一些见解吗?
作为参考,由于我不断遇到与错误版本的 webpack 相关的文章和问题,以下是我的版本:
- 反应15.5.4
- 网页包 2.6.1
- Webpack-开发服务器 2.4.5
- 打字稿 2.3.2
Update 1: 2017.06.05
So, looking at
this SO question https://stackoverflow.com/questions/42793207/webpack-loader-cannot-find-module and
this post on Medium https://medium.com/@sapegin/css-modules-with-typescript-and-webpack-6b221ebe5f10, I've been able to identify that the problem lies not with how I've used webpack, but with that fact that I'm using TypeScript. The error is a typescript error caused by the fact that the typescript compiler doesn't know what a .jpg file is.
显然,我需要提供 d.ts 文件或使用 require 语句。
差不多了...