Babel无法正常用于ES6导入/导出

时间:2019-01-09 19:16:53

标签: javascript node.js express babeljs

我只是想让导入/导出代码在使用babel-node的浏览器中工作。但是到目前为止,我只能使它与一个文件一起使用。我不断在控制台中收到Uncaught SyntaxError:Unexpected token {,这无疑意味着它没有通过babel进行转换。

我尝试在package.json文件中使用不同的标志来运行该应用程序。以及将文件移动到不同的文件夹和目录。

        // App.js
        const express = require('express');
        const path = require('path');

        const app = express();

        console.log('App file')

        app.get('/', (req, res) => res.sendFile(path.join(__dirname+'/index.html')));

        app.use('/static', express.static('src'))

        const port = process.env.PORT || 8000;

        app.listen(port, () => console.log(`Server running on port ${port}.`))

package.json

        {
          "name": "babel-test",
          "version": "1.0.0",
          "description": "",
          "main": "app.js",
          "scripts": {
            "start": "nodemon app.js src/** --exec babel-node",
            "test": "echo \"Error: no test specified\" && exit 1"
          },
          "author": "AB",
          "license": "MIT",
          "dependencies": {
            "axios": "^0.18.0",
            "babel-cli": "^6.26.0",
            "babel-preset-env": "^1.7.0",
            "express": "^4.16.4",
            "nodemon": "^1.18.9"
          }
        }

文件夹树

            ├── app.js
            ├── index.html
            ├── node_modules
            ├── package-lock.json
            ├── package.json
            ├── public
            └── src
                ├── index.js
                ├── script1.js
                ├── script2.js
                ├── script3.js
                └── script4.js

index.html

            <!DOCTYPE html>
            <html lang="en">

            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <meta http-equiv="X-UA-Compatible" content="ie=edge">
                <title>NodeJS</title>
            </head>

            <body>

                <h1>Hi there from Nodejs</h1>
                <script src="http://localhost:8000/static/script1.js"></script>
                <script src="http://localhost:8000/static/script2.js"></script>
            </body>

            </html>

所有要做的就是处理文件之间的导入和导出语句,而不会出现错误。

1 个答案:

答案 0 :(得分:2)

您应该安装和设置Webpack。然后创建一个webpack.config.js文件并进行配置。 https://webpack.js.org/

相关问题