【问题标题】:browser throw error of export/import keyword even webpack and babel is installed即使安装了 webpack 和 babel,浏览器也会抛出 export/import 关键字的错误
【发布时间】:2018-12-09 10:46:42
【问题描述】:

我正在使用核心 javascript 和 html 开发一个非常基本和简单的应用程序 我已经安装了 webpack v 4 并使用

启动服务器

npm run webpack

项目编译成功;下面是输出

> canvas@1.0.0 webpack /opt/parixan/canvas
> webpack-dev-server --inline --hot

ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wdm」: Hash: 99985e9b8632c783a375
Version: webpack 4.12.1
Time: 819ms
Built at: 2018-06-30 18:45:48
        Asset     Size  Chunks             Chunk Names
    bundle.js  354 KiB    main  [emitted]  main
bundle.js.map  406 KiB    main  [emitted]  main
Entrypoint main = bundle.js bundle.js.map
[./js/color.js] 359 bytes {main} [built]
[./js/index.js] 628 bytes {main} [built]
[./node_modules/loglevel/lib/loglevel.js] 7.68 KiB {main} [built]
[./node_modules/sockjs-client/dist/sockjs.js] 176 KiB {main} [built]
[./node_modules/url/url.js] 22.8 KiB {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 7.75 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.58 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.05 KiB {main} [built]
[./node_modules/webpack-dev-server/node_modules/strip-ansi/index.js] (webpack)-dev-server/node_modules/strip-ansi/index.js 161 bytes {main} [built]
[0] multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./js/index.js 52 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./node_modules/webpack/hot/dev-server.js] (webpack)/hot/dev-server.js 1.6 KiB {main} [built]
[./node_modules/webpack/hot/emitter.js] (webpack)/hot/emitter.js 77 bytes {main} [built]
[./node_modules/webpack/hot/log-apply-result.js] (webpack)/hot/log-apply-result.js 1.27 KiB {main} [built]
[./node_modules/webpack/hot/log.js] (webpack)/hot/log.js 1010 bytes {main} [built]
    + 14 hidden modules
ℹ 「wdm」: Compiled successfully.

但是当我导航到 localhost:8080/alphabet.html 时,它会在控制台中引发错误

Uncaught SyntaxError: Unexpected token export 。字母表.js:30

我还注意到 webpack.config.js

中提到的 build 文件夹下没有 bundle.js 文件

这是我的文件夹结构

├── README.md
├── alphabet.css
├── alphabet.html
├── build
├── fruits
├── js
      ├── alphabet.js
      ├── color.js
      └── index.js
├── .babelrc
├── package.json
└── webpack.config.js
  • 节点-v 8.9.2
  • npm -v 5.5.1
  • macOS -v 10.13.3
  • babel --version
    6.26.0 (babel-core 6.26.3)

.babelrc

{
    "presets": ["@babel/preset-env"]
}

package.json

 "scripts": {
    "webpack": "webpack-dev-server --inline --hot",
    "start": "http-server"
  },
  "main": "./js.index.js",

  "devDependencies": {
    "@babel/core": "^7.0.0-beta.51",
    "babel-loader": "^8.0.0-beta.4",
    "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/preset-env": "^7.0.0-beta.51",
    "babel-eslint": "^7.2.3",
    "babel-preset-es2015": "^6.24.1",
    "path": "^0.12.7"
  }

webpack.config.js

module.exports = {
  context: __dirname,
  entry: "./js/index.js",
  mode: "development",
  output: {
    path: __dirname + "/build",
    filename: "bundle.js"
  },
  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"]
  }
};

/js/index.js

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


const colorBox = color;
console.log("colorBox", colorBox);

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

fetchImage(colorBox);

js/alphabet.js

export const fetchImage = letter => {
  const fruit = fruits[letter] || "tamarindo";
  const request = new Request(`./fruits/${fruit}.png`, myInit);
  fetch(request)
    .then(response => response.blob())
    .then(blob => {
      const objectURL = URL.createObjectURL(blob);
      const img = new Image(200);
      img.src = objectURL;
      let element = document.getElementById("figure");
      while (element.firstChild) {
        element.removeChild(element.firstChild);
      }
      element.appendChild(img);
    });
};

我对这个 alphabet.html 文件的主要怀疑

alphabet.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Alphabet</title>
   <link rel="stylesheet" href="./alphabet.css">
</head>
<body>
    <div class="content" >
    <section class="alphabet"></section>
    <figure id="figure"></figure>
</div>
<script  src="./js/alphabet.js"></script>
</body>
</html>

如果我更改 &lt;script src="./js/index.js"&gt; 会引发错误

Uncaught SyntaxError: Unexpected token {

importexport 关键字无法识别

如何解决这个问题?

【问题讨论】:

  • 您是否尝试过使用&lt;script type="module" ... /&gt;?如果目标是使用应该有效的importexport 语句。
  • 哇......这就像魔术一样。请将此添加为答案
  • 1:webpack-dev-server 将 bundle 直接构建到内存中,这就是为什么最好使用 html-webpack-plugin,所以 bundle 会自动插入到你的 html 中。 2:您收到此错误是因为您引用的是 es6 文件,而不是实际的包。这可能不适用于所有浏览器。
  • 感谢@MatheusSilva 提供这些信息,但如何以及如何为 html-webpack-plugin 编写内容
  • github.com/jantimon/html-webpack-plugin 你只需要模板选项

标签: javascript node.js webpack babel-loader


【解决方案1】:

如果您的目标是启用 importexport 语句,则应在脚本标签上使用 module 类型:

<script type="module" ... />

这将被不支持它的旧浏览器忽略,这意味着您可以确保旧浏览器甚至不尝试解析它。为确保较新的浏览器不会解析旧代码,您可以使用nomodule

<script type="text/javascript" nomodule ... />

有关使用 &lt;script&gt; 标签的更多信息,请参阅 MDN 上的文档,例如:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

【讨论】:

    【解决方案2】:

    1:webpack-dev-server 将 bundle 直接构建到内存中,这就是为什么最好有 html-webpack-plugin 的原因,所以 bundle 会自动插入到你的 html 中。

    2:您收到此错误是因为您引用的是 es6 文件,而不是实际的包。这可能不适用于所有浏览器。


    要使用html-webpack-plugin只需将其添加到您的构建中。 Ps:这希望你有一个基本的 html,其中将插入资产。

    https://github.com/jantimon/html-webpack-plugin

    plugins: [
        new HtmlWebpackPlugin({
          template: 'path/to/my/index.html'
        })
      ]
    

    【讨论】:

    • 这会在启动 webpack 时出现此错误:Child html-webpack-plugin for "index.html": 1 asset Entrypoint undefined = index.html [./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 649 bytes {0} [built] [./node_modules/lodash/lodash.js] 527 KiB {0} [built] [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 489 bytes {0} [built] [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built] ℹ 「wdm」: Compiled successfully.
    • 如果你在任何地方都使用 __dirname,你不需要上下文...也不需要 .html 来在解析的扩展中。因为它被其他人打破而拒绝回答甚至没有意义。
    猜你喜欢
    • 2022-09-29
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 2018-09-11
    • 2022-06-30
    相关资源
    最近更新 更多