我正在尝试使用基于Web6 4的基本ES6 import
/ export
,而Webpack似乎无法解析我的模块,尽管根据错误信息,它看起来正确:
$ make
./node_modules/.bin/webpack --mode production src/app.js -o dist/bundle.js
Hash: 6decf05b399fcbd42b01
Version: webpack 4.1.1
Time: 339ms
Built at: 2018-3-11 14:50:58
1 asset
Entrypoint main = bundle.js
[0] ./src/app.js 41 bytes {0} [built]
ERROR in ./src/app.js
Module not found: Error: Can't resolve 'hello.js' in '/home/(myhomedir)/code/js/src'
@ ./src/app.js 1:0-31 2:0-5
这是我的设置(node_modules
,dist
等省略):
$ npm ls --depth=0
.
├── webpack@4.1.1
└── webpack-cli@2.0.11
$ tree
.
├── Makefile
└── src
├── app.js
└── hello.js
生成文件:
webpack = ./node_modules/.bin/webpack --mode production
entry = src/app.js
webpack: $(entry)
$(webpack) $(entry) -o dist/bundle.js
的src / app.js:
import {hello} from "hello.js";
hello();
的src / hello.js:
function hello() {
alert("yes it's hello");
}
export { hello };
我在app.js
的导入路径上尝试了很多变体,但它们都得到了相同的结果:Can't resolve
模块文件。我错过了什么?
答案 0 :(得分:4)
你需要使用babel& amp;使用babel-loader。
此外,您不需要使用制作,只需使用 npm脚本。
导入import { hello } from 'hello.js'
等错误应该是import { hello } from './hello.js'
或没有 .js ,例如import { hello } from './hello'
尝试以下方法 -
npm install --save-dev babel-core babel-loader babel-preset-env webpack @ next webpack-cli
import { hello } from "./hello";
hello();
function hello() {
console.log("yes it's hello");
}
export { hello };
const path = require("path");
module.exports = {
entry: "./src/app.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
exclude: /(node_modules)/
}
]
}
};
{
"name": "webpack-test",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"build": "webpack --mode development",
"prod": "webpack --mode production",
"start": "node dist/bundle.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"webpack": "^4.0.0-beta.3",
"webpack-cli": "^2.0.11"
}
}
{
"presets": ["env"]
}
首次运行npm run build
或npm run prod
&然后运行npm run start
,这将记录输出
答案 1 :(得分:0)
现代的解决方案是使用node.js 13+,然后将"type": "module"
添加到package.json文件中。这将允许您使用导入语法而不是require。更多信息,请点击https://nodejs.org/dist/latest-v13.x/docs/api/esm.html
Webpack仍然需要require语法,因此您必须将webpack.config.js
重命名为webpack.config.cjs
,然后通过将webpack --config webpack.config.cjs
添加到package.json脚本中,让Webpack知道新的配置文件是什么。命令。如果webpack修复了require的问题,请密切注意https://github.com/webpack/webpack-cli/issues/1165
这意味着您不需要任何通行证或翻译机。