浏览器里使用import

Author Avatar
Aryb1n 7月 10, 2017

开始

本来想只要在浏览器里用

<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);
</script>
<div id="root">
</div>

这样乱搞一下就可以了,结果发现会报错

Uncaught ReferenceError: require is not defined

天哦,找了找资料,好像是说不能只用babel就实现浏览器里支持import
看这样子只能用webpack

学习webpack

最后的目录结构是这样子的

.
├── app.js
├── bundle.js
├── index.html
├── node_modules
├── npm-debug.log
├── package.json
└── webpack.config.js

app.js

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

用webpack将app.js output成,然后引入到html里

index.html

<div id="root">
</div>
<script src="bundle.js">
</script>

遇到一个坑,就是这个bundle.js,放到root前面会报错,找不到root

Uncaught Invariant Violation: _registerComponent(…): Target container is not a DOM element.

package.json

{
  "name": "react_learn",
  "version": "1.0.0",
  "description": "an example",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "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.1",
    "babel-preset-react": "^6.24.1"
  }
}

这里是npm install 了 react, react-dom,以及打包相关的babel-*,这个一堆babel是为了支持es6的import,也就是我们目的所在

webpack.config.js

module.exports = {
  entry: './app.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  }
}

这些都配好以后只要 webpack一下就可以得到我们的bundle,在这里我跑了一下不知道为什么FF不可以,chrome是可以的