gpt4 book ai didi

webpack - 如何在 Webpack 4 中使用 ES6 导入/导出?

转载 作者:行者123 更新时间:2023-12-04 15:06:58 24 4
gpt4 key购买 nike

我正在尝试获得一个基本的 ES6 import/export使用 Webpack 4,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_modulesdist 等省略):
$ 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模块文件。我错过了什么?

最佳答案

您需要使用 babel 转译它并使用 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

src/app.js

import { hello } from "./hello";
hello();

src/hello.js
function hello() {
console.log("yes it's hello");
}
export { hello };

webpack.config.js
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)/
}
]
}
};

包.json
{
"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"
}
}

.babelrc
{
"presets": ["env"]
}

第一次运行 npm run buildnpm run prod & 然后运行 ​​ npm run start这将记录输出

关于webpack - 如何在 Webpack 4 中使用 ES6 导入/导出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49224431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com