2016-05-04 12 views
8

Il Webpack viene compilato correttamente e posso navigare sulla mia pagina web. Tuttavia, Javascript non riesce, dicendo: "le dichiarazioni di importazione possono apparire solo al livello superiore di un modulo"Nel webpack come posso risolvere "le dichiarazioni di importazione possono comparire solo al livello superiore di un modulo"?

Di seguito è riportato il mio app.js che contiene le istruzioni di importazione.

Come si modifica il file di configurazione del pacchetto Web per eliminare le istruzioni di importazione durante la creazione?

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 

Ecco il mio attuale file di configurazione:

'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() 
    ] 
}; 

mio 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" 
    ] 
} 
+0

Potrebbe aggiungere il tsconfig.json? –

+0

babel-eslint. https://stackoverflow.com/questions/39158552/ignore-eslint-error-import-and-export-may-only-appear-at-the-top-level –

risposta

1

Ok, ho ottenuto questo per funzionare in qualche modo, non proprio sicuro di quale parte lo ha fatto, ma qui ci sono tutti i miei file di configurazione per chiunque abbia lo stesso problema in futuro;

webpack:

'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; 
var srcPath = path.join(rootPath, 'src/client'); 
var distPath = path.join(rootPath, 'dist/client'); 

module.exports = 
{ 
    bail: true, 
    cache: false, 
    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, 'typings'] 
    }, 
    module: 
    { 
     loaders: 
     [ 
      {test: /\.js$/, loader: 'babel-loader?cacheDirectory', exclude: /(node_modules|typings)/ }, 
      {test: /\.jsx$/, loader: 'babel-loader?cacheDirectory', exclude: /(node_modules|typings)/ }, 
      {test: /\.ts$/, loader: 'ts-loader?cacheDirectory', exclude: /(node_modules|typings)/ }, 
      {test: /\.tsx$/, loader: 'ts-loader?cacheDirectory', exclude: /(node_modules|typings)/ }, 
      {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() 
    ] 
}; 

.babelrc:

{ 
    "presets": ["es2015", "react"] 
} 

package.json

{ 
    "name": "ekaya", 
    "private": "true", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "dependencies": 
    { 
     "jquery": "2.2.3", 
     "lodash": "4.11.1", 
     "font-awesome": "4.6.1", 
     "history": "2.1.1", 
     "react": "15.0.2", 
     "react-dom": "15.0.2", 
     "react-router": "2.4.0", 

     "compression": "1.0.3", 
     "cors": "2.5.2", 
     "helmet": "1.3.0", 
     "loopback": "2.22.0", 
     "loopback-boot": "2.6.5", 
     "loopback-component-explorer": "2.4.0", 
     "loopback-datasource-juggler": "2.39.0", 
     "serve-favicon": "2.0.1" 
    }, 
    "devDependencies": 
    { 
    "node-sass": "3.7.0", 
    "nsp": "2.1.0", 
    "babel-core": "6.8.0", 
    "babel-loader": "6.2.4", 
    "babel-preset-es2015": "6.6.0", 
    "babel-preset-react": "6.5.0", 
    "css-loader": "0.23.1", 
    "file-loader": "0.8.5", 
    "jsx-loader": "0.13.2", 
    "font-awesome": "4.6.1", 
    "copy-webpack-plugin": "2.1.3", 
    "html-webpack-plugin": "2.16.1", 
    "sass-loader": "3.2.0", 
    "style-loader": "0.13.1", 
    "ts-loader": "0.8.2", 
    "typescript-loader": "1.1.3", 
    "typescript": "1.8.10", 
    "typings": "0.8.1", 
    "webpack": "1.13.0", 
    "webpack-dev-server": "1.14.1" 
    }, 
    "scripts": 
    { 
    "test": "echo \"Error: no test specified\" && exit 1", 
    "build": "./node_modules/.bin/webpack --progress --colors", 
    "run": "./node_modules/.bin/webpack-dev-server --hot --inline --progress --colors --watch" 
    }, 
    "repository": 
    { 
    "type": "git", 
    "url": "" 
    }, 
    "config": 
    { 
    "port": "8080" 
    }, 
    "author": "", 
    "license": "private", 
    "homepage": "" 
} 

tsconfig.json:

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

typings.json

{ 
    "ambientDependencies": { 
    "jquery": "registry:dt/jquery#1.10.0+20160417213236", 
    "lodash": "registry:dt/lodash#3.10.0+20160330154726", 
    "react": "registry:dt/react#0.14.0+20160423065914", 
    "react-dom": "registry:dt/react-dom#0.14.0+20160412154040" 
    }, 
    "dependencies": {} 
} 

Raccomando anche eliminare il proprio output compilato (mia cartella 'dist') e la ricostruzione, senza utilizzando il webpack devserver.

E dal momento che alcune delle tipizzazioni storia reagire-router non sembrano lavorare, scrivere il proprio:

declare module 'history/lib/createBrowserHistory' { 
    const x: any; 
    export = x; 
} 

declare module 'react-router' { 
    const x: any; 
    export = x; 
} 
11

Ho avuto lo stesso problema. Hai installato ES6. L'importazione fallisce senza.

Babel file is copied without being transformed

EDIT:

Per impostazione predefinita, Babel 6.x non esegue alcun trasformazioni. È necessario indicare cosa trasformazioni a correre:

npm install babel-preset-es2015 

ed eseguire

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

o creare a.file di babelrc contenente

{ 
    "presets": [ 
     "es2015" 
    ] 
} 
+0

@armatita ti rendi conto di una risposta minima che in realtà fornisce nuove l'informazione è molto meglio di niente, giusto? Perché ero l'unico a rispondere. E non era una risposta solo di collegamento. – DoktorDooLittle

+0

DoktorDooLittle Non ho minimizzato la tua risposta (se questo è ciò che hai assunto). Quando ho fatto la recensione (e ho notato che è apparso in revisione probabilmente perché qualcuno lo ha contrassegnato come di bassa qualità) la tua risposta non si adattava ai criteri SO. Quindi il suggerimento di commento (che è un testo pre-formattato). Sarò felice di rimuovere il mio commento di revisione in base alle informazioni aggiuntive. In ogni caso sembra che @Richard abbia trovato una soluzione. – armatita

+0

@armatita Non importa. Ho supposto che, mi dispiace per quello. Sì, ha involontariamente inciampato nella soluzione. Ho risposto interamente con il prossimo, cercando lo stesso problema in mente. – DoktorDooLittle

4

Ho incontrato lo stesso problema e ho scoperto che la mia struttura dei file è stato il problema:

I moduli possono solo importato dallo stesso o inferiore livello del punto di ingresso configurato in webpack.config.js in module.exports.entry, vale a dire:

module.exports = { 
    entry: path.resolve(__dirname, 'javascripts', 'main.js') 
} 

stavo cercando di importare locali da un livello più alto:

├── javascripts 
│ └── main.js 
└── locales 
    ├── de.js 
    └── en.js 

Dopo aver spostato la directory locali, l'importazione ha funzionato:

└── javascripts 
    ├── locales 
    │ ├── de.js 
    │ └── en.js 
    └── main.js 
2

Se stai seguendo la guida su https://webpack.js.org, potrebbe non rendersi conto che il sito è solo documentando Webpack versione 2 o successiva, non Webpack 1. Una delle nuove funzionalità di Webpack 2 è che include ES6 originale import, export e System.import.

È necessario installare Webpack 2 prima:

npm install --save-dev [email protected] 

Se si desidera visualizzare un elenco di tutti Webpack rilascia, eseguire:

npm show webpack versions --json