我正在尝试在ReactJS应用程序中使用GSAP进行客户端动画制作。如果我通过npm安装gsap模块,然后尝试在模块中使用gsap,则会出现以下错误:

node_modules/gsap/src/uncompressed/TweenMax.js:2535
            _doc = document,
                   ^

ReferenceError: document is not defined
    at Function.<anonymous> (/Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/gsap/src/uncompressed/TweenMax.js:2535:11)
    at [object Object].check (/Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/gsap/src/uncompressed/TweenMax.js:5794:61)
    at new Definition (/Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/gsap/src/uncompressed/TweenMax.js:5811:10)
    at window._gsDefine (/Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/gsap/src/uncompressed/TweenMax.js:5816:12)
    at Array.<anonymous> (/Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/gsap/src/uncompressed/TweenMax.js:2489:11)
    at /Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/gsap/src/uncompressed/TweenMax.js:7570:9
    at Object.<anonymous> (/Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/gsap/src/uncompressed/TweenMax.js:7581:3)
    at Module._compile (module.js:435:26)
    at Module._extensions..js (module.js:442:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/gcardella/Documents/TOG/SOLID/mockups/solid-website/node_modules/babel-register/lib/node.js:138:7)


ReactJS中是否有编码的方法:如果它在服务器上呈现,则没有文档,因此请不要加载gsap,但是一旦下载了已编译的bundle.js(我的客户端负责接管客户端的js),请使用gsap因为文件存在?

我当前正在使用的解决方法是将gsap嵌入index.ejs中:

<!DOCTYPE html>
<html>
  <head>
    <title>Solid Website</title>
  </head>

  <body>
    <section id="react-app" class="container-fluid">
      <%- markup %>
    </section>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.2/TweenMax.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.2/TimelineMax.min.js"></script>
    <script src="build.js"></script>
  </body>
</html>


更新:webpack.config.js

var path = require('path');

module.exports = {
  entry: path.join(process.cwd(), 'client-render.js'),
  output: {
    path: './public/',
    filename: 'build.js'
  },
  module: {
    loaders: [
      {
        loader: 'babel'
      }
    ]
  }
}

最佳答案

在我的webpack.config.js中:

module.exports = {
  entry: path.join(process.cwd(), 'client/client-render.js'),
  output: {
    path: './public/',
    filename: 'build.js'
  },
  module: {
    loaders: [
      {
        test: /.js$/,
        loader: 'babel'
      }
    ]
  },
  /* this is new */
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        APP_ENV: JSON.stringify('browser')
      }
    })
  ]
}


然后在我的模块中:

if (process.env.APP_ENV === 'browser') {
  load_the_module_for_browser;
}

10-06 09:58