简体   繁体   English

SyntaxError: 'import' 和 'export' 可能只与 'sourceType: module' 一起出现 - Gulp

[英]SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' - Gulp

Consider the following two files:考虑以下两个文件:

app.js

import Game       from './game/game';
import React      from 'react';
import ReactDOM   from 'react-dom';

export default (absPath) => {
  let gameElement = document.getElementById("container");

  if (gameElement !== null) {
      ReactDOM.render(
          <Game mainPath={absPath} />,
          gameElement
      );
  }
}

index.js

import App from './src/app';

The gulpfile.js gulpfile.js

var gulp        = require('gulp');
var source      = require('vinyl-source-stream');
var browserify  = require('browserify');
var babelify    = require("babelify");
var watch       = require('gulp-watch');

gulp.task('make:game', function(){
  return browserify({
    entries: [
      'index.js'
    ]
  })
  .transform('babelify')
  .bundle()
  .pipe(source('index.js'))
  .pipe(gulp.dest('app/'));
});

The error:错误:

gulp make:game
[13:09:48] Using gulpfile ~/Documents/ice-cream/gulpfile.js
[13:09:48] Starting 'make:game'...

events.js:154
      throw er; // Unhandled 'error' event
      ^
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

What is this error?这是什么错误? What am I doing wrong?我究竟做错了什么?

Older versions of Babel came with everything out of the box.旧版本的 Babel 随附开箱即用的所有内容。 The newer version requires you install whichever plugins your setup needs.较新的版本要求您安装设置所需的任何插件。 First, you'll need to install the ES2015 preset.首先,您需要安装 ES2015 预设。

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

Next, you need to tell babelify to use the preset you installed.接下来,您需要告诉 babelify 使用您安装的预设。

return browserify({ ... })
  .transform(babelify.configure({
    presets: ["es2015"]
  }))
  ...

Source来源

ESLint natively doesnt support this because this is against the spec. ESLint 本身不支持这一点,因为这违反了规范。 But if you use babel-eslint parser then inside your eslint config file you can do this:但是如果你使用 babel-eslint 解析器,那么在你的 eslint 配置文件中你可以这样做:

{
    "parser": "babel-eslint",
    "parserOptions": {
        "sourceType": "module",
        "allowImportExportEverywhere": true
    }
}

Doc ref: https://github.com/babel/babel-eslint#configuration文档参考: https : //github.com/babel/babel-eslint#configuration

Answer referred from here : ignore eslint error: 'import' and 'export' may only appear at the top level从这里引用的答案: 忽略 eslint 错误:'import' 和 'export' 可能只出现在顶层

I came across the same error trying to import a module from node_modules that exports in ES6 style.我在尝试从以 ES6 样式导出的node_modules中导入模块时遇到了同样的错误。 Nothing that has been suggested on SO worked out for me.没有任何关于 SO 的建议对我有用。 Then I found FAQ section on babelify repo .然后我在babelify repo上找到了 FAQ 部分。 According to the insight from there, the error appears since modules from node_modules are not transpiled by default and ES6 declarations like export default ModuleName in them are not understood by node powered by Common.js-style modules.根据那里的见解,出现错误是因为来自node_modules模块在默认情况下未转换,并且其中的 ES6 声明(如export default ModuleName不被 Common.js 样式模块支持的节点理解。

So, I updated my packages and then used global option to run babelify as a global transform excluding all node modules but the one I was interested in as indicated on the babelify repo page:因此,我更新了我的包,然后使用global选项将 babelify 作为全局转换运行,不包括所有节点模块,但我感兴趣的模块如 babelify repo 页面所示:

...    
browserify.transform("babelify", 
    {
        presets: ["@babel/preset-env"], 
        sourceMaps: true, 
        global: true, 
        ignore: [/\/node_modules\/(?!your module folder\/)/]
    }).bundle()
...

Hope it helps.希望它有帮助。

For some reason, babelify 8.0.0 didn't work for me with either the es2015 or env presents.出于某种原因,babelify 8.0.0 对我来说不管是 es2015 还是 env 都不起作用。 However, as of 2018-07-10 , the esmify plugin by mattdesl did work for me.但是, 截至 2018 年 7 月 10日, esmify插件对我有用 My test case was exporting Spinner from spin.js as a window global.我的测试用例是将Spinnerspin.js导出为全局窗口。 My example repo is here ;我的示例回购在这里 key details follow.关键细节如下。

main.js

import {Spinner} from 'spin.js';
window.Spinner = Spinner;

Test测试

In an empty directory:在空目录中:

npm init

and accept all defaults, then:并接受所有默认值,然后:

npm install --save spin.js
npm install --save-dev browserify esmify
npx browserify -p esmify main.js -o main-packed.js

Test HTML file测试 HTML 文件

<html><head>
    <link rel="stylesheet" href="node_modules/spin.js/spin.css" />
    <script src="main-packed.js"></script>    <!-- <== the browserify output -->
</head>
<body>
    <div id="x"></div>
    <script>
    var target = document.getElementById('x');
    var spin = new Spinner().spin(target);
    </script>
</body></html>

When loaded, it displays a spinner in the center of the page.加载后,它会在页面中央显示一个微调器。

Note: I am not affiliated with mattdesl or esmify.注意:我不隶属于 mattdesl 或 esmify。

In .eslintrc you may have to specify the parser options, for example:.eslintrc 中,您可能必须指定解析器选项,例如:

{
"rules": {
    "indent": [
        2,
        4
    ],
    "linebreak-style": [
        2,
        "unix"
    ],
    "semi": [
        2,
        "always"
    ]
},
"env": {
    "es6": true,
    "browser": true,
    "node": true,
    "mocha": true
},
"extends": "eslint:recommended",
"parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
        "jsx": true
    }
}

} }

Please check the documentation guide from eslint .请查看eslint的文档指南。

For correct compiling es2015-react code you should install some node modules:为了正确编译 es2015-react 代码,您应该安装一些节点模块:

globally全球

npm install -g browserify

in your app directory:在您的应用程序目录中:

npm install --save-dev browserify babelify babel-preset-es2015 babel-preset-stage-0 babel-preset-react

Then create gulp task:然后创建 gulp 任务:

    var browserify = require("browserify");
    var babelify = require("babelify");

    gulp.task('es6-compile', function() {
      browserify({ debug: true })
        .transform(babelify.configure({ presets: ["es2015","react", "stage-0"] }))
        .require("./public/src/javascripts/app.js", { entry: true })
        .bundle()
        .pipe(gulp.dest('./public/dest/javascripts'));
    });

In ./public/dest/javascripts directory you will find compiled es5 app.js file.在 ./public/dest/javascripts 目录中,您将找到已编译的 es5 app.js 文件。

If you want to use anything by import or require method in npm to clientside just do the following steps如果你想通过 npm 中的importrequire方法使用任何东西到客户端,只需执行以下步骤

  1. Run npm install browserify babelify @babel/preset-env @babel/preset-react @babel/core es2015 --save-dev to install the required presets运行npm install browserify babelify @babel/preset-env @babel/preset-react @babel/core es2015 --save-dev安装所需的预设
  2. Add this code into your package.json将此代码添加到您的package.json
"babel": {
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ] 
}
  1. Create a file named as dom_front.js inside of /app folder the file which you want to convert as clientside js./app文件夹中创建一个名为dom_front.js的文件,该文件要转换为客户端 js。
const ReactDOM  = require('react-dom')
import React, {Component} from 'react' 
export {Component,React,ReactDOM};

This is the mixed export data of modules and require files.这是模块和需要文件的混合导出数据。

Note: dont forget to install react-dom & react注意:不要忘记安装 react-dom & react

  1. Using browserify api - create js file such as browserifyload.js and assets folder使用 browserify api - 创建 browserifyload.js 等 js 文件和 assets 文件夹
const browserify = require("browserify")
const fs = require('fs')
browserify("./dom_front.js", {
  debug : true,
  standalone: "util"
}).transform(['babelify', { compact: false }], {
  global: true,                                  
  ignore: [/\/node_modules\/(?!@vizuaalog\/)/],     
  presets: [ 
    "@babel/preset-env",
    "@babel/preset-react"] 
  }).bundle().on('error', function (err) {
    console.log(err);  
  }).pipe(fs.createWriteStream('assets/mynpmmodule.js')).on('end', function(){
    console.log( 'finished writing the browserify file' );
  });
  1. Now the folder structure is现在文件夹结构是
app
--dom_front.js
--browserifyload.js
--assets(folder)
  1. Run /node_proj/app$ node browserifyload.js or run /node_proj/app$ browserify dom_front.js --transform babelify --standalone util > ./assets/mynpmmodule.js运行/node_proj/app$ node browserifyload.js /node_proj/app$ browserify dom_front.js --transform babelify --standalone util > ./assets/mynpmmodule.js或运行/node_proj/app$ browserify dom_front.js --transform babelify --standalone util > ./assets/mynpmmodule.js
  2. Check the assets folder, where it now creates the file named as mynpmmodule.js检查资产文件夹,它现在创建名为mynpmmodule.js的文件
  3. Add this file into your HTML <script src="assets/mynpmmodule.js"></script>将此文件添加到您的 HTML <script src="assets/mynpmmodule.js"></script>
  4. Now you can use the exported npm modules/classes or required files using the standalone key mentioned above util like现在,您可以使用上面提到的出口NPM模块/类或使用独立的密钥所需的文件util
<script>
  const Component = util.Component;
  console.log(Component);
  const ReactDOM = util.ReactDOM;
</script>

I tried all the answers above, none of them worked for me, I even tried using gulp-include / require syntax , they were neither the solution nor enough for my requirement.我尝试了上面的所有答案,没有一个对我有用,我什至尝试使用gulp-include / require 语法,它们既不是解决方案,也不足以满足我的要求。

Here was my requirement.这是我的要求。

  1. Bundle all modules/files into one将所有模块/文件捆绑成一个
  2. Keep all comments/JSDocs保留所有评论/JSDocs
  3. Keep all types ( such as const example = (parameter: string) => {} )保留所有类型(例如const example = (parameter: string) => {}
  4. Use import/export syntax使用导入/导出语法

The reason for the listed requirements is because we need a repository to store our shared-function, shared-config, shared-types, and shared constants as an npm package ( install with URL ).列出要求的原因是因为我们需要一个存储库来将我们的共享功能、共享配置、共享类型和共享常量存储为 npm 包(使用 URL 安装)。 In this case, we already know our projects are all using TypeScript so there is no need to compile our shared-module into .js , and we also need to keep all descriptions as other packages do ( JSDoc and Type really help ).在这种情况下,我们已经知道我们的项目都在使用 TypeScript,因此不需要将我们的共享模块编译成.js ,我们还需要像其他包一样保留所有描述(JSDoc 和 Type 确实有帮助)。

So far the best I can do is using browserify with tsify .到目前为止,我所能做的最好是使用browserifytsify I accidentally found this workaround from here .我不小心从这里找到了这个解决方法。

browserify()
    .plugin(tsify, { target: 'es6' })
    .transform(babelify, { extensions: [ '.tsx', '.ts' ] })

I am still searching for a way to keep our inline-types and comments/JSDocs, but I believe this is enough for your need.我仍在寻找一种方法来保留我们的内联类型和评论/JSDocs,但我相信这足以满足您的需要。

    return browserify(jsConfig.src)
  .transform(babelify.configure({
    presets: ["@babel/preset-env"]
  }))
  .bundle()
  .on('error', function (e) {
    console.log(e.message);

    this.emit('end');
  })

Works for me.为我工作。

This error can be caused by not including tsify plugin to compile typescript in the gulp task.这个错误可能是由于在 gulp 任务中没有包含 tsify 插件来编译打字稿。

example例子

    var tsify = require('tsify');

    return browserify({ ... })
      .plugin(tsify)
      .transform(babelify.configure({
        presets: ["es2015"]
      }))
      ...

See installation and usage here: https://www.npmjs.com/package/tsify在此处查看安装和使用: https : //www.npmjs.com/package/tsify

in my case i used export instead of exports .在我的情况下,我使用export而不是exports

change export to exports .出口更改为出口

暂无
暂无

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

相关问题 开玩笑的返回错误:SyntaxError:“导入”和“导出”可能仅与“ sourceType:“模块””一起出现(21:0) - jest return ERROR: SyntaxError: 'import' and 'export' may appear only with 'sourceType: “module”' (21:0) cypress + lerna: ParseError: 'import' 和 'export' 可能只出现在 'sourceType: module' 中 - cypress + lerna: ParseError: 'import' and 'export' may appear only with 'sourceType: module' Cypress ParseError: 'import' 和 'export' 可能只出现在 'sourceType: module' - Cypress ParseError: 'import' and 'export' may appear only with 'sourceType: module' &#39;import&#39; 和 &#39;export&#39; 只能与 &#39;sourceType: &quot;module&quot;&#39; 一起出现 (16:0) - 'import' and 'export' may appear only with 'sourceType: "module"' (16:0) ParseError: 'import' 和 'export' 可能只出现在 'sourceType: module', browserify - ParseError: 'import' and 'export' may appear only with 'sourceType: module', browserify Babel 7 不转译 node_modules 中的依赖项:&#39;import&#39; 和 &#39;export&#39; 可能只与 &#39;sourceType: module&#39; 一起出现 - Babel 7 not transpiling dependencies in node_modules: 'import' and 'export' may appear only with 'sourceType: module' 如何告诉 eslint:禁用下一行“&#39;import&#39;和&#39;export&#39;可能只与&#39;sourceType:module&#39;一起出现” - How to tell eslint to: disable next line "'import' and 'export' may appear only with 'sourceType: module'" NPM + Browserify 错误:ParseError: 'import' 和 'export' 可能只出现在 'sourceType: module' 中 - NPM + Browserify error: ParseError: 'import' and 'export' may appear only with 'sourceType: module' Browserify Rails错误-ParseError:“导入”和“导出”可能仅与“ sourceType:模块”一起出现 - Browserify Rails Error - ParseError: 'import' and 'export' may appear only with 'sourceType: module' create-react-app eslint 错误“解析错误:‘import’和‘export’可能只出现在‘sourceType:module’中” - create-react-app eslint error "Parsing error: 'import' and 'export' may appear only with 'sourceType: module'"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM