webpack Cannot use import statement outside a module
时间: 2023-10-15 18:27:41 浏览: 129
报错:Uncaught SyntaxError: Cannot use import statement outside a module 详解
The error message "Cannot use import statement outside a module" typically occurs in a JavaScript when you are using the ES6 `import` syntax but have not set up your project to support modules.
To fix this issue, you need to make sure that your project is configured to use modules. Here are some steps you can follow:
1. Make sure you have a valid `package.json` file in your project directory. If not, create one by running `npm init` in your terminal.
2. Install webpack and the necessary loaders by running the following command in your terminal:
```
npm install webpack webpack-cli babel-loader @babel/core @babel/preset-env --save-dev
```
3. Create a webpack configuration file (e.g., `webpack.config.js`) in your project root directory. Add the following code to configure webpack to use Babel for transpiling:
```javascript
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
],
},
};
```
4. Create a `.babelrc` file in your project root directory and add the following code:
```json
{
"presets": ["@babel/preset-env"]
}
```
5. Update your `index.js` file (or whatever file you are importing modules in) to use `import` and `export` statements.
6. Build your project by running `npx webpack` in the terminal.
7. The transpiled code will be generated in the `dist` directory. You can include the `bundle.js` file in your HTML file.
By following these steps, you should be able to use the `import` statement without encountering the "Cannot use import statement outside a module" error.
阅读全文