[英]ES6 Webpack Relative imports - Module not found: Error: Cannot resolve module
I'm trying to find some information about Webpack and relative imports when working with ES6 and Babel. 在使用ES6和Babel时,我试图找到有关Webpack和相对导入的一些信息。
I have an import line in a simple entry point in my app: 我的应用程序中的一个简单入口处就有一个导入行:
// app.es6
import * as sayHello from 'sayHello';
console.log(sayHello());
sayHello.es6
is the same directory as app.es6
. sayHello.es6
与app.es6
是同一目录。 (The contents of sayHello.es6
is not significant). (
sayHello.es6
的内容不重要)。
When I run the Webpack compiler via the command line: 当我通过命令行运行Webpack编译器时:
$ webpack
I get the following error: 我收到以下错误:
ERROR in ./app/app.es6
Module not found: Error: Cannot resolve module 'sayHello' in /Users/username/Code/projectname/app
This is solved by setting the path to relative: 这可以通过将路径设置为relative来解决:
// app.es6 - note the ./ in the import
import * as sayHello from './sayHello';
console.log(sayHello());
This is a bit of a pain because it's different to the example es6 code on Babel website under the Modules section. 这有点麻烦,因为它与Babel网站上“模块”部分下的示例es6代码不同。
Here is my Webpack config: 这是我的Webpack配置:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'babel-polyfill',
'./app/app.es6'
],
output: {
publicPath: '/',
filename: './dist/app.js'
},
debug: true,
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js|\.es6$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:
{
presets:['es2015']
}
}
]
},
resolve: {
extensions: ['', '.js', '.es6'],
},
};
Question: Does any one know why there is this difference? 问题:有人知道为什么会有这种区别吗? Or where the relevant information regarding ES6 module imports is in the Webpack documentation?
还是Webpack文档中有关ES6模块导入的相关信息在哪里?
This is by design, without prefixing it indicates the module should be loaded from node_modules directory. 这是设计使然,不带前缀,表示应从node_modules目录中加载模块。 You can set up an alias in your webpack config which would remove the need for relative module imports
您可以在webpack配置中设置别名,这将消除相对模块导入的需要
resolve: {
alias: {
sayHello: '/absolute/path/to/sayHello'
},
extensions: ['', '.js', '.es6']
}
Then Webpack would fill in the gaps in your import statements and allow you to omit the relative path and import * as sayHello from 'sayHello';
然后,Webpack将填补您的import语句中的空白,并允许您省略相对路径并以
import * as sayHello from 'sayHello';
would work throughout your project 将在您的整个项目中工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.