Javascript / React(与Gulp / Babel) - 无法导入

时间:2017-07-19 10:27:37

标签: javascript reactjs jira

我正在为Atlassians JIRA系统开发一个插件,我想提供一些高级用户控件。 我已经尝试过实现ES2015 / Babel / Gulp,它可以使用ECMA6函数。 但是,我还有几个 - 已经过测试和验证 - 用React编写的控件可用。

从基本的东西开始,我试着引用一个例子并在我的视图中渲染它。 但是,我总是在浏览器中获得“No React-DOM”(如果我试图在我的主脚本中导入它,则为“No React”)。我在这里缺少什么?

ReactTest.js(摘录,只显示一些代码)

import React from 'react';

let MNMLogo = 'http://www.mercurynewmedia.com/images/default-source/logos/mercury-logo-circle-201x201.png';

class SimpleExample extends React.Component {
    // React components are simple functions that take in props and state, and render HTML
    render() {
        return (
            <div>
            ...
            </div>
        );
    }
}

导出默认SimpleExample;

主脚本(从我构建视图的地方)

import ReactDOM from 'react-dom';

var buildPage = function (auiUserSelectOptions) {
    ...

    ReactDOM.render(<SimpleExample />, document.getElementById("ReactTest"));
};

的package.json

"dependencies": {

},
"devDependencies": {
  "babel": "^6.23.0",
  "babel-preset-es2015": "^6.24.0",
  "babel-preset-react": "^6.0.15",
  "babel-register": "^6.24.0",
  "gulp": "gulpjs/gulp#4.0",
  "gulp-babel": "^6.1.2",
  "gulp-debug": "^3.1.0",
  "gulp-if": "^2.0.2",
  "gulp-plumber": "^1.1.0",
  "gulp-rename": "^1.2.2",
  "gulp-uglify": "^2.1.2",
  "lazypipe": "^1.0.1",
  "react": "^15.6.1",
  "react-dom": "^15.6.1"
},
"engines": {
  "node": "^6.9.0",
  "yarn": "^0.21.3"
},

我的观点“sucess.vm”(速度模板)

<html>
<head>
    <title>$i18n.getText("wfenhance.library-management.title")</title>
    <meta name="decorator" content="atl.admin">
</head>
...

<div id="ReactTest"></div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您需要使用Webpack或Browserify等模块捆绑包才能在应用程序中使用import。 Babel确实会将import转换为require,但浏览器无法require个模块。

我的建议是使用Webpack,因为这是目前最成熟和最受欢迎的捆绑包。在这种情况下,您也不需要使用Gulp。

的package.json

...
"scripts": {
  "watch": "webpack --progress --watch --display-error-details"
}
"dependencies": {
  "react": "^15.6.1",
  "react-dom": "^15.6.1"    
},
"devDependencies": {
  "babel-core": "^6.25.0",
  "babel-loader": "^7.1.1",
  "babel-preset-es2015": "^6.24.0",
  "babel-preset-react": "^6.24.0",
  "babel-register": "^6.24.0",
  "webpack": "^3.3.0"
},
"engines": {
  "node": "^6.9.0",
  "yarn": "^0.21.3"
},
...

webpack.config.js

(我猜你的源文件在/src内,而构建输出将转到/build

const path = require('path');

module.exports = {
  entry: ["src/js/main.jsx"], // The main script entry
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "js/bundle.js",
    publicPath: "/"
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.resolve(__dirname, "src"),
        use: 'babel-loader'
      }
    ]
  },

  resolve: {
    modules: ["node_modules", path.resolve(__dirname, "src")],
    extensions: [".js", ".jsx"],
  },
}

使用npm run watch

启动项目