首页 > 解决方案 > 恒定导出不适用于反应应用程序

问题描述

babel我正在使用自己的配置从头开始构建简单的 React 应用程序,webpack而没有使用create-react-app.

Css 导入、React 组件、ES6 转译效果很好。当我创建常量文件并在我的组件文件中导入时,出现错误

我已经将常量移到组件本身,它工作正常。但是当我创建常量文件并从组件中导入它时,它不起作用。

export default SKILLS = [
  {
    id: 1,
    title: 'React',
    point: 8,
  },
  {
    id: 2,
    title: 'Redux',
    point: 8,
  }
]

这是我的常量文件代码

import SKILLS from '../data/skills';

这是在我的组件中导入部分

文件夹结构

|-data
|  |-skills.js
|-components
|  |-ResumeSection.js

这应该可以正常工作。

我在 chrome 的开发控制台上遇到的错误:

skills.js:2 Uncaught ReferenceError: SKILLS is not defined
    at eval (skills.js:2)
    at Module../src/data/skills.js (index_bundle.js:3921)
    at __webpack_require__ (index_bundle.js:727)
    at fn (index_bundle.js:101)
    at eval (ResumeSection.js:5)
    at Module../src/components/ResumeSection.js (index_bundle.js:3874)
    at __webpack_require__ (index_bundle.js:727)
    at fn (index_bundle.js:101)
    at eval (App.js:6)
    at Module../src/App.js (index_bundle.js:3828)
(anonymous) @ skills.js:2
./src/data/skills.js @ index_bundle.js:3921
__webpack_require__ @ index_bundle.js:727
fn @ index_bundle.js:101
(anonymous) @ ResumeSection.js:5
./src/components/ResumeSection.js @ index_bundle.js:3874
__webpack_require__ @ index_bundle.js:727
fn @ index_bundle.js:101
(anonymous) @ App.js:6
./src/App.js @ index_bundle.js:3828
__webpack_require__ @ index_bundle.js:727
fn @ index_bundle.js:101
(anonymous) @ index.js:6
./src/index.js @ index_bundle.js:3933
__webpack_require__ @ index_bundle.js:727
fn @ index_bundle.js:101
(anonymous) @ client:3
0 @ index_bundle.js:3944
__webpack_require__ @ index_bundle.js:727
(anonymous) @ index_bundle.js:794
(anonymous) @ index_bundle.js:797

我的 webpack 配置:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'index_bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader'],
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
}

标签: reactjswebpack

解决方案


这是无效的语法,如果要使用default导出,您有两个选择:

const SKILLS = [
  {
    id: 1,
    title: 'React',
    point: 8,
  },
  {
    id: 2,
    title: 'Redux',
    point: 8,
  }
]

export default SKILLS;
export default [
  {
    id: 1,
    title: 'React',
    point: 8,
  },
  {
    id: 2,
    title: 'Redux',
    point: 8,
  }
]

否则,您可以使用命名导出:

export const SKILLS = [
  {
    id: 1,
    title: 'React',
    point: 8,
  },
  {
    id: 2,
    title: 'Redux',
    point: 8,
  }
]

但这将用作import { SKILLS } from "../resources/skill";


推荐阅读