在跟着webpack官网指南打的时候,打到shimming这个章节使用到imports-loader,但是报'import' and 'export' may only appear at the top level
我的目录与官网类似
webpack-demo
|- package.json
|- webpack.config.js
|- /dist
|- /src
|- index.js
|- /node_modules
import _ from 'lodash';
import { cube } from './math';
import Print from './print'
if(process.env.NODE_ENV !== 'production') {
console.log('development');
}
// import './style.css';
function component ( ) {
var elm = document.createElement('div');
var btn = document.createElement('button');
var br = document.createElement('br');
elm.innerHTML = join(['hel1lo','webpack'], ' ');
// elm.innerHTML = ['hello webpac1k!'].join(' ');
btn.innerHTML = 'click print';
this.alert('Hmmm, this probably isn\'t a great idea...');
elm.appendChild(br);
elm.appendChild(btn);
btn.onclick = Print.bind(null, 'hello')
return elm;
}
document.body.appendChild(component())
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
app: './src/index.js',
vendor: ['lodash']
another: './src/another-module.js'
},
module: {
rules: [
{
test: require.resolve('./src/index.js'),
use: 'imports-loader?this=>window'
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use:[
'file-loader'
]
},
{
test: /\.(csv|tsv)$/,
use: [
'csv-loader'
]
},
{
test: /\.xml$/,
use: [
'xml-loader'
]
},
]
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'production'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'runtime'
}),
new webpack.ProvidePlugin({
join: ['lodash', 'join']
})
],
output: {
filename: '[name].[hash].bundle.js',
path: path.resolve(__dirname, 'dist'),
chunkFilename: '[name].bundle.js'
}
}
但是报了以下错误
ERROR in ./src/index.js
Module parse failed: 'import' and 'export' may only appear at the top level (7:0)
You may need an appropriate loader to handle this file type.
| * Created by Administrator on 2017/10/23.
| */
| import _ from 'lodash';
| import { cube } from './math';
| import Print from './print'
@ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/index.js
但是使用import()或者require()的方式是没问题的,是因为ES6 import一定要放顶层的缘故吗?求大神们解答一下
的确ES6的
import
和export
一定是要在最外层,不能被包含在函数或是代码块中。但是这里实际上并没有使用
imports-loader
吧,虽然在webpack中有配置,但是在js中并不是通过require+参数方式使用。可以多研究下
imports-loader
的文档。https://www.npmjs.com/package...