导入不适用于babel和webpack

时间:2018-09-11 09:50:44

标签: javascript webpack babel

我尝试使用webpack和babel启动一个新项目。 我可以使用我的代码es2015和es6。

但是我的导入遇到了麻烦。
当我尝试导入函数,变量或对象时,出现此错误:

错误

使用Chrome

  

未捕获的SyntaxError:意外的标识符

使用Mozilla

  

SyntaxError:导入声明只能出现在模块的顶层

你能告诉我怎么了吗?

这是我的结构

  • index.html
  • package.json
  • node_modules
  • webpack.config.js
  • 资产
    • dist
      • bundle.js
    • js
      • app.js
      • test.js

Webpack文件

const path = require('path');
module.exports = {
    entry: './assets/js/app.js',
    watch: true,
    mode: 'development',
    output: {
        path: path.resolve(__dirname, './assets/dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env'],
                    }
                },
            },
        ]
    }
};

Package.json

{
  "name": "svg-wipe",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/core": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/register": "^7.0.0",
    "babel-loader": "^8.0.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-register": "^6.26.0",
    "webpack": "^4.18.0",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.8"
  },
  "dependencies": {}
}

test.js

function myImport(m) {
    return console.log(m);
}
export default myImport;

app.js

import myImport from './test'

myImport('hello i m imported function !');

在我的index.html中

<script src="./assets/js/app.js" ></script>

谢谢!!

1 个答案:

答案 0 :(得分:2)

使用输出包。

<script src="./assets/dist/bundle.js" ></script>