import m1 from './img/1.png' m1为undefined

环境:react^16.5.2+typescript3.1.2+url-loader^1.1.2

webpack.config.js

 module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif|svg|ico|cur)(\?[=a-z0-9]+)?$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 8192,
            name: 'images/[hash:6].[ext]',
            fallback: 'file-loader',
            publicPath: './dist/'
          }
        }]
      }
    ]
  }
}

test.tsx

 import * as React from 'react'
import m1 from './img/1.png'

import './index.less'
export default class Test extends React.Component<any, any> {
    constructor(props: any) {
        super(props)
    }
    componentDidMount () {
        console.log('图片地址') 
        console.log(m1) // undefined
    }


    render() {
        return (
            <div className='test'>
                <span>图片引入测试</span>
                <img src={m1} alt='test-m1' title='test-m1'/>
            </div>
        )
    }
} 

首先我保证import m1 from './img/1.png'的路径一没有写错

问题已解决,在这里自问自答一下希望可以帮助到有相同问题的同学们:主要问题有两点,第一个时图片的导入方式由原来的import m1 from './img/1.png'修改为import * as m1 from './img/1.png',第二点是在webpack.config.js中关于url-loader配置中的publicPath节点,由原来的publicPath: './dist/'修改为publicPath: './',从这里我们知道publicPath会影响项目启动时的资源路径,同时对于第一点为什么要修改为import * as m1 from './img/1.png'我也由疑惑,但是这样确实就可以了。正确源码大家可以通过以下路径访问到:https://github.com/dxiuxiu/react-typescript-urlLoader-fileLoader.git

你确定m1是存在的吗

说实话,这种用法虽然可以,但真正这么用的比较少,为什么要用loader处理图片呢,可以试试换种思路,在css中或sass中用图片,先将图片上传至cdn,或干脆编码至BASE64,都是可以的