导入组件的时候省略后缀名
在webpack.config.js文件里添加如下代码
resolve:{
extensions:['.js','.jsx','.json']//表示这几个的后缀名可以参略
}
表示省略.js、.jsx、.json三个后缀名的文件
如我们创建Hello.jsx模块
import React from 'react'//创建组件、虚拟dom元素,生命周期
function Hello(props){
return <a>姓名:{props.name}---年龄:{props.age}</a>
}
export default Hello
然后在导入的时候只需要
import Hello from './components/Hello'
react会在components文件夹下根据extensions里的顺序依次查询,先查询Hello.js文件,发现没有,再查找Hello.jsx,如果还没有,就查找Hello.json
配置webpack根目录
在webpack.config.js文件里添加如下代码
resolve:{
alias:{
'@':path.join(__dirname,'./src')
}
}
导入模块的时候我们就可以写成
import Hello from '@/components/Hello'
webpack.config.js最终代码
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');//导入 在内存中自动生成index页面的插件
//创建一个插件的实例对象
const htmlPlugin = new HtmlWebPackPlugin({
template:path.join(__dirname,'./src/index.html'),//源文件
filename:'index.html'//生成的内存中的首页名称
})
module.exports = {
mode:'development', //development开发。production 发布
plugins:[
htmlPlugin
],
module: {
rules: [
{
test: /\.js|jsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
resolve:{
extensions:['.js','.jsx','.json'],//表示这几个的后缀名可以参略
alias:{
'@':path.join(__dirname,'./src')
}
}
}
网友评论