2017-07-25 161 views
1

我想建立一個基本的模塊化程序,但我似乎遇到導入模塊的問題。我試圖導入我的自定義模塊,我得到以下錯誤巴貝爾ES6導入錯誤,SyntaxError:意外的令牌導入

(function (exports, require, module, __filename, __dirname) { import testStep from 'testStep'; 
                  ^^^^^^ 
SyntaxError: Unexpected token import 

導致該問題的代碼:

testcase.js

import testStep from 'testStep'; 

testStep.hello(); 

testStep.js

var testStep = { 
    hello: hello, 
}; 

var hello =() => { 
    console.log('hello world'); 
}; 

export default {testStep}; 

package.json

{ 
    "name": "rebuild-poc", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
    }, 
    "author": "", 
    "license": "ISC", 
    "devDependencies": { 
    "babel-polyfill": "^6.23.0", 
    "babel-preset-env": "^1.6.0" 
    }, 
    "dependencies": {} 
} 

.babelrc

{ 
    "presets": [ 
    "env" 
    ] 
} 

我已經嘗試過其他幾個補丁,比如設置一步步測試,作爲一個階級,以及使用要求(」 ./ testStep.js'),但那些都似乎已經工作了。

我有什麼東西與babel或我的文件之一設置不正確嗎?

***編輯:我正在運行testCase.js與 '節點testCase.js'

+0

看起來像'testStep'中有一個額外的括號或額外逗號 – Matthew

+1

'import'不能在一個函數內 –

+0

@Meshe在es6尾隨逗號是允許的,但我試過了,它刪除了,它沒有修復問題。 –

回答

4

請安裝babel-cli並致電您的文件:./node_modules/.bin/babel-node testcase.js

它會失敗。現在我們必須修復你的代碼。

testStep.js應該是這樣的:

var hello =() => { 
    console.log('hello world'); 
}; 

var testStep = { 
    hello: hello, 
}; 

export default testStep; 

然後,它會工作。 ;)

https://babeljs.io/的第一次介紹是,你應該安裝babel-clibabel-preset-env。 ;)

你也可以寫你的testStep.js這樣的:

var testStep = { 
    hello: hello, 
}; 

function hello() { 
    console.log('hello world'); 
}; 

export default testStep; 

這使提升的初衷。像Jacob在他的第一點說。

+1

這解決了我的問題!謝謝! –

0
  1. 您需要定義hellofunction,使用var,你不會有function hoisting,所以聲明testStep時,hello未定義。

  2. 如果要使用es模塊,可以使用babel-registerbabel-node。 在您的代碼中,節點無法處理es模塊。

通天註冊

隨着倍倍爾註冊,所有的模塊將被處理巴貝爾在導入時。

首先,yarn add babel-register babel-cli --devnpm install babel-register babel-cli -dev 然後創建一個入口文件:

// entry.js 
require('babel-register') 
require('testcase') 

在你的測試用例,你可以使用ES模塊現在。

編輯您的package.json:

"scripts": { 
    "test": "node entry.js" 
}, 

可以運行在終端yarn testnpm run test。你不需要babel-polyfill,這是瀏覽器,而不是節點。

+0

解決吊裝問題的好處。 ;) – danbruegge

0

從巴貝爾6發行說明:

插件預置

$ npm install --save-dev babel-preset-es2015 

保存它.babelrc文件

{ 
    presets: [「es2015」] 
} 

發佈說明: https://babeljs.io/blog/2015/10/29/6.0.0

+1

巴別爾建議使用另一個軟件包'babel-preset-env' –

相關問題