简体   繁体   English

babel webpack import export关键字不起作用

[英]babel webpack import export keyword not working

I have created a simple HTML page with js now to add more functionality I have added webpack and install some node packages and run npm start webpack it starts fine and I can access localhost:8080 but it throws the error of import and export keyword. 我现在用js创建了一个简单的HTML页面以添加更多功能,我添加了webpack并安装了一些节点程序包并运行npm start webpack它可以正常启动,并且我可以访问localhost:8080,但是它抛出import和export关键字错误。

package.json 的package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack-dev-server --inline --hot",
    "start": "http-server"
},

"devDependencies": {
    "@babel/core": "^7.0.0-beta.51",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.7.0",
    "babel-register": "^6.26.0",
    "jsxobj": "^1.1.0",
    "webpack": "^4.12.1",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4",
    "webpack-node-externals": "^1.7.2"
  },
  "dependencies": {
    "babel-eslint": "^7.2.3",
    "babel-preset-es2015": "^6.24.1",
    "path": "^0.12.7"
  }

webpack.config.js webpack.config.js

var nodeExternals = require("webpack-node-externals");
module.exports = {
  entry: "./js/index.js",
  mode: "development",
  output: {
    path: __dirname + "/build",
    filename: "bundle.js"
  },
  target: "node",
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"]
          }
        }
      }
    ]
  },
  devtool: "source-map",
  resolve: {
    extensions: [".html", ".js", ".json", ".css", ".less"]
  }
};

js/index.js JS / index.js

import { fetchImage } from "../alphabet.js";

let i = 0;
const colorBox = {
    red: "#f00000",
    green: "#38c138",
    blue: "#0a6de8",
    orange: "#e69110",
    chocolate: "#1b1818",
    purple: "#632363",
    yellow: "#f1e904",
    bottle: "#102923",
    black: "#000000",
    white: "#d4d4d4"
};

const len = Object.keys(colorBox).length;

document.addEventListener(
    "keydown",
    e => {
        const key = e.key;
        i++;
        i = i % len == 0 ? 1 : i;
        let qs = document.querySelector(".alphabet");
        document.body.style.backgroundColor = Object.values(colorBox)[i];
        let str = key.toUpperCase();
        qs.innerHTML = str;
        fetchImage(key);
    },
    false
);

alphabet.html alphabet.html

 "use strict"; const fruits = { a: "apple", b: "banana", c: "coconut", e: "elephant", g: "grapes", l: "lemon", m: "mango", o: "orange", p: "pineapple", s: "strawberry", t: "tomato" }; export const fetchImage = letter => { console.log("letter", letter); const myHeaders = new Headers({ "Content-Type": "image/jpeg" }); const myInit = { method: "GET", headers: myHeaders, mode: "same-origin" }; const fruit = fruits[letter] || "tamarindo"; console.log("fruit", fruit); const myRequest = new Request(`./fruits/${fruit}.png`, myInit); fetch(myRequest) .then(function(response) { return response.blob(); }) .then(function(myBlob) { console.log("inside then"); var objectURL = URL.createObjectURL(myBlob); const img = new Image(200); img.src = objectURL; let element = document.getElementById("figure"); while (element.firstChild) { element.removeChild(element.firstChild); } element.appendChild(img); }); }; 
 .content { display: grid; grid-template: auto/ repeat(2, 1fr); align-items: center; justify-content: center; justify-items: center; color: white; grid-gap: 10px; font-weight: 700; font-family: 'Open Sans'; text-transform: uppercase; background-color: transparent; } .alphabet { font-size: 25em; } 
 <body> <div class="content"> <section class="alphabet"></section> <figure id="figure"></figure> </div> <script src="./js/index.js"></script> </body> 

alphabet.js alphabet.js

.babelrc .babelrc

{{
    "presets": ["env", {
      "targets": {
        "node": "current"
      }
    }]
}

How make simple JS program to understand export and import keyword? 如何使简单的JS程序理解导出和导入关键字?

You are using target: node in webpack, which is not supposed to work on browser, especially with nodeExternals. 您正在使用webpack中的target: node ,这在浏览器上不起作用,尤其是在nodeExternals上。 Try to remove the following lines: 尝试删除以下行:

  • target: "node" : is used when the script would be used by nodejs, just remove it and it will be set as target: "browser" by default. target: "node" :在nodejs使用脚本时使用,只需将其删除,默认情况下它将被设置为target: "browser"
  • externals: [nodeExternals()] - it means do not bundle these packages into the resulting file, but in this case browser wouldn't be able to find them. externals: [nodeExternals()] -表示不要将这些软件包捆绑到生成的文件中,但是在这种情况下,浏览器将无法找到它们。 Just remove this line. 只需删除此行。

update 更新

Working gist 工作要点

The main changes: 主要变化:

  • updated script in index.html index.html更新脚本
  • package.json : for simplicity, removed unnecessary packages and update babel-related packages (in order to work with babel 7), and updated webpack script (see in the comments) package.json :为简单起见,删除了不必要的软件包并更新了与babel相关的软件包(以便与babel 7一起使用),并更新了webpack脚本(请参见评论)
  • webpack.config.js : removed target: "node" and all node-related stuff webpack.config.js :删除了target: "node"以及所有与节点相关的东西

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

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