简体   繁体   English

如何编译导入的ES6节点模块?

[英]How to compile imported ES6 node modules?

I have an app written in ES6, and I am using babel to transform all of the files within that app. 我有一个用ES6编写的应用程序,并且正在使用babel转换该应用程序中的所有文件。 This app also includes a node_module with React components (that is also written in ES6). 这个应用程序还包括带有React组件的node_module(也用ES6编写)。

I am importing the components like so: 我正在像这样导入组件:

import { Box } from 'components/Box'

When I run 当我跑步

babel-node --presets es2015,stage-0,react

on the file that is importing the Box component, I get an error in the components/Box file on line 1: 在导入Box组件的文件上,在第1行的components / Box文件中出现错误:

(function (exports, require, module, __filename, __dirname) { import React, { Component } from 'react'
                                                              ^^^^^^
SyntaxError: Unexpected token import

I think the reason why this is happening is because babel-node is not transpiling the node_modules. 我认为发生这种情况的原因是因为babel-node没有转译node_modules。 Which, makes sense, since most node modules are written in commonjs format. 这是有道理的,因为大多数节点模块都是以commonjs格式编写的。 Is there a way to whitelist this particular node-module so it can be transpiled? 有没有一种方法可以将该特定的节点模块列入白名单,以便可以对其进行编译?

Can you provide more info? 您可以提供更多信息吗? maybe the other files you are referring to? 也许您要引用的其他文件? what are you trying to achieve? 您想达到什么目的?

I tried running the following package.json and it worked just fine. 我尝试运行以下package.json ,但效果很好。

{
  "name": "babel-node-test",
  "version": "1.0.0",
  "description": "",
  "main": "something.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "react": "^0.14.7"
  }
}

with these files as test: 这些文件作为测试:

something.js

import { Box } from './components/Box';

and components/box.js components/box.js

import React, { Component } from 'react';

class Box extends Component{

}

export default Box;

Also, on a side note, quoting from the docs: 另外,在旁注中,引用了文档:

Not meant for production use You should not be using babel-node in production. 不适用于生产用途您不应在生产中使用babel-node。 It is unnecessarily heavy, with high memory usage due to the cache being stored in memory. 由于缓存存储在内存中,因此不必要地增加了内存使用量。 You will also always experience a startup performance penalty as the entire app needs to be compiled on the fly. 由于整个应用程序都需要动态编译,因此您还将始终遭受启动性能损失。

why not use any of the build systems mentioned here https://babeljs.io/docs/setup/ 为什么不使用这里提到的任何构建系统https://babeljs.io/docs/setup/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM