删除text / babel类型以允许捆绑的js文件在浏览器

时间:2018-03-10 02:56:26

标签: javascript reactjs browserify babel babelify

我使用browserify将所有需求打包成适合在浏览器环境中运行的捆绑js文件。运行npm run build-dist命令时,以下代码运行正常。我现在如何更改package.json文件以从index.html文件中删除type="text/babel"属性?

index.js:

import React from 'react';
ReactDOM.render(<h1>Hello World</h1>, document.getElementById('root'));

的index.html

<html>
  <head>
    <title>React, Browserify Demo</title>
  </head>
  <body>
    <script src="bundle.min.js" type="text/babel"></script>
  </body>
</html>

的package.json

{
  "name": "facebookalbums2",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react-dom": "^16.2.0",
    "react-image-lightbox": "^4.5.0",
    "react-scripts": "1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",

    "build-dev": "browserify --debug src/index.js > build/bundle.min.js",
    "build-dist": "SET NODE_ENV=production & browserify src/index.js | uglifyjs -m > build/bundle.min.js",

    "watch-dev": "watchify --debug src/index.js -o build/bundle.min.js",
    "watch-dist": "SET NODE_ENV=production & watchify src/index.js | uglifyjs -m -o build/bundle.min.js"
  },
  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": ["env"],
          "compact":false
        }
      ]
    ]
  },
  "babel": {
    "presets": [
      "env",
      "react",
      "stage-2"
    ]
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "babelify": "^8.0.0",
    "browserify": "^16.1.1",
    "react": "^16.2.0",
    "uglify-js": "^3.3.13",
    "watchify": "^3.11.0"
  }
}

删除“text / babel”属性时浏览器出错:

Uncaught Error: Target container is not a DOM element.
    at invariant (react-dom.development.js?ver=4.9.4:66)
    at renderSubtreeIntoContainer (react-dom.development.js?ver=4.9.4:15854)
    at Object.render (react-dom.development.js?ver=4.9.4:15964)
    at Object.11.react (bundle.min.js?ver=4.9.4:1)
    at f (bundle.min.js?ver=4.9.4:1)
    at s (bundle.min.js?ver=4.9.4:1)
    at bundle.min.js?ver=4.9.4:1

1 个答案:

答案 0 :(得分:0)

我试图根据我在wordpress插件+ Reactjs代码中看到的内容提供一个简单的示例。在我推出之前,我需要记住测试我的代码。谢谢大家。

<强>的index.html;

<html>
  <head>
    <title>React + Browserify Demo</title>
  </head>
  <body>
        <div id="root"></div>
    <script src="bundle.min.js"></script>
  </body>
</html>

<强> index.js:

import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<h1>Hello World</h1>, document.getElementById('root'));