在 webpack 中如何修复“导入声明可能只出现在模块的顶层"? [英] In webpack how do I fix 'import declarations may only appear at top level of a module'?

查看:66
本文介绍了在 webpack 中如何修复“导入声明可能只出现在模块的顶层"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Webpack 构建成功,我可以浏览到我的网页.但是,Javascript 失败,说:导入声明可能只出现在模块的顶层"

下面是我输出的包含导入语句的 app.js.

如何更改我的 webpack 配置文件以在构建时去掉 import 语句?

webpackJsonp([0],{/***/0:/***/功能(模块,出口,__webpack_require__){__webpack_require__(1);__webpack_require__(74);module.exports = __webpack_require__(76);/***/},/***/76:/***/函数(模块,导出){严格使用";导入'app/tools/typescriptImports.ts';import * as mainScreenHelper from 'app/tools/mainScreenHelper';从反应"导入反应;import * as reactDom from 'react-dom';从反应路由器"导入路由器;从'history/lib/createBrowserHistory'导入createBrowserHistory;从app/tools/routes"导入路由;导入样式/app.scss";导入 'font-awesome/scss/font-awesome.scss';mainScreenHelper.removeLoadingScreen();mainScreenHelper.createReactApp();/***/}});//# sourceMappingURL=app.js.map

这是我当前的配置文件:

'use strict';//https://webpack.github.io/docs/configuration.htmlvar webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');var CopyWebpackPlugin = require('copy-webpack-plugin');var path = require('path');var rootPath = __dirname;//埃卡亚var srcPath = path.join(rootPath, 'src/client');//ekaya/src/客户端var distPath = path.join(rootPath, 'dist/client');//ekaya/dist/客户端模块.exports ={保释金:真的,缓存:真实,上下文:根路径,调试:真的,devtool: 'source-map',//inline-source-map, https://webpack.github.io/docs/configuration.html#devtool目标:'网络',//节点,网络开发服务器:{contentBase:distPath,historyApiFallback: 真,outputPath: path.join(distPath, 'devServer')},入口:{应用程序:path.join(srcPath, 'app/home.jsx'),lib: ['react', 'react-router', 'react-dom', 'jquery', 'lodash', 'history']},输出:{路径:distPath,公共路径:'',文件名:'[名称].js',路径信息:真},解决:{根:srcPath,扩展名:['', '.js', '.jsx', '.ts', '.tsx'],modulesDirectories: ['node_modules', srcPath]},模块:{装载机:[{test:/\.js$/, loader: 'babel-loader?cacheDirectory', exclude:/(node_modules)/},{test:/\.jsx$/, loader: 'babel-loader?cacheDirectory', exclude:/(node_modules)/},{test:/\.ts$/, loader: 'ts-loader?cacheDirectory', exclude:/(node_modules)/},{test:/\.tsx$/, loader: 'ts-loader?cacheDirectory', exclude:/(node_modules)/},{test:/\.scss$/, 加载器: ['style', 'css', 'sass']},{测试:/\.png$/,加载器:'文件加载器'},{测试:/\.jpg$/,加载器:'文件加载器'},{测试:/\.jpeg$/,加载器:'文件加载器'},{test:/\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=image/svg+xml'},{test:/\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/font-woff"},{test:/\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/font-woff"},{test:/\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/octet-stream"},{test:/\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader"}]},插件:[新的 CopyWebpack 插件([{ from: path.join(srcPath, 'images'), to: 'images' }]),新的 webpack.optimize.CommonsChunkPlugin('lib', 'lib.js'),新的 HtmlWebpack 插件({注入:真实,模板:path.join(srcPath, 'index.html')}),新的 webpack.NoErrorsPlugin()]};

我的 tsconfig.json

<代码>{buildOnSave":假,compileOnSave":假,编译器选项":{"allowJs": 真,"jsx": "反应","noImplicitAny": 真,"module": "commonjs","outDir": "dist/client/ts","removeComments": 真,源地图":假,目标":es5"},排除":[节点模块",区"]}

解决方案

我遇到了同样的问题.你安装了 ES6.导入失败,没有它.

babel 文件被复制而不被转换

<块引用>

默认情况下,Babel 6.x 不执行任何转换.您需要告诉它要运行哪些转换:

npm install babel-preset-es2015

<块引用>

然后运行

babel --presets es2015 proxy.js --out-file proxified.js

<块引用>

或创建一个包含

的 .babelrc 文件

<代码>{预设":[es2015"]}

Webpack builds successfully and I can browse to my webpage. However, the Javascript fails, saying: 'import declarations may only appear at top level of a module'

Below is my outputted app.js that contains the import statements.

How do I change my webpack config file to get rid of the import statements when it builds?

webpackJsonp([0],{

/***/ 0:
/***/ function(module, exports, __webpack_require__) {

    __webpack_require__(1);
    __webpack_require__(74);
    module.exports = __webpack_require__(76);


/***/ },

/***/ 76:
/***/ function(module, exports) {

    "use strict";

    import 'app/tools/typescriptImports.ts';
    import * as mainScreenHelper from 'app/tools/mainScreenHelper';
    import React from 'react';
    import * as reactDom from 'react-dom';
    import Router from 'react-router';
    import createBrowserHistory from 'history/lib/createBrowserHistory';
    import routes from 'app/tools/routes';
    import 'style/app.scss';
    import 'font-awesome/scss/font-awesome.scss';

    mainScreenHelper.removeLoadingScreen();
    mainScreenHelper.createReactApp();

/***/ }

});
//# sourceMappingURL=app.js.map

Here is my current config file:

'use strict';

//https://webpack.github.io/docs/configuration.html

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');
var rootPath = __dirname; //ekaya
var srcPath = path.join(rootPath, 'src/client'); //ekaya/src/client
var distPath = path.join(rootPath, 'dist/client'); //ekaya/dist/client

module.exports =
{
    bail: true,
    cache: true,
    context: rootPath,
    debug: true,
    devtool: 'source-map', //inline-source-map, https://webpack.github.io/docs/configuration.html#devtool
    target: 'web', //node, web
    devServer:
    {
        contentBase: distPath,
        historyApiFallback: true,
        outputPath: path.join(distPath, 'devServer')
    },
    entry:
    {
        app: path.join(srcPath, 'app/home.jsx'),
        lib: ['react', 'react-router', 'react-dom', 'jquery', 'lodash', 'history']
    },
    output:
    {
        path: distPath,
        publicPath: '',
        filename: '[name].js',
        pathInfo: true
    },
    resolve:
    {
        root: srcPath,
        extensions: ['', '.js', '.jsx', '.ts', '.tsx'],
        modulesDirectories: ['node_modules', srcPath]
    },
    module:
    {
        loaders:
        [
            {test: /\.js$/, loader: 'babel-loader?cacheDirectory', exclude: /(node_modules)/ },
            {test: /\.jsx$/, loader: 'babel-loader?cacheDirectory', exclude: /(node_modules)/ },
            {test: /\.ts$/, loader: 'ts-loader?cacheDirectory', exclude: /(node_modules)/ },
            {test: /\.tsx$/, loader: 'ts-loader?cacheDirectory', exclude: /(node_modules)/ },
            {test: /\.scss$/, loaders: ['style', 'css', 'sass']},
            {test: /\.png$/, loader: 'file-loader'},
            {test: /\.jpg$/, loader: 'file-loader'},
            {test: /\.jpeg$/, loader: 'file-loader'},
            {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=image/svg+xml'},
            {test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/font-woff"},
            {test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/font-woff"},
            {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader?mimetype=application/octet-stream"},
            {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader"}
        ]
    },
    plugins:
    [
        new CopyWebpackPlugin
        ([
            { from: path.join(srcPath, 'images'), to: 'images' }
        ]),
        new webpack.optimize.CommonsChunkPlugin('lib', 'lib.js'),
        new HtmlWebpackPlugin
        ({
            inject: true,
            template: path.join(srcPath, 'index.html')
        }),
        new webpack.NoErrorsPlugin()
    ]
};

My tsconfig.json

{
    "buildOnSave": false,
    "compileOnSave": false,
    "compilerOptions":
    {
        "allowJs": true,
        "jsx": "react",
        "noImplicitAny": true,
        "module": "commonjs",
        "outDir": "dist/client/ts",
        "removeComments": true,
        "sourceMap": false,
        "target": "es5"
    },
    "exclude":
    [
        "node_modules",
        "dist"
    ]
}

解决方案

I had the same problem. You installed ES6. The import fails w/o it.

Babel file is copied without being transformed

EDIT:

By default, Babel 6.x does not perform any transformations. You need to tell it what transformations to run:

npm install babel-preset-es2015

and run

babel --presets es2015 proxy.js --out-file proxified.js

or create a .babelrc file containing

{
    "presets": [
        "es2015"
    ]
}

这篇关于在 webpack 中如何修复“导入声明可能只出现在模块的顶层"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆