在nodejs中使用ES6模块语言时,出现了以下错误 铬浏览器中的“导入无法在模块外使用”错误。
我正在尝试使用Node js express猫鼬morgan express-handlebars和ES6构建项目
但是当我运行项目时,它给我一个错误
我尝试使用.babelrc和webpack.config.js,但无法解决。 谁能帮助我实现目标?
我正在放置我的项目的图像以供参考。
谢谢
在此处输入图片描述
Babelrc:
{
“预设”:[ [“ @ babel / env”,{ “ useBuiltIns”:“用法”, “ corejs”:“ 3”, “目标”:{ “浏览器”:[ “最后5个版本”, “即> = 8” ] } }] ] }
webpack.config.js:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template using Handlebars',
filename: 'index.html',
template: 'main.hbs'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
],
loaders: [
{ test: /\.hbs$/, loader: "handlebars-loader" }
]
}
};
main.js:
enter code here
import Search from './models/search';
import Movie from './models/Movie'
import User from './models/user'
import * as searchView from './views/searchView'
import * as movieView from './views/movieView'
import { elements , renderLoader, clearLoader } from './views/base'
const state = {};
const controlSearch = async () => {
// const query = searchView.getInput();
const query = 'avengers';
if (query) {
searchView.clearInput();
searchView.clearResult();
state.search = new Search(query);
state.user = new User();
searchView.clearInput();
searchView.clearResult();
renderLoader(elements.searchRes);
await state.search.getResult();
await state.user.userSignUp();
clearLoader();
console.log(state.search.result);
searchView.renderResults(state.search.result);
}
};
elements.searchForm.addEventListener('submit', e => {
e.preventDefault();
controlSearch();
});
main.hbs
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Movie Recherer</title>
<link rel="stylesheet" href="/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/css/all.min.css"/>
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/css/home.css" />
</head>
<body>
<div class="container">
<div class="row">
{{{body}}}
</div>
</div>
<script src="/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script language="javascript" src="/js/main.js"></script>
<script language="javascript" src="/js/models/Movie.js"></script>
<script language="javascript" src="/js/models/search.js"></script>
<script language="javascript" src="/js/views/base.js"></script>
<script language="javascript" src="/js/views/movieView.js"></script>
<script language="javascript" src="/js/views/searchView.js"></script>
</body>
</html>
答案 0 :(得分:0)
您需要将导入包含在模块中: 试试这个:
<script type="module"> import btn from './helper' </script>
在main.hbs文件的每个脚本标签中添加type="module"