ES6 在 webpack 2 中导入 AMD(例如 jQuery 3.1.1)模块
ES6 import of AMD (e.g. jQuery 3.1.1) module in webpack 2
我正在使用最新最好的 webpack 2 版本进行一些测试,并在尝试将 jQuery 3.1.1 作为依赖项导入时遇到问题。
我只是使用 import {$} from 'jquery';
进行导入,但生成的包在执行时生成了一个异常 TypeError: __webpack_require__.i(...) is not a function
。
使用 const $ = require('jquery');
按预期工作。
据我了解,对于 webpack 2,我可以(几乎)独立于库的格式使用 es6 导入。
webpack.config.js:
'use strict';
const path = require('path');
const webpack = require('webpack');
function config(env) {
const PRODUCTION = env && typeof env.production !== 'undefined';
const PLUGINS = [
new webpack.DefinePlugin({
DEVELOPMENT: JSON.stringify(!PRODUCTION),
PRODUCTION: JSON.stringify(PRODUCTION)
})
];
if (PRODUCTION) {
PLUGINS.push(new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
dead_code: true,
unused: true,
}
}));
}
return {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js$/i,
include: /src/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
compact: false,
presets: [['es2015', {modules: false}]]
}
}
]
}
]
},
plugins: PLUGINS,
devtool: 'source-map'
};
}
module.exports = config;
两个问题:
- 这是一个错误还是只是没有按我预期的那样工作?
- 异常
TypeError: __webpack_require__.i(...) is not a function
一般表示什么错误?
我的错误:我使用了命名导入而不是默认导入。
正确:
import $ from 'jquery';
错误:
import {$} from 'jquery';
我正在使用最新最好的 webpack 2 版本进行一些测试,并在尝试将 jQuery 3.1.1 作为依赖项导入时遇到问题。
我只是使用 import {$} from 'jquery';
进行导入,但生成的包在执行时生成了一个异常 TypeError: __webpack_require__.i(...) is not a function
。
使用 const $ = require('jquery');
按预期工作。
据我了解,对于 webpack 2,我可以(几乎)独立于库的格式使用 es6 导入。
webpack.config.js:
'use strict';
const path = require('path');
const webpack = require('webpack');
function config(env) {
const PRODUCTION = env && typeof env.production !== 'undefined';
const PLUGINS = [
new webpack.DefinePlugin({
DEVELOPMENT: JSON.stringify(!PRODUCTION),
PRODUCTION: JSON.stringify(PRODUCTION)
})
];
if (PRODUCTION) {
PLUGINS.push(new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
dead_code: true,
unused: true,
}
}));
}
return {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js$/i,
include: /src/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
compact: false,
presets: [['es2015', {modules: false}]]
}
}
]
}
]
},
plugins: PLUGINS,
devtool: 'source-map'
};
}
module.exports = config;
两个问题:
- 这是一个错误还是只是没有按我预期的那样工作?
- 异常
TypeError: __webpack_require__.i(...) is not a function
一般表示什么错误?
我的错误:我使用了命名导入而不是默认导入。
正确:
import $ from 'jquery';
错误:
import {$} from 'jquery';